Chapter 30 Unity Character Controller Character Controller

In our previous chapters we have learned about Colliders and Rigidbodies. However, for the rigid body component, there are two ways to use it. One is to use it to simulate movement or collision effects in the real world (for example, the opening and closing of a door); the other is to use code to control object movement or collision (for example, the walking of a character). The usage scenarios of the two methods are just different.

The character controller that this chapter will talk about is also a component, which is used to control the operation of game objects. It should be noted that this component has collision properties (capsule collision body) but no rigid body properties (does not accept motion control of rigid bodies). If we use a game object A with a rigid body component to collide with a game object B with a character controller, our game object B will not move due to the collision. The character controller component provides methods such as Move and SimpleMove for movement control.

Next, we will create a "SampleScene6.unity" scene and add a sphere and capsule to it.

For the sphere, we add a sphere collision body component and a rigid body component, as well as a force in the positive direction of the X-axis.

Then there is our capsule body, adding a CharacterController component. Here, we need to note that by default, the capsule we add will come with the "Capsule Collider" collision component, we can just cancel it.

Then we Play to run our entire project, as shown below: 

We found that when the sphere collided with the capsule, both stopped running and did not penetrate the model. This shows that our character controller component has collision body properties, but does not have rigid body properties (if it has rigid body properties, it should be affected by the collision and move to the right). Even if we add a rigid body, it will not have rigid body characteristics. Character controller is a component specially used to control character movement. Different from using Transform or rigid body directly, CharacterController has better effect. Next, we will briefly introduce this component.

Slope Limit: Slope limit, set the maximum slope angle value (in degrees) that the character can walk on.

Step Offset: Step height, set the maximum step height value that the character can step on.

Skin width: Skin thickness, which determines the degree of mutual penetration of two colliders after collision. Larger skin width reduces jitter. Smaller skin width may cause the character to get stuck. A reasonable setting is to set this value to 10% of the radius.

Min Move Distance: Minimum movement distance, set the minimum movement value of the character object.

Center: Sets the position of the capsule collider in world coordinates.

Radius: Sets the cross-sectional radius of the capsule collider.

Height: Set the height of the capsule collision body.

The first four parameters mainly deal with the settings when encountering obstacles during movement; the last three parameters are used to set the collision shape. CharacterController provides us with two movement methods: Move and SimpleMove, both of which require a Vector3 type parameter. First let's try the Move method. We cancel the Sphere game object and add a plane to act as a slope, as shown below:

 

Next, we create a "CharacterMove.cs" script to control capsule movement. When you think of moving, you will definitely think of the Translate method. This method is what we learned before and is used for moving. We first use it to perform mobile operations. The code is as follows:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CharacterMove : MonoBehaviour
{
    // 移动速度
    private float speed = 10.0f;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.A))
        {
            transform.Translate(Vector3.left * speed * Time.deltaTime);
        }
        if (Input.GetKey(KeyCode.D))
        {
            transform.Translate(Vector3.right * speed * Time.deltaTime);
        }
    }
}

The above code is very simple. It just makes the capsule move left and right when the "A" and "D" keys are pressed.

We found that the capsule did move, but it crossed the slope and did not climb up the slope. Next, we will try it using the Move method of CharacterController. The code is modified as follows:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CharacterMove : MonoBehaviour
{
    // 移动速度
    private float speed = 10.0f;

    // 角色控制器组件
    private CharacterController controller;

    // Start is called before the first frame update
    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.A))
        {
            //transform.Translate(Vector3.left * speed * Time.deltaTime);
            controller.Move(Vector3.left * speed * Time.deltaTime);
        }
        if (Input.GetKey(KeyCode.D))
        {
            //transform.Translate(Vector3.right * speed * Time.deltaTime);
            controller.Move(Vector3.right * speed * Time.deltaTime);
        }
    }
}

Then we re-play the project as follows:

 

