我正在製作一個遊戲,玩家在不同高度的平臺之間移動,每個平臺之間的距離不同。因爲我希望遊戲每次都有所不同,所以我編寫了代碼來自動生成玩家已經傳遞給玩家前方位置的「冰塊」。在Objective-C中產生一個約束的隨機距離物體-I
float viewHeight = self.view.bounds.size.height;
float fViewHeightMinusIceHeight = viewHeight – 55.0f;
int iViewHeightMinusIceHeight = (int)fViewHeightMinusIceHeight;
if (ice.center.x >= (self.view.bounds.size.width + 8))
{
float y = random() %iViewHeightMinusIceHeight;
y = y + 22.5f;
float x = (random() % 20) – 8;
ice.center = CGPointMake(x,y);
}
這只是其中一個對象。相同的代碼用於ice1,ice2等。
這會生成對象就好了。第一個問題是我想限制只有合理結果的可能性(例如沒有巨大差距),以便玩家可以從一個物體移動到另一個物體。
第二個問題是,有時物體會彼此重疊。
可能的重複[如何創建從4到10的隨機數](http://stackoverflow.com/questions/18262895/how-to-create-random-numbers-from-4-to-10) –
取看看我的答案在這裏:http://stackoverflow.com/a/17193450/1075405 – Groot