Menu
CoddyTech

接住它

本课属于 Coddy Unity 学习旅程的“Unity 脚本基础”单元。第 52 课,共 85 课。

challenge icon

挑战

中等

接住星星,并统计接住的次数。

  1. 添加一个字段 private int score;。
  2. 星星移动后,当 Vector3.Distance(transform.position, star.position) < 1f 时,将 score 加 1,并记录 "Caught! Score: " + score。
  3. 在这个 if 语句中,将星星移回 y = 6f 的位置,同时保留它的 x 和 z。

按“开始”,滑到星星下方:控制台会显示 Caught! Score: 1。然后点击“检查”。

亲手试试

using UnityEngine;

public class Catcher : MonoBehaviour
{
    [SerializeField] private float speed = 6f;
    [SerializeField] private Transform star;
    [SerializeField] private float fallSpeed = 3f;

    void Update()
    {
        float x = transform.position.x;
        if (Input.GetKey(KeyCode.RightArrow))
        {
            x += speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            x -= speed * Time.deltaTime;
        }
        x = Mathf.Clamp(x, -4f, 4f);
        transform.position = new Vector3(x, transform.position.y, transform.position.z);

        star.position += Vector3.down * fallSpeed * Time.deltaTime;
    }
}

Unity 脚本基础中的所有课

自己练习: Unity 在线编辑器