【问题标题】:Unity code issues. Character is not moving统一代码问题。人物不动
【发布时间】:2019-04-10 09:46:06
【问题描述】:

我有一个负责控制角色的类。但是这个类中的代码不起作用。

private ObjectSequence Patrocle;

public bool moving = false;
private float moveAxis = 0;
public float accelaration = 0.1f;
public float moveSpeed = 10f;

public Rigidbody2D rBody;

private Dictionary<KeyCode, bool> pressed = new Dictionary<KeyCode, bool>();

void Start()
{
    pressed.Add(KeyCode.LeftArrow, false);
    pressed.Add(KeyCode.RightArrow, false);
    Patrocle = GetComponent<ObjectSequence>();
}

private void FixedUpdate()
{
    moving = pressed[KeyCode.LeftArrow] ^ pressed[KeyCode.RightArrow];
    if (moving)
    {
        moveAxis += pressed[KeyCode.RightArrow] ? accelaration : (accelaration * -1f);
        moveAxis = Mathf.Clamp(moveAxis, -1, 1);
        rBody.velocity = new Vector2(moveAxis * moveSpeed, rBody.velocity.y);
    }
    else
        moveAxis = 0f;
}

它应该向右移动,但它不会让任何东西缺席。有什么问题?

【问题讨论】:

  • 如何检查是否按下了左箭头或右箭头?在这种情况下,它们总是错误的。

标签: c# unity3d


【解决方案1】:

它不会移动,因为您将 KeyCode 与检测是否按下某个键的方法混淆了。

KeyCode.LeftArrow 只是一个指定左箭头键的值。按下左箭头键不会改变。

更准确地说,问题在于以下行:

moving = pressed[KeyCode.LeftArrow] ^ pressed[KeyCode.RightArrow];

请尝试以下方法:

moving = (Input.GetKey(KeyCode.LeftArrow)) ^ (Input.GetKey(KeyCode.RightArrow))

【讨论】:

  • 他正在尝试做一个异或。
  • 哦,是的,你完全正确 :D 那周太喜欢按位的东西了,我忘了这也适用于布尔值 ^^
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多