-1

I am new in spritekit and trying to develop a game with Acceleromotion restricting the SKSpritNode going outide the screen.It is working fine when I set the Player.physicsBody!.dynamic = true but same code is not working when setting this property to "false" . Please tell me where I am going wrong Below is the code:

import SpriteKit
import CoreMotion

class EndScene : SKScene,SKPhysicsContactDelegate   {

  let kShipName = "ship"
  var Player = SKSpriteNode(imageNamed: "Airplane")
  let motionManager: CMMotionManager = CMMotionManager()

  override func didMoveToView(view: SKView) {

physicsWorld.contactDelegate = self
        physicsBody = SKPhysicsBody(edgeLoopFromRect: frame)
        Player.position = CGPointMake(self.size.width / 2, self.size.height / 5)
        Player.physicsBody = SKPhysicsBody(rectangleOfSize: Player.frame.size)
        Player.physicsBody?.affectedByGravity = false
        Player.physicsBody?.categoryBitMask = PhysicsCategory.Player
        Player.physicsBody?.contactTestBitMask = PhysicsCategory.Enemy
        Player.physicsBody?.dynamic = false
        Player.physicsBody!.mass = 0.02
        self.addChild(Player)
        Player.setScale(0.4)
        Player.name = kShipName

        motionManager.startAccelerometerUpdates()
}

func processUserMotionForUpdate(currentTime: CFTimeInterval) {
        // 1
        if let ship = childNodeWithName(kShipName) as? SKSpriteNode {
            // 2
            if let data = motionManager.accelerometerData {
                // 3
                if fabs(data.acceleration.x) > 0.2 {
                    // 4 How do you move the ship?

                    Player.physicsBody!.applyForce(CGVectorMake(30.0 * CGFloat(data.acceleration.x), 0))
                }
            }
        }
    }


 override func update(currentTime: CFTimeInterval) {
              processUserMotionForUpdate(currentTime)
    }


}

1 Answers1

-1

If your sprite is not dynamic you cannot apply Forces/Impulses to it.

As per apples documentation on the dynamic property of SKPhysicsBodies.

"The default value is YES. If the value is NO, the physics body ignores all forces and impulses applied to it. This property is ignored on edge-based bodies; they are automatically static."

As others have pointed out, you should also clean your pyramid of doom

func processUserMotionForUpdate(currentTime: CFTimeInterval) {
    // 1
    guard let ship = childNodeWithName(kShipName) as? SKSpriteNode else { return }
    // 2
    guard let data = motionManager.accelerometerData else { return }
    // 3
    guard fabs(data.acceleration.x) > 0.2 else { return }
    // 4 How do you move the ship?
    Player.physicsBody!.applyForce(CGVectorMake(30.0 * CGFloat(data.acceleration.x), 0))
}

Also try to follow the swift guidelines, your player property should start with a small letter

let player = SKSpriteNode(imageNamed: "Airplane") 
crashoverride777
  • 10,581
  • 2
  • 32
  • 56