Search code examples
c++sfmlshapes

Make a shape move towards mouse in SFML


Here is my code:

void Ant::Update(float dt, sf::RenderWindow& window) {
// calculate difference between mouse pos and ant pos
float x = sf::Mouse::getPosition(window).x;
float y = sf::Mouse::getPosition(window).y;

if (this->pos.x + radius > x) {
    this->pos.x -= speed * dt;
}
if (this->pos.y + radius > y) {
    this->pos.y -= speed * dt;
}
if (this->pos.x + radius < x) {
    this->pos.x += speed * dt;
}
if (this->pos.y + radius < y) {
    this->pos.y += speed * dt;
}

this->antCircle.setPosition(this->pos.x, this->pos.y);
}

So I want a circle to smoothly (like rotate) to face the computer mouse. Right now, it doesn't circularly rotate to move towards the mouse; it just changes direction abruptly to follow the mouse. I know this involves some trig but I'm hoping someone can help work through this with me. Thank you!

EDIT 1: I tried this

void Ant::Update(float dt, sf::RenderWindow& window) {
// calculate difference between mouse pos and ant pos
float x = sf::Mouse::getPosition(window).x;
float y = sf::Mouse::getPosition(window).y;

if (this->stackSpeed.x > 3) {
    this->stackSpeed.x = 0;
}
if (this->stackSpeed.y > 3) {
    this->stackSpeed.y = 0;
}

if (this->pos.x + radius > x) {
    //this->pos.x -= speed * dt;
    this->stackSpeed.x -= speed * dt;
}
if (this->pos.y + radius > y) {
    //this->pos.y -= speed * dt;
    this->stackSpeed.y -= speed * dt;
}
if (this->pos.x + radius < x) {
    //this->pos.x += speed * dt;
    this->stackSpeed.x += speed * dt;
}
if (this->pos.y + radius < y) {
    //this->pos.y += speed * dt;
    this->stackSpeed.y += speed * dt;
}

this->pos.x += this->stackSpeed.x;
this->pos.y += this->stackSpeed.y;

this->antCircle.setPosition(this->pos.x, this->pos.y);

}

No luck. This just makes the ball vibrate all over the screen.


Solution

  • I found the solution. I used the distance formula sqrt((x2-x1)^2 + (y2-y1)^2):

    void Ant::Update(float dt, sf::RenderWindow& window) {
    // calculate difference between mouse pos and ant pos
    float x = sf::Mouse::getPosition(window).x;
    float y = sf::Mouse::getPosition(window).y;
    
    float xDist = x - (this->pos.x + radius);
    float yDist = y - (this->pos.y + radius);
    float dist = sqrt((xDist * xDist) + (yDist * yDist));
    
    if (dist > 1) {
        this->pos.x += xDist * dt * speed;
        this->pos.y += yDist * dt * speed;
    }
    
    this->antCircle.setPosition(this->pos.x, this->pos.y);
    

    }