iosswifttouchesmoved

How do I change the texture of my node when Im moving the joystick to the left or right?


I have this node that is controlled by a joystick and when I move the joystick to the left I would like to change the image of the node and the same thing when I move the joystick to the right. How would I do that? Here is the code I have:

    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch in touches {
        let location = touch.locationInNode(self)

        if stickActive == true {

             //EDIT Code to change texture when moving joystick to left or right.

             if joyStick.position.x < base.position.x {

                plane.texture = SKTexture(imageNamed: "planeleft")

            } else {

                plane.texture = SKTexture(imageNamed: "planeright")

            }



        plane.removeActionForKey("stopaction")
        plane.physicsBody?.affectedByGravity = false


        xJoystickDelta = location.x - base.position.x
        yJoystickDelta = location.y - base.position.y


        let v = CGVector(dx: location.x - base.position.x, dy: location.y - base.position.x)
        let angle = atan2(v.dy, v.dx)
        let length: CGFloat = base.frame.size.height / 2
        let xDist: CGFloat = sin(angle - 1.57079633) * length
        let yDist: CGFloat = cos(angle - 1.57079633) * length


        if (CGRectContainsPoint(base.frame, location)) {
            joyStick.position = location
        }else {

            base.alpha = 0.5 //sets the opacity to 0.5 when the joystick is touched
            joyStick.position = CGPointMake(base.position.x - xDist, base.position.y + yDist)

        }
      }
    }
  }

override func update(currentTime: CFTimeInterval) {

    let xScale = 0.08 
    let yScale = 0.08

    let xAdd = self.xJoystickDelta * CGFloat(xScale)
    let yAdd = self.yJoystickDelta * CGFloat(yScale)

    self.plane.position.x += xAdd
    self.plane.position.y += yAdd
}

Solution

  • I'm not familiar with this, but I know the logic you should use for this.

    Complicated:

    To detect if the joystick is on the left, you should use a range of the furthest left the joystick can go to the centre of the joystick when it's in the middle. The right side would be from the centre to the furthest right it can go.

    Simple:

    For the left, make it when the X value if the joystick is less than the default centre position. The right would be an X position greater than the middle.

    These would be if statements inside the update function so it's constantly checking for this. In the statements would be something like this:

    plane.texture = SKTexture(imageNamed: "TextureName")
    

    Note: This all assumes that the joystick is in a fixed position and has a set centre

    Hope this helps!