Moving Targets
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 67 of 71.
Challenge
HardWrite the targets: they slide across the range, and a ball knocks them out.
- In
Start(), keepstartX = rb.position.x. InFixedUpdate(), move withrb.MovePositionalong x atspeed, flipping adirectionof 1 or -1 oncerangefromstartX. - In
OnCollisionEnter, whencollision.gameObject.CompareTag("Ball"), logname + " hit!"and destroy the ball and the target.
Press Play and knock out all three. Then Check.
Try it yourself
using UnityEngine;
public class Target : MonoBehaviour
{
[SerializeField] private float speed = 2f;
[SerializeField] private float range = 3f;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
// slide from side to side; a ball that hits the target knocks it out
}
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