Menu
CoddyTech

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 icon

Challenge

Medium

Let the player set off a shockwave with Space.

  1. On Input.GetKeyDown(KeyCode.Space), loop foreach (Collider hit in Physics.OverlapSphere(transform.position, radius)), skipping the player's own collider.
  2. For each hit.TryGetComponent(out Rigidbody body), take away = hit.transform.position - transform.position with away.y = 0f.
  3. 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

Practice on your own: Unity playground