Cannon Range
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 61 of 63.
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
HardThe Inspector gives Cannon ballPrefab (a Rigidbody: the Ball prefab, mass 2, tagged Ball), angle (30), turnSpeed (40), power (30) and balls (5).
- The up arrow raises
angleand the down arrow lowers it, atturnSpeeddegrees per second, never below 10 or above 60. Every frame, set the barrel's rotation toQuaternion.Euler(-angle, 0, 0): in Unity a positive x angle tips the front down, so the minus sign tilts it up. - Space fires a ball while
ballsis above 0: spawn it 1 unit in front of the barrel's center, along the barrel, kick it with an Impulse ofpoweralong the barrel, take 1 offballsand log what is left, asBalls left: 4. With no balls left, Space does nothing.
Each target has a kinematic Rigidbody, and the Inspector gives Target speed and range (2 and 3 for Target1).
- Every physics step, move the target along x with
MovePositionatspeedunits per second, and turn it back whenever it getsrangeunits from where it started. - When a ball (tagged
Ball) hits the target, log the target's name andhit!, asTarget2 hit!, and destroy both the target and the ball. Anything that is not a ball leaves it alone.
Press Play and knock out all three targets, 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
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall