Search code examples
iosswiftsprite-kitangleskphysicsbody

Rotation of sprite by using sprites velocity (swift) flappy bird game


So I am learning how to build iOS games by using sprites. I am remaking flappy bird as my first project. The last bit of code I cannot figure out how to get working correctly is the rotation of the bird as it falls through the air.

As my bird falls via gravity it will nose dive down which is good. When I apply a vertical impulse when the screen is tapped. The bird flips 180 straight away to look directly vertical. It is kind of what I but how do I smoothen out the transition from nose dive to looking vertical?

bird.physicsBody?.allowsRotation = true
var velocityvector = bird.physicsBody?.velocity
let angle = atan2(velocityvector?.dy ?? 0, velocityvector?.dx ?? 0)
bird.zRotation = angle

This is the code I made to rotate the bird.


Solution

  • bird.physicsBody?.allowsRotation = true 
    var velocityvector = bird.physicsBody?.velocity
    let angle = atan2(velocityvector?.dy ?? 0, velocityvector?.dx ?? 0)
    let rotateAction = SKAction.rotate(byAngle: angle, duration: 0.5)
    // Or let rotateAction = SKAction.rotate(toAngle: angle, duration: 0.5)
    bird.run(rotateAction)