简体   繁体   中英

How to move objects diagonally in SFML?

So I can move my object down and up by changing the y variable. I can move my object left and right by changing the x variable. 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.

Is there some kind of equation with cos and sin to make an object move in a direction it is pointed to? I would want to be able to change it's direction with SFML(Simple Fast Multimedia Library) built in function setRotation() .

Thank you in advance.

In SFML rotating an object won't affect the direction where it is going. 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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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