您的位置:首页 > 移动开发 > Unity3D

Unity输入与控制

2014-09-25 11:01 162 查看
主要概念:

  1.虚拟轴

  2.输入预先设置

示例:

通过键盘控制物体移动

private float speed = 10.0F;    //速度

private float rotaSpeed = 100.0F;   //旋转速度

// Update is called once per frame
void Update () {

//获取垂直方向的虚拟轴,控制w,s
float translation = Input.GetAxis("Vertical") * speed;

//获取水平方向的虚拟轴,控制a,d
float rotation = Input.GetAxis("Horizontal") * rotaSpeed;

//根据时差进行变幻
translation *= Time.deltaTime;
rotation *= Time.deltaTime;

//进行变换
transform.Translate(0, 0, translation);
transform.Rotate(0,rotation,0);
}


主要注意 : 要使用

rotation *= Time.deltaTime;

等语句来获得与刷新的帧率无关的移动效果(平滑性)

3.键盘检测

GetKey和GetButton

GetKey两种方式:

if (Input.GetKey(KeyCode.UpArrow))
{
print("get up");
}


if (Input.GetKey(“up”))
{
print("get up");
}


GetButton的方式:

if(Input.GetButton("Fire1")){
print("pressed Fire1");
}


可知GetButton获取的是虚拟轴的名称

可用于检测单一键盘事件的发生;譬如射击

4.鼠标事件

检测单击事件:

if (Input.GetMouseButtonDown(0))
{
print("按下了左键");
}


0-左键,1-右键,2-中键

检测长按事件:

if (Input.GetMouseButton(0))
{
print("按下了左键");
}


检测按键释放:

if (Input.GetMouseButtonUp(0))
{
print("放开了左键");
}


在GUI系统中可以按照如下进行双击检测

void OnGUI()
{
Event e = Event.current;
if (e.isMouse && (e.clickCount == 2))
{
Debug.Log("双击了鼠标");
}
}


,使用的主要是GUI的事件机制。

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