- Home /
how to track object movement speed 2d
Hi . In my game this far I have a object that spawns in to the game .I dont apply any move force to it it only have RigitBody 2d on it and box colider . Is there any way to calculate movement speed in space ? I need to calculate move speed to determine impact damage once object has collided with other object. So higher move speed will result in gigher damage number . Only problem is how do I find out speed of that object before it collides with other object ? Thanks
sisse008 has already posted what should be the correct answer, but in case you weren't sure how to estimate speed manually:
using UnityEngine;
using System.Collections;
public class Check$$anonymous$$ySpeed : $$anonymous$$onoBehaviour
{
private Vector3 previousPosition;
private float estimatedSpeed;
// Take an initial value for our position. The first value might end up
// being zero, but this tends to happen with numerical approximations.
void Awake ()
{
this.previousPosition = this.transform.position;
}
// It sounded like you were using physics on your objects, so we'll
// check the speed in the physics update
void FixedUpdate ()
{
// "Speed" is defined as the change in position divided by the change in time.
float delta = (this.transform.position - previousPosition).magnitude;
this.estimatedSpeed = delta / Time.fixedDeltaTime;
// Confirm it's working
Debug.LogFormat ("Check$$anonymous$$ySpeed.estimatedSpeed: {0}", this.estimatedSpeed);
}
}
Answer by sisse008 · Jan 09, 2018 at 01:16 PM
you can get magnitude of velocity:
float mag = GetComponent<Rigidbody2D>().velocity.magnitude;
by this metode volocity is getting bigger and bigger as long as my object is moving even if the speed in game looks the same ! For example if objects free falls long distance straight down - you can see that it falls at the same speed all the time but numbers from float mag = GetComponent().velocity.magnitude; are growing until object stops !So this metod is not working in my case . What I need is to get move speed as it is if object moves faster number should be higher and if it moves slower number should be lower .
This should be the answer @REICHTAG unless you have a requirement that the calculation must be prior to collision.
Answer by Cambesa · Jan 09, 2018 at 03:26 PM
You could subtract their position Vectors, it will result in a new Vector that indicates the force and direction of impact. Multiply this with Time.deltaTime to see how much force/second it has. It's a framerate independent measurement. Please do keep in mind relativity. An object moving downwards with 100 units/time colliding with an object moving upwards with 100 units/time will result in an impact of 200 units. But when the 2nd object is not moving, aka 0 units/time, it will have an impact of 100 units.
Kind regards, Yorick