Jump with an Impulse
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 3 of 71.
AddForce takes a second argument, a ForceMode, that says how to use the vector. Without it you get ForceMode.Force, a push that lasts one physics step, so it has to be added step after step. A kick, a jump or an explosion happens all at once, and that is ForceMode.Impulse: the whole push in one go, changing the speed by the impulse divided by the mass.
This football (0.5 kg) is kicked on a click. Its speed jumps by (0, 2, 6) / 0.5 = (0, 4, 12) m/s at the next physics step, and gravity and the grass take over from there:
void Update()
{
if (Input.GetMouseButtonDown(0))
{
rb.AddForce(new Vector3(0, 2, 6), ForceMode.Impulse);
}
}A one-off push can be called from Update(), on the frame of the click: Unity keeps it and applies it at the next physics step. The four modes differ in two ways, all at once or over a step, and with or without the mass:
Force: over a step, divided by mass (engines, wind).Acceleration: over a step, mass ignored.Impulse: all at once, divided by mass (kicks, jumps).VelocityChange: all at once, mass ignored: the vector is added straight to the speed.
Challenge
EasyMake the frog jump once per press of Space.
- Below the comment, write
if (Input.GetKeyDown(KeyCode.Space)). - Inside it, call
rb.AddForce(Vector3.up * jumpImpulse, ForceMode.Impulse);, so the frog's 2 kg count.
Press Play and press Space: the frog hops up and falls back. Then Check.
Try it yourself
using UnityEngine;
public class FrogJump : MonoBehaviour
{
public float jumpImpulse = 10f;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
// Space: one upward kick of jumpImpulse
}
}
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad4Coroutines
InvokeInvokeRepeating, CancelInvokeYour First CoroutineLoops in CoroutinesStopping CoroutinesRecap: Countdown10Project: Arena Escape
The ArenaHunters2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable WallPractice on your own: Unity playground