• 【Unity】7.3 键盘输入


    分类:Unity、C#、VS2015

    创建日期:2016-04-21

    一、简介

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

    image

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

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

    image

    二、基本用法示例

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

    void Update()

    {

    //按下键盘A键

    if(Input.GetKeyDown(KeyCode.A))

    {

    //...

    }

    //按住键盘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
  • 相关阅读:
    fiddler https
    Windows Media Player 网页播放器 参数含义
    ActionScript3.0程序开发工具
    同一目录两程序引用同一个类库dll,所引发的问题
    Flash在浏览器里调试获取trace
    linux下的i2c驱动框架
    IIC原理及简单流程
    Linux操作系统下 NAND FLASH驱动程序框架
    Linux操作系统简单NOR FLASH驱动开发
    网卡驱动
  • 原文地址:https://www.cnblogs.com/rainmj/p/5415428.html
Copyright © 2020-2023  润新知