Search code examples
iosswiftsprite-kitgame-physicsskphysicsbody

Prevent sprite rotation from changing gravity


I have a function in SpriteKit that spawns a sprite (which is a square) at the top of the screen, and then gravity pulls the sprite to the bottom of the screen. I'm trying to get the sprite to rotate smoothly for an indefinite amount of time until it is removed when it reaches the bottom of the screen. The following code is in the class for the sprite:

func rotate() {
    var action = SKAction.rotateByAngle(CGFloat(M_PI_2), duration: NSTimeInterval(1.5))
    var repeatAction = SKAction.repeatActionForever(action)
    self.runAction(repeatAction)
}

The problem that I am having is that, as the sprite turns, the sprite travels in the direction of the bottom of itself, not towards the bottom of the screen (the direction gravity is supposed to be). To further clarify, the object rotates, but as it rotates to 90 degrees, it travels sideways instead of downwards. This doesn't make sense to me. This is the code I'm using to add gravity in the didMoveToView() function:

self.physicsWorld.gravity = CGVectorMake(0.0, -1.8)

and this is the code used to spawn the sprite (the rs.rotate() calls the rotate method that is listed above):

func spawnRedSquares() {
    if !self.gameOver {
        let rs = RedSquare()
        var rsSpawnRange = randomNumberBetween(self.leftSideBar.position.x + rs.sprite.size.width / 2, secondNum: self.rightSideBar.position.x - rs.sprite.size.width / 2)
        rs.position = CGPointMake(rsSpawnRange, CGRectGetMaxY(self.frame) + rs.sprite.size.height * 2)
        rs.zPosition = 3
        self.addChild(rs)
        self.rsArray.append(rs)
        rs.rotate()

        let spawn = SKAction.runBlock(self.spawnRedSquares)
        let delay = SKAction.waitForDuration(NSTimeInterval(timeBetweenRedSquares))
        let spawnThenDelay = SKAction.sequence([delay, spawn])
        self.runAction(spawnThenDelay)
    }
}

How can I get the object to rotate, but still fall down as if it were affected by normal gravity?


Solution

  • It looks like you are adding the rotation action to 'self' which I would assume is your scene as opposed to your sprite. This is causing the entire scene to rotate, and therefore its gravity is rotating as well.

    Add the rotating action to your sprite and that should solve the issue.

    Example: assuming your square sprite is called squareSprite:

    let action = SKAction.rotateByAngle(CGFloat(M_PI_2), duration: NSTimeInterval(2))
    let repeatAction = SKAction.repeatActionForever(action)
    squareSprite.runAction(repeatAction) //Add the repeatAction to your square sprite