按钮释放后,Unity将旋转返回到0

时间:2018-05-12 05:00:21

标签: c# unity3d unityscript

我写了一个小游戏,其中我有一个向前移动并左右转动的对象。当用户按下 A 对象向左移动并向左旋转如果用户按下 D 它向左移动并向左旋转,i用户按下按键后将旋转设置为0 / p>

bool slowbtn = Input.GetKey("s");
bool right = Input.GetKey("d");

if (right == true)
{
    rd.AddForce(sideForce * Time.deltaTime, 0, 0,ForceMode.VelocityChange);
    rd.transform.eulerAngles = new Vector3(0, 10 , 0);
}
if (Input.GetKey("a"))
{
    rd.AddForce(-sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    rd.transform.eulerAngles = new Vector3(0, -10 , 0);
}

如果我想在用户释放键时将旋转设置回 0 我正在使用此

if (Input.GetButtonUp("a"))
{
    rd.transform.eulerAngles = new Vector3(0, 0, 0);
}
if (Input.GetButtonUp("d"))
{
    rd.transform.eulerAngles = new Vector3(0, 0, 0);
}

但是它不起作用我不明白为什么,它也会制动我以前的代码,所以如果没有前进则反对

2 个答案:

答案 0 :(得分:2)

Unity的Input.GetButtonUp和Input.GetButtonDown句柄"虚拟"按钮,您在输入设置中设置。 Input.GetKeyUp / Input.GetKeyDown与键盘上的键有关。因此,您应该选择GetKey或GetButton,但不能同时选择两者。

正如我所看到的,您希望在用户按下某个键的所有时间内旋转对象。我建议你使用添加"州"你班上的财产:

private State state = State.IDLE;
private enum State {
  LEFT, RIGHT, IDLE
};

更新您的代码:

if (Input.GetKeyDown(KeyCode.D)) {
  state = State.RIGHT;
}
if (Input.GetKeyDown(KeyCode.A)) {
  state = State.LEFT;
}
if (Input.GetKeyUp(KeyCode.D) || Input.GetKeyUp(KeyCode.A)) {
  state = State.IDLE;
}
switch (state) {
  case State.LEFT:
    rd.AddForce(sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    rd.transform.eulerAngles = new Vector3(0, 10, 0);
  break;
  case State.RIGHT:
    rd.AddForce(-sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    rd.transform.eulerAngles = new Vector3(0, -10 , 0);
  break;
  case State.IDLE:
    rd.transform.eulerAngles = Vector3.zero;
  break;
}

几个推荐:

  1. 使用FixedUpdate()方法而不是Update()
  2. 进行物理操作
  3. 使用Unity的键盘键的KeyCode枚举
  4. 保持代码清洁
  5. 首先开发算法,然后将该算法转换为代码

答案 1 :(得分:1)

当我更换

Input.GetButtonUp("a")

Input.GetKeyUp("a")

这完全没问题。

您是否尝试自行调试此代码?因为通过在此行中设置断点来判断Input.GetButtonUp(…)未被调用非常简单。

顺便说一下。我会考虑像这样写输入代码:

if (Input.GetKey("d"))
{
    rd.AddForce(sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    rd.transform.eulerAngles = new Vector3(0, 10, 0);
}
else if (Input.GetKey("a"))
{
    rd.AddForce(-sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    rd.transform.eulerAngles = new Vector3(0, -10, 0);
}
else
{
    rd.transform.eulerAngles = new Vector3(0, 0, 0);
}