首页 > 解决方案 > 用 KeyCode 改变速度针

问题描述

我有一个脚本,它以 0km/h 开头显示一个速度计。现在我想借助“UpArrow”等键码来提高速度,并用“DownArrow”来降低速度。谢谢你的帮助!

using System.Collections;
using System.Collections.Generic;

using UnityEngine;
using UnityEngine.UI;

public class NewSpeedometer : MonoBehaviour
{
    

    public float maxSpeed = 0.0f; // The maximum speed of the target ** IN KM/H **

    public float minSpeedArrowAngle;
    public float maxSpeedArrowAngle;

    [Header("UI")]
    public Text speedLabel; // The label that displays the speed;
    public RectTransform arrow; // The arrow in the speedometer

    private float speed = 0.0f;
    private void Update()
    {
        

        if (speedLabel != null)
            speedLabel.text = ((int)speed) + " km/h";
        if (arrow != null)
            arrow.localEulerAngles =
                new Vector3(0, 0, Mathf.Lerp(minSpeedArrowAngle, maxSpeedArrowAngle, speed / maxSpeed));
    }

    
}

标签: c#unity3d

解决方案


在 Update() 中,您应该放置一个 if(Input.GetKey(keycode.uparrow)) 并在其中设置速度以增加乘以 Time.deltaTime 的值和可以称为加速度的值。

对于减速,您可以做同样的事情,但将值从速度中提取出来。


推荐阅读