feat(pathfinding): 支持从不可行走位置开始寻路
改进寻路系统,允许玩家从不可行走的当前位置开始寻路到可行走区域。 当玩家位于不可行走位置时,系统会自动寻找最近的可行走位置作为起点, 并临时将起点设置为可行走状态以启动A*算法。 主要变更: - AStarPathfinding: 临时修改起点可行走状态以支持算法启动 - PlayerController: 检测玩家当前位置并自动传送到最近可行走点 - TiledMapPathfinder: 在寻路前验证起点并寻找替代位置
This commit is contained in:
@@ -65,11 +65,15 @@ export class AStarPathfinding extends Component {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (!this.grid[startX][startY].walkable || !this.grid[targetX][targetY].walkable) {
|
||||
console.warn('起点或终点不可行走');
|
||||
// 检查终点是否可行走
|
||||
if (!this.grid[targetX][targetY].walkable) {
|
||||
console.warn('终点不可行走');
|
||||
return [];
|
||||
}
|
||||
|
||||
// 注意:起点可能不可行走,我们在TiledMapPathfinder中已经处理了这种情况
|
||||
// 这里不再检查起点是否可行走,允许从不可行走的起点开始寻路
|
||||
|
||||
if (startX === targetX && startY === targetY) {
|
||||
return [new Vec2(startX, startY)];
|
||||
}
|
||||
@@ -80,6 +84,10 @@ export class AStarPathfinding extends Component {
|
||||
const startNode = this.grid[startX][startY];
|
||||
const targetNode = this.grid[targetX][targetY];
|
||||
|
||||
// 临时将起点设置为可行走,以便算法能够开始
|
||||
const originalStartWalkable = startNode.walkable;
|
||||
startNode.walkable = true;
|
||||
|
||||
const openSet: PathNode[] = [];
|
||||
const closedSet: PathNode[] = [];
|
||||
|
||||
@@ -101,12 +109,16 @@ export class AStarPathfinding extends Component {
|
||||
|
||||
// 如果到达目标节点,重建路径
|
||||
if (currentNode === targetNode) {
|
||||
// 恢复起点的原始可行走状态
|
||||
startNode.walkable = originalStartWalkable;
|
||||
return this.retracePath(startNode, targetNode);
|
||||
}
|
||||
|
||||
// 检查相邻节点
|
||||
const neighbors = this.getNeighbors(currentNode);
|
||||
for (const neighbor of neighbors) {
|
||||
// 如果当前节点不可行走,我们仍然允许它连接到可行走的相邻节点
|
||||
// 这样可以从不可行走的起点移动到可行走的区域
|
||||
if (!neighbor.walkable || closedSet.indexOf(neighbor) !== -1) {
|
||||
continue;
|
||||
}
|
||||
@@ -126,6 +138,9 @@ export class AStarPathfinding extends Component {
|
||||
}
|
||||
}
|
||||
|
||||
// 恢复起点的原始可行走状态
|
||||
startNode.walkable = originalStartWalkable;
|
||||
|
||||
// 没有找到路径
|
||||
return [];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user