【问题标题】:Dealing with floating point precision [duplicate]处理浮点精度[重复]
【发布时间】:2015-02-10 22:41:17
【问题描述】:

我正在统一创建游戏,但在将速度重置为 0 时遇到了问题。

游戏使用多个油门级别:-2 -1 0 1 2。当设置为油门级别时,对象意味着加速到设定的速度。这可行,但是当我将其重置为 0 时,即使设置了 0,速度也会将其自身设置为 0.0999999。

我该如何解决这个问题?

using UnityEngine;
using System.Collections;
using System;

public class Script_Control : MonoBehaviour {
public static float speedLvL;
public static float speed;
public static float health;
public static float manoverablity;
public static float tarSpeed;
public static float curSpeed;           
// Use this for initialization
void Start () {

//setting per ship stats
speedLvL = 0F;
speed = .25F;
health = 25F;
manoverablity = .25F;
//General Stats
tarSpeed = 0F;
curSpeed = 0F;

}

// FixedUpdate is called once per Time
void FixedUpdate () {
    Debug.Log(curSpeed);
//setting speed 
if (speedLvL == 0F){
    tarSpeed = 0.00000F;
}
if (speedLvL == 1F)  {
    tarSpeed = speed/2F;
}
if (speedLvL == 2F)  {
    tarSpeed = speed;
}
if (speedLvL == -1F)  {
    tarSpeed = -speed/5F;
}
if (speedLvL == -2F)  {
    tarSpeed = -speed/2.5F;
}

if (curSpeed < tarSpeed){
    curSpeed += .1F;
}
if (curSpeed > tarSpeed){
    curSpeed -= .1F;
}
    transform.Translate(curSpeed, 0, 0);

}
void Update(){

    if (Input.GetAxis("Throttle") > 0 && speedLvL <= 1 &&  speedLvL >= -2){
        speedLvL = speedLvL+1;      
        DateTime t = DateTime.Now; 
        DateTime tf = DateTime.Now.AddSeconds(.25);
        while (t < tf)
        {
            t = DateTime.Now;
        } 
    }   

    if (Input.GetAxis("Throttle") < 0 && speedLvL <= 2 &&  speedLvL >= -1){
        speedLvL = speedLvL-1;
        DateTime t = DateTime.Now; 
        DateTime tf = DateTime.Now.AddSeconds(.25);
        while (t < tf)
        {
            t = DateTime.Now;
        }
    }

    if (Input.GetAxis("Stearing") < 0){
        transform.Rotate(Vector3.forward* Time.deltaTime, manoverablity );

    }
    if (Input.GetAxis("Stearing") > 0){
        transform.Rotate(Vector3.forward* Time.deltaTime, -manoverablity);

    }
}



}

`

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    在 FixedUpdate 函数中,您设置了将速度重置为 0 的 if 语句,

    if (speedLvL == 0F){
        tarSpeed = 0.00000F;
    }
    

    但是,在相同的功能中,您可以使用以下功能来加速或减慢船速。

    if (curSpeed < tarSpeed){
        curSpeed += .1F;
    }
    

    在我看来,当您将船重置为 0 时,它会在停止调整之前添加 .1F

    您可能需要将该函数拆分为 2 个单独的部分!

    希望对你有帮助

    【讨论】:

    • 谢谢,我太沉迷于浮动的不精确性,我认为这不会是什么
    【解决方案2】:

    您无法与浮点值(floatdouble)进行精确比较,因为它们对其所代表的值的精度具有固有的限制。

    当您需要比较浮点值时,您必须始终在要比较的目标值周围使用一个范围(上下) - 这样您就可以解决浮点存储的不精确性。

    阅读此问题/答案了解更多详情:Is it safe to check floating point values for equality to 0?

    【讨论】:

    • 其实不用你回答,你提供的链接就够了。
    • @I4V 是的,我在搜索时已经兴奋地输入了它。
    猜你喜欢
    • 2012-07-26
    • 1970-01-01
    • 2021-09-16
    • 2011-02-23
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多