欢迎来到多呀多啊的博客
Zou-Wang
多呀多啊
世界大雨磅沱,万物苟且而活,无人为你背负更多

Unity中使用A*寻路方式步骤

1、在Unity中使用A*寻路方法步骤(这里暂不对A*算法进行讲解)

 (1)导入A*寻路插件(该插件需要在较高版本使用【例如2017,5.6无法使用】)—搭建场景—场景中设置两个层级,地面(Ground)和障碍物(Obstacle)且分别为地面和障碍物设置对应的层—设置两个标签,地面(Ground)和障碍物(Obstacle)且分别为地面和障碍物设置对应的标签

   (2)创建一个空物体命名为“A*”,为其添加Astar Path组件(组件库中搜Pathfinder组件或【Components–>Pathfinding–>Pathfinder】),用于设置寻路参数

(3)在Astar Path组件的Graphs选项中选择Grid Graph—在面板中对各种参数进行详细设置—点击Scan可查看场景中形成的网格

(4)为寻路物体添加Seeker脚本—创建C#脚本,编译代码,并挂载到寻路物体上

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;//需要引入Pathfinding
public class MySkker : MonoBehaviour {

    public GameObject target;  //目标物
    private Seeker seeker1;
    private Path path1;  //路径
    private float nextwaypointDistance=1; //距离下一个点的距离
    private int currentwaypoint = 0; //当前路点
    public float speed = 100;
    public float rotspeed = 60; //旋转速度
    // Use this for initialization

    void Start () {
        seeker1 = this.GetComponent<Seeker>();
        seeker1.pathCallback += OnpathCompeleter;
        seeker1.StartPath(transform.position,target.transform.position);
    }
    // Update is called once per frame

    void Update () {
        if (path1==null) {
            print("为空了");
            return;
        }

        if (currentwaypoint>=path1.vectorPath.Count) {
            return;
        }

        Vector3 dir = (path1.vectorPath[currentwaypoint] - transform.position).normalized;
        dir *= speed * Time.deltaTime;
        transform.Translate(dir,Space.World);
        Quaternion targetrotation = Quaternion.LookRotation(dir);
        transform.rotation = Quaternion.Slerp(transform.rotation,targetrotation,Time.deltaTime*rotspeed);

        if (Vector3.Distance(transform.position,path1.vectorPath[currentwaypoint]) < nextwaypointDistance){
            currentwaypoint++;
            return;
        }
    }

    private void OnpathCompeleter(Path p) {

        if (!p.error) {
            path1=p;
            currentwaypoint = 0;
        }
    }

}

 

posted @ 2020-05-03 01:17  多呀多啊  阅读(2041)  评论(0编辑  收藏  举报
Live2D
看板娘