![](/img/trans.png)
[英]ios - Spritekit - How to calculate the distance between two nodes?
[英]Call method on certain distance between nodes in Spritekit
我正在嘗試創建一個敵人跟隨玩家的游戲。 我嘗試枚舉所有敵人節點並計算到玩家的距離。 我在Update
函數中完成了所有這些工作。 這樣做會使我的FPS大幅下降,CPU使用率幾乎達到100%。 還有其他方法可以實現相同的行為嗎?
[self enumerateChildNodesWithName:@"enemy" usingBlock:^(SKNode * _Nonnull node, BOOL * _Nonnull stop) {
if(SDistanceBetweenPoints(self.player.position, node.position)<120)
{
if((![[node.userData objectForKey:@"move"] boolValue])&&
((SDistanceBetweenPoints(self.player.position, node.position)>45)))
{
[self findPathFor:node To:self.player.position];
}
else if (round(SDistanceBetweenPoints(self.player.position, node.position) <= 32.01) &&
(![node hasActions]) &&
(![[self.player.userData objectForKey:@"move"] boolValue]))
{
[self thisNode:node attack:self.player];
}
[self update:node WithDeltaTime:deltaTime];
}
}];
編輯 :當我從self
列舉敵人時,也許這會花費很多時間,因為我self
有很多節點。 也許最好為敵人創造一個獨立的自我事物 ?
EDIT2 :我嘗試將所有敵人添加到數組中,並用於循環而不是枚舉。 現在,我獲得了穩定的60 fps和±40%的CPU使用率。
for (SKNode *node in self.enemiesArray) {
[self update:node WithDeltaTime:deltaTime];
}
SKAction *enemiesFollow = [SKAction runBlock:^{
for(SKNode *node in self.enemiesArray){
[...]
}
}];
SKAction *wait = [SKAction waitForDuration:0.5];
if(![self actionForKey:@"enemyFollow"]){
[self runAction:[SKAction sequence:@[wait, enemiesFollow]] withKey:@"enemyFollow"];
}
這是正確的方法嗎?
我認為采用其他方法會更好。
與其計算每次更新時玩家與每個節點之間的距離,不如使用碰撞框架,該框架的計算速度要快得多。
向玩家添加透明顏色的圓形節點(UIColor的alpha 0),該節點的半徑為當敵人靠近時想要發生多遠的距離。 當敵人與圈子碰撞時,運行您的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.