Public Group

# Sprite movement

This topic is 5226 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Say I have a sprite that I want to move to a certain point on the screen (for example, it starts at 10, 10 and I want it to move to 70, 50) Is there a way to "point" the sprite in that direction and have it move along a trajectory towards that point? Right now, the only way I know to do this is to continuously increase (or decrease) the sprites position_x and position_y until the desired point is reached. This causes a problem because it might reach the correct x location before it reaches the y location and the movement ends up looking very unnatural. I guess I'm talking about vectors or something... Any ideas, suggestions? Thanks!

##### Share on other sites
Calculate the difference between the X distance and Y distance, then you simply move the sprite accordingly.
For example, if you want to move the sprite from (10,10) to (20,30), you'd do something like this:

ratio = (x2 - x1) / (y2 - y1) = (20-10) / (30-10) = 0.5while y is not y2    x = x + ratio * step    y = y + ratioend while

This pseudocode is pretty clunky, but you'll hopefully get the basic idea.

##### Share on other sites
A good technique is to give the sprite an x and y velocity, which can be represented by a vector.

First you can find the difference from dest to start
dest - start = diff
<70,50> - <10,10> = <60,40>

Imagine the vector <60,40> as an arrow pointing 60 units left and 40 units up.

            B            |            | 40A___________|     60

Using the pythagorean theorem you can find the length of the arrow from A to B.

sqrt(602+402) = 72.11..

To normalize the vector you divide the x and y components by the magnitude

normal = <60,40> / 72.11 = <0.832,0.555>

The normalized vector represents the proportional amount of change in each component. Basically for every 0.832 you add to x, you must add 0.555 to y to move along a straight line from A to B in the above picture.

normal * speed (where speed is a value you choose to get the desired speed) is how much you need to move per frame.

##### Share on other sites
Thanks fellas! Both really useful and informative replys! Now I can tell people I've normalized my first vector! Cool! ;)

On the same subject, could I tell a sprite to move at a certain angle (from 0 - 360 degrees)? For example, to tell a sprite to move along a trajectory angled at 35 degrees...

##### Share on other sites
It shouldn't be too hard. Use cos(angle) * velocity to get the movement speed for the X axis, and sin(angle) * velocity to get the speed for the Y axis.

EDIT: Don't forget that the standard math functions use radians rather than degrees, so don't forget to convert from deg to rad.

1. 1
2. 2
3. 3
Rutin
28
4. 4
khawk
14
5. 5

• 11
• 11
• 23
• 10
• 9
• ### Forum Statistics

• Total Topics
633648
• Total Posts
3013111
×