Unity implements chasing and interception

1. First create a plane and two small balls, one of which is named Player, and the other named enemy, and give them different colors to show the difference, as shown in the figure below

2. Write a script to make the Player move 

Create a script named move and assign it to the ball. The code is as follows:

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

public class move : MonoBehaviour
{
    public float speed = 6.0f;
    public float gravity = -9.8f;
    private CharacterController _charController;
    // Start is called before the first frame update
    void Start()
    {
        _charController = GetComponent<CharacterController>();//使用附加到相同对象上的其他组件
    }

    // Update is called once per frame
    void Update()
    {
        float x = Input.GetAxis("Horizontal") * speed;
        float z = Input.GetAxis("Vertical") * speed;
        Vector3 movement = new Vector3(x, 0, z);
        movement = Vector3.ClampMagnitude(movement, speed);//使对角移动的速度和沿轴移动的速度一样
        movement.y = gravity;
        movement *= Time.deltaTime;
        movement = transform.TransformDirection(movement);//本地坐标变为全局坐标
        _charController.Move(movement);//character通过movement向量移动
    }
}

Note: To add a characterController to the ball, the ball can move

3. The enemy chases the player

First bake the grid, Windows->AI->navigation, then select the plane, set the parameters as follows, select bake, click bake in the lower right corner to bake

Create a cube as an obstacle and place the cube in a suitable position

Continue to bake, select cube, set the parameters of nagivation as follows, select bake, click bake in the lower right corner to bake

The effect after baking is as follows, where the blue area is the walkable area, and the white area is the non-walkable area

 Add a navigation grid to the enemy, select the enemy, and select Component

 Write a script named enemy, and assign the script to enemy, the code is as follows:

using System.Collections;
using System.Drawing;
using UnityEngine;
using UnityEngine.AI;

public class enemy : MonoBehaviour
{
    NavMeshAgent pathfinder;
    Transform target;
    void Start()
    {
        pathfinder = GetComponent<NavMeshAgent>();
        target = GameObject.FindGameObjectWithTag("Player").transform;

    }
void Update()
    {
        pathfinder.SetDestination(target.position);
    }
}

Click to run, and the enemy can run after the player!

Guess you like

Origin blog.csdn.net/lxy20011125/article/details/129684500