Hunter23
Hunter23

Reputation: 69

Node positions in Sprite Kit

I am making a side scrolling game in sprite kit with a lot of nodes in many different positions. But i am having trouble setting all the positions so they are in the same place on all devices. I know i can test which device it is then set my node position, but this is really a lot of work when i have 20 nodes or more. i am also looping through some of them with a plist and arrays which is even harder because i don't want to make a new plist for every device with all the positions.

is there a simple way to have them all set in the same position for all different screen sizes?

Upvotes: 1

Views: 178

Answers (2)

sangony
sangony

Reputation: 11696

You position your nodes in a dynamic way dependent on your screen size like this:

// get screen size
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width/100;
CGFloat screenHeight = screenRect.size.height/100;

myNode.position = CGPointMake(screenWidth*6, screenHeight*25);

In effect you are using percentages of actual screen width and height.

Upvotes: 1

AlexKoren
AlexKoren

Reputation: 1605

There are two schools of thought here.

The first is that you set their positions at a specific (x, y) such as (20, 50). This will make sure they are always the same distance from the bottom left corner in SpriteKit. It also means that things may move off screen on smaller devices that fit on larger devices.

The second school of thought (and the one I most often use) is using ratios. Instead of static (x, y) you have (xR, yR) where xR and yR are the ratio of distance across the size of the screen. Let's say that you want a character in the center of the screen, you would use (.5, .5) and then when you go to place the character just multiply xR by the width of the screen and yR by the height of the screen.

CGPoint position = CGPointMake(xR * self.size.width, yR * self.size.height);

where self is the scene in SpriteKit or whatever the super node is.

Upvotes: 0

Related Questions