# Accelerate towards points.

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

## Recommended Posts

I have a function that looks like this:

public void moveTowardPoint(float targetX, float targetY, float steps)
{
float fX = targetX - currX;
float fY = targetY - currY;
double dist = Math.sqrt( fX*fX + fY*fY );
double step = steps / dist;
currX += fX * step;
currY += fY * step;
}


I want to add acceleration to this function but I have no idea how.

##### Share on other sites

Does this method actually work as expected?

For acceleration you need another member variable, which increases every turn and is then multiplied by the change of position.

Easiest would be if you leave the steps variable, and just tell the method which direction you want to go.

##### Share on other sites

Think of it in vector terms.

You have 2 points:

A : Start Point

B : End Point

To get a position of any Point X on the line between A and B, you use this equation :

X = A + k * (B-A)


k : coefficient in range <0,1>. if it is zero, you are at point A;   if it is one, you are at point B;   any other value in that range - you are somewhere between A,B

For a Constant speed you basically figure out the percent of time spent in movement (from its start):

k = Time_Elapsed_From_Start_Of_Movement / Total_Time_Length_Of_Movement


For acceleration, simply multiply the above by acceleration coefficient:

k *= Acceleration_Coefficient


I strongly recommend having a following class/structure to improve readability/debuggability of time-related functionality:

struct STiming
{
bool InProgress;
float TimeStart;
float TimeEnd;
float TimeLength;
};


The bool variable helps in readability a lot. You set it true when animation/movement starts and set it to false, when the time expires or you reached your destination.

This means, that if k > 1.0f, you set it to false (and cap the k to 1.0f to stop it at desired End point (to prevent it to overshoot behind its destination) - you never know how much time next frame will take - since there can be quite a time difference between two consecutive render frames).

I am using the system above in my game, and it is rock-stable whether the framerate suddenly drops to single-digits (antivirus/ OS task / whatever) or shoots to quadruple-digits.

1. 1
2. 2
Rutin
19
3. 3
4. 4
5. 5

• 14
• 13
• 9
• 12
• 9
• ### Forum Statistics

• Total Topics
631437
• Total Posts
3000070
×