1. 程式人生 > 實用技巧 >利用A* Pathfinding專案在unity中實現自動尋路

利用A* Pathfinding專案在unity中實現自動尋路

A* Pathfinding 專案地址: https://arongranberg.com/astar/

學習視訊:Unity 2D AI自動尋路功能 [風農譯製]_嗶哩嗶哩 (゜-゜)つロ 乾杯~-bilibili

素材地址:2D Beginner: Tutorial Resources | 資源包 | Unity Asset Store

1.生成導航網格

首先製作一個瓦片地圖,並且加上一個瓦片地圖碰撞器

建立一個空物體,掛上pathfinder元件

建立一個網格圖

勾選2d物理系統選項,將網格覆蓋瓦片地圖,之後選擇瓦片地圖所在的層。

在下方選擇掃描,生成導航網格。

2.尋路指令碼

給物件掛上seeker指令碼,seeker指令碼可以用來生成尋路路徑。接著建立一個新指令碼(EnemyContorller),用來操控物件自動尋路。

編寫指令碼EnemyContorller

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

public class EnemyContorller : MonoBehaviour
{
    public float enemyspeed;//敵人速度
    public Transform target;//
設定跟隨目標 public float nextWaypointDistance = 3f;//敵人距離一個路標點多近的時候,需要向下一個點移動 public Animator animator; Path path;//儲存路徑 int currentWayPoint = 0;//代表在當前路徑上,正在朝哪一個路標點移動 bool reachedEndOfPath = false;//是否到達最後一個點 Rigidbody2D rigidbody2d; Seeker seeker; void Start() { rigidbody2d
= GetComponent<Rigidbody2D>(); seeker = GetComponent<Seeker>(); enemyCurrentHealth = enemyMaxHealth; InvokeRepeating("UpdatePath", 0, 0.5f);//第二個引數,多久第一次呼叫它,第三個引數,呼叫速率 } private void UpdatePath() { if(seeker.IsDone())//如果沒有在計算路徑,進行下一次更新 seeker.StartPath(rigidbody2d.position, target.position, OnPathComplete); //生成路徑,第三個引數為生成路徑完成後呼叫的函式 } void FixedUpdate() { if (path == null) return;//路徑為空,退出 if (currentWayPoint >= path.vectorPath.Count) { reachedEndOfPath = true; return; } else { reachedEndOfPath = false; }//檢查路徑點是否走完 Vector2 direction = ((Vector2)path.vectorPath[currentWayPoint] - rigidbody2d.position).normalized; //設定朝向 animator.SetFloat("Look X", direction.x); animator.SetFloat("Look Y", direction.y); Vector2 force = direction * enemyspeed * Time.deltaTime;//設定力 animator.SetFloat("Speed", force.magnitude);//播放行走動畫 rigidbody2d.AddForce(force);//給敵人施加力 float distance = Vector2.Distance(rigidbody2d.position, path.vectorPath[currentWayPoint]); //計算到下一個點的距離 if (distance < nextWaypointDistance) { currentWayPoint++; }//小於,移動到下一個座標點 } private void OnPathComplete(Path p) { if(!p.error) { path = p; currentWayPoint = 0; }//若路徑無錯誤,使用這個路徑 } }