当前位置:网站首页>Explain the mobile control implementation of unity in detail
Explain the mobile control implementation of unity in detail
2022-07-28 20:53:00 【Dream small day young】
Preface
The last article wrote several Unity How to move in , There is physical movement , There are non physical movements, etc , Let's talk about this Unity Mobile control mode in , To combine the methods mentioned in the previous article , To use . General control is to process the role movement logic by obtaining user input , The user input device has a keyboard 、 mouse 、 Handle, etc , This article only introduces the most commonly used ways of keyboard and mouse control character movement .
Catalog
Front row reminders : This article only represents personal views , For exchange and learning , If you have different opinions, please comment , The author must study hard , Day day up .
Video Explanation :
Detailed explanation Unity Mobile control implementation _BiLiBiLi
Use of this article Translate To demonstrate mobile control , If you want to use other mobile methods , Update its mobile logic
One 、 Listen to the specified key Input.GetKey()
stay Input Class is specially used to listen for the specified key , Such as GetKey( Whether to press a key continuously )、GetKeyDown( Whether to press a key ), Can pass if Judge whether these keys are pressed to trigger the corresponding movement logic , Put the overall logic into the update function , Loop listening execution , To achieve the purpose of mobile control .
Use GetKey Function to monitor whether a key is pressed continuously , If you want to respond to multiple directions at the same time , Please don't write if…else form
public float speed = 3.0f;
void Update()
{
Move_Update();
}
private void Move_Update()
{
if (Input.GetKey(KeyCode.W))
{
transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.S))
{
transform.Translate(Vector3.back * speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.A))
{
transform.Translate(Vector3.left * speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.D))
{
transform.Translate(Vector3.right * speed * Time.deltaTime);
}
}
Two 、 Monitor virtual key ( axial ) Input.GetAxis()
stay Input Class is also used to listen for axial , You can think of it this way :
Unity Built in some virtual keys , among Vertical Means when you press “ On ” Key or “ Next ” Trigger on key ,Horizontal Means when you press “ Left ” or “ Right ” Trigger on key , The trigger returns a range of plus or minus 1 Of float value , And this return value can replace the Vertor.forward、back equivalence . The advantage of this definition is high portability , For example, this example can still work normally when transplanted to mobile phones , Triggered when you drag the rocker of the mobile phone screen upward Vertical, The rest is the same .
About GetAxis Details of the virtual key defined , You can go to Edit-Project Settings-Input Manager Find .
Use GetAxis Function to monitor whether the virtual key is continuously pressed , This kind of writing is more concise than the previous one , And the movement stops more softly , Compared with the previous one, you can see that it is obviously stiff
public float speed = 3.0f;
void Update()
{
Move_Update();
}
private void Move_Update()
{
Vector3 v = Input.GetAxis("Vertical") * Vector3.forward;
Vector3 h = Input.GetAxis("Horizontal") * Vector3.right;
// Multiply here by V3 The vector is for Translate, Because this function only accepts V3 vector
transform.Translate(v * speed * Time.deltaTime);
transform.Translate(h * speed * Time.deltaTime);
}
3、 ... and 、 Monitor virtual key Input.GetButton()
The last section said Unity Built in some virtual keys , among Vertical Means when you press “ On ” Key or “ Next ” Trigger on key … These are only for direction , Mouse and other real virtual control keys with axial direction . And for those with strong functionality , Like jumping , Shooting , Operations such as punching cannot be defined by axes ,Unity Then we define some virtual keys , For these functions . Monitor usage GetButton function .
About GetAxis Details of the virtual key defined , You can go to Edit-Project Settings-Input Manager Find .
Use GetAxis Function to listen for axial , Use GetButton Function to listen for virtual keys
Here's an example , Used GetButton To monitor the firing button ( Left mouse button )、 Jump button ( Space ), Because generally, the fire button is the left mouse button , Spaces are jumping . So these are conventional things . Of course, you can change , You can also jump with the left mouse button , As long as someone is willing to pay , After all, game engines are just tools .
void Update()
{
if (Input.GetButtonDown("Jump"))
{
transform.GetComponent<Rigidbody>().AddForce(transform.up * 100);
}
if(Input.GetButtonDown("Fire1"))
{
Debug.Log(" FireStarter !");
}
}
Four 、 Objects follow the mouse
In the previous example, we monitor virtual keys to control the movement of objects back and forth , This time we control the mouse movement to make the object follow , Still used Input Value in class , When the monitor key is set, and then when the mouse moves , It will trigger the return of a range between positive and negative 1 Of float value , As shown in the figure below , This is a screen range , Moving the mouse to the right of the screen returns greater than 0 And less than 1 Relative to the proportion of the screen , To the left is the opposite . If you just want the returned value to be positive or negative 1 Words , Avoid using GetAxis(), But use GetAxisRaw(), This example uses this method to demonstrate .
Repeat again about Input Details of the virtual key defined , You can go to Edit-Project Settings-Input Manager Find .
This example uses Mouse X and Mouse Y These two virtual keys .
This example is simply modified transform Of XZ Coordinates to achieve movement , To make accurate objects follow the mouse movement , You need to convert screen coordinates to world coordinates , Only through the displacement operation of the converted world coordinate position , The next example uses the knowledge of transforming coordinates .
public float speed = 10f;
void Update()
{
Move_Update();
}
private void Move_Update()
{
float mouseX = Input.GetAxisRaw("Mouse X");
float mouseY = Input.GetAxisRaw("Mouse Y");
transform.Translate(Vector3.right * mouseX * Time.deltaTime * speed);
transform.Translate(Vector3.forward * mouseY * Time.deltaTime * speed);
}
5、 ... and 、 Click the mouse to move the character
The above examples are all controlled by keyboard or mouse movement , There are also many games that move through mouse clicks , There are also many ways to get the location information when the mouse clicks , But the focus is on how to 2 The dimension plane is converted to 3 The actual location of the dimensional world , This involves the transformation between world coordinates and screen coordinates , And related knowledge of radiation , Readers may consult by themselves API understand . I will also write related articles in the future .
The idea of moving roles by clicking the mouse is as follows : When the mouse clicks , Generate a ray from the current mouse click position , Get the real world coordinates through the screen through transformation , Then move the character to the corresponding position by updating the function
private bool isNextMove = false;
private Vector3 point;
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Input.GetMouseButtonDown(0))
// When the mouse clicks , To trigger radiographic testing
{
if (Physics.Raycast(ray, out hitInfo))
// When the ground is detected
{
isNextMove = true;
point = hitInfo.point;
// take isNextMove Set to true, Then save the current impact point position
}
}
if(isNextMove == true)
// When isNextMove It's true , Then keep calling Move
{
Move(point);
}
}
void Move(Vector3 pos)
{
// Use Vector3 To move the position
transform.position = Vector3.MoveTowards(transform.position, pos, Time.deltaTime * 3.0f);
if (transform.position == pos)
// When the target reaches the position , take isNextMove Set as false, Wait for the next move command
isNextMove = false;
}
6、 ... and 、 Summary and reference
1. summary
This article mainly introduces the realization of mobile control
- adopt Input.GetKey() Monitor keyboard
- adopt Input.GetMouseButton() Monitor the mouse
- adopt Input.GetAxis() Monitor virtual axis
- adopt Input.GetButton() Monitor virtual key
2. Reference
[1] The Internet .Unity official API & Unity Canon API
[2] Dream of a young man . Detailed explanation Unity Several mobile ways of
[3] Dream of a young man . Detailed explanation Unity Radiation and radiographic testing in
边栏推荐
- JS win7 transparent desktop switching background start menu JS special effect
- Unity gadget displays the file size of the resource directory
- 全链路灰度在数据库上我们是怎么做的?
- Random talk on GIS data (VI) - projection coordinate system
- Redis 3.0源码分析-数据结构与对象 SDS LIST DICT
- Dynamic planning: code summary of knapsack problem template
- 云原生编程挑战赛火热开赛,51 万奖金等你来挑战!
- Classes and objects (medium)
- Explain the life cycle function in unity in detail
- js图表散点图例子
猜你喜欢

