Rotate an object in its direction of motion

前端 未结 1 1987
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-17 07:11

Is there a relatively simple way to rotate SKSpriteNode so that it is always facing the direction it is moving? My class Gamescene has a system of objects with their relativ

相关标签:
1条回答
  • 2020-12-17 08:14

    It's fairly straightforward to rotate a sprite in the direction of its motion. You can do this by converting the x and y components of the sprite's velocity into an angle with the atan2 function. You should rotate the sprite only when its speed is greater than some nominal value to prevent the sprite from resetting to zero degrees when the sprite's speed is (nearly) zero.

    If we extend CGVector to compute speed and angle from the velocity's components by

    extension CGVector {
        func speed() -> CGFloat {
            return sqrt(dx*dx+dy*dy)
        }
        func angle() -> CGFloat {
            return atan2(dy, dx)
        }
    }
    

    we can rotate a sprite to face in the direction of its motion with

    override func didSimulatePhysics() {
        if let body = sprite.physicsBody {
            if (body.velocity.speed() > 0.01) {
                sprite.zRotation = body.velocity.angle() - offset
            }
        }
    }
    

    where offset = CGFloat(M_PI_2) if your sprite faces up when zRotation is zero, and offset = 0 if your sprite faces to the right when zRotation is zero.

    0 讨论(0)
提交回复
热议问题