Menu
CoddyTech

Knockback

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 54 of 63.

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

The player can set off a shockwave. Write the Shockwave script on the Player. The Inspector gives it radius (4), power (6) and lift (2). The Player script is ready: the arrows walk the player.

  • When Space is pressed, find every collider within radius of the player with Physics.OverlapSphere.
  • Each one that has a Rigidbody, except the player itself, gets an Impulse: power straight away from the player across the ground, plus lift upward.
  • Colliders without a Rigidbody, such as the ground, are left alone.

Press Play, walk among the crates and press Space, 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
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Physics and Gameplay