Hi all,
I’ve learn’t two ways to calculate velocity of a 3D game object without using Rigidbody, which are shown below. I attached the two scripts onto a same object (a cube) and I’ve noticed the velocity outcomes of the two methods at the same moment are not exactly the same. Can you please tell me which one can represent the velocity more precisely? And can you please tell me why the two scripts work differently? Thanks a million.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class VelocityReader : MonoBehaviour
{
public Vector3 linearVelocity;
private float previousRealTime;
//private GeometryTwist message;
private Vector3 previousPosition = Vector3.zero;
private Quaternion previousRotation = Quaternion.identity;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float deltaTime = Time.realtimeSinceStartup - previousRealTime;
linearVelocity = (transform.position - previousPosition) / deltaTime;
Vector3 angularVelocity = (transform.rotation.eulerAngles - previousRotation.eulerAngles) / deltaTime;
Debug.Log("Vlinear" + linearVelocity);
previousRealTime = Time.realtimeSinceStartup;
previousPosition = transform.position;
previousRotation = transform.rotation;
}
}
And the second script is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjVelocityReader : MonoBehaviour
{
Vector3 PrevPos;
Vector3 NewPos;
Vector3 PrevRot;
Vector3 NewRot;
public Vector3 ObjVelocity;
public Vector3 ObjRotation;
// Use this for initialization
void Start()
{
PrevPos = transform.position;
PrevRot = transform.eulerAngles;
}
// Update is called once per frame
void FixedUpdate()
{
transform.rotation = Quaternion.identity;
NewPos = transform.position; // each frame track the new position
ObjVelocity = (NewPos - PrevPos) / Time.fixedDeltaTime;
PrevPos = NewPos; // update position for next frame calculation
Debug.Log("ObjVlinear" + ObjVelocity);
NewRot = transform.eulerAngles; // each frame track the new rotation
ObjRotation = (NewRot - PrevRot) / Time.fixedDeltaTime;
PrevRot = NewRot; // update position for next frame calculation
}
}