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

大家好。我用的是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()方法不能嵌套使用。

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



  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值