Preface:
Whether it’s RPGS, ACT, AVG, or TPS games, there are plenty of games with third-person characters, and TPS, in particular, is directly named after third-person characters
Type of game:
RPG
Role-playing gamesACT
: Action gamesAVG
: Adventure gameSRPG
Role-playing simulation gamesTPS
: Third person game design
For the third person, all the states of the character are exposed to the player’s perspective, and all the animation, logic, and camera representation of the character needs to be the perfect experience for the player
1. Role model import:
Before we can start developing third-person games using Unity design, we need to get the right character models. Unity supports models in a variety of formats, and when working with models with animations, we tend to choose FBX formats
Once the model is selected, you can import the model toUnity
, and then we need to adjust some parameters of the model. After clicking the model, you can clickInspector
The panel sees these parameters:
You can click on the question mark in the upper right corner to check the official documentation to see what these parameters mean. I have also listed a few key points below to help you complete the Settings:
1. If the role model import scene is too large:
- In response to this problem, most players will probably directly adjust the character in the scene
Transform
The component’sScale
To scale, we’re going to try to avoid doing that, but in the modelScale Factor
To resize your model:
2. Animation Type option under Rig:
- Since our characters tend to be human, we usually choose
Humanoid
As aAnimation Type
A better way to do this is to select an option that will allow your animation to play normally:
3. Animation is the third option
- We’ll talk about that later
2. Character animation controller
In order to animate the character in response to the player’s actions, an animation controller can be used to manage a series of state animations. Check out my blog on character animations here:
Unity Character Animation:
But in this case, we’ll look at a new animation configuration effect: animation blending tree
The animation mixing tree can make the transition of character animation smoother and make the game experience of players more real. The specific steps to create the animation mixing tree are as follows:
2.1. Create animation blending tree:
1, inAnimator
Panel right click to selectCreate state
And choose between themFrom New Blend Tree
To complete the creation,
To create theBlend Tree
After that, we can click to enter the animation control tree configuration panel:
As you can see, create theState
A parameter is automatically created, similar to the one we addedfloat
Parameter, which can be adjusted to smoothly switch several states: Here we add several states to the animation blending tree:
Right click just createBlend Tree
Or click the plus sign on the right to add state, or animation, to the tree.
After the creation, the main adjustments are shown in the red box below:
aboutBlend Type
, the animation mixing type. By clicking the knockdown Angle, we can find the following mixing methods:
Because this case with the method of animation speed control switch, so choose 1 d to as animation directly mixed type, which need only through the most the right side of a numerical parameters to control the animation switch box, when we put the animation into, choose three state of corresponding parameters, when the parameter weight slowly close to a certain state of corresponding parameters, the animation will slowly transform, As shown in figure:
As can be seen from the figure, after mixing three kinds of animation, smooth series of animation from slow to fast can be realized
2.2. How to use mixed trees with scripts:
Similar to the Unity Character Animation configuration chapter, we can use Blend directly for smooth animation movement. For example, to animate a character from stationary to moving, we can use an interpolation to get how fast the animation needs to switch:
private float Blend;
private Animator ani;
private void Start()
{
ani = this.GetComponent<Animator>();
}
private void Update()
{
if(Input.GetKey(KeyCode.W))
{
Blend = Mathf.Lerp(Blend, 0.5 f.0.01 f);
}
if(! Input.GetKey(KeyCode.W)) { Blend = Mathf.Lerp(Blend,0.0.01 f);
}
ani.SetFloat("Blend", Blend);
}
Copy the code
So when we press W, the parameters controlling the animation blending tree will increase the interpolation until 0.5 (corresponding to the motion state) and when we do not press W, the animation interpolation goes back to 0 and the character slowly stops moving
3. Character movement and rotation control
3.1. Add components to roles
Before scripting, we need to add some components to the scene model to help us with character movement, rotation, and character animation control:
Add role controller:
- To achieve animation control, you need to add one for the character
Animator
To host the one that we just createdPlayer
The animation controller also needs to drag in the skeleton of the modelAvater
, as for the following parameters can be adjusted according to need
Add rigid body components:
- Moving objects need rigid bodies to simulate their physics, we need to control the movement and rotation of the character, so we need this component, but at the same time, some of the object characteristics of this component are not needed:
-
Since we control the rotation of objects, we only need the effect on the Y axis, and the rotation of the X or Z axis often causes our characters to fall to the ground, which is obviously not what we need, so we can use the
Constraints
In theFreeze Rotation
Check X and Z to freeze its rotation function
Add collider:
- To make sure that the character is as realistic as possible, and not so invincible that it can go through walls or floors, add the appropriate colliders, which can be clicked
Edit Collider
inScene
Panel to adjust its size, or directly adjust the following three lines of parameters to adjust:
3.2. The script controls the character movement
The first option:
Mobile:
- First is the movement of the character, through a series of calculations to calculate the position of the character movement, and then use
rigidbody.MovePosition()
Method to control the character to move to that position
Rotation:
- If the Angle is greater than 0, the player can pass
Vector3.Slerp()
Method to perform interpolation rotation
Animation:
- Monitor the player’s keyboard input, interpolate the change parameters that control the animation’s playback, and combine that parameter with the movement rotation so that the animation perfectly matches the character’s state changes
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControl : MonoBehaviour
{
private Transform m_transform;
private Rigidbody rigidbody;
private Animator ani;
// Movement speed and rotation speed
private float transloatSpeed=2.5 f;
private float rotateSpeed=5;
private Vector3 targetPos;
private float Blend;
// Get the previously added component
private void Start()
{
m_transform = this.transform;
rigidbody = this.GetComponent<Rigidbody>();
ani = this.GetComponent<Animator>();
}
private void Update()
{
// Introduce animation parameters
ani.SetFloat("Blend", Blend);
// Determine the character movement vector by monitoring user input and control the character movement to the target position in FixUpdate
Vector3 v3 = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")).normalized;
targetPos = v3 * Time.deltaTime * transloatSpeed * Blend;
// Determine the rotation Angle by interpolating the target vector with the positive direction of the character and using the rotation
Vector3 targetDir = Vector3.Slerp(m_transform.forward, v3, rotateSpeed * Time.deltaTime);
m_transform.rotation = Quaternion.LookRotation(targetDir);
// Monitor user input and control animation parameters
if (Input.GetKey(KeyCode.W)||Input.GetKey(KeyCode.S)|| Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))
{
if(Input.GetKey(KeyCode.LeftShift))
{
Blend = Mathf.Lerp(Blend, 1f.0.03 f);
return;
}
Blend = Mathf.Lerp(Blend, 0.5 f.0.03 f);
}
if(! (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))) { Blend = Mathf.Lerp(Blend,0.0.03 f); }}private void FixedUpdate()
{
// Control character movement through target vector and positionrigidbody.MovePosition(targetPos + m_transform.position); }}Copy the code
So you can have a better the effect of rotation and start, but when we started, discovers the role is based on the world coordinate, when we press W, is always facing the world coordinates of the Z axis movement, rather than moving in the direction of the role in the face of the current state, so this kind of design is more suitable for fixed third-person perspective game mobile game, such as king’s glory, You get a smoother experience
This happens because:
rigidbody.MovePosition()
It is calculated relative to the world coordinates, and the rotation does not change the direction of the world coordinates of the character, so the next time the character moves, it will still be calculated as the coordinate axis
The second option:
General display (similar to the third-person control of the original deity) :
Character control script:
In order to have a better integration with the camera, we can judge the camera direction and then determine the positive direction of the character, so that the design can be directly accompanied by the camera. In order to have a better effect, we can use a camera plug-in Cinemachine to make the game experience better:
Since the camera lens can rotate freely around the Y-axis, the camera can be used to rotate the character, and the Angle of the character can be changed according to the Angle of the camera, so as to have a better experience: When we press W, the character will move back to the camera, giving the player a more real experience:
A general explanation of the code:
- 1. First, when we input control variables (
WASD
), animation parametersblend
The interpolation will increase, and the speed will change according to this parameter, and the character will have the effect of moving forward- 2. Next, we need to control the character’s turning. The reference for our character’s turning is the basis and the camera
Vector3.ProjectOnPlane(cam.transform.forward, Vector3.up)
Method to get the projection of the camera’s Z axis in the world coordinates of X and Y, that is, the horizontal plane, and if the roleforword
In with the cameraforword
If the projection of the X axis and Z axis is inconsistent, the interpolation is rotated to the projection direction of the camera’s Z axis. This ensures that when the player presses W, it really feels like they are going forward, as shown in the picture, keeping the two pink vectors aligned
- 3. The same is true for pressing down
ASD
Key, respectively corresponding to the camera on the horizontal plane (X-axis and z-axis combination of the plane) projection, rotate the role to the corresponding Angle- 4. Pass one
Vector3
Vector to control character movement, and add influence speedmoveSpeed
,blend
Two variables,
Here is the code for the second control script, noting that in addition to the components that the character added earlier, it also needs to get the camera to follow
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerTest : MonoBehaviour
{
/// <summary>
///Gets the character's follow camera
/// </summary>
public Camera cam;
/// <summary>
///Gets role-related components
/// </summary>
private Transform m_transform;
private Rigidbody rig;
private Animator anim;
/// <summary>
///Define several movement parameters
/// </summary>
private Vector3 targetPos;
private Vector3 movePos;
private Vector3 camPos;
public float moveSpeed=10f;
private float blend;
private void Start()
{
m_transform = this.transform;
rig = this.GetComponent<Rigidbody>();
anim = GetComponent<Animator>();
}
private void Update()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
anim.SetFloat("Blend", blend);
// cam.transform.LookAt(m_transform);
// camPos = m_transform.position + new Vector3(0, camy, camZ);
Transform. position = vector3. Lerp(cam.transform.position, 0.1f);
if (Input.GetKey(KeyCode.W))
{
blend = Mathf.Lerp(blend, 0.5 f.0.02 f);
targetPos.z = 1;
Vector3 targetDir = Vector3.Slerp(m_transform.forward, Vector3.ProjectOnPlane(cam.transform.forward, Vector3.up), 0.02 f);
m_transform.rotation = Quaternion.LookRotation(targetDir, Vector3.up);
}
if (Input.GetKey(KeyCode.S))
{
blend = Mathf.Lerp(blend, 0.5 f.0.02 f);
targetPos.z = 1;
Vector3 targetDir = Vector3.Slerp(m_transform.forward, -Vector3.ProjectOnPlane(cam.transform.forward, Vector3.up), 0.02 f);
m_transform.rotation = Quaternion.LookRotation(targetDir,Vector3.up);
}
if (Input.GetKey(KeyCode.A))
{
blend = Mathf.Lerp(blend, 0.5 f.0.02 f);
targetPos.z = 1;
Vector3 targetDir = Vector3.Slerp(m_transform.forward, -Vector3.ProjectOnPlane(cam.transform.right, Vector3.up), 0.02 f);
m_transform.rotation = Quaternion.LookRotation(targetDir, Vector3.up);
}
if (Input.GetKey(KeyCode.D))
{
blend = Mathf.Lerp(blend, 0.5 f.0.02 f);
targetPos.z = 1;
Vector3 targetDir = Vector3.Slerp(m_transform.forward, Vector3.ProjectOnPlane(cam.transform.right, Vector3.up), 0.02 f);
m_transform.rotation = Quaternion.LookRotation(targetDir, Vector3.up);
}
if(! Input.GetKey(KeyCode.W)&&! Input.GetKey(KeyCode.S)&& ! Input.GetKey(KeyCode.A) && ! Input.GetKey(KeyCode.D)) { targetPos.z =0;
blend = Mathf.Lerp(blend, 0f.0.02 f); } movePos = targetPos * Time.deltaTime * moveSpeed* blend; transform.Translate(movePos); }}Copy the code
Camera plug-in:
After writing the character control script, we need to add a follow camera for the character. In order to have a better effect, we don’t write the script to implement this follow function, but use an official camera component Cinemachine to complete the camera follow free view effect:
First click On Windows and select Package Manager to open Explorer. Then enter Cinemachine in the input box to find the camera plug-in, download it and import it into the project. Since I have already downloaded and imported it, it shows Up to Date:
Once you’ve imported the plugin, you’ll see Cinemachine options in the navigation bar above, click and selectCreate FreeLook Camera
Create a camera with a perspective that can move freely aboutCinemachine
You can refer to the official documentation for the details of the. Here I will only specify the parameters to be used:
The first things to adjust are the Look At and Follow parameters. Who the camera is looking At and who the camera is following is obviously our character, so we can drag the character (or a part of the character, like the eyes) into it
Next we look around the character and see three red circles that indicate how far the camera can move around the character. We can also adjust the parameters on the virtual camera:
After completion, we found that there would be some problem of picture stuttering when moving the camera. At this time, we can click our MainCamera to modify some parameters to be consistent with those in the picture:
conclusion
It’s not that you’re doing a bad job, it’s that the end result is affected by multiple metrics, and you can spend some time tweaking those metrics and polishing your game, and it will work out
After a while, if you still don’t feel like it’s working, you might want to think about designing your third-person controller differently. There is no best, only the most suitable, come on