【Unity】7.3 键盘输入

分类:Unity、C#、VS2015 编码

建立日期:2016-04-21 spa

1、简介

键盘事件也是桌面系统中的基本输入事件。和键盘有关的输入事件有按键按下、按键释放、按键长按,Input类中能够经过下图所示的方法来处理: code

image

上面的方法经过传入按键名称字符串或者按键编码KeyCode指定要判断的按键。 orm

下图所示是经常使用按键的按键名与KeyCode编码,供读者参考,完整的按键编码请查阅Unity用户手册。blog

image

2、基本用法示例

下面的代码演示了如何响应键盘按键事件: 事件

void Update() 字符串

{ get

//按下键盘A键 it

if(Input.GetKeyDown(KeyCode.A)) io

{

//...

}

//按住键盘A键

if(Input.GetKey(KeyCode.A))

{

//...

}

//抬起键盘A键

if(Input.GetKeyUp(KeyCode.A))

{

//...

}

//按下键盘左Shift键

if(Input.GetKeyDown(KeyCode.LeftShift))

{

//...

}

//按住键盘左Shift键

if(Input.GetKey(KeyCode.LeftShift))

{

//...

}

//抬起键盘左Shift键

if(Input.GetKeyUp(KeyCode.LeftShift))

{

//...

}

}

示例(Demo3_1_ControlExample.unity)

该例子演示如何控制模型在x平面上移动。

下面的代码演示了如何获得Horizontal轴的值

void Update () {

//获得Horizontal轴的值

float axisH = Input.GetAxis("Horizontal");

}

下面的代码用键盘方向键或者W、A、S、D按键来控制模型在x平面上移动,只须要将脚本(ControlExample.cs文件)添加到模型上便可:

using UnityEngine;
using System.Collections;
public class ControlExample : MonoBehaviour
{
    public float speed = 10.0f;          //行驶速度
    public float rotationSpeed = 100.0f; //转向速度
    void Update()
    {
        //使用上下箭头或者W、S键来控制前进后退
        float translation = Input.GetAxis("Vertical") * speed;
        //使用左右箭头或者A、D键来控制左右旋转
        float rotation = Input.GetAxis("Horizontal") * rotationSpeed;
        translation *= Time.deltaTime;
        rotation *= Time.deltaTime;
        //在x-z平面上移动
        transform.Translate(0, 0, translation);
        transform.Rotate(0, rotation, 0);
    }
}

运行效果:

image
相关文章
相关标签/搜索