在 SFML 中使形状向鼠标移动

Make a shape move towards mouse in SFML

这是我的代码:

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);
}

所以我想要一个圆圈平滑地(比如旋转)面对电脑鼠标。现在,它不是循环旋转向鼠标移动;它只是突然改变方向以跟随鼠标。我知道这涉及一些技巧,但我希望有人能帮助我解决这个问题。谢谢!

编辑 1: 我试过这个

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);

}

运气不好。这只会让球在屏幕上震动。

实现更平滑运动的一种简单方法是让圆有自己的速度,然后根据位置修改该速度。

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->speed.x -= force * dt;
    }
    if (this->pos.y + radius > y) {
        this->speed.y -= force * dt;
    }
    if (this->pos.x + radius < x) {
        this->speed.x += force * dt;
    }
    if (this->pos.y + radius < y) {
        this->speed.y += force * dt;
    }

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

您可能还想确保速度不会太大。给它一个不允许超过的最大值。 或者使用一些适当的物理和数学来进行更实际的计算。

我找到了解决方案。我使用了距离公式 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);

}