你赢了
本课属于 Coddy Unity 学习旅程的“物理与游戏玩法”单元。第 33 课,共 71 课。
挑战
中等让玩家在达到 target 分时获胜。
- 在
Ball.cs中,添加public int target = 10;和bool IsPlaying(),让它返回timeLeft > 0f && score < target。 - 在
Update()和FixedUpdate()中使用IsPlaying()替代timeLeft > 0f,并让AddScore以if (!IsPlaying()) return;开头。 - 在分数语句之后,当
score >= target时,记录You win!。
按下“开始”并收集 8 分,然后点击“检查”。
亲手试试
using UnityEngine;
public class Ball : MonoBehaviour
{
public float force = 10f;
public int score;
public float timeLimit = 60f;
public float timeLeft;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
timeLeft = timeLimit;
}
void Update()
{
if (timeLeft > 0f)
{
timeLeft -= Time.deltaTime;
if (timeLeft <= 0f)
{
timeLeft = 0f;
Debug.Log("Time's up! Score: " + score);
}
}
}
void FixedUpdate()
{
if (timeLeft > 0f)
{
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 在线编辑器