Unity Car Game在文本上显示Kph Speed

时间:2018-02-26 03:29:37

标签: c# unity3d

我想在屏幕上显示车速kph,但我只有0kph并且它无法工作..虽然我有这个代码..任何建议都会很好谢谢

enter image description here

public Text text;
private double Speed;
private Vector3 startingPosition, speedvec;

void Start () 
{
    startingPosition = transform.position;
}

void FixedUpdate()
{
    speedvec = ((transform.position - startingPosition) / Time.deltaTime);
    Speed = (int)(speedvec.magnitude) * 3.6; // 3.6 is the constant to convert a value from m/s to km/h, because i think that the speed wich is being calculated here is coming in m/s, if you want it in mph, you should use ~2,2374 instead of 3.6 (assuming that 1 mph = 1.609 kmh)

    startingPosition = transform.position;
    text.text = Speed + "km/h";  // or mph

}

任何续订/新编辑的代码都会很棒。谢谢

2 个答案:

答案 0 :(得分:1)

我目前在我的项目中使用此代码,它可以完美运行。请记住,我添加了一些选项并使它更加完整。

using System;
using UnityEngine;
using UnityEngine.UI;

public enum SpeedUnit
{
    mph,
    kmh
}

public class SpeedOMeter : MonoBehaviour
{
    private float currentSpeed;
    [SerializeField] private Text speedText;
    [SerializeField] private string previousText;
    [SerializeField] private SpeedUnit speedUnit;
    [SerializeField] private int decimalPlaces;
    Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        

        if (speedUnit == SpeedUnit.mph)
        {

            // 2.23694 is the constant to convert a value from m/s to mph.
            currentSpeed = (float)Math.Round(rb.velocity.magnitude * 2.23694f, decimalPlaces);

            //currentSpeed = (float)Math.Round((double)rb.velocity.magnitude * 2.23694f, 0);

            speedText.text = previousText + currentSpeed.ToString() + " mph";

        }

        else 
        {

            // 3.6 is the constant to convert a value from m/s to km/h.
            currentSpeed = (float)Math.Round(rb.velocity.magnitude * 3.6f, decimalPlaces);

            //currentSpeed = (float)Math.Round((double)rb.velocity.magnitude * 3.6f, 0);

            speedText.text = previousText + currentSpeed.ToString() + " km/h";

        }
    }
}

答案 1 :(得分:0)

我来自未来。只是想让您知道是否想要像这样的东西开箱即用,您可以使用我的代码:

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

using UnityEngine;
using UnityEngine.UI;

public class realSpeedOMeter : MonoBehaviour
{
    public float currentSpeed;
    public Text speedText;
    Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        currentSpeed = rb.velocity.magnitude * 2.23694f;

        speedText.text = currentSpeed.ToString() + "MPH";
    }
}