- Home /
Use addForce to Jump
It's my code
void FixedUpdate(){
if (Input.GetKey (KeyCode.Space)) {
GetComponent<Rigidbody2D> ().AddForce (new vector2(0,5) );
}
}
But it's not working
Your code is fine but you are not applying sufficient force to move up.And its Vector2
not vector2
.
public float Speed=20.0f;
void FixedUpdate()
{
if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.Space))
{
GetComponent<Rigidbody2D>().AddForce(new Vector2(0, 5* Speed));
}
}
i suggest reformatting it to
"It's my code
void FixedUpdate(){
if (Input.Get$$anonymous$$ey ($$anonymous$$eyCode.Space)) {
GetComponent<Rigidbody2D> ().AddForce (new vector2(0,5) );
}
}
But it's not working"
Answer by SohailBukhari · Jul 25, 2017 at 06:48 AM
AddForce take parameter vector2 Components of the force in the X and Y axes.
Rigidbody2D.AddForce Adds a force to the Rigidbody.
Force is applied continuously along the direction of the force vector. Specifying the ForceMode mode allows the type of force to be changed to an Acceleration, Impulse or Velocity Change.
Force can be applied only to an active Rigidbody. If a GameObject is inactive, AddForce has no effect.
By default the Rigidbody's state is set to awake once a force is applied, unless the force is Vector3.zero.
Try this code:
public float Speed;
void FixedUpdate()
{
if (Input.GetKey(KeyCode.Space))
{
GetComponent<Rigidbody2D>().AddForce(Vector2.up* Speed);
}
}
See the Docs:https://docs.unity3d.com/ScriptReference/Rigidbody2D.AddForce.html