2015-02-10 152 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