Changing the angle of a SKSpriteNode during a rotation

Viewed 42

I am trying to make a drifting game. In order for the car to drift, the car (when turning) needs to be at an angle. I have tried rotation, however this conflicts with the code I already have for turning the car. Here is my code, any help?

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            if let touch = touches.first {
                let location = touch.previousLocation(in: self)
                let position = touch.location(in: self)
                let node = self.nodes(at: location).first

if position.x < 0 {
                    let rotate = SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(M_PI), duration: 0.8))
                    car.run(rotate, withKey: "rotating")
         
            } else {
                    let rotate = SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(-M_PI), duration: 0.8))
                    car.run(rotate, withKey: "rotating")
                
               
                
                }
            
        }
            
    }





    override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered
    car.position = CGPoint(x:car.position.x + cos(car.zRotation) * 3.0,y:car.position.y + sin(car.zRotation) * 3.0)

    }

}

This code currently turns the car without adding any angle, or "drifting" effect.

1 Answers

one approach is you could nest your car inside another SKNode as a container. apply your steering rotation to the car node, as you're doing it now. then apply the drift rotation to the container node. the result effect will be the sum of the two.

//embed car inside a SKNode container so you can apply different rotations to each
let car = SKShapeNode(ellipseOf: CGSize(width: 20, height: 40)) //change to how you draw your car
let drift_container = SKNode()
drift_container.addChild(car) //embed car inside the container
self.addChild(drift_container) //`self` here is a SKScene

//apply angle rotation to the container
func drift(byAngle angle:CGFloat) {
    let rotate = SKAction.rotate(toAngle: angle, duration: 0.2)
    drift_container.run(rotate)
}

then in update be sure to update drift_container.position instead of the car's position

Related