Rigidbody2D.velocity not working! [SOLVED]

Updated on August 28, 2016 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
10 on August 26, 2016

Hi everyone,

I’m making a simple gravity simulator for Android and I have an issue. I will simplify the code, inserting only the section where I have issues

 void Update () {
 ...
 else if (Input.GetTouch (0).phase == TouchPhase.Ended){
 ...
 Instantiate (asteroid, conversion, Quaternion.Euler (0f, 0f, 0f));
 astRigid = asteroid.GetComponent ();
 astRigid.velocity = new Vector2 (diffConVectors.x,diffConVectors.y);
 }
 }
 

diffConVectors is a Vector3 which does have values, but unfortunately astRigid.velocity always results in a (0.0,0.0) vector. I cannot understand why. I initially thought it was because I was only setting an initial velocity and not repeating it in the update method every frame, but then I also tried the following:

 astRigid.AddForce (new Vector2 (diffConVectors.x, diffConVectors.y), ForceMode2D.Impulse);
 

and nothing happens again. There are no major errors given by the console. There is something I do not understand about this topic apparently, but I don’t know what it is.

  • Liked by
Reply
3 on August 27, 2016

Just to make sure, the rigidbody component on the object has the isKinematic bool set to true?

Devoted
on August 27, 2016

You meant false, right?

on August 27, 2016

lol yeah i meant false šŸ˜

Helpful
on August 28, 2016

Alright will look into that, thx!

Edit: apparently it was set to false the whole time.. it’s very strange, the scripts don’t give errors on this but it still does not function.

Show more replies
  • Liked by
Reply
Cancel
3 on August 28, 2016

Is the game object “asteroid” consideredĀ an instance once instantiated? Because if it’s still considered as a prefab, then the addforce might be added directly to that stored prefab which is not in the hierarchy, which would not work.. but I do not know if that’s the case.

on August 28, 2016

oh you might be right, just do smth like

GameObject astInstance =Ā Instantiate (asteroid, conversion, Quaternion.Euler (0f, 0f, 0f));

and then do the rigidbody stuff with the astInstance isntead of the asteroid, I think that should work? because you were reffering to the prefab like you said and not the created gameobject

Show more replies
  • Liked by
Reply
Cancel
1 on August 28, 2016

Thanks guys, will try that in a few mins!

Edit: Yes it works! Great, I’m very happy, why wasn’t it considered an instance though? Thanks so much!

  • Liked by
Reply
Cancel