How to make the design of governance structure more flexible when the homogenization token is combined with NFT?

Random talk on GIS data (VI) - projection coordinate system

PXE_ KS unattended system

UE4 3dui widget translucent rendering blur and ghosting problems

Laser slam:logo-loam --- code compilation, installation and gazebo test

融合数据库生态:利用 EventBridge 构建 CDC 应用

LVM logical volume

Unity typewriter teaches you three ways

Three deletion strategies and eviction algorithm of redis

Integrating database Ecology: using eventbridge to build CDC applications
随机推荐
Pl515 SOT23-5 single / Dual Port USB charging protocol port controller Parkson electronic agent
How to make the design of governance structure more flexible when the homogenization token is combined with NFT?
"When you are no longer a programmer, many things will get out of control" -- talk to SUSE CTO, the world's largest independent open source company
太空射击第10课: Score (繪畫和文字)
flask 静态文件服务搭建
一文读懂Okaleido Tiger近期动态,挖掘背后价值与潜力
JS page black and white background switch JS special effect
Redis入门一:Redis实战读书笔记
一文了解 Rainbond 云原生应用管理平台
Soft raid
TCP.IP
Interpretation of ue4.25 slate source code
Learn about the native application management platform of rainbow cloud
【服务器数据恢复】HP StorageWorks系列存储RAID5两块盘故障离线的数据恢复案例
网络各层性能测试
js可拖拽alert弹窗插件
Alibaba cloud MSE supports go language traffic protection
UE4.25 Slate源码解读
Network layer performance test
不懂就问,快速成为容器服务进阶玩家!






