Unity的C#编程教程_27_if 条件语句挑战5速度控制

  • 创建一个程序用于控制速度
  • 按下 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 的时候,会不断发出提示
Tags: