Unity赛车码表原理

近日在制作赛车游戏时,遇到了码表,较为有趣,遂记录如下。

 

Unity赛车码表原理_第1张图片

首先观察码表速度0mph时,指针Roatation的z轴角度为-133

Unity赛车码表原理_第2张图片

然后140mph时的z轴角度为-43,则

由 140 mph = 270°

=> 1 mph = 270/140 °

=> α mph = α * 270 / 140 °

之间的夹角正好为90度,那么按顺时针的话,从0mph到140mph的欧拉角为270度。

 

夹角计算出来后,需要跟据速度来换算成角度,推导如下:所以重要结论 每公里的欧拉角为 α * 270 / 140 °

 

换算成代码:

// 获取码表度数
float newZRotation = zRotation - currentSpeed * (270 / 140f);

这边顺便讲一下,通过轮胎的角速度获取车子整体的位移速度

// 获取速度
float speed = Mathf.Round(flWheelCollider.rpm * (flWheelCollider.radius * 2 * Mathf.PI) * 60 / 1000);

flWheelCollider是轮胎的WheelCollider,rpm是旋转速度,一分钟多少圈;之后这个2ΠR应该大家都能看懂,也就是周长;

乘以 60 / 1000,是千米每小时的单位。那么如此一来就获取了位移速度,通过上面提到的速度换成为角度的公式就可以实现了。

 

完整代码:

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

public class SpeedDisplay : MonoBehaviour
{
    public WheelCollider flWheelCollider;
    private UILabel label;
    public float currentSpeed;
    public Transform pointContainer;
    private float zRotation;

    // Start is called before the first frame update
    void Start()
    {
        label = this.GetComponent();
        zRotation = pointContainer.eulerAngles.z;
    }

    // Update is called once per frame
    void Update()
    {
        // 获取速度
        float speed = Mathf.Round(flWheelCollider.rpm * (flWheelCollider.radius * 2 * Mathf.PI) * 60 / 1000);
        if (speed < 0) speed = Mathf.Abs(speed);
        label.text = speed.ToString();
        // 获取码表度数
        float newZRotation = zRotation - currentSpeed * (270 / 140f);
        pointContainer.eulerAngles = new Vector3(0, 0, newZRotation);
    }
}

 

你可能感兴趣的:(Unity,c#)