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

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -