- Home /
Add Drag on one local axis to prevent fish tail of 2D Spaceship
That is one long question huh? So here is what I am trying to do. I am using an object with a Rigidbody2D for a top down 2D space combat RPG. When the player gives a ship a move order, I want the ship to rotate slowly around and begin thrusting at its destination when its current angle and desired angle reach less than 30 degrees. This much I have working.
However, since it begins thrusting before it is perfectly aimed, picks up some sideways velocity, causing it to keep rotating to face its target because of the drift. Thus the ship fishtails around its target, which looks really silly.
So what I want to do is apply drag on the local x velocity so that the ship can compensate for the incorrect velocity (similar to what RCS thrusters do for real space ships).
Here is the relevant code I have now:
function Navigate()
{
if(Destination != null)
{
var newRotation = Quaternion.LookRotation(transform.position - Destination.position, Vector3.forward);
newRotation.x = 0.0;
newRotation.y = 0.0;
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * RotSpeed);
var TargetAngle = Vector3.Angle(-transform.up, Vector3.Normalize(transform.position - Destination.position));
Debug.Log("Angle to target = " + TargetAngle);
if(TargetAngle < 30)
{
Debug.Log("Begin move");
var correction : float = TargetAngle / 30;
rigidbody2D.AddForce(transform.up * ShipSpeed * correction);
rigidbody2D.velocity = Vector2.Scale(rigidbody2D.velocity, (Vector2(transform.up.x, transform.up.y) * 0.5));
}
}
}
Thanks in advance for any help you can provide : D
Answer by robertbu · Feb 07, 2014 at 05:09 AM
I have no idea if this is the right solution for your problem. It seems to me you'd want to just increase the drag in general and then up the force to compensate a bit. But if you want to add a drag-like change to the velocity, you may do it this way:
rigidbody2D.velocity.x = rigidbody2D.velocity.x * dragFactor;
'dragFactor' will be some number close to but less than 1.0 like 0.985. This needs to be executed in FixedUpdate().
$$anonymous$$ind of right, but that woulden't that only effect the global x velocity. The ship rotates so velocity.x wont always be its local x axis.
Untested: use Transform.InverseTransformDirection() to transform velocity to local coordinates, scale, then transform it back:
var dir = transform.InverseTransformDirection(rigidbody.velocity);
dir.x = dir.x * dragFactor;
rigidbody.velocity = transform.TransformDirection(dir);