繁体   English   中英

Unity 2D C#怪异的移动行为

[英]Unity 2D C# weird movement behaviour

我正在用C#统一制作自上而下的2D游戏。 目前只是设置运动,但是我已经遇到了一个我无法解决的问题。 游戏设置在网格中,我只是使用箭头键向上,向下,向左和向右移动。 这是我的脚本:

public class Player : MonoBehaviour 
{

    public float playerSpeed;

    void FixedUpdate()
    {
        // Movement
        if (transform.position.x < 0.25)
        {
            if (Input.GetKeyUp(KeyCode.RightArrow))
            {
                transform.position += new Vector3(playerSpeed, 0, 0);
            }         
        }
        if (transform.position.x > -0.3)
        {
            if (Input.GetKeyUp(KeyCode.LeftArrow))
            {
                transform.position += new Vector3(-playerSpeed, 0, 0);
            }
        }
        if (transform.position.y < 0.15)
        {
            if (Input.GetKeyUp(KeyCode.UpArrow))
            {
                transform.position += new Vector3(0, playerSpeed, 0);
            }
        }
        if (transform.position.y > -0.10)
        {
            if (Input.GetKeyUp(KeyCode.DownArrow))
            {
                transform.position += new Vector3(0, -playerSpeed, 0);
            }
        }
    }
}

每个方向的第一个if语句是确保玩家没有离开房间的边界。 正在发生的讨厌的就是移动时,它漂亮的平方数开始了如预期一样0.050.10.15 ,等等,但随后熄灭过程中不知何故并给出了号码,如-0.05000001-7.450581e-090.04999999 ,这接近所需数字,但不够准确。 有任何想法吗? 所有建议表示赞赏。

static void Main(string[] args)
{
  float wMyFloat = 1.5f;
  for(int i = 0; i < 100; i++)
  {
    wMyFloat += 0.1f;
  }


  Console.WriteLine(wMyFloat.ToString());
  Console.ReadLine();
}

除此以外,您等于11.5,但打印件告诉您等于11.50001

+= float加上float(或double),您将得到一个偏移量。 而且您将也无法执行== 11.5 != 11.50001

void FixedUpdate(){
        // Check to see if bounds left right
        if(transform.position.x < 0.25f && tranform.position.x > -0.3f){
            if (Input.GetKeyUp(KeyCode.RightArrow))
            {
                transform.position += new Vector3(playerSpeed, 0, 0);
            }    

            else if (Input.GetKeyUp(KeyCode.LeftArrow))
            {
                transform.position += new Vector3(-playerSpeed, 0, 0);
            }
        }
        // Check to see if bounds up and down
        if(transform.position.y < 0.15f && tranform.position.y > -0.1f){
            if (Input.GetKeyUp(KeyCode.UpArrow))
            {
                transform.position += new Vector3(0, playerSpeed, 0);
            }

            else if (Input.GetKeyUp(KeyCode.DownArrow))
            {
                transform.position += new Vector3(0, -playerSpeed, 0);
            }

        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM