简体   繁体   中英

Swift how to move sprite?

I would like to know how to move a sprite in spritekit depending on the side of the screen the user is pressing down on. Like if the user taps the right side of the screen the sprite should move to the right and when the user removes his finger the sprites stops moving. Any suggestions? thank you so much

use the touchesBegan func and get position of touch with:

for location: AnyObject in touches {
var positionOfTouch = location.locationInNode(self)
//position of touch is of value CGPoint
}

store the value of xposition and yposition

var xPostion = positionOfTouch.position.x
var yPosition = positionOfTouch.position.y
//all in the touchesBegan func

make an if else statement to see if the user touches a side or not

if xPosition < 10 && yPosition > 10 && yPosition < self.size.height-10 {
//left side
let moveToLeftSide = SKAction.moveTo(x: 0, duration: 10)
object.run(moveToLeftSide)
}

continue setting values for the sides, then set the touchesEnded func inside the touchesEnded func, write:

object.removeAllActions()

hope it helped... if you found this answer helpful remember to set this answer to correct ; )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM