当前位置:网站首页>[unity3d] human computer interaction input
[unity3d] human computer interaction input
2022-06-26 05:02:00 【little_ fat_ sheep】
1 Preface
Input yes Unity3D Tools for human-computer interaction in , Users can call their GetKey、GetMousePosition、GetMouseButton、GetAxis、GetButton And other methods to obtain the status information of the keyboard and mouse , Then control the game object through these state information , So as to realize human-computer interaction .
1) Keyboard entry
// Press and hold the key
public static bool GetKey(KeyCode key)
// Press the button
public static bool GetKeyDown(KeyCode key)
// Lift the button
public static bool GetKeyUp(KeyCode key)
KeyCode The value is :
A~Z
F1~F15
// Number at the top of the keyboard
Alpha0~Alpha9
Left、RightArrow、UpArrow、DownArrow
LeftCtrl、LeftShift、LeftAlt、LeftWindows、RightCtrl、RightShift、RightAlt、RightWindows
Tab、Space、Backspace、Return
// plus 、 minus sign 、 asterisk 、 Slash 、 The backslash 、 Left parenthesis 、 Right bracket 、 Less than no. 、 More than no. 、 be equal to 、 Upper tip
Plus、Minus、Asterisk、Slash、Backslash、LeftBracket、RightBracket、Less、Greater、Equals、Caret
// comma 、 Order number 、 question mark 、 A semicolon 、 The colon 、 Single quotation marks 、 The quotation marks 、 Double quotes 、 Exclamatory mark
Comma、Period、Question、Semicolon、Colon、Quote、BackQuote、DoubleQuote、Exclaim
// @ Symbol 、$ Symbol 、& Symbol 、 Underline
At、Dollar、Ampersand、Underscore
Insert、Delete、Home、End、PageUp、PageDown、Print
CapsLock、Numlock、ScrollLock
Keypad0~Keypad9、KeypadPeriod
KeypadPlus、KeypadMinus、KeypadMultiply、KeypadDivide
KeypadEquals、KeypadEnter
// Left mouse button 、 Right mouse button 、 Middle of mouse
Mouse0、Mouse1、Mouse2
2) Mouse input
// Hold down the mouse
public static bool GetMouseButton(int button)
// Press mouse
public static bool GetMouseButtonDown(int button)
// Raise the mouse
public static bool GetMouseButtonUp(int button)
// Mouse coordinates
Vector3 position = Input.mousePosition
explain :button The value is 0、1、2, Respectively represents the left mouse button 、 Right click 、 In the key .
3) Virtual axis input
stay 【Edit→Project Settings→Input】 Can be opened in InputManager Configuration interface , You can configure the virtual axis information here .
// Press the left and right arrows or A、D key ,hor stay -1~1 Change between
float hor = Input.GetAxis("Horizontal");
// Press the up and down arrows or W、S key ,hor stay -1~1 Change between
float ver = Input.GetAxis("Vertical");
// Get the movement of the mouse in the horizontal direction
float mouseX = Input.GetAxis("Mouse X");
// Get the movement of the mouse in the vertical direction
float mouseY = Input.GetAxis("Mouse Y");
4) Virtual key input
InputManager Configure virtual keys in the configuration interface , as follows :
// Press and hold the virtual key
public static bool GetButton(string buttonName)
// Press the virtual key
public static bool GetButtonDown(string buttonName)
// Lift the virtual key
public static bool GetButtonUp(string buttonName)
// According to the above configuration , Hold down Q Key or left mouse button to return true, It means firing
bool fire = Input.GetButton("Fire");
2 application
This section will realize the tank battle game .
1) Implementation requirements
- draw 2 A tank , One represents one's own side , One represents the enemy ;
- The user can control the forward and backward movement of his own tank through the up and down arrow keys , Use the left and right arrow keys to control the left and right movement or left and right steering of your tanks ;
- The user can fire shells through the left mouse button ;
- Enemy tanks can automatically turn and aim at their own tanks , But there is a delay , Turn fast and then slow , The delay interpolation coefficient is 0.6;
- Enemy tanks aim at their own tanks ( Allow 5° error ), Automatic firing , The firing interval needs to be greater than 1 second .
2) Create game objects
The object of the game Transform The component parameters are as follows :
name | type | position | Rotation | scale | Color/Texture |
MyTank | Empty | (0, 0.25, -5) | (0, 0, 0) | (1, 1, 1) | —— |
Button | Cube | (0, 0, 0) | (0, 0, 0) | (2, 0.5, 2) | #228439FF |
Top | Cube | (0, 0.5, 0) | (0, 0, 0) | (1, 0.5, 1) | #228439FF |
Gun | Cylinder | (0, 0, 1.5) | (90, 0, 0) | (0.2, 1, 0.4) | #228439FF |
FirePoint | Empty | (0, 1.15, 0) | (0, 0, 0) | (1, 1, 1) | —— |
MyBullet | Sphere | (0, 0, -2) | (0, 0, 0) | (0.2, 0.2, 0.2) | #82EA4FFF |
Plane | Plane | (0, 0, 0) | (0, 0, 0) | (10, 10, 10) | GrassRockyAlbedo |
EnemyTank | Empty | (0, 0.25, 5) | (0, 180, 0) | (1, 1, 1) | 15D3F9FF |
EnemyBullet | Sphere | (0, 0, 2) | (0, 0, 0) | (0.2, 0.2, 0.2) | #4C55F8FF |
explain : EnemyTank from MyTank Copy it , Just changed the color properties of itself and its children ;EnemyBullet from MyBullet Copy it , Then the color attribute is modified ; take MyBullet and EnemyBullet Drag to Assets Window Resources/Prefabs Under the table of contents , Generate preset (prefab), And then delete Hierarchy Under the window MyBullet and EnemyBullet object .
The hierarchy of the game object is as follows :
The game interface is as follows :
3) Script components
MyTank.cs
using UnityEngine;
public class MyTank : MonoBehaviour {
private Transform firePoint; // Firing point
private GameObject bulletPrefab; // Shell preset
void Start() {
firePoint = transform.Find("Top/Gun/FirePoint");
bulletPrefab = (GameObject) Resources.Load("Prefabs/MyBullet");
Debug.Log(bulletPrefab);
}
void Update () {
float hor = Input.GetAxis("Horizontal");
float ver = Input.GetAxis("Vertical");
move(hor, ver);
if (Input.GetMouseButtonDown(0)) { // fire
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, Quaternion.identity); // Create shells from presets
bullet.GetComponent<Bullet>().setMoveDir(transform.forward); // Set the direction of the shell
}
}
private void move(float hor, float ver) {
// Mobile scheme 1 : The up and down arrows control the forward and backward movement , The left and right arrows control the left and right movement
// transform.Translate(hor * Time.deltaTime * 3, 0, ver * Time.deltaTime * 3);
// Mobile scheme II : The up and down arrows control the forward and backward movement , The left and right arrows control the left and right turns
transform.Translate(0, 0, ver * Time.deltaTime * 3);
transform.Rotate(Vector3.up * hor * Time.deltaTime * 120f);
}
}
explain :MyTank.cs The script component is attached to MyTank On the object of the game .
EnemyTank.cs
using UnityEngine;
public class EnemyTank : MonoBehaviour {
private Transform target; // The goal is
private Transform top; // Gun head
private Transform firePoint; // Firing point
private GameObject bulletPrefab; // Shell preset
private float fireInternal = 0; // Firing interval
void Start () {
target = GameObject.Find("MyTank/Top").transform;
top = transform.Find("Top");
firePoint = transform.Find("Top/Gun/FirePoint");
bulletPrefab = (GameObject) Resources.Load("Prefabs/EnemyBullet");
}
void Update () {
Quaternion dir = Quaternion.LookRotation(target.position - top.position);
top.rotation = Quaternion.Lerp(top.rotation, dir, Time.deltaTime * 0.6f); // The enemy turned to his own side
float angle = Vector3.Angle(target.position - top.position, top.forward);
if (angle < 5 && fireInternal > 1) {
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, Quaternion.identity); // Create shells from presets
bullet.GetComponent<Bullet>().setMoveDir(top.forward); // Set the direction of the shell
fireInternal = 0;
}
fireInternal += Time.deltaTime;
}
}
explain :EnemyTank.cs The script component is attached to EnemyTank On the object of the game .
Bullet.cs
using UnityEngine;
public class Bullet : MonoBehaviour {
private Vector3 moveDir; // The direction in which the shell flew
void Start () {
Destroy(gameObject, 2); // 2 Automatically destroy in seconds
}
void Update () {
if (moveDir != null) {
transform.Translate(moveDir * Time.deltaTime * 6);
}
}
public void setMoveDir(Vector3 dir) {
moveDir = dir;
}
}
explain :Bullet.cs The script component is attached to MyBullet and EnemyBullet On the preset body .
4) Running effect
The left and right arrow keys control the left and right movement of your tanks
The left and right arrow keys control the left and right steering of your tank
边栏推荐
- 【Unity3D】刚体组件Rigidbody
- Multipass Chinese document - use instance command alias
- 2. < tag dynamic programming and conventional problems > lt.343 integer partition
- 钟珊珊:被爆锤后的工程师会起飞|OneFlow U
- A new paradigm for large model application: unified feature representation optimization (UFO)
- 5. <tag-栈和常规问题>补充: lt.946. 验证栈序列(同剑指 Offer 31. 栈的压入、弹出序列)
- date_ Range creation date range freq parameter value table and creation example
- How MySQL deletes all redundant duplicate data
- Computer Vision Tools Chain
- Resample
猜你喜欢
PSIM software learning ---08 call of C program block
DBeaver 安装及配置离线驱动
Genius makers: lone Rangers, technology giants and AI | ten years of the rise of in-depth learning
Machine learning final exercises
Pycharm package import error without warning
【Latex】错误类型总结(持更)
File upload and security dog
Schematic diagram of UWB ultra high precision positioning system
Nabicat connection: local MySQL & cloud service MySQL and error reporting
Status of processes and communication between processes
随机推荐
【Latex】错误类型总结(持更)
1.18 learning summary
Anti withdrawal test record
Statsmodels Library -- linear regression model
ThreadPoolExecutor implements file uploading and batch inserting data
2. < tag dynamic programming and conventional problems > lt.343 integer partition
date_ Range creation date range freq parameter value table and creation example
一个从坟墓里爬出的公司
6.1 - 6.2 Introduction à la cryptographie à clé publique
Dbeaver installation and configuration of offline driver
【Unity3D】人机交互Input
微信小程序保存圖片的方法
[latex] error type summary (hold the change)
Codeforces Round #800 (Div. 2)
2.8 learning summary
2.< tag-动态规划和常规问题>lt.343. 整数拆分
Illustration of ONEFLOW's learning rate adjustment strategy
Multipass中文文档-使用Packer打包Multipass镜像
Resample
Happy New Year!