swift - Sprite follows touch -


i trying sprite follow finger around when touch screen. have searched around , found works seems little process; beginner i'm not sure if best.

let player = skspritenode(imagenamed: "player")  var location = cgpoint(x: 0, y: 0) var touched: cgpoint? = nil  override func didmovetoview(view: skview) {     backgroundcolor = skcolor.whitecolor()      player.position = cgpoint(x: size.width * 0.5, y: size.height * 0.25)      addchild(player)      runaction(skaction.repeatactionforever(         skaction.sequence([             skaction.runblock(addenemy),             skaction.waitforduration(0.25)             ])         )) }  override func touchesbegan(touches: nsset, withevent event: uievent) {  touched = true touch: anyobject in touches {     location = touch.locationinnode(self) } }  override func touchesmoved(touches: nsset, withevent event: uievent) {  touch: anyobject in touches {     location = touch.locationinnode(self) } }  override func touchesended(touches: nsset, withevent event: uievent) { // stop node moving touch touched = false }  override func update(currenttime: nstimeinterval) {  if (touched) {     movenodetolocation() } }  // move node location of touch func movenodetolocation() { // how fast move node let speed = 1 cgfloat // compute vector components in direction of touch var dx = location.x - player.position.x var dy = location.y - player.position.y let mag = sqrt(dx*dx+dy*dy) // normalize , scale dx = dx/mag * speed dy = dy/mag * speed player.position = cgpointmake(player.position.x+dx, player.position.y+dy)  } 


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -