Monday, March 13, 2017

xna - How do I make a moving object stop smoothly at the end of a path?


There are a dozen ways I could word this question, but to keep my thoughts in line, I'm phrasing it in line with my problem at hand.



So I'm creating a floating platform that I would like to be able to simply travel from one designated point to another, and then return back to the first, and just pass between the two in a straight line. However, just to make it a little more interesting, I want to add a few rules to the platform.



  1. I'm coding it to travel multiples of whole tile values of world data. So if the platform is not stationary, then it will travel at least one whole tile width or tile height.

  2. Within one tile length, I would like it to accelerate from a stop to a given max speed.

  3. Upon reaching one tile length's distance, I would like it to slow to a stop at given tile coordinate and then repeat the process in reverse.


enter image description here


The first two parts aren't too difficult, essentially I'm having trouble with the third part. I would like the platform to stop exactly at a tile coordinate, but being as I'm working with acceleration, it would seem easy to simply begin applying acceleration in the opposite direction to a value storing the platform's current speed once it reaches one tile's length of distance (assuming that the tile is traveling more than one tile-length, but to keep things simple, let's just assume it is)- but then the question is what would the correct value be for acceleration to increment from to produce this effect? How would I find that value?



Answer



Using these steering behaviors as a guide. Looking at the arrive behavior:



enter image description here



Arrival behavior is identical to seek while the character is far from its target. But instead of moving through the target at full speed, this behavior causes the character to slow down as it approaches the target, eventually slowing to a stop coincident with the target.



We can create an "arrive at" function like something similar to this:


arriveAtPoint(Vector2f position, Vector2f target) {
float slowing_distance = 1;
Vector2f target_offset = target - position;
float distance = target_offset.length();
float ramped_speed = currentVelocity * (distance / slowing_distance);

float clipped_speed = Math.min(ramped_speed, currentVelocity);
targetLinearVelocity = target_offset.scale(clipped_speed / distance);
acceleration = targetLinearVelocity -linearVelocity;
}

This will update the acceleration we need to use to apply to the object in motion.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...