c++ - 在 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);
}
您可能还想确保速度不会变得太大。给它一个不允许超过的最大值。或者使用一些适当的物理和数学来进行更现实的计算。
推荐阅读
- ios - 在允许 FCM 推送通知时修复错误 403
- regex - 删除工作表中所有 URL 的指定部分
- python - 如果在 add_mutually_exclusive_group 中添加元素,内容将消失
- javascript - 如何识别具有单击事件及其源代码的元素,即使它是动态附加的,理想情况下是在调试器中?
- caching - Google Cloud CDN 不会缓存 https 页面,因为它们具有 Vary 标头 x-forwarded-proto
- mysql - 当客户使用 NodeJS/MySQL 选择产品时,使用 (connection.query(update...)) 努力更新值
- email - 无法在可编辑的电子邮件插件中附加我的范围报告。我在 Jenkins 工作的工作区是空的。是这个原因吗?
- javascript - ReactJS/Javascript/Graphql/React-apollo:无法读取未定义的属性“名称”
- python - Python/Django - 如何调试变量
- c# - Asp.Net Regex C# 替换功能不起作用