Davigor
Davigor

Reputation: 403

Spawning sprites on screen edges while keeping anchor point in center

I'm developing a simple game where there's a player sprite in the middle of my screen and monster sprites spawn at random locations on the screen edge and slowly move toward the player sprite. Originally, this worked just fine by setting the GameScene anchor point to the lower left with self.anchorPoint = CGPoint(x: 0.0, y: 0.0), and the positioning the player in the center with player.position = CGPoint(x: size.width * 0.5, y: size.height * 0.5). However, because I changed the anchor point, when I rotate my iPad, the player ends up being off center.

I think it's easier to work with a (0,0) anchor point, because then I can spawn monsters randomly from the edges using lines like randomEdgePosition = CGPoint(x: 0.0, y: randomFloat(min: 0.0, max: 1.0) * size.height). But it's easier for my player's positioning to keep the anchor point centered. How can the screen edges be calculated with a central anchor point? Alternatively, how could I keep my player centered with a (0,0) anchor point?

Upvotes: 0

Views: 184

Answers (2)

Knight0fDragon
Knight0fDragon

Reputation: 16837

The problem with randomizing on an edge is that you will see more enemies spawning in the corners than in the centers of the edges because there is more edge on the corners. To evenly distribute around the entire scene, you want to position based on a circle, and use the longest edge / 2 + the longest edge / 2 of the enemy (I assume you want to spawn off screen) as your radius

let theta = CGFloat(randomFloat(min: 0.0, max: 1.0) * Float.pi * 2)
let radius = max(size.width, size.height)/2 + max(enemy.size.width, enemy.size.height)/2 
let randomPosition = CGPoint(x: cos(theta) * radius, y: sin(theta) * radius)

This will also solve your issue with the anchorPoint, and allows you to keep it at the center of the screen (0.5,0.5), making it easier to detect which way the enemies are coming from without having to do additional subtraction. (E.G. enemy at -x is left of the player, no need to check if x < player.x0

Upvotes: 0

Ron Myschuk
Ron Myschuk

Reputation: 6061

Keep the anchor point in the center of your screen and spawn your monsters using this

randomEdgePosition = CGPoint(x: 0 - size.width / 2, y: randomFloat(min: 0.0, max: 1.0) * size.height)

Upvotes: 2

Related Questions