- Home /
[C#] Accelerate then decelerate to its wanted position
I have an object that needs to accelerate towards a location then decelerate to a given position using velocity's.
Here's what I have.
//Movement
public float decelDist;
public float distanceTo;
protected virtual void Movement() //Called from FixedUpdate
{
float adjustedAccel;
adjustedAccel = acceleration / rigidbody.mass;
decelDist = ((new Vector3(Velocity.x * Velocity.x, 0, Velocity.z * Velocity.z)) / (2 * adjustedAccel)).magnitude;
distanceTo = Vector3.Distance(transform.position, wantedPos);
if(decelDist >= Vector3.Distance(transform.position, wantedPos))
{
//slow down
Velocity -= (wantedPos - transform.position).normalized * adjustedAccel;
Debug.Log("slow down");
}
else if (decelDist < Vector3.Distance(transform.position, wantedPos))
{
Velocity += (wantedPos - transform.position).normalized * adjustedAccel;
Debug.Log("speed up");
}
}
In my mind this seems like it should work, however, it clearly doesn't. it has an tendency to overshoot, then head back, overshoot a lot (1/4 of stating distance ish) again, and repeat.
It does have to use that Velocity variable because other things will be effecting it later on.
Thank you, for all the help!
You may be interested in a script that implements many interpolators which do what you want: http://wiki.unity3d.com/index.php?title=$$anonymous$$athfx and http://wiki.unity3d.com/index.php/Interpolate
Although they may get the effect I want, the velocity will be effected by other forces, so a simple slerp won't actually function here.
Answer by sparkzbarca · Jul 08, 2013 at 04:45 PM
vectors cant be perfect. the slower you go the closer you'll get but at a certain point you need to either accept being "close enough" or if you want exact positioning you need to get very very close and teleport there.
use mathf.approximate to make sure your either "close enough" or close enough to teleport.
so
if(mathf.approximate(current_postion,desired_position))
{
teleport or stop and accept it as good enough
}
Your answer
Follow this Question
Related Questions
How do I create a rubber band effect on a camera forward movement? 1 Answer
Move Player without acceleration 1 Answer
Spaceship movement with acceleration and deceleration on Unity 0 Answers
Acceleration problems (don't know how to make it stop moving) 0 Answers
When does a pos of a gameObject change from its velocity? 1 Answer