gpt4 book ai didi

arrays - 将一个数组选项取出一个周期

转载 作者:行者123 更新时间:2023-11-30 13:32:21 24 4
gpt4 key购买 nike

好吧,我有这样的代码,其中将生成位置放入数组中,然后使用以下代码随机选择其中一个位置:

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 个水平位置中的任何一个位置生成。

enter image description here

最佳答案

玩家只能被困在头骨和屏幕边缘之间。您应该跟踪当前是否正在“楔入”玩家,例如:

//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;
}

Note: Your algorithm must return 0 or spawnLocations.count as very first index for this to work. Else your skulls may start at the center and still wedge the player in without you realizing it.

关于arrays - 将一个数组选项取出一个周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36434190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com