Search Unity

Get the velocity of a non-rigidbody gameobject?

Discussion in 'Physics' started by TKDHayk, Jun 26, 2016.

  1. TKDHayk

    TKDHayk

    Joined:
    Dec 22, 2015
    Posts:
    130
    How can I get the velocity of an object (gun ) being moved by mouse movement and WASD input? Tried attaching a rigidbody to the moving object and accessing rigidbody.velocity.magnitude, but it always returns as 0 because it is not being moved by addForce().
     
  2. Edy

    Edy

    Joined:
    Jun 3, 2010
    Posts:
    2,508
    You might try simply calculating the velocity out of the latest consecutive positions:

    // Initialization

    Vector3 lastPosition = transform.position;

    // At each frame:

    Vector3 velocity = (transform.position - lastPosition) / Time.deltaTime;
    lastPosition = transform.position;
     
  3. TKDHayk

    TKDHayk

    Joined:
    Dec 22, 2015
    Posts:
    130
    thanks! tried this. It works, but very buggy. If i shoot while strafing very fast, the bullet does indeed travel straight, same as if the gun was not moving at all. However, the origin point of the bullet gets shifted in the direction of movement, so the bullet does not even instantiate at the tip of the barrel, but to the left.