Reputation: 950
I am developing a game and I need to create a method to create a movement. What it needs to do is take x y
and target x y
values and create a float[]
with the movement inside of it defined to a certain time. The movement will be used every frame for a certain amount of frames until it has reached the target in a specific time. Here is what I have so far.
public void calculateRoute(int time) {
if(x > tx){
movement[0] = -((x - tx) / time);
}else if(x < tx){
movement[0] = ((tx - x) / time);
}else if(x == tx){
movement[0] = 0;
}
if(y > ty){
movement[1] = -((y - ty) / time);
}else if(y < ty){
movement[1] = ((ty - y) / time);
}else if(y == ty){
movement[1] = 0;
}
}
The problem with this is that the farther the target, the quicker the movement is. I want to have the movement regulating to a certain speed but still reach its target. Basically I need to calculate the time
variable to a speed that will always be the same, no matter the distance. I tried this with setting the movement to 1 but it would miss its target since x
could be 500, and the y
could be 700. It would end up being x = 700, y = 700
. Any help is appreciated! :)
Also some sample code would be nice!
Upvotes: 0
Views: 118
Reputation: 33954
Maybe what you're asking is, given:
distance
between point A and point BstepSize
You want to have in a float []
:
One element for every step it will take to travel distance
, one stepSize
at a time. So:
stepSize = speed / 60.0; // 60 fps
stepCount = distance / stepSize;
Then a for loop that goes from 0 to stepCount-1, moving stepSize distance on each step.
I don't know what you need a float[] for in that case. If your step size doesn't evenly divide the distance you need to travel, and on the last step you've overshot you're target a bit, then on the last step simply set the (x, y) to the target (x, y)
Upvotes: 0
Reputation: 33954
Some things to consider:
speed*time=distance moved
If you're using a game engine, which would be a really good idea because this is a solved problem, they will provide some kind of "delta" time that tells you how much time has elapsed since the last logic/physics/AI update. You can use that value.
Upvotes: 1