getComponent().Velocity always returns 0?
I want to detect the velocity of an object(which is controlled by mouse position ) at the time of entering a trigger . what I've done so far is
void OnTriggerEnter(Collider other){ someVector3 = getComponent().velocity; } but it always evaluates to zero, why is this happening and how can I fix it?
Did you mean other.GetComponent<Rigidbody>().velocity
?
Answer by unity_PNVpFX7xnCpieQ · Mar 24, 2018 at 08:03 AM
Super old, but anyhow since it doesn't have an answer and I needed one, I put a bunch of other semi-related posts together to define a work around and thought I would share since this zero velocity thing made me pull my hair out.
Basically, moving something (like your weapon) with a controller (or motion controller in my case) does not give the rigidbody anything to work with cause there is no force applied to it. It just magically "moves" from one place to the other based on your physical movements. Thus you have to calculate the velocity yourself. It's unfortunately really simple, but took me a while to put it all together.
on the object you want to track Velocity, you need to setup the following variables (note that I did this for 3d but you can do it in 2d as well).
Vector3 PrevPos;
Vector3 NewPos;
Vector3 ObjVelocity;
And I initialized them
void Start()
{
PrevPos = transform.position;
NewPos = transform.position;
}
Then in my FixedUpdate I calculate the velocity for this GameObject. I used FixedUpdate cause determining velocity over 24 frames/second was good enough and saved resources compared to 120 frames/second using Update.
void FixedUpdate()
{
NewPos = transform.position; // each frame track the new position
ObjVelocity = (NewPos - PrevPos) / Time.fixedDeltaTime; // velocity = dist/time
PrevPos = NewPos; // update position for next frame calculation
}
now in my code I can use ObjVelocity anyway I want. In this case, my controller is hitting a ball, so we send it flying based on the position of my controller and the magnitude of the controller velocity.
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("ball"))
{
HitBall (other.gameObject, transform, ObjVelocity.magnitude);
}
}
I'd been pulling my hair out for the last two days over this. Thank you!! This worked for me.
Answer by SuperRaed · Aug 24, 2015 at 08:27 AM
the reason why velocity always returned as 0 was because I never accessed the rigidbody component i.e add force to it, all I did was simply change the object's location based on mouse input. however I want to know how can I combine between taking mouse position with adding force to object?
Your answer
Follow this Question
Related Questions
Rigidbody.velocity Movement code produce wildly different gravity interactions 0 Answers
How to set velocity from connected Rigidbody? 0 Answers
,Two Similar Rigidbodies with velocity behaving differently 1 Answer
A trigger that changes the downforce of any rigidbody that hits it? 0 Answers
Falling Platform 1 Answer