当前位置:网站首页>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
边栏推荐
- Yyds dry inventory interview must brush top101: every k nodes in the linked list are turned over
- 记一次Runtime.getRuntime().exce(“command“)报错
- 微信公众号授权登录后报redirect_uri参数错误的问题
- H5 wechat shooting game source code
- 既要便捷、安全+智能,也要颜值,萤石发布北斗星人脸锁DL30F和极光人脸视频锁Y3000FV
- Laser slam:logo-loam --- code compilation, installation and gazebo test
- Huawei cloud digital asset chain, "chain" connects the digital economy, infinite splendor
- 微信小程序的分包加载
- 不懂就问,快速成为容器服务进阶玩家!
- 瀚高数据库最佳实践配置工具HG_BP日志采集内容
猜你喜欢

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

漂亮的蓝色背景表单输入框样式

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

leetcode:2141. 同时运行 N 台电脑的最长时间【最值考虑二分】

JS win7 transparent desktop switching background start menu JS special effect

第六七八次作业

Pl515 SOT23-5 single / Dual Port USB charging protocol port controller Parkson electronic agent

“当你不再是程序员,很多事会脱离掌控”—— 对话全球最大独立开源公司SUSE CTO...

Unity performance optimization

Space shooting Lesson 11: sound and music
随机推荐
“当你不再是程序员,很多事会脱离掌控”—— 对话全球最大独立开源公司SUSE CTO...
Use order by to sort
Seventeen year operation and maintenance veterans, ten thousand words long, speak through the code of excellent maintenance and low cost~
Teach you unity scene switching progress bar production hand in hand
融合数据库生态:利用 EventBridge 构建 CDC 应用
Interpretation of ue4.25 slate source code
太空射击第13课: 爆炸效果
Random talk on GIS data (VI) - projection coordinate system
Dynamic planning: code summary of knapsack problem template
华为云数字资产链,“链”接数字经济无限精彩
Unity uses shader to quickly make a circular mask
Three deletion strategies and eviction algorithm of redis
js飞入js特效弹窗登录框
Pl515 SOT23-5 single / Dual Port USB charging protocol port controller Parkson electronic agent
Network shell
记一次Runtime.getRuntime().exce(“command“)报错
一文读懂Okaleido Tiger近期动态,挖掘背后价值与潜力
Report redirect after authorized login on wechat official account_ The problem of wrong URI parameters
Introduction to redis II: RedHat 6.5 installation and use
Read the recent trends of okaleido tiger and tap the value and potential behind it






