Unity is for beginners, how to make objects move and let them move freely. Several mobile solutions explained

I. Introduction

In most Unity game development, movement is an extremely important part. The feel of movement determines the success or failure of the game. An excellent mobile feel can undoubtedly bring a very comfortable experience to the game. There are many movement methods in Unity, using Transform, using Rigidbody, using CharacterController, using NavMesh navigation system and so on. Of course, for novices, the most common movement solution is to use the two components Transform and Rigidbody. Therefore, this article will analyze and explain these two mobile solutions.

Notice! ! ! The following codes are all 2D scenes, the same applies to 3D

2. Transform

The Transform component is the transformation component of GameObject, which can manipulate the GameObject's position (Position), size (Scale), rotation (Rotation), etc. Therefore, using the Transform component to move objects is a very good choice. The following are several movement methods achieved through the Transform component, as well as the corresponding scenarios.

1.Translate

Use Transform's Translate function to translate in the GameObject's local coordinate system. You can pass in a displacement vector as a parameter to specify the direction and distance of the translation.

[SerializeField] private float moveSpeed;
    private void Update()
    {
        //自动向右移动
        transform.Translate(Vector2.right * moveSpeed * Time.deltaTime);
    }
//物体沿向量指向方向移动
//Vector2.right 向右移动向量,也可以写成自己定义的
//moveSpeed 移动速度,通常为float型

The Translate method can be used to move objects in the game, and is suitable for simple movement methods, such as boxes automatically moving on a plane, etc.

2.MoveTowards

Use Transform's MoveTowards function to move straight to the target location. You can pass in the current position, target position and movement speed to control the movement speed and reach the target position.

The three parameters corresponding to the MoveTowards function are (current position, target position, moving speed). The first two are of Vector type, and the last one is of float type, which can also be written as an integer, etc.

For example: move the object to the position of (5, 5)

    [SerializeField] private float moveSpeed;
    private void Update()
    {
        transform.position = Vector2.MoveTowards(transform.position,new Vector2(5,5),moveSpeed);
    }

3.Lerp

Smooth interpolation movement can be achieved using Transform's Lerp function. You can pass in the starting position, target position and interpolation scale to control the transition effect of the movement.

The three parameters corresponding to the Lerp function are (current position, target position, interpolation scale), the first two are Vector type, the last one is float type = type, the interpolation scale range is [0, 1], when lerp takes 0 , the object does not move. When lerp is 1, the object moves directly to the target position. The larger the lerp value, the faster the object moves.

For example: move the object to (5, 5)

[SerializeField] private float moveSpeed;
[SerializeField] private float lerp;
private void Update()
{
    transform.position = Vector3.Lerp(transform.position, new Vector2(5,5), lerp); 
}

Next, we will explain the movement principle of the Lerp function:

The interpolation coefficient lerp is essentially the ratio of the distance of each movement of the object to the current position of the object to the target position. After each movement of the object, the next movement distance will be reset, but the ratio remains unchanged, that is, the object moves towards the target point. , the distance moved each time will become shorter. It sounds very convoluted, right? Let’s use a picture to explain this principle.

 The red vertical line is the position it moved to for the first time, so its moving distance is L1=S1*lerp. The blue vertical line is the position it moves to for the second time, then the distance it moves to is L2=S2*lerp. Similarly , L3=S3*lerp. As can be seen from the figure, the distance that objects move each time is shortened, but the ratio of the distance they move each time to the distance from the current position to the target position remains unchanged. Moreover, we can also find that the larger the lerp value is, the larger the single movement distance is, that is, the faster the speed is. On the contrary, the smaller the lerp value is, the smaller the word movement distance is. Finally, it is not difficult for us to find that in the Lerp function, the distance the object moves is always the distance from the current position to the target position * lerp. That is to say, the object can never reach the target position, but will only get infinitely close to the target position. Therefore, in order for the object to reach the target position, we can add an if condition. When the distance from the object's target position is less than a certain value, the object position becomes the target position.

if (Vector2.Distance(transform.position, new Vector2(5, 5))<0.1f)
{
     transform.position = new Vector2(5, 5);
}

