简体   繁体   English

如何在SFML中对角移动对象?

[英]How to move objects diagonally in SFML?

So I can move my object down and up by changing the y variable. 因此,可以通过更改y变量来上下移动对象。 I can move my object left and right by changing the x variable. 我可以通过更改x变量左右移动对象。 But how do I move diagonally at the same velocity. 但是,如何以相同的速度对角移动。 If i just do 如果我只是做

x += velocity;
y += velocity;

it will move about 1.5 times faster. 它将以大约1.5倍的速度移动。

Is there some kind of equation with cos and sin to make an object move in a direction it is pointed to? 是否存在某种带有cossin的方程式,以使对象沿其指向的方向运动? I would want to be able to change it's direction with SFML(Simple Fast Multimedia Library) built in function setRotation() . 我希望能够使用内置在setRotation()函数中的SFML(Simple Fast Multimedia Library)来更改其方向。

Thank you in advance. 先感谢您。

In SFML rotating an object won't affect the direction where it is going. 在SFML中旋转对象不会影响其前进方向。 So you have to implement it yourself. 因此,您必须自己实施。

x+=vel*sin(angle)
y+=vel*cos(angle)

For diagonal moving angle=45 degrees or (45*PI)/180 radians depending which sin/cos library you are using(C/C++ library require radians as argument). 对于对角线移动角度= 45度或(45 * PI)/ 180弧度,取决于您使用的是哪个sin / cos库(C / C ++库需要以弧度为参数)。

The answer here doesn't really show you why the transforms are so damn useful. 这里的答案并没有真正向您展示为什么这些转换是如此有用。 For example, assuming you have a Vector2f that represents the distance the object moves over a single 'tick' you can obtain the velocity relative to the rotation of the object. 例如,假设您有一个Vector2f来表示对象在单个“刻度”上移动的距离,则可以获得相对于对象旋转的速度。 This is most likely more convenient for complicated things. 对于复杂的事情,这很可能更方便。

sf::Transform rotation;
rotation.setRotation(getRotation()); 
sf::Vector2f velocity;//This could be (1,0) or (0,1) (or anything else) 
setPosition(getPosition()+rotation.transformPoint(velocity);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM