我正在创建一个统一的游戏,并在将速度重置为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);
}
}
}
`
答案 0 :(得分:1)
在FixedUpdate函数中,设置if语句,将速度重置为0,
if (speedLvL == 0F){
tarSpeed = 0.00000F;
}
然而,在同一功能中,您可以使用以下功能来加速或减慢速度。
if (curSpeed < tarSpeed){
curSpeed += .1F;
}
当你将船重置为0时看起来像我,然后在停止调整之前添加.1F
您可能需要将该功能分成两个独立的部分!
希望这有帮助
答案 1 :(得分:0)
您无法对浮点值(float
或double
)执行精确比较,因为它们对其所代表的值的精度具有固有限制。
当您需要比较浮点值时,您必须始终使用您要比较的目标值周围的范围(上方和下方) - 这样您就可以解释浮点存储的不精确性。 / p>
阅读此问题/答案以获取更多详细信息:Is it safe to check floating point values for equality to 0?