所以我有了一个小的雪车原型。我目前正在编写一些控件,以补充我所应用的RigidBody物理。我的目标是在左转或右转的相反方向上施加一个力,以获得一种打滑,边缘捕捉的效果,然后向前施加一个力来补偿动量的损失。
但是,我不能做到这一点,因为无论出于什么原因,我都不能让GetKeyDown()或GetKeyUp()函数工作。我已经包含了下面的代码。基本上发生的是“按钮释放”。文本不断地得到输出,然后偶尔我会得到一个“按钮按下”的输出,在返回到“按钮释放”之前只发生一次。输出。即使是这样的情况也很罕见。通常我得不到任何检测的迹象。
我确信我遗漏了一些微不足道的东西,我也在寻找类似的问题,但似乎没有一个问题能解决我的问题。如果有人能给我任何建议,我将不胜感激。此外,任何优化技巧都将不胜感激。对于C#和Unity,我还是个新手。
我正在调整和试验中,所以如果我错过了一些不必要的评论,我道歉。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;
public bool sidePhysics;
public bool keyPress;
// Use this for initialization
void Awake()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
var x = Input.GetAxis("Horizontal") * Time.deltaTime * 50.0f;
// No vertical controlls for now.
//var z = Input.GetAxis("Vertical") * Time.deltaTime * 40.0f;
// Get axis against which to apply force
var turnAngle = rb.transform.position.x;
transform.Rotate(0, x, 0);
//transform.Translate(0, 0, z);
// Debug to test input detection
keyPress = Input.GetKeyDown(KeyCode.A);
Debug.Log("keyPress: " + keyPress);
// On either right or left key input down, apply force
// Later once keys are being detected - addForce forward too
if (Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.LeftArrow)
|| Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.D))
{
Debug.Log("Button pressed. ");
// Add opposing force proportionate to the degree of the turn
rb.AddForce((turnAngle * (-x * 10)), 0, 0, ForceMode.Acceleration);
}
else
{
Debug.Log("Button released.");
}
//Debug.Log("RigidBody: " + rb +
// " Rotation: " + x +
// " turnAngle: " + turnAngle);
}
}
发布于 2018-08-22 07:53:29
如果你想在按键的时候继续做一些事情,你可以使用Input.GetKey
函数。如果你想要在按键被按下的时候做一次,你可以使用Input.GetKeyDown
函数,因为在释放并再次按下这个键之前,它只会计算为true一次。理解这两者之间的区别是很重要的。
现在,为了检测按钮何时被释放,在检查Input.GetKey
之后不要使用else
语句。你不会得到你想要的效果。要检测按钮何时释放,请使用Input.GetKeyUp
函数。在那里添加另一条if
语句。
更像是这样:
if (Input.GetKeyDown(KeyCode.A))
{
//KEY PRESSED
}
if (Input.GetKey(KeyCode.A))
{
//KEY PRESSED AND HELD DOWN
}
if (Input.GetKeyUp(KeyCode.A))
{
//KEY RELEASED
}
最后,应该始终检查Update
函数而不是FixedUpdate
函数中的输入。
https://stackoverflow.com/questions/51958042
复制相似问题