Greg M. Krsak
Greg M. Krsak

Reputation: 2132

iOS: Implementing user-controlled camera "zoom" with Sprite Kit

I have a working 2D platformer engine that wraps Sprite Kit. To implement a scrolling world, I'm following Apple's guidance in their Advanced Scene Processing documentation: My scene contains a world; the world contains all nodes, including a camera node.

Now I'm making the level editor, and that's also working just fine. Here's my problem: I can't figure out how to "zoom the camera in and out" within the level editor.

I searched and found this question on Stack Overflow. Using DogCoffee's answer, I was able to implement zoom behavior that appeared correct but caused incorrect sprite node positions (in my editor, when zoomed in or out, I can no longer select sprites).

How should I be zooming my camera? Or, how should I be adjusting my object positions following a zoom operation?

If you have a tested solution, I'm all ears. I mean...eyes. Yeah.

Upvotes: 4

Views: 910

Answers (1)

Greg M. Krsak
Greg M. Krsak

Reputation: 2132

Ok, this is what happens when you ignore answers with a lower score. Revisiting the same question I linked to, above, I tried JKallio's answer and got it working.

Here's a quick rundown of my implementation (reworked to be free of my personal class names):

In my UI manager:

- (IBAction)pressedZoomIn:(id)sender
{
  CGFloat newZoom = [EditorState zoom] - 0.1f;
  [EditorState setZoom:newZoom];
  [EditorState currentScene].size = CGSizeMake([EditorState currentScene].size.width * newZoom, 
                                               [EditorState currentScene].size.height * newZoom);
}
- (IBAction)pressedZoomOut:(id)sender
{
  CGFloat newZoom = [EditorState zoom] + 0.1f;
  [EditorState setZoom:newZoom];
  [EditorState currentScene].size = CGSizeMake([EditorState currentScene].size.width * newZoom, 
                                               [EditorState currentScene].size.height * newZoom);
}

This solution does give you some "inertia" on your zoom control, but it works for what I'm doing.

Upvotes: 4

Related Questions