与时间赛跑
本课属于 Coddy Unity 学习旅程的“物理与游戏玩法”单元。第 32 课,共 71 课。
挑战
中等为 Coin Rush 添加一个计时器。
- 在
Ball.cs中,添加public float timeLimit = 60f;和public float timeLeft;;在Start()中设置timeLeft = timeLimit;。 - 新增一个
Update(),当timeLeft > 0f时,从中减去Time.deltaTime;当时间到 0 时,将其设为0f,并记录"Time's up! Score: " + score。 - 在
FixedUpdate()中,仅当timeLeft > 0f时施加推力。
按“运行”,观察计时器。然后按“检查”。
亲手试试
using UnityEngine;
public class Ball : MonoBehaviour
{
public float force = 10f;
public int score;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
rb.AddForce(new Vector3(x, 0f, z) * force);
}
public void AddScore(int points)
{
score += points;
Debug.Log("Score: " + score);
}
}
物理与游戏玩法中的所有课
自己练习: Unity 在线编辑器