SKPhysics与Swift和SpriteKit

时间:2014-10-09 09:59:18

标签: ios swift sprite-kit skphysicsbody

我正在尝试使用Swift编程语言创建一个iOS游戏。 我想在屏幕上使用滑动手势让角色(玩家)向上,向下,向左和向右移动

到目前为止一切顺利。但我想要一些物理学。我希望播放器与屏幕边缘发生碰撞。 (后来我希望它与其他东西发生冲突,但我需要先知道代码;)

问题:如何识别2个对象(播放器和屏幕边缘)之间的碰撞

   import SpriteKit

class GameScene: SKScene, SKPhysicsContactDelegate {

var player:SKSpriteNode = SKSpriteNode()
let moveUp = SKAction.moveByX(0, y:2000, duration:10.0) //it is set to 2000 because I want to see if it collides with the edge of the screen
let moveDown = SKAction.moveByX(0, y: -200, duration: 2.0)




// Define the bitmasks identifying various physics objects
let worldCategory:UInt32 = 0x1 << 0
let playerCategory:UInt32 = 0x1 << 1




override func didMoveToView(view: SKView) {

}



override init(size:CGSize) {
    super.init(size: size)
    self.backgroundColor = SKColor.whiteColor()
    player = SKSpriteNode(imageNamed: "Kundvagn1")
    player.position = CGPointMake(self.frame.size.width/2, player.size.height/2 + 20)
    self.addChild(player)


    player.runAction(moveUp)


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




    player.physicsBody = SKPhysicsBody(rectangleOfSize: player.size)
    player.physicsBody?.dynamic = true //I dont think the question marks should be there, but Xcode doesn´t accept the code if there is no question marks there
    player.physicsBody?.categoryBitMask = playerCategory
    player.physicsBody?.contactTestBitMask = worldCategory
    player.physicsBody?.collisionBitMask = 0
    player.physicsBody?.usesPreciseCollisionDetection = true




}


func didBeginContact(contact: SKPhysicsContact!) {
    println("Collision")
}

2 个答案:

答案 0 :(得分:0)

假设您想要阻止左右边缘,只需将两个SKShapeNode矩形对象添加到场景中,将其高度设置为屏幕高度,并将它们放置在屏幕的左右边缘之外。建立他们的物理机构,你应该好好去。

如果您希望屏幕的所有边缘都是边界,则需要为场景设置基于线的物理主体,详见此处:Add boundaries to an SKScene

答案 1 :(得分:0)

我添加了这个,以防你需要jonogilmour指令的代码示例。在viewController中打开ShowsPhysics = true以查看物理。双方都应该是蓝色的。如果你想要一个联系通知,你当然会用你的位掩码添加到这段代码中。希望这有帮助!

 var leftEdge = SKNode()
    leftEdge.physicsBody = SKPhysicsBody(edgeFromPoint: CGPointZero, toPoint: CGPointMake(0.0, self.size.height))
    leftEdge.position = CGPointZero;
    self.addChild(leftEdge)

    var rightEdge = SKNode()
    rightEdge.physicsBody = SKPhysicsBody(edgeFromPoint: CGPointZero, toPoint: CGPointMake(0.0, self.size.height))
    rightEdge.position = CGPointMake(self.size.width, 0.0);
    self.addChild(rightEdge)