教程:点击移动

指向并点击的移动方式:角色走到你在地面上点击的位置,并绕开挡路的东西。

1. 准备

准备
  1. 角色是带有 NavAgent 的 Capsule。
  2. 关卡里有智能体可以行走的地面(导航在 Project Settings 中设置)。
  3. 可选:一个名为 Marker 的小球,显示它要去的位置。

2. 脚本

脚本

Scripts/ClickToMove.cs

public class ClickToMove : Behaviour
{
    GameObject marker;

    public override void Start() { marker = GameObject.Find("Marker"); }

    public override void Update(float deltaTime)
    {
        if (Input.GetMouseButtonDown(0))
        {
            // a ray from the camera through the pointer: where it meets something is where to go
            Ray ray = Camera.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out RaycastHit hit, 500f))
            {
                gameObject.agent.SetDestination(hit.point);
                if (marker != null) marker.transform.position = hit.point + Vector3.up * 0.1f;
            }
        }
        if (marker != null) marker.SetActive(!gameObject.agent.arrived);
    }
}

保存为 Scripts/ClickToMove.cs,加到角色上。

3. 工作原理

工作原理

4. 试一试

试一试

在关卡中间加一堵墙,点击另一侧:角色会绕过去。

下一步:倒计时。