Menu
CoddyTech

Cannon Range

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 66 of 71.

A cannon stands at one end of a firing range, and three targets slide from side to side across the range at different distances. You tilt the barrel up and down to reach each distance and time each shot for when a target crosses the line of fire. A ball that hits a target knocks it out and is used up; anything else that bumps a target leaves it alone. The targets are kinematic bodies, so hits never push them, and the cannon holds five balls.

Write two scripts: Cannon on the Barrel and Target on each target.

challenge icon

Challenge

Hard

Write the cannon: aim it, then fire five balls.

  1. In Update(), add Input.GetAxisRaw("Vertical") * turnSpeed * Time.deltaTime to angle, clamp it to 10 to 60, and set transform.rotation = Quaternion.Euler(-angle, 0f, 0f);.
  2. On Space while balls > 0, spawn ballPrefab at transform.position + transform.forward and AddForce(transform.forward * power, ForceMode.Impulse).
  3. Take 1 off balls and log "Balls left: " + balls.

Press Play and fire. Then Check.

Try it yourself

using UnityEngine;

public class Cannon : MonoBehaviour
{
    [SerializeField] private Rigidbody ballPrefab;
    [SerializeField] private float angle = 30f;
    [SerializeField] private float turnSpeed = 40f;
    [SerializeField] private float power = 30f;
    [SerializeField] private int balls = 5;

    void Update()
    {
        // aim with the up and down arrows, fire with Space
    }
}

All lessons in Physics and Gameplay

Practice on your own: Unity playground