view - Swift SpriteKit contain nodes within screen width -


i have randomly spawning nodes moving vertically down view.

here code doing this:

    let metetexture = sktexture(imagenamed: "redmete.png")     let movementamount = arc4random() % uint32(self.frame.width)     let meteoffset = cgfloat(movementamount) - self.frame.width / 2     let metetime = arc4random_uniform(4) + 3;     let movemete = skaction.move(by: cgvector(dx: 0, dy: -2 * self.frame.height), duration: timeinterval(metetime))      redmete = skspritenode(texture: metetexture)     redmete.position = cgpoint(x: self.frame.midx + meteoffset, y: self.frame.midy + self.frame.height / 2) 

my problem meteoffset uses centre of sprite therefore can spawn 50% or out of view.

i have tried

let movementamount = arc4random() % uint32(self.frame.width - metetexture.size().width / 2) 

i've tried

let meteoffset = cgfloat(movementamount) - metetexture.size().width / 2 - self.frame.width / 2 

but neither keep whole of sprite within view. how can this?

you want initial position between sub range of frame height inset half height of meteor.

you need have :

let meteorheight    = metetexture.size().height  let verticalrange   = self.frame.height - meteorheight let randomxposition = meteorheight/2  + arc4random() % verticalrange  

same goes horizontal position (if want random well) :

let meteorwidth     = metetexture.size().width  let horizontalrange = self.frame.width - meteorwidth let randomyposition = meteorwidth/2  + arc4random() % horizontalrange  

you can set position directly random xy coordinates

redmete.position = cgpoint(x:randomxposition, y:randomyposition) 

if don't want meteor appear close edges, can reduce value of verticalrange , horizontalrange further subtracting fixed offset or multiplying fraction.


Comments

Popular posts from this blog

Retrieving ETA (estimated time of arrival) with Google Distance Matrix API and public transit as transport mode -

android - ConstraintLayout: Realign baseline constraint in case if dependent view visibility was set to GONE -

c# - Populating Gridview inside Listview ItemTemplate On Web User Control from Code Behind -