- Home /
The question is answered, right answer was accepted
Adding Force to Rigidbody2D in C#
I've only recently started programming, so I hope this is an easy fix. Anyways, I started out with my script functioning in the 2D sections of unity. I originally could not get rigidbody2D.AddForce(x,y); to work, so as I test I moved it all over to 3D for rigidbody3D.AddForce(x,y,z); and it worked! At this point, I'm entirely unsure of what the problem is. Here is the portion of the script using this.
//If player is moving and if player is not moving too fast;
if (Input.GetButton ("Horizontal") ) {
//Set horizontal movement;
if(velocityTracker < velocityCap ){
rigidbody2D.AddForce(speed * horizontal * Time.deltaTime * 100 * boostX, 0f);
Debug.Log (rigidbody2D.velocity);
}
}
Answer by Tomer-Barkan · Apr 11, 2014 at 06:26 AM
If you only changed the code to rigidbody3d and it worked, then this means that your gameobject has a rigidbody3d component, and you can't use rigidbody2d commands.
In the unity editor, select your GameObject, and check which component it has (in the inspector). If it is a "rigidbody" component, then remove it, and then add a rigidbody2d component instead (under component -> physics 2d -> rigidbody 2d).
The script wont even compile, not to mention I have changed the GameObject's rigidbody to 2D.
"Error CS1501: No overload for method 'AddForce' takes '2' arguments (CS1501) (Assembly-CSharp)"
I suppose I should have included this.
That's because AddForce needs to receive a Vector2, not two parameters.
Try:
rigidbody2D.AddForce(new Vector2(speed * horizontal * Time.deltaTime * 100 * boostX, 0f));
Thank you sir! Your answer really helped me !
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Help with movement script 2 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers