Knockback
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 57 of 71.
A knockback is a kick away from whatever hit you: one impulse along the line from the hitter to the thing hit. This bumper knocks back everything that bumps into it:
[SerializeField] private float power = 8f;
void OnCollisionEnter(Collision collision)
{
Vector3 away = collision.transform.position - transform.position;
away.y = 0f;
collision.rigidbody.AddForce(away.normalized * power, ForceMode.Impulse);
}collision.transform.position - transform.position points from the bumper to the thing that hit it. Its y is set to 0 so the kick stays level, and normalized makes it the same size however far apart the two centers are. ForceMode.Impulse is a one-off kick: it changes the velocity by power divided by the mass, at once, so a ball of mass 2 flies off at half the speed of a ball of mass 1. The default ForceMode.Force is meant to be applied in every step and gives one step's worth, 50 times less.
The kick lasts only while nothing overwrites the velocity. A player whose FixedUpdate sets rb.linearVelocity from the arrows in every step loses it one step later, so a script like that has to leave the velocity alone for a moment after a hit, or move the player with forces.
Challenge
MediumLet the player set off a shockwave with Space.
- On
Input.GetKeyDown(KeyCode.Space), loopforeach (Collider hit in Physics.OverlapSphere(transform.position, radius)), skipping the player's own collider. - For each
hit.TryGetComponent(out Rigidbody body), takeaway = hit.transform.position - transform.positionwithaway.y = 0f. - Call
body.AddForce(away.normalized * power + Vector3.up * lift, ForceMode.Impulse);.
Press Play and press Space among the crates. Then Check.
Try it yourself
using UnityEngine;
public class Shockwave : MonoBehaviour
{
[SerializeField] private float radius = 4f;
[SerializeField] private float power = 6f;
[SerializeField] private float lift = 2f;
void Update()
{
// on Space: push every Rigidbody within radius away from the player
}
}
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