我是一名初學者開發人員,我正在製作一款遊戲,其中有兩個綵球落下。你必須得到藍色的,避免紅色的。現在,球出現在屏幕頂部的一個隨機點上,但有時候一些球會出現在其他球的頂部,我想知道是否有辦法檢測並在代碼中避免它,因爲我不知道如何實現它。謝謝!如果您需要更多信息,請隨時向我提問。避免Sprite Kit節點彼此堆疊
0
A
回答
0
您可以創建一個靜態全局變量,它保存最後一個添加的球的前一個x位置,並檢查新創建的球是否與最後一個球具有相同的值,然後您可以重新放置球的位置並檢查再次。 例子:
// here is the global variable declaration
static float _lastRandomX = 0;
//this method creates a rock (you can call it addBall)
- (void)addRock
{
SKSpriteNode *rock = [[SKSpriteNode alloc] initWithColor:[SKColor brownColor] size:CGSizeMake(8, 8)];
rock.name = @"rock";
// the work goes here
CGFloat newRandomX = 0;
while(_lastRandomBall == newRandomX) {
newRandomX = getRandomX();
}
rock.position = CGPointMake(newRandomX, yourYPos);
_lastRandomX = newRandomX
[self addChild:rock];
}
// now here is the action calling this method
- (void)runAction {
SKAction *makeRocks = [SKAction sequence:@[
[SKAction performSelector:@selector(addRock) onTarget:self],
[SKAction waitForDuration:0.10 withRange:0.15]]];
[self runAction:[SKAction repeatActionForever:makeRocks]];
.....
}
1
這可能是最好有一個SKNode只是球和增加新球的時候只是去直通節點和檢查球在哪兒。
//balls node variable in scene, SKNode *ballsNode,
//add this to init or other method:
//self.ballsNode = [SKNode node];
//[self addChild:self.ballsNode];
//
-(void)addRock
{
SKSpriteNode *rock = [[SKSpriteNode alloc] initWithColor:[SKColor brownColor] size:CGSizeMake(8, 8)];
CGFloat newRandomX;
CGPoint ballPosition;
BOOL positionIsOk = NO;
while(!positionIsOk)
{
newRandomX = getRandomX();
ballPosition = CGPointMake(newRandomX, yourYPos);
for(SKSpriteNode *node in self.ballsNode.children)
{
if(!CGRectContainsPoint (node.frame, ballPosition))
{
positionIsOk = YES;
break;
}
else
{
newRandomX = getRandomX();
ballPosition = CGPointMake(newRandomX, yourYPos);
}
}
}
rock.position = ballPosition;
[self.ballsNode addChild:rock];
}
這樣你就可以穿過所有的球並獲得位置,所以它不會與所有球碰撞。
+0
這段代碼可以寫的更好,但它會做你需要的工作;) – BSevo
相關問題
- 1. 堆疊在彼此
- 2. 水平堆疊軸彼此
- 3. 在tkinter中彼此不堆疊的幀
- 4. Sprite Kit中的彈跳節點
- 5. Sprite kit節點在接觸時口吃
- 6. Cytoscape:避免重疊分組節點
- 7. 堆疊div彼此相鄰/水平
- 8. 將兩個div彼此堆疊
- 9. 在彼此之間堆疊圖像
- 10. 問題與divs彼此堆疊
- 11. 表td/UI李堆疊在彼此
- 12. 如何在彼此之上堆疊Div
- 13. 圖像堆疊到彼此onLayout Android
- 14. CSS Image成爲彼此堆疊
- 15. 畫布上的圖像彼此堆疊
- 16. 表單塊不會彼此堆疊
- 17. 幻燈片堆疊在彼此
- 18. 2D塔防 - 彼此堆疊的單位
- 19. 堆疊在彼此上的圖像
- 20. 堆棧ImageButtons彼此
- 21. Sprite Kit - 使用Switch Case向場景添加隨機Sprite節點
- 22. 防止TextBlocks彼此重疊
- 23. 重疊DIV彼此
- 24. CCSprite彼此重疊
- 25. 如何避免定時器堆疊
- 26. 避免圖像在手機上堆疊
- 27. 如何避免堆疊jquery post()
- 28. achartengine堆疊條形圖的X和Y圖彼此重疊?
- 29. 在Sprite-Kit中將點轉換爲節點
- 30. 我如何在彼此旁邊堆疊div並在彼此之上?
你如何創造球?在for循環還是在行動? –
通過創建節點(球)的方法創建球......該方法在遊戲開始時首先被調用,並不斷創建球。 –