lisovaccaro
lisovaccaro

Reputation: 33996

Calculate the velocity of an object being moved manually?

I'm directly modifying an object position by moving it around with the mouse button.

Vector3 touchPosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);
Vector3 touchPosition = new Vector3 (touchPosition.x, touchPosition.y, transform.position.z);
touchPosition.z = transform.position.z;

if(Input.GetMouseButton(0)) {
    transform.position = newPosition;
}

What I want to find out is what is the average velocity of the object in the last few frames. Any idea how to do this?

Upvotes: 0

Views: 820

Answers (1)

maraaaaaaaa
maraaaaaaaa

Reputation: 8193

Probably would look something like this:

Vector3 velocity;

Vector3 lastPosition = transform.position;
Vector3 touchPosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);
Vector3 touchPosition = new Vector3 (touchPosition.x, touchPosition.y, transform.position.z);
touchPosition.z = transform.position.z;

if(Input.GetMouseButton(0)) {
    transform.position = newPosition;
    velocity = (newPosition - lastPosition) / Time.deltaTime;
}

Upvotes: 1

Related Questions