ios - SpriteKit - Mouse Snaps to Center On Sprite Drag -


i'm trying create ios game , have when item touched , moved dragged. when dragged mouse snapped center of sprite. how make wouldn't happen?

here example of happening.

here functions dealing touch input

override func touchesbegan(touches: set<nsobject>, withevent event: uievent) {      var papers = 0      touch in (touches as! set<uitouch>) {         let location = touch.locationinnode(self)         let touchednode = nodeatpoint(location)          if ((touchednode.name?.contains("paper")) != nil) {              touchednode.position = location             touchednode.position.x = cgrectgetmidx(self.frame)         }     } } override func touchesmoved(touches: set<nsobject>, withevent event: uievent) {         touch: anyobject in touches {             let location = touch.locationinnode(self)             let touchednode = nodeatpoint(location)              if ((touchednode.name?.contains("paper")) != nil) {                  touchednode.position = location                 touchednode.position.x = cgrectgetmidx(self.frame)             }         }     }  override func touchesended(touches: set<nsobject>, withevent event: uievent) {     touch: anyobject in touches {         let location = touch.locationinnode(self)         let touchednode = nodeatpoint(location)         if ((touchednode.name?.contains("paper")) != nil) {             touchednode.zposition = 0             touchednode.position.x = cgrectgetmidx(self.frame)         }     } } 

p.s. contains extension off of string class check if substring in string

thanks in advance!

it's straightforward drag sprite touch location instead of center of sprite. this, calculate , store difference (i.e., offset) between touch location , center of sprite. then, in touchesmoved, set sprite's new position touch location plus offset.

you can optionally overload + , - operators simplify adding , subtracting cgpoints. define outside of gamescene class:

func - (left:cgpoint,right:cgpoint) -> cgpoint {     return cgpoint(x: right.x-left.x, y: right.y-left.y) }  func + (left:cgpoint,right:cgpoint) -> cgpoint {     return cgpoint(x: right.x+left.x, y: right.y+left.y) } 

in gamescene, define following instance variable

var offset:cgpoint? 

and in touchesbegan, replace

touchednode.position = location 

with

offset = location - touchednode.position 

and in touchesmoved, replace

touchednode.position = location 

with

if let offset = self.offset {     touchednode.position = location + offset } 

i generalized solution offset sprite's position in both x , y dimensions. in app, can offset sprite's y position since x ignored.


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -