当前位置:网站首页>Role movement in the first person perspective
Role movement in the first person perspective
2022-07-06 12:54:00 【SQ Liu】
The role movement of the first person perspective
One 、 Material download
1、 In the resource store , Search the name to download :Low-Poly Simple Nature Pack.
2、 After downloading , Import all directly .
Two 、 Scenario deployment
1、 open Demo scene , use Demo Scene to practice .
2、 Right click to create an empty object , Rename it to Environment.
3、 Select all objects except the camera , Drag in Environment in , Easy to manage , Fold it up .
4、 Create a new capsule , Rename it to Player. Use it as our controlling role .
5、 Reset Transform Location .
6、 A little adjustment Player Location , Don't let it get stuck in the ground . then Cameras Move to Player in , As a child object . Reset Cameras Of Transform.
7、 Scenario deployment completed , Next is the code time .
3、 ... and 、 Finalize the code
( One ) by Camaras Add a script
1、 New folder , rename Scripts, Store scripts .
2、 newly build CameraController Script , Control the camera . take CameraController Drag script to Cameras in .
3、 Double click to open the script .
(1) Define two first float Variable of type , To get the value of mouse movement .
private float mouseX, mouseY; // Get the value of mouse movement
(2) You can add a sensitivity to the mouse , Used to control the speed of mouse movement .
public float mouseSensitivity; // Mouse sensitivity
(3) stay Update In the method , Use... In the input system GetAxis Method to get the value of mouse movement , Multiply by mouse sensitivity , Multiplied by Time.deltaTime. The value of moving the mouse left and right is thus obtained .
private void Update()
{
mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
}
(4) By controlling Player The way to rotate , To control the camera angle to move left and right , So you need a Player Of Transform.
public Transform player;
(5) go back to Update In the method , Use Transform Of Rotate() Method to rotate Player. This method has 6 Refactoring , We just need to fill in one Vector3 The value of . We need to control Player Of Y Shaft rotation , To make it rotate left and right .
player.Rotate(Vector3.up * mouseX);
(6) Next we have to rotate the camera , Use transform.localRotation Methods , Let the camera rotate up and down . Use localRotation Can not be affected by the rotation of the parent object . because localRotation Attribute , So we have to assign a value to it . Make it equal to Quaternion.Euler,Euler Three values need to be passed in the method , Fill in here -mouseY,0,0.
transform.localRotation = Quaternion.Euler(-mouseY, 0, 0);
(7) go back to Unity3D in , Set the value to be set to .
(8) The runtime found a problem , When moving the mouse up and down , The perspective is card by card , And cannot move . Where is the problem ? The problem is :Y The shaft GetAxis Method , Returns the -1 To 1 The floating point number between , When the mouse moves , The value will change with the direction , When the mouse is not moving , The value will rebound to 0. So we will see the problem just now . We just need to declare one float Variables to accumulate mouseY That's all right. .
public float xRotation;
(9) stay Update Write in :xRotation -= mouseY;, Then put the following -mouseY Change it to xRotation .
(10) Back to Unity3D Run it , Will find : Players will rotate the angle of view up and down without limit . occasionally , We need to make some restrictions , Not to make players present a strange state , Come back to the code again . We need to xRotation The value of is limited to a range , So we can use mathematical functions Mathf.Clamp() To limit ,Clamp Three values need to be filled in the method : The first is the variables that need to be restricted , The second is the minimum of the limit , The third is the maximum value of the limit .
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -70f, 70f);
(11) Final CameraController The script code is as follows .
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
public Transform player;
private float mouseX, mouseY; // Get the value of mouse movement
public float mouseSensitivity; // Mouse sensitivity
public float xRotation;
private void Update()
{
mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -70f, 70f);
player.Rotate(Vector3.up * mouseX);
transform.localRotation = Quaternion.Euler(xRotation, 0, 0);
}
}
( Two ) by Player Add a script
1、 newly build PlayerController Script , Used to control players' actions .
2、 take PlayerController Added to the Player In the object ; Delete capsule controller ; Add role controller , It has its own collision body and rigid body .
3、 Double click to open the code .
(1) First you need to get Player Of CharacterController Components .
private CharacterController cc;
(2) Definition Player Moving speed and jumping speed .
public float moveSpeed;
public float jumpSpeed;
(3) Define two variables to get the key value .
private float horizontalMove, verticalMove;
(4) Define 3D variables dir Control direction .
private Vector3 dir;
(5) stay Start() Use in a function GetComponent Methods to get CharacterController.
cc = GetComponent<CharacterController>();
(6) stay Update Use... In the same way Input.GetAxis() Method to get the value of the key .dir Store the direction of movement . Next use CharacterController Medium Move() Method to move Player.
horizontalMove = Input.GetAxis("Horizontal") * moveSpeed;
verticalMove = Input.GetAxis("Vertical") * moveSpeed;
dir = transform.forward * verticalMove + transform.right * horizontalMove;
cc.Move(dir * Time.deltaTime);
(7) go back to Unity3D, Assign a value to the variable just defined .
(8) Click on the run , Now you can move . take Player Move into the air , It didn't fall , Obviously, there is a lack of gravity ,CharacterController It's without an object engine , So we have to write a gravity for it manually .
(9) Back in the code , Define two variables , One is gravity , One is speed .
public float gravity;
private Vector3 velocity; // Used to control Y Axial acceleration
(10) stay Update in ,velocity.y -= gravity * Time.deltaTime;, In this way, the value of subtracting gravity from it decreases every second . Reuse Move() Method to move Y Axis .
velocity.y -= gravity * Time.deltaTime; // Every second it subtracts the value of gravity and keeps falling
cc.Move(velocity * Time.deltaTime);
(11) go back to Unity3D in , take Player Improve the position of , Click Run to see the effect . A problem has been identified : At first, it can fall smoothly , After a while, I will be unable to lift it card by card ? We mouse on Inspector On the text of the view , Right click Debug.
Hereunder , We can see the definition just now velocity Of y The value is decreasing , That's the problem . Want to make it no longer reduce after landing , We need to go back to the code .( Gravity is manually set to 9.8)
(12) We just need to test Player It's ok if it's on the ground , Here you can use Physics Medium CheckSphere() Method . The description of this method is : If the defined sphere collides with an object , Return to true . So in order to use this method , We need to define several variables .
public Transform groundCheck; // The central position of the detection point
public float checkRadius; // Radius of detection point
public LayerMask groundLayer; // Detected layer
public bool isGround; // Boolean value to store Physics.CheckSphere The return value of
go back to Update In the method , Write code at the beginning :
isGround = Physics.CheckSphere(groundCheck.position, checkRadius, groundLayer);
if (isGround && velocity.y < 0)
{
velocity.y = -3f; // Less than 0 The number next to it is ok
}
(13) go back to Unity3D, Assign a value to the variable just set .
stay Player Next, create an empty object , Rename it to GroundCheck
Then drag it to Player The position at the bottom , The bottom position detects whether it touches the ground
then GroundCheck Drag in , Set the radius 0.4
also Ground Layer, You can click Layer layer ,Add Layer…, Add one yourself Ground Layer is OK . take Ground Layer It is amended as follows Ground.
(14) take Environment Of Layer Layer changed to Ground, And then a dialog box pops up , Direct point Yes,change children, Its child objects will be applied Ground Layer.
(15) function , Free fall has been solved . Now there are still jumping functions left to be realized .
(16) Back in the code . We need to get the event of the jump button , So we use Input In the system GetButtonDown() Method , It will return a Boolean value , When pressed ( Key ) Will return true , The value Jump It can also be in InputManager View in . When the jump key is pressed , take velocity.y = jumpSpeed, In this way, there will be an upward speed in an instant , In the process, it will also fall slowly with gravity .
if (Input.GetButtonDown("Jump") && isGround)
{
velocity.y = jumpSpeed;
}
(17) Final PlayerController The script code is as follows .
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private CharacterController cc;
public float moveSpeed;
public float jumpSpeed;
private float horizontalMove, verticalMove;
private Vector3 dir;
public float gravity;
private Vector3 velocity; // Used to control Y Axial acceleration
public Transform groundCheck; // The central position of the detection point
public float checkRadius; // Radius of detection point
public LayerMask groundLayer; // Detected layer
public bool isGround; // Boolean value to store Physics.CheckSphere The return value of
private void Start()
{
cc = GetComponent<CharacterController>();
}
private void Update()
{
isGround = Physics.CheckSphere(groundCheck.position, checkRadius, groundLayer);
if (isGround && velocity.y < 0)
{
velocity.y = -3f; // Less than 0 The number next to it is ok
}
horizontalMove = Input.GetAxis("Horizontal") * moveSpeed;
verticalMove = Input.GetAxis("Vertical") * moveSpeed;
dir = transform.forward * verticalMove + transform.right * horizontalMove;
cc.Move(dir * Time.deltaTime);
if (Input.GetButtonDown("Jump") && isGround)
{
velocity.y = jumpSpeed;
}
velocity.y -= gravity * Time.deltaTime; // Every second it subtracts the value of gravity and keeps falling
cc.Move(velocity * Time.deltaTime);
}
}
Four 、 To complete the effect
边栏推荐
- Combination of fairygui check box and progress bar
- [algorithm] sword finger offer2 golang interview question 12: the sum of the left and right sub arrays is equal
- Unity场景跳转及退出
- 平衡二叉树详解 通俗易懂
- 基于rtklib源码进行片上移植的思路分享
- (core focus of software engineering review) Chapter V detailed design exercises
- Fabrication of fairygui simple Backpack
- [algorithm] sword finger offer2 golang interview question 3: the number of 1 in the binary form of the first n numbers
- Unity3d, Alibaba cloud server, platform configuration
- [algorithm] sword finger offer2 golang interview question 9: subarray with product less than k
猜你喜欢
The service robots that have been hyped by capital and the Winter Olympics are not just a flash in the pan
[算法] 剑指offer2 golang 面试题9:乘积小于k的子数组
idea问题记录
Compilation principle: preprocessing of source program and design and implementation of lexical analysis program (including code)
[算法] 剑指offer2 golang 面试题6:排序数组中的两个数字之和
C code implementation of robust estimation in rtklib's pntpos function (standard single point positioning spp)
[algorithm] sword finger offer2 golang interview question 3: the number of 1 in the binary form of the first n numbers
Mysql database index
There is no red exclamation mark after SVN update
Fabrication d'un sac à dos simple fairygui
随机推荐
[algorithm] sword finger offer2 golang interview question 1: integer division
Knowledge system of digital IT practitioners | software development methods -- agile
(the first set of course design) 1-4 message passing interface (100 points) (simulation: thread)
[算法] 剑指offer2 golang 面试题7:数组中和为0的3个数字
KF UD分解之伪代码实现进阶篇【2】
[algorithm] sword finger offer2 golang interview question 10: subarray with sum K
idea问题记录
The service robots that have been hyped by capital and the Winter Olympics are not just a flash in the pan
地球围绕太阳转
记录:下一不小心写了个递归
[算法] 剑指offer2 golang 面试题8:和大于或等于k的最短子数组
VLSM variable length subnet mask partition tips
Fairygui loop list
Pride-pppar source code analysis
[untitled]
Lean product development - Lean Software Development & lean product development
idea中导包方法
Halcon knowledge: gray_ Tophat transform and bottom cap transform
RTKLIB: demo5 b34f.1 vs b33
Fabrication d'un sac à dos simple fairygui