我正在学习Unity,但我的按键输入未被检测到。
为什么isJumpPressed总是false? 我做错了什么? 从我的理解来看,这应该是有效的,但显然我漏掉了一些东西。 更新: 感谢所有提出想法的人。 当我停止尝试检测空格键时,我成功使isJumpPressed返回true。
或者
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public Rigidbody myBody;
private float time = 0.0f;
private bool isMoving = false;
private bool isJumpPressed = false;
void Start(){
myBody = GetComponent<Rigidbody>();
}
void Update()
{
isJumpPressed = Input.GetKeyDown(KeyCode.Space);
Debug.Log(isJumpPressed);
}
void FixedUpdate(){
if(isJumpPressed){
myBody.velocity = new Vector3(0,10,0);
isMoving = true;
Debug.Log("jump");
}
if(isMoving){
time = time + Time.fixedDeltaTime;
if(time>10.0f)
{
//Debug.Log( Debug.Log(gameObject.transform.position.y + " : " + time));
time = 0.0f;
}
}
}
}
为什么isJumpPressed总是false? 我做错了什么? 从我的理解来看,这应该是有效的,但显然我漏掉了一些东西。 更新: 感谢所有提出想法的人。 当我停止尝试检测空格键时,我成功使isJumpPressed返回true。
isJumpPressed = Input.GetKeyDown("a");
有人知道为什么这个会起作用而另一个却不行吗?
isJumpPressed = Input.GetKeyDown(KeyCode.Space);
或者
isJumpPressed = Input.GetKeyDown("space");
更新2:显然,这是Linux的一个bug。我已经读到说,当游戏只在编辑器中构建时,不会发生这种情况。我在https://forum.unity.com/threads/space-not-working.946974/?_ga=2.25366461.1247665695.1598713842-86850982.1598713842#post-6188199找到了一个解决方法。
如果有谷歌员工遇到这个问题,请参考以下代码,因为这对我有效。
public class Player : MonoBehaviour
{
public Rigidbody myBody;
private float time = 0.0f;
private bool isMoving = false;
private bool isJumpPressed = false;
void Start(){
myBody = GetComponent<Rigidbody>();
}
void Update()
{
isJumpPressed = Input.GetKeyDown(SpacebarKey());
if(isJumpPressed)
{
Debug.Log(isJumpPressed);
}
}
void FixedUpdate(){
if(isJumpPressed){
myBody.velocity = new Vector3(0,10,0);
isMoving = true;
Debug.Log("jump");
}
if(isMoving){
time = time + Time.fixedDeltaTime;
if(time>10.0f)
{
//Debug.Log( Debug.Log(gameObject.transform.position.y + " : " + time));
time = 0.0f;
}
}
}
public static KeyCode SpacebarKey() {
if (Application.isEditor) return KeyCode.O;
else return KeyCode.Space;
}
}