Alex Zabrodskiy Alex Zabrodskiy - 1 year ago 110
Swift Question

SpriteKit origination and angle of gesture

I am very new to SpriteKit, so apologies for a beginner's question.

I have two objects from which a user can swipe into direction of a "target". I need to determine the origination point (that is from which of two objects the touch was originated) and the swipe angle.

I can use touchesBegan and touchesEnded to calculate those myself, but wonder if there is any other way to do it with sprites.


Answer Source

There is always another way of doing something--this is programming! But, as Rube Goldberg demonstrates below, another way may not be the best / easiest way:

enter image description here

Using touchesEnded you are making sort of like a 'fling' gesture, which can be somewhat limited in it's capabilities.

Example, If you want the object to continuously gain velocity at some f of x / make small path changes (without necessarily having to lift the finger), you can use touchesMoved. Fill it with whatever calculations / functions you like.

Example: drag a node with your touch:

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    //-Main touch processoereor
    for touch in touches {

        let TPOINT  = touch.locationInNode(self)
        my_super_cool_node!.position = TPOINT

        // Put math stuff here, etc.


This gives you MUCH more control over what happens to your sprite from point A to point B.

Here is a good tutorial:

And Apple's stuff:

Unfortunately, the best things in SpriteKit are going to require some clever implementations / math, and can't all be done with the Scene Editor and and nodes.

What you are talking about doing is a fairly routine (math) function, the distance formula, so it's pretty advantageous to make an actual func out of it, so that way you can customize it and not have to manually write a ton of a code for each thing you want to do. SK makes things super easy already. Doing even the basic hello world with spinny spaceships would have been a thousand lines of code (or more) back in the day with C++ Direct3d / OpenGL (and tons of advanced math).

The SK editor is great, and with a little bit of programming on the backend, you can actually make full games from just the editor.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download