Learn Courses My Dashboard

Random location

Hello,
Im trying to build an app with randomly placed objects (SKSpriteNode), I have tried some solutions but nothing is working. In other words, some solutions worked, but they were only placing the objects into one fourth of the screen.
I was trying to find something that would work but Im struggling with that.

Here are some solution I’ve tried.
the first one:
let maxX = (scene?.frame.maxX)!
let maxY = (scene?.frame.maxY)!
let xPos = CGFloat( Float(arc4random()) / Float(UINT32_MAX)) * maxX
let yPos = CGFloat( Float(arc4random()) / Float(UINT32_MAX)) * maxY

and the second one:

let PositionX1 = arc4random_uniform(UInt32(( self .view?.frame.width)! - objectWidth))

let PositionY1 = arc4random_uniform(UInt32(( self .view?.frame.height)! - objectHeight))

Hi @Tomaskrat17 It’s been a while, good to hear from you again! :slight_smile:

Both of the solutions you’ve provided are generating random x and y positions for the objects, but they are using different methods to do so. The first solution uses the maxX and maxY values of the scene’s frame to generate a random value between 0 and the maximum x and y positions. The second solution uses the width and height of the view, subtracting the object’s width and height to ensure that the object stays within the visible area of the screen.

Both solutions can work, but they have different limitations. For example, the first solution will generate random positions anywhere within the maximum x and y positions of the scene, while the second solution will only generate random positions within the visible area of the screen.

It’s hard to say which solution would work best for you without knowing more about your specific requirements and constraints. But you can try to combine both solutions together, by getting the random position in first solution and then checking if it’s inside the view or not if not then adjust the position accordingly.

Additionally, you might also want to consider other factors such as the number of objects you want to place and how close together they can be placed.

Hello @joash,
Thank you very much for your advice. :smiley:

1 Like

Hello,
I have another question :D, because it is associated with the first one I will write it here.
I tried to combine the two methods in some way but, the object is always placed only on one fourth of the screen. It goes only to the positive x and y values. I absolutely don’t know why and how to solve it.
Can somebody give me an advice. Im struggling to find the solution.
Thank you very much :D.

Helli @Tomaskrat17

If you have a repository for your project and if you can share it here, I think that would help us a lot. :blush: