2014-10-09 32 views
0

我想創建一個使用Swift編程語言的iOS遊戲。 我想在屏幕上使用滑動手勢使角色(玩家)向上,向下,向左,向右移動SKPhysics與斯威夫特和SpriteKit

目前爲止這麼好。但我想要一些物理學。我希望玩家與屏幕邊緣發生碰撞。 (後來我想這與其他的東西發生碰撞,但我首先要知道的代碼;)

問題:如何識別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") 
} 

回答

0
之間的碰撞

假設您想要阻止左右邊緣,只需將兩個SKShapeNode矩形對象添加到場景中,將它們的高度設置爲屏幕高度,然後將它們放在屏幕的左側和右側邊緣之外。建立他們的物理機構,你應該很好走。

如果你想在屏幕的四周邊緣是邊界,你需要安裝一個基於行的物理機構場景,詳見這裏:Add boundaries to an SKScene

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) 
+0

我沒有使用rect,但edgeFromPoint它似乎適合手頭的工作。 – 2014-12-28 21:27:30