Unity的C#編程教程_27_if 條件語句挑戰5速度控制
- 2020 年 8 月 13 日
- AI
- C/C++/C#
- 創建一個程序用於控制速度
- 按下 w 鍵,速度增加
- 按下 s 鍵,速度減小
- 當速度超過 80 的時候,提示減速
- 當速度減小到 0 的時候,提示加速
- 速度不能小於 0
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpeedController : MonoBehaviour
{
public int speed = 10;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.W)) // 判斷按下的是哪個按鍵 w 為加速
{
speed += 10; // 加速
if (speed >= 80)
{
Debug.Log("Please slow down!"); // 達到 80 顯示需要減速
}
}
else if (Input.GetKeyDown(KeyCode.S)) // 按下 s 為減速
{
speed -= 10; // 減速
if (speed <= 0) // 達到 0 顯示需要加速
{
speed = 0; // 重置速度為 0,因為速度不能為負
Debug.Log("Speed up!");
}
else if (speed >= 80) // 在超過 80 的情況依然提示減速
{
Debug.Log("Please slow down!");
}
}
}
}
- 我們也可以把速度的監測和顯示提示放到按鍵監測的外面,但是這樣由於每一幀都會執行監測,那速度大於 80 的時候,會不斷發出提示