Gameplaykit之Pathfinding

本文仅介绍Gameplaykit之Pathfinding

1.import GameplayKit

2.Obstacles: 使用SKNode的extension中的obstacles方法,获得你想定义的障碍物数组[GKPolygonObstacle]

3.GKObstacleGraph: 使用障碍物数组和缓冲半径创建GKObstacleGraph

4.GKGraphNode2D设置: 给npc出发位置与结束位置赋值2D位置

5.将建好的GKObstacleGraph实例对象使用.connectNodeUsingObstacles关联出发位置与结束位置

6.使用GKObstacleGraph实例对象调用.findPath自动获取最佳路径path

7.遍历路径path,获得GKGraphNode,转换GKGraphNode为GKGraphNode2D,创建移动action,将所有action加入一个动作数组 . 让精灵运行队列动作sequence,执行动作数组中的action

示例func:

func moveBetweenTwoNode(_ startNode: SKSpriteNode,_ endNode: SKSpriteNode) {

let startGraphNode = GKGraphNode2D(point: SIMD2<Float>(Float(startNode.position.x), Float(startNode.position.y)))

let endGraphNode = GKGraphNode2D(point: SIMD2<Float>(Float(endNode.position.x), Float(endNode.position.y)))

//获取scene中你想定义为障碍物的node

let obstacles = SKNode.obstacles(fromNodeBounds: self.children.filter({ (element ) -> Bool in

return element.name == "barrierNode"

}))

let obstacleGraph = GKObstacleGraph(obstacles: obstacles, bufferRadius:10) // 你想要的缓冲半径)

//寻找最佳路径

obstacleGraph.connectUsingObstacles(node: startGraphNode)

obstacleGraph.connectUsingObstacles(node: endGraphNode)

let path:[GKGraphNode] = obstacleGraph.findPath(from: startGraphNode, to: endGraphNode)

var actions = SKAction

for node:GKGraphNode in path {

if let point2d = node as? GKGraphNode2D {

let point = CGPoint(x: CGFloat(point2d.position.x), y: CGFloat(point2d.position.y))

let action = SKAction.move(to: point, duration: 0.5)

actions.append(action)

}

startNode.run(SKAction.sequence(actions))

}

posted on 2024-11-05 15:34  E-ran  阅读(1)  评论(0编辑  收藏  举报

导航