首页 > 解决方案 > 在 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);

}

没运气。这只会让球在整个屏幕上振动。

标签: c++sfmlshapes

解决方案


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

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

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


推荐阅读