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;
void Start()
{
}
void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
speed += 10;
if (speed >= 80)
{
Debug.Log("Please slow down!");
}
}
else if (Input.GetKeyDown(KeyCode.S))
{
speed -= 10;
if (speed <= 0)
{
speed = 0;
Debug.Log("Speed up!");
}
else if (speed >= 80)
{
Debug.Log("Please slow down!");
}
}
}
}
- 我们也可以把速度的监测和显示提示放到按键监测的外面,但是这样由于每一帧都会执行监测,那速度大于 80 的时候,会不断发出提示