We found that the capsule can climb up the slope smoothly, but when moving back, it will stay in the air and continue to move. In other words, the Move method does not consider the effect of gravity. What about the SimpleMove method?

        if (Input.GetKey(KeyCode.A))
        {
            //transform.Translate(Vector3.left * speed * Time.deltaTime);
            //controller.Move(Vector3.left * speed * Time.deltaTime);
            controller.SimpleMove(Vector3.left * speed);
        }
        if (Input.GetKey(KeyCode.D))
        {
            //transform.Translate(Vector3.right * speed * Time.deltaTime);
            //controller.Move(Vector3.right * speed * Time.deltaTime);
            controller.SimpleMove(Vector3.right * speed);
        }

Please note that the SimpleMove method does not require Time.deltaTime time, which simplifies our code writing. Next, we re-Play the current project, the effect is as follows:

This time we discovered that when moving this time, it will be affected by gravity. Through comparison, we can clearly know the differences between Translate, Move and SimpleMove. Without a doubt, we ended up choosing the SimpleMove method, which provides collision detection as well as gravity effects.

In addition, since CharacterController does not have direct collision components and rigid body components, the OnCollisionXXX and OnTriggerXXX methods cannot be used, but the character controller specifically provides the OnControllerColliderHit method. Next, let's try this method. Its parameter is the ControllerColliderHit object, which has attributes such as gameObject, collider, rigidbody, and controller that can be used.

    void OnControllerColliderHit(ControllerColliderHit hit)
    {
        Debug.Log("碰撞物体为:" + hit.gameObject.name);
    }

After adding the above code, re-run the current project.

Note that "Plane" is our ground and "Plane(1)" is our slope. Since collision detection is very fast and a large amount of Log information will be output, we can click "Collapse" to collapse and display the repeated content. In addition, the Character controller provides us with an isGrounded property, through which we can determine whether the current character has collided with the ground.

Next, we summarize the usage scenarios of rigid bodies, collision bodies and character controllers.

First of all, rigid bodies are mostly used for "prop objects" in the scene. Their movement is controlled through Unity's physics system. All we have to do is to use code to apply a force to these "prop objects". Rigidbody's AddForce() method .

Next is the collision body, which defines the "outline shape" of the game object. Collision detection is calculated based on this "outline shape". Almost all game objects that need to be interacted with in the scene require collision bodies. Even for "stationary" game objects in the scene, in order to avoid the "cross-mode" phenomenon, we also need to add collision bodies (such as flowers, trees, buildings in the scene) etc). Colliders are generally used in conjunction with rigid bodies. For game objects that can "move" in the scene, colliders and rigid bodies are usually added at the same time. If you want Unity's physics system to control the movement of "moving objects", just follow the default properties of rigid bodies (such as the "prop objects" we mentioned above). If you want to use code to control the movement of a "kinematic object", you need to check the Is Kinematic property of the rigid body. The difference between the two is also reflected in the OnCollisionEnter and OnTriggerEnter methods. In addition, the Is Kinematic property of the rigid body can also be controlled through scripts, allowing control to be switched between the physical system and script code.

Finally, there is the character controller, which is mostly used for "characters" in games, because game characters require a lot of interactive control, and their movement and rotation are relatively complicated. Their movement is either player-controlled or script-controlled, so generally does not need to be controlled by a physics system. At this time, it is very convenient for us to use the CharacterController component to control the "character". The essence of the CharacterController component is "capsule collision body" + "mobile code encapsulation". It has no rigid body characteristics, will not be affected by force, and will not produce force effects. Please note that when using the CharacterController component, you do not need to use rigid bodies and colliders, and do not use Translate() to move. You must use its own SimpleMove() method to move objects. If you need to use CharacterController for collision detection, just use its OnControllerColliderHit.

The content involved in this course has been shared on Baidu Cloud Disk:https://pan.baidu.com/s/1e1jClK3MnN66GlxBmqoJWA?pwd=b2id

Guess you like

Origin blog.csdn.net/konkon2012/article/details/130480057