- Home /
Take final position after a force applied to a GameObject
I apply a force to a gameobject and it goes as expected. I want to take the final position of this gameobject when its velocity become zero. I use an algorithm like that
void Shoot ()
{
...
if(Mouse button clicked)
{
gameobject.rigidbody.AddForce;
shoot = true;
}
}
void Update ()
{
Shoot();
if(gameobject.rigidbody.velocity.magnitude==0 && shoot==true)
{
finalPosition==gameobject.transform.position;
shoot = false;
}
}
However, for the very first instant frame I just shoot(Force is applied but velocity isnt changing instantly), velocity == 0 and shoot become true. That is why I take start position instead of final position. Can you please show me a way?
Answer by hav_ngs_ru · Jan 27, 2015 at 04:37 PM
its like a dirty patch, but...
void Shoot ()
{
...
if(Input.GetMouseButton(0)) // <<<< fix
{
rigidbody.AddForce( ... ); // <<<< fix. you should specify parameters here
shoot = true;
lockFinalCheck = true; // <<<< add
}
}
void Update ()
{
if(!lockFinalCheck ) { // <<<< add
if(rigidbody.velocity.magnitude==0 && shoot==true) // <<<< fix. use rigidbody instead of gameObject.rigidbody
{
finalPosition==gameobject.transform.position;
shoot = false;
}
} // <<<< add
lockFinalCheck = true; // <<<< add
}
EDIT: void Shoot has been fixed
bu generally you should review your architecture... like this:
bool shoot = false, flying = false;
void Shoot() {
...
shoot = true; // just fire flag, dont apply forces
}
void FixedUpdate() {
if(flying && !shoot) {
... // fix final pose
flying = false;
}
if(shoot) {
... // ApplyForce here
shoot = false; // <<< fixed
flying = true;
}
}
EDIT: fixed typo :)
Sorry man, I made a mistake and updated my code in post. Could you please rewrite? I think there is a mistake in your code because shoot never becomes false after shooting?
never $$anonymous$$d, I thought this is pseudocode :) but actually your second revision is not correct too (see edited version in my answer).
What about my mistake in "rewrite architecture" code - you are right, it was my mistake. Fixed it now.