好的,所以我有这个代码,其中将spawn位置放入一个数组中,然后使用以下代码随机选取其中一个位置:
let randx = spawnLocations[Int(arc4random_uniform(UInt32(spawnLocations.count)))]
obstacle.position = CGPoint(x: randx, y: 0)
对象产生代码:
var spawnLocations:[CGFloat] = []
func getObjectSpawnLocation() {
//Create 5 possible spawn locations
let numberOfNodes = 5
// Spacing between nodes will change if: 1) number of nodes is changed, 2) screen width is changed, 3) node's size is changed.
for i in 0...numberOfNodes - 1 {
// spacing used to space out the nodes according to frame (which changes with screen width)
var xPosition = (frame.maxX /*- thePlayer.size.width*/) / CGFloat((numberOfNodes - 1)) * CGFloat(i)
//add a half of a player's width because node's anchor point is (0.5, 0.5) by default
xPosition += thePlayer.size.width/2
//I have no idea what this does but it works.
xPosition -= frame.maxX/1.6
spawnLocations.append( xPosition )
}
()
}
但是我有一个问题,因为有时游戏会产生如下图所示的对象,如果没有它们死亡,它不会让我的玩家继续前进,所以我的问题是:
无论如何我可以阻止它这样做吗?
可能暂时从阵列中取出一个产卵位置?
我还应该注意,每个物体(骷髅)都是一个接一个地产生,而不是同时产生,并且头骨可以在5个水平位置中的任何一个产生。
答案 0 :(得分:0)
玩家只能被困在头骨和屏幕边缘之间。你应该跟踪你是否正在“楔入”玩家,例如:
//Keep instance variables to track your current state
BOOL lineFromEdge; //YES if you're currently drawing a "line" of skulls from an edge
BOOL leftEdge; //YES if the line originates from the left edge, NO if from the right
int previousIndex;
然后按如下方式确定值:
- (int) randomIndex {
int randIndex = Int(arc4random_uniform(UInt32(spawnLocations.count)));
// This expression tells you if your current index is at an edge
if (randIndex == 0 || randIndex == (spawnLocations.count - 1)) {
lineFromEdge = YES;
leftEdge = randIndex == 0;
}
//Check if you left a gap
BOOL didLeaveGap = abs(randIndex - previousIndex) > 1
if (didLeaveGap) lineFromEdge = NO;
if ((lineFromEdge && leftEdge && randomIndex == spawnLocations.count) ||
(lineFromEdge && !leftEdge && randomIndex == 0)) {
//You have drawn a line from one edge to the other without leaving a gap;
//Calculate another index and perform the same checks again
return [self randomIndex];
}
//Your index is valid
previousIndex = randIndex;
return randIndex;
}
注意:您的算法必须返回
0
或spawnLocations.count
作为第一个索引才能生效。否则你的头骨可能会从中心开始,并且在没有意识到的情况下仍然将玩家楔入其中。