Walking in any direction

Started by
5 comments, last by wilsq 18 years, 8 months ago
Hi, I'm making a crimsonland like top-town shooting game. In the game, I'm trying to make the hero move freely in any direction (0-360), instead of just 4 or 8. The direction is controled by mouse. When player holds the [w] key, the hero starts moving towards the mouse pointer. I can make the hero always face the mouse pointer by rotating the sprite, but I can't figure out how to make the sprite move by a certain angle (e.g. 25 degrees to the north). Thankyou.
Advertisement
trigonometric functions, ie sinus and cosinus, are your friend.

look them up and you can probably figure out how to use them better than i could explain it.
Let's take your example of 25 degrees to the north. That means character is also walking 90 - 25 = 65 degrees to the east or west. Use trigonometry to figure out how much to move character in both cardinal directions:

movement factor for north = sin 25 degrees (OR cos 65 degrees) = 0.42 (approx)
movement factor for east or west = cos 25 degrees (OR sin 65 degrees) = 0.91 (approx)
I'm assuming since you can rotate your sprite, you are somewhat familiar with trigonometry and vector math.

One thing you could try is to use 2d vectors to "encode" your character's movement. Start with a 2d vector pointing towards your initial direction. The head of the vector should always face the direction of movement. The size of the vector depends on your walk speed. You can start with a unit vector (length of 1) and just scale it to whatever your walk speed is. This can give you an easier way to change your character's speed by just scaling the vector. When you rotate your sprite, rotate your vector also. Then when the user presses [w] or your move forward button, just add the vector's components to the character's location. This will move the character in the proper direction. If you want to go backwards, then just subtract the vector from the location.

This solution may be a little more complicated than what you were looking for but I think you will like the results.
Edmund Weese7-bit Games
thank you guys,
That refreshed my maind, because I've been thinking about using "line-drawing" algorithms. 2D vectors will work just fine! Thank you again!

-wilsq
Now, there's a new problem. In theory, the 2d vector gives a ideal path, but on the screen, the smallest unit is 1 (1 pixel). There is a problem with converting a real number into pixels: say the x-factor is 0.42 and the y-factor is 0.91. In that case we can't simply round 0.42 in to nothing and 0.91 into 1, because that way, the sprite will move horizontally. So how is this problem solved with the vector algorithms?
Don't worry. I just realized that was just a silly question : P

This topic is closed to new replies.

Advertisement