我在Unity 4.6.2f中工作。我正在使用Physics2D,UnityScript和A *寻路(http://arongranberg.com/astar/)免费版本3.6。我的问题是用我的EnemyAI脚本移动敌人,它在Gizmo中正确显示路径,但我的敌人没有跟随它。看起来他总是试图到达路径的第0点,它只是在空中飞来飞去。
EnemyAI脚本 - 我认为问题可能出现在最后4行代码中:
import Pathfinding;
@script RequireComponent(Seeker)
@script RequireComponent(Rigidbody2D)
var seeker : Seeker;
var rb : Rigidbody2D;
var path : Path;
var target : Transform;
var updateRate : float = 2f;
var currentWaypoint : int = 0;
var nextWaypointDistance : float;
var pathIsEnded :boolean;
var speed : float = 300f;
var fMode : ForceMode2D;
function Start () {
rb = GetComponent.<Rigidbody2D>();
seeker = GetComponent.<Seeker>();
if (target == null)Debug.LogError("!!!NO PLAYER FOUND!!!");
//Start the path
seeker.StartPath(transform.position, target.position,OnPathComplete);
StartCoroutine(UpdatePath());
}
//function for finding new way when target moves
function UpdatePath() :IEnumerator {
if (target == null) {
//TODO: Insert a player search here.
return;
}
seeker.StartPath (transform.position, target.position, OnPathComplete);
yield WaitForSeconds( 1f/updateRate );
StartCoroutine(UpdatePath());
}
function OnPathComplete (p:Path) {
Debug.Log ("We got a path. Did it have an error? " + p.error);
if (!p.error) {
path = p;
currentWaypoint = 0;
}
}
function FixedUpdate(){
if (target == null) {
//TODO: Insert a player search here.
return;
}
//TODO: Always look at player?
if (path == null)
return;
if (currentWaypoint >= path.vectorPath.Count) {
if (pathIsEnded)
return;
Debug.Log ("End of path reached.");
pathIsEnded = true;
return;
}
pathIsEnded = false;
//Direction to the next waypoint
var dir: Vector3 = (path.vectorPath[currentWaypoint] - transform.position).normalized;
dir *= speed * Time.fixedDeltaTime;
//Move the AI
rb.AddForce (dir, fMode);
Debug.Log(dir);
var dist:float = Vector3.Distance (transform.position, path.vectorPath[currentWaypoint]);
if (dist < nextWaypointDistance) {
currentWaypoint++;
return;
}
}
答案 0 :(得分:1)
事实上,似乎问题出现在最后4行。以下是一些可能出错的事情:
始终检查您的变量是否已初始化,并且在处理2D时,不要忽略Z坐标,它有其用途,它也可能会弄乱您的距离计算。