重力属性在SpriteKit场景中不起作用

时间:2015-11-10 21:21:41

标签: ios swift sprite-kit skphysicsbody

import SpriteKit

class GameScene: SKScene {
 override func didMoveToView(view: SKView) {
    /* Setup your scene here */
 }

 override func touchesBegan(touches: Set<UITouch>, withEvent event:            UIEvent?) {
   /* Called when a touch begins */

    for touch in touches {
        let location = touch.locationInNode(self)

        let sprite = SKSpriteNode(imageNamed:"Beach Ball-100")
        self.addChild(sprite)

        sprite.xScale = 0.5
        sprite.yScale = 0.5
        sprite.position = location
        sprite.color = UIColor.redColor()
        sprite.physicsBody = SKPhysicsBody(edgeLoopFromRect:self.frame)
        sprite.physicsBody?.affectedByGravity = true
        var action = SKAction.rotateByAngle(CGFloat(M_PI), duration:1)

  }
  }

  }

上面的代码出现在我的场景类中。当我运行它时,由于gravity属性设置为true,因此球对象没有按预期下降。请解释我的错误。

2 个答案:

答案 0 :(得分:3)

物理学家是错的。你需要精灵的框架,而不是世界的框架:

sprite.physicsBody = SKPhysicsBody(rectangleOfSize: sprite.frame.size)

答案 1 :(得分:1)

添加SKPhysicsContactDelegate

class GameScene: SKScene, SKPhysicsContactDelegate 

physicsWorlddidMoveToView中定义touchesBegan(就像您在示例中所做的那样)

physicsWorld.gravity = CGVectorMake(0, -1.0)
physicsWorld.contactDelegate = self

为您的节点提供正确的SKPhysicsBody尺寸

sprite.physicsBody = SKPhysicsBody(circleOfRadius: frame.size.width / 2)