Fabez
Fabez

Reputation: 412

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

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:

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))
        }
    }

Upvotes: 3

Views: 179

Answers (1)

Fault
Fault

Reputation: 1294

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

Upvotes: 3

Related Questions