zoukankan      html  css  js  c++  java
  • 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;
            }
        }
    
    }
  • 相关阅读:
    Delphi/XE2 使用TIdHttp控件下载Https协议服务器文件[转]
    [Delphi]实现使用TIdHttp控件向https地址Post请求[转]
    让PowerShell用上Git
    解答WPF中ComboBox SelectedItem Binding不上的Bug
    那么小伙伴么,问题来了,WPF中,控件的Width="*"在后台怎么写?
    WPF Adorner+附加属性 实现控件友好提示
    关于Mvvm的一些深入理解
    第一个WP8程序,照相机
    夜深了,我们为什么加班(转载)
    Linux学习-SRPM 的使用 : rpmbuild (Optional)
  • 原文地址:https://www.cnblogs.com/duoyaduoa/p/12820512.html
Copyright © 2011-2022 走看看