2015-02-10 146 views
-1

我建立在統一遊戲和復位速度爲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); 

    } 
} 



} 

`

回答

1

在您設定的if語句,其速度重置爲0 FixedUpdate功能,

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

然而,在同樣的功能,你將擁有以下起着加速或減速船的作用。

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

看起來像我當你的船重置爲0時則增加了.1F上停止調整

之前,您可能需要該功能分成2個獨立的部分!

希望這會有所幫助

+1

謝謝多數民衆贊成我太被捲入浮動不精確我不認爲它可能是任何東西 – 2015-02-10 22:56:02

0

不能針對浮點值(floatdouble),因爲它們具有他們所代表的值的精度固有界限進行精確的比較。

當您需要比較浮點值時,您必須始終使用您試圖比較的目標值周圍的範圍(高於和低於) - 這樣可以說明浮點存儲的不精確性。

閱讀更多細節這個提問/回答:Is it safe to check floating point values for equality to 0?

+0

事實上,不需要您的回答,您提供的鏈接就足夠了。 – I4V 2015-02-10 22:54:12

+0

@ I4V是的,當我搜索它的時候,我已經興奮地輸入了它。 – xxbbcc 2015-02-10 22:55:00