The above are several ways to use Transform to move objects. Of course, there are many ways to use Transform components to move objects. You can explore them by yourself.

Of course, there is sometimes a small bug when using the Transform component to move objects, which we will explain in Rigidbody.

3. Rigidbody

Rigidbody, a rigid body component, in this component, we can use the definition of physics to perform operations such as object movement. Moreover, this is also the most commonly used component to control player movement. Of course, rigid body components are not only used to move GameObject, but also have many operations. Here, we only talk about the use of movement.

As mentioned above, Transform has a small bug, that is, it will cause mold penetration. That is to say, when the object is moving and encounters an obstacle and continues to move, it will cause it to pass through the obstacle. This is a fatal bug. . However, rigid body components can solve this bug very well. Here, I checked some information, and it is roughly that the Transform component is a change of position, that is, the position change occurs one at a time, which is equivalent to a teleportation flash every time, and it is in one position for the first time. The next time it teleports to the next position, in this case, when squeezing an obstacle, it is extremely easy to cause the object and the obstacle to intersect, resulting in abnormal collision detection, resulting in mold penetration, and the rigid body component is quite When it comes to pulling objects to move, there is no such bug. If you are interested in this aspect, you can check the relevant information.

Let's continue to explain how the Rigidbody component controls the movement of GameObject.

1.AddForce

Use the AddForce function to apply force to the rigid body to move the object. In whichever direction you want to move, add force in that direction.

The parameters of the AddForce function are AddForce (direction vector * magnitude of force);

[SerializeField] private float force;
private Rigidbody2D rigidbody2D;
private void Start()
{
    //获取挂载脚本的物体的刚体组件
    rigidbody2D = GetComponent<Rigidbody2D>();
}
private void Update()
{
    //向上施加一个大小为force的力
    rigidbody2D.AddForce(Vector2.up * force);
}

2.MovePosition

The MovePosition function can directly set the position of the object.

The parameter of the MovePosition function is MovePosition (position (such as tramsform.position))

The following code is the length of the speed of the object flashing/teleporting to the right each time. Note that this method may also cause mold breakage.

[SerializeField] private float speed;
private Rigidbody2D rigidbody2D;
private void Start()
{
    //获取挂载脚本的物体的刚体组件
    rigidbody2D = GetComponent<Rigidbody2D>();
}
private void Update()
{
    //向右移动,2D中为向右/前,X轴正方向
    rigidbody2D.MovePosition(transform.position + Vector3.right * speed * Time.deltaTime);
}

Of course, you can also directly fill in the target position to make the object flash to the specified target position.

[SerializeField] private Transform targetTransform;
private Rigidbody2D rigidbody2D;
private void Start()
{
    //获取挂载脚本的物体的刚体组件
    rigidbody2D = GetComponent<Rigidbody2D>();
}
private void Update()
{
    //传送到targetTransform的位置
    rigidbody2D.MovePosition(targetTransform.position);
}

3.velocity

The first thing to explain is that velocity is not a function, but a parameter, which is the speed of the object.

So by adding speed to the direction in which the object is going to move, we can make the object move at a fixed speed beyond the specified direction.

[SerializeField] private float moveSpeed_X;
[SerializeField] private float moveSpeed_Y;
private Rigidbody2D rigidbody2D;
private void Start()
{
    //获取挂载脚本的物体的刚体组件
    rigidbody2D = GetComponent<Rigidbody2D>();
}
private void Update()
{
    //水平方向
    float horizontal = Input.GetAxis("Horizontal");
    //竖直方向
    float vertical = Input.GetAxis("Vertical");
    rigidbody2D.velocity=new Vector2 (horizontal*moveSpeed_X*Time.deltaTime, vertical* moveSpeed_Y * Time.deltaTime);
    //也可以只改变x或y的值
    rigidbody2D.velocity = new Vector2(horizontal * moveSpeed_X * Time.deltaTime, rigidbody2D.velocity.y);
    rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, vertical * moveSpeed_Y * Time.deltaTime);
}

4. Ending

The above are several simple ways to move objects. Of course, there are many ways to move objects. Here are just a few. Interested friends can take a closer look.

Guess you like

Origin blog.csdn.net/qq_63486332/article/details/131953729
Recommended