Menu
CoddyTech

移动靶

本课属于 Coddy Unity 学习旅程的“物理与游戏玩法”单元。第 67 课,共 71 课。

challenge icon

挑战

困难

编写目标:它们会在范围内滑动,球会将它们击倒。

  1. 在 Start() 中,保留 startX = rb.position.x。在 FixedUpdate() 中,使用 rb.MovePosition 沿 x 轴以 speed 移动;当与 startX 的距离达到 range 时,将 direction 从 1 切换为 -1,或从 -1 切换为 1。
  2. 在 OnCollisionEnter 中,当 collision.gameObject.CompareTag("Ball") 时,记录 name + " hit!",并销毁球和目标。

按下 Play,击倒全部三个目标。然后点击 Check。

亲手试试

using UnityEngine;

public class Target : MonoBehaviour
{
    [SerializeField] private float speed = 2f;
    [SerializeField] private float range = 3f;
    private Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    // 左右滑动;球击中目标后,会把它撞飞
}

物理与游戏玩法中的所有课

自己练习: Unity 在线编辑器