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
HardWrite the cannon: aim it, then fire five balls.
- In
Update(), addInput.GetAxisRaw("Vertical") * turnSpeed * Time.deltaTimetoangle, clamp it to 10 to 60, and settransform.rotation = Quaternion.Euler(-angle, 0f, 0f);. - On Space while
balls > 0, spawnballPrefabattransform.position + transform.forwardandAddForce(transform.forward * power, ForceMode.Impulse). - Take 1 off
ballsand 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
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