Home > other >  How can I flip horizontally a sprite when moving left or right?
How can I flip horizontally a sprite when moving left or right?

Time:04-06

In my SpriteKit project I have a boat that I drag left and right to catch items falling from the sky, I would like the boat to look in the direction it's moving, I think I have to change xScale from CGFloat(1) to CGFloat(-1) but I don't know how, any suggestion is appreciated, this is how I handle the boat movement:

class GameScene: SKScene {

var node = SKSpriteNode()
var nodePosition = CGPoint()
var startTouch = CGPoint()


override func didMove(to view: SKView) {
    self.anchorPoint = CGPoint(x: 0.5, y: 0.5)

    // node set up
    node = SKSpriteNode(color: .red, size: CGSize(width: 50, height: 50))
    node.position = CGPoint.zero
    self.addChild(node)
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
    if let location = touch?.location(in: self){
        startTouch = location
        nodePosition = node.position
    }
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
    if let location = touch?.location(in: self){
        node.run(SKAction.move(to: CGPoint(x:  nodePosition.x   location.x - startTouch.x, y: nodePosition.y   location.y - startTouch.y), duration: 0.1))
    }
}

}

CodePudding user response:

inside touchesMoved you can use touch.location and touch.previousLocation to determine a change in the x position. then if the delta x is positive or negative you can flip your xScale accordingly.

//grab current and previous locations
let touchLoc = touch.location(in: self)
let prevTouchLoc = touch.previousLocation(in: self)

//get deltas and update node position
let deltaX = touchLoc.x - prevTouchLoc.x
let deltaY = touchLoc.y - prevTouchLoc.y
node.position.x  = deltaX
node.position.y  = deltaY

//set x flip based on delta
node.xScale = deltaX < 0 ? 1 : -1
  • Related