我正在玩一款玩家跟随触摸的游戏。游戏有障碍和寻路,我正在经历极度滞后的触动。加载游戏后,一切正常,但是在我的手指拖动几秒钟后(尤其是在障碍物周围),游戏会冻结到移动触摸将冻结所有物理(0 fps)直到触摸结束的程度。
我假设罪魁祸首是我的函数makeGraph()
,它为player.position:CGPoint()
到player.destination:CGPoint()
的玩家找到路径,在player.goto:[CGPoint()]
中存储路径,更新函数然后负责移动到下一个转到点。
此功能在touchesmoved
的每个周期调用,因此如果手指在障碍物上移动,玩家可以切换方向
我的问题是:1)此代码中的内容导致无法忍受的延迟,2)如何使此代码更有效?
我的代码:
初始化变种:
var obstacles = [GKPolygonObstacle(points: [float2()])]
var navgraph = GKObstacleGraph()
设置图表(在级别开始时调用):
func setupGraph(){
var wallnodes :[SKSpriteNode] = [SKSpriteNode]()
self.enumerateChildNodes(withName: "wall") {
node, stop in
wallnodes.append(node as! SKSpriteNode)
}
self.enumerateChildNodes(withName: "crate") {
node, stop in
wallnodes.append(node as! SKSpriteNode)
}
obstacles = SKNode.obstacles(fromNodeBounds: wallnodes)
navgraph = GKObstacleGraph(obstacles: obstacles, bufferRadius: Float(gridSize/2))
}
touchesmoved:我使用字符串跟踪多个触摸。只有一根手指可以充当“MoveFinger”。此字符串在touchesbegan
创建,并在touchesended
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
touchloop: for touch in touches {
if MoveFinger == String(format: "%p", touch) {
let location = touch.location(in: self)
player.destination = location
makeGraph()
player.moving = true
player.UpdateMoveMode()
continue touchloop
}
// .... more if statements ....
}
}
和图形函数(称为每个触摸移动循环):
func makeGraph(){
let startNode = GKGraphNode2D(point: float2(Float(player.position.x), Float(player.position.y)))
let endNode = GKGraphNode2D(point: float2(Float(player.destination.x), Float(player.destination.y)))
let graphcopy = navgraph
graphcopy.connectUsingObstacles(node: startNode)
graphcopy.connectUsingObstacles(node: endNode)
let path = graphcopy.findPath(from: startNode, to: endNode)
player.goto = []
for node:GKGraphNode in path {
if let point2d = node as? GKGraphNode2D {
let point = CGPoint(x: CGFloat(point2d.position.x), y: CGFloat(point2d.position.y))
player.goto.append(point)
}
}
if player.goto.count == 0 {
//if path is empty, go straight to destination
player.goto = [player.destination]
} else {
//if path is not empty, remove first point (start point)
player.goto.remove(at: 0)
}
}
任何想法?