问题描述
一般来说,我是编码和Unity3d的新手。因此,我试图学习并弄清事情是如何工作的,我决定使用Jason Weimann在他的YT频道上制作的在线教程中的一些代码来使我着手进行玩家移动。
我下载了整个项目,并在Unity中将其打开(将项目从Unity 2019.3.4f1升级到Unity 2020.1.1f1)。
触发场景(几乎没有几个简单的环境元素,一个带有角色控制器的播放器)。
一切按预期进行,直到我按空格键使播放器跳起来。
因此,我深入研究了代码,将Input.GetKey(KeyCode.Space)
更改为Input.GetKey(KeyCode.E)
,它可以工作了……我尝试了其他各种键,除了空格键,它们都可以工作。我也尝试过Input.GetKeyDown
也可以,但是当键指定为Space时却不能。
知道为什么会这样吗?
即使我认为它没有任何问题,也请查看下面的代码(因为其他任何键都可以正常工作,而且我不是一个可以大声笑的人)
编辑
感谢到目前为止的所有建议。
即使Unity文档未提及使用此关键代码(仅适用于Input.GetKey
和Input.GetKeyDown
),该代码的作者仍可以使该代码与Input.GetKeyUp
一起使用。脚本可与其他任何关键代码一起使用。
我尝试在一个全新的项目中使用此代码,并获得了与以前相同的结果-无法使用空间跳转,其他所有键都起作用。
在我的Unity3D设置中有问题吗?
using UnityEngine;
public class CharacterMove : MonoBehaviour
{
[SerializeField] private float _moveSpeed = 10f;
[SerializeField] private float _jumpSpeed = 0.5f;
[SerializeField] private float _gravity = 2f;
CharacterController _characterController;
Vector3 _moveDirection;
void Awake() => _characterController = GetComponent<CharacterController>();
void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 inputDirection = new Vector3(horizontal,vertical);
Vector3 transformDirection = transform.TransformDirection(inputDirection);
Vector3 flatMovement = _moveSpeed * Time.deltaTime * transformDirection;
_moveDirection = new Vector3(flatMovement.x,_moveDirection.y,flatMovement.z);
if (PlayerJumped)
_moveDirection.y = _jumpSpeed;
else if (_characterController.isGrounded)
_moveDirection.y = 0f;
else
_moveDirection.y -= _gravity * Time.deltaTime;
_characterController.Move(_moveDirection);
}
//this is the part that does not work when the KeyCode is set to Space,but works with ANY other key.
private bool PlayerJumped => _characterController.isGrounded && Input.GetKey(KeyCode.Space);
}
解决方法
通常,您希望您的属性获取器尽可能简单,通常只是获取一个已缓存的值,而不是计算得出的值,因为每次请求该值时都会影响性能。
尝试通过将box = driver.find_element_by_id("awyMjb")
box.send_keys(image_query)
命令保存在本地变量中来对其进行缓存。然后在FixedUpdate中查看该变量。这一直对我有用,并且被认为是最佳实践。
关于使用Input.GetKey,Unity文档告诉我们,空格键是由Input.GetKeyDown和Input.GetKeyUp而不是Input.GetKey检测到的。 https://docs.unity3d.com/ScriptReference/Input.GetKey.html
,好。显然,这是一个已知的错误,仅在编辑器中不会在内置游戏中发生。错误地检测到输入。没有修复AFAIK。 不知道它是仅Linux还是其他环境也受到影响。 显然,解决此问题的唯一方法是使用其他密钥或部署然后进行测试。