Menu
CoddyTech

Moving Targets

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

challenge icon

Challenge

Hard

Write the targets: they slide across the range, and a ball knocks them out.

  1. In Start(), keep startX = rb.position.x. In FixedUpdate(), move with rb.MovePosition along x at speed, flipping a direction of 1 or -1 once range from startX.
  2. In OnCollisionEnter, when collision.gameObject.CompareTag("Ball"), log name + " 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

Practice on your own: Unity playground