1

This 'object' is a rectangle in 2D coordinates. (Game is in Unity 3D)

With Rigidbody.velocity.z I can know if the object is moving right or left, but how can I know if this object (a spaceship) is moving to its own right or left?

Imagine a spaceship that accelerates forward. Then after a while the ship rotates 90°, having its right side now aligned with the direction of movement. If then the ship rotates 180°, it will have its left side aligned with the direction it is moving.

I think another way of asking would be, how to know in which side of the ship is the vector of movement?

Context

The ship has a maximum speed. If the ship is at maximum speed and it needs to change direction, first it has to slowdown. If the vector of the ships movement is somewhere to its right side, then it has to add a force pushing against it, rigidbody.addForce (transform.left * force)

(I haven't written this in the code yet, but below "headed" is the normalized vector of where the ship is headed, and shipDirection is the normalized vector of the ships direction. Supposedly when they match is when ship is pointed at where it is going, but I have to test it first)

if (throttle > 0) {
  if (headed != shipDirection) {
    if (body.velocity.z > 0)
      Rigidbody.addForce (transform.right * force);
    if (body.velocity.z < 0)
      Rigidbody.addForce (transform.left * force);
  }
}

The problem above is that transform.right or transform.left can be at either side depending on the object orientation, so it could either speed or slow the ship.

1 Answer 1

2

You can perform the dot product of the velocity with any directional vector to give the component in that direction. E.g. Vector2f.DotProduct(Rigidbody.velocity, Rigidbody.right) will be positive if the object is moving to its own right, and vice versa.

1
  • 1
    Just want to add that this is a projection of the vector Rigidbody.right onto Rigidbody.velocity(assuming i'm reading this correctly)
    – Daxtron2
    Commented Apr 9, 2018 at 13:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.