4

In my game I need to use the mouse to select units.

However, I am encountering problems as I do not know how to get the coordinates of the click relative to the game, not to the window.

For example, if Unit 1 is at the (0,0) point of the game, it could be at any point on the window depending on how I pan and zoom the window, but I want the mouse click to return (0,0) no matter how I move the window as long as I click on the same spot.

Right now I am using:

override func mouseDown(with event: NSEvent) {
    eventPos = event.location(in: self)
    ...
}

(The rest of the code does not matter for the mouse click location).

This is all inside a GameScene, which is an SKScene. So how do I get the location relative to the GameScene of the mouse click?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Student-LTB
  • 103
  • 8
  • `eventPos` should be in scene coordinates. Are you panning/zooming using SpriteKit's built-in camera? Also, did you try `let selectedUnit = atPoint(eventPos)` to select a unit? – 0x141E Mar 20 '17 at 19:01
  • I am using a camera made through code, it is an SKCamera node, but IS NOT the one you make by dragging one and placing one through the Game Scene SKS. – Student-LTB Mar 22 '17 at 17:57
  • Panning an zooming are custom functions I made. – Student-LTB Mar 22 '17 at 17:57
  • If you use the built-in SpriteKit camera for panning/zooming, the mouse positions will be in scene coordinates with the code you provided above. I also suspect it will simplify your app development effort. – 0x141E Mar 22 '17 at 20:22

1 Answers1

5

You need convert your point from view to scene coordinates:

eventPos = view!.convert(event.locationInWindow, to: view!.scene!)
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571