Search Unity

Help with getting velocity...

Discussion in 'Scripting' started by tecra134, Jun 29, 2012.

  1. tecra134

    tecra134

    Joined:
    Mar 19, 2011
    Posts:
    94
    I have an empty GameObject that's being moved from one position to the next via Mathf.SmoothDamp. I'm trying to have the camera match its speed. This is what I have so far but I can't get the velocity readings from the rigidbody when the gravity is turned off.

    Empty Object script (And the object does have a rigidbody attached)
    Code (csharp):
    1.  
    2. var howFast:Vector3;
    3.  
    4. function Update()
    5. {
    6. transform.position.x = Mathf.SmoothDamp(transform.position.x,target.position.x,currentV,smoothTime,maxSpeed);
    7. transform.position.z = Mathf.SmoothDamp(transform.position.z,target.position.z,currentV,smoothTime,maxSpeed);
    8.  
    9. howFast = rigidbody.velocity;
    10. }
    11.  
    Is there a better way to get the velocity of an object or a better way to have the camera match the same speed as an object, that's not Camera.main.transform.position = target.position and also only relative to Space.World?
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    You can't get anything out of .velocity if you're moving an object manually. You need to apply physics forces for that (including gravity).

    --Eric
     
  3. tecra134

    tecra134

    Joined:
    Mar 19, 2011
    Posts:
    94
    That's what I figured. What is the best way I can match the velocity/speed of an object and apply it to another?
     
  4. flaminghairball

    flaminghairball

    Joined:
    Jun 12, 2008
    Posts:
    868
    Code (csharp):
    1.  
    2. var pseudoVelocity = Vector3.zero;
    3.  
    4. private var lastPos = Vector3.zero;
    5.  
    6. function Awake(){
    7.   lastPos = transform.position;
    8. }
    9.  
    10. function Update(){
    11.   pseudoVelocity = transform.position - lastPos;
    12.   lastPos = transform.position;
    13. }
    14.  
    And Bob's your uncle.
     
  5. npsf3000

    npsf3000

    Joined:
    Sep 19, 2010
    Posts:
    3,830
    Code (csharp):
    1. pseudoVelocity = (transform.position - lastPos) * Time.deltaTime;