Hello. I’m building a spaceflight simulator game, and having a maddening problem.
I want my “Brake” function to apply thrust to my ship (which is a Rigidbody) to match the velocity of another object, ReferenceBody (which is not necessarily a Rigidbody, because it might be something huge like a planet that needs a mass>10).
This seems like it should be very simple.
Relative Velocity = My Velocity - Reference Velocity,
Thrust Vector = -Relative Velocity
But when I run the game and step on the brakes, ReferenceBody keeps getting farther away, even though after some time holding down the breaks, my velocity reads as equal to ReferenceBody’s. Braking slows me down, but then I appear to be stopped in absolute coordinates, not relative ones.
I must be doing something really dumb. I’ve stripped the operations down to their simplest form and the problem won’t go away, but I don’t see my mistake. Hopefully it will be obvious to someone else?
Relevant bits of code here:
//ReferenceBody Class
void FixedUpdate() {
//everything here is a Vector3
position = _transform.position;
velocity = (position - lastPosition);
lastPosition = position;
}
//Ship Class
void FixedUpdate ()
{
_velocity = rigidBody.velocity;
_position = rigidBody.position;
_relativePosition = (rigidBody.position - ReferenceBody.position);
_relativeVelocity = (rigidBody.velocity - ReferenceBody.velocity);
}
public void Brake ()
{
Vector3 _reverseVector = -_relativeVelocity;
rigidBody.AddForce (_reverseVector);
}
Thanks for any help!