Turning Object with SkSpriteNode

2019-08-01 03:07发布

问题:

I have an image named "Ghost" and it moves throughout the screen. I want to have the SpriteNode constantly turning without being pressed on.

Ghost = SKSpriteNode(imageNamed: "Ghost1")
    Ghost.size = CGSize(width: 50, height: 50)
    Ghost.position = CGPoint(x: self.frame.width / 2 - Ghost.frame.width, y: self.frame.height / 2)
    Ghost.physicsBody = SKPhysicsBody(circleOfRadius: Ghost.frame.height / 1.4)
    Ghost.physicsBody?.categoryBitMask = PhysicsCatagory.Ghost
    Ghost.physicsBody?.collisionBitMask = PhysicsCatagory.Ground | PhysicsCatagory.Wall
    Ghost.physicsBody?.contactTestBitMask = PhysicsCatagory.Ground | PhysicsCatagory.Wall | PhysicsCatagory.Score
    Ghost.physicsBody?.affectedByGravity = false
    Ghost.physicsBody?.isDynamic = true
    Ghost.zPosition = 2

    self.addChild(Ghost)

I have looked for some answers on Stack Overflow but I can't seem to find any one with this same question, please help.

回答1:

You could apply a force of an angular type, so as to rotate the body, and turn off damping so it continues to rotate forever:

https://developer.apple.com/reference/spritekit/skaction/1417775-applyangularimpulse

Or, apply torque:

Firstly, make sure it’s able to rotate by setting this to true:

https://developer.apple.com/reference/spritekit/skphysicsbody/1519986-allowsrotation

Make sure there’s no angular damping so that it doesn’t slow in rotation rate:

https://developer.apple.com/reference/spritekit/skphysicsbody/1519913-angulardamping

Now make it spin by applying a torque:

https://developer.apple.com/reference/spritekit/skphysicsbody/1519588-applytorque

Or, set a spin rate:

https://developer.apple.com/reference/spritekit/skphysicsbody/1519766-angularvelocity



回答2:

To have the SKSpriteNode constantly rotating, add this to wherever you want to start the rotating:

let rotate = SKAction.rotate(byAngle: CGFloat.pi * 2.0, duration: 2)
Ghost.run(SKAction.repeatForever(rotate), withKey: "rotateGhost")

To rotate in the opposite direction, change CGFloat.pi to -CGFloat.pi

You can fidget with the duration to change the duration for a complete rotation.

If you wish to remove the action, call:

removeAction(forKey: "rotateGhost")

Or you can just pause the action instead.