您的位置:首页 > 编程语言 > C#

C#键盘输入方法(Input.GetKey()和Input.GetKeyUp())需要注意的一个问题(一个U3D初学者的总结)

2017-10-07 22:59 1241 查看
大家好。我用的是2017.1.1f1Personal版本。

最近在复习蓄力发射时(按下空格键的时间越长,游戏对象Sphere发射的越远),发现这样一个问题,代码如下:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class AddForceByTime : MonoBehaviour

{

 float timer = 0f;

 public GameObject sphere;

 void Update ()

 {

  if (Input.GetKey (KeyCode.Space)) {

   timer += Time.deltaTime;

   if (Input.GetKeyUp (KeyCode.Space)) {

    GameObject bullet = Instantiate (sphere, transform.position, transform.rotation);

    bullet.GetComponent<Rigidbody> ().AddForce (Vector3.right * 500f * timer);

    timer = 0f;

   }

  }

 }

}

此处Input.GetKeyUp()嵌套在Input.GetKey()方法里面,感觉逻辑没有问题,但实际运行后,会出现这样一个问题:当空格键弹起时,很多时候Sphere并没有发射出去,一旦发射出去,又发射的特别远。代码改成如下后,问题解决:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class AddForceByTime : MonoBehaviour

{

 float timer = 0f;

 public GameObject sphere;

 void Update ()

 {

  if (Input.GetKey (KeyCode.Space)) {

   timer += Time.deltaTime;

  }

  if (Input.GetKeyUp (KeyCode.Space)) {

   GameObject bullet = Instantiate (sphere, transform.position, transform.rotation);

   bullet.GetComponent<Rigidbody> ().AddForce (Vector3.right * 500f * timer);

   timer = 0f;

  }

 }

}

此处Input.GetKeyUp()在Input.GetKey()方法外面,输出结果合理。到底是什么原因,我不是太清楚。请表哥道明真相。

总结:Input.GetKey()和Input.GetKeyUp()方法不能嵌套使用。

如果哪里不对,还请前辈指正,谢谢。。




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