2015-12-15 112 views
0

我已經創建了一個簡單的項目,但碰撞中有問題。兩個物體之間的碰撞

這很簡單(球移動和垂直線),但沒有弄清楚如果接觸線時如何停止球。

import SpriteKit 

class GameScene: SKScene,SKPhysicsContactDelegate { 

var rPipe = SKSpriteNode() // Left Pipe 
var ball1 = SKSpriteNode() // Ball 

enum ColliderType:UInt32 { 

case Ball1 = 1 
case Pipe = 2 

} 

override func didMoveToView(view: SKView) { 

    self.physicsWorld.contactDelegate = self 

    // Pipe 
    let rPipeTexture = SKTexture(imageNamed: "pipe_r.png") 
    rPipe = SKSpriteNode(texture: rPipeTexture) 
    rPipe.position = CGPoint(x: CGRectGetMaxX(self.frame)-50, y: CGRectGetMidY(self.frame)-30) 
    rPipe.physicsBody = SKPhysicsBody(rectangleOfSize: rPipeTexture.size()) 
    rPipe.physicsBody?.dynamic = false 
    rPipe.physicsBody?.categoryBitMask = ColliderType.Pipe.rawValue 
    rPipe.physicsBody?.contactTestBitMask = ColliderType.Pipe.rawValue 
    rPipe.physicsBody?.collisionBitMask = ColliderType.Pipe.rawValue 
    self.addChild(rPipe) 

    // Ball 
    let ballTexture = SKTexture(imageNamed: "gBall.png") 
    ball1 = SKSpriteNode(texture: ballTexture) 
    ball1.position = CGPoint(x: CGRectGetMinX(self.frame)+675, y: CGRectGetMaxY(self.frame)-220) 
    ball1.physicsBody = SKPhysicsBody(circleOfRadius: ballTexture.size().height/2) 
    ball1.physicsBody?.dynamic = false 
    ball1.physicsBody?.categoryBitMask = ColliderType.Ball1.rawValue 
    ball1.physicsBody?.contactTestBitMask = ColliderType.Pipe.rawValue 
    ball1.physicsBody?.collisionBitMask = ColliderType.Pipe.rawValue 
    self.addChild(ball1) 

} 


override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { 

    for touch in (touches) { 

     let location = touch.locationInNode(self) 
      if ball1.containsPoint(location) { 
       ball1.position.x = location.x 
      } 
     } 
} 

func didBeginContact(contact: SKPhysicsContact) { 

    print("Contact") 

} 
+0

所附鏈接,供大家參考項目:[鏈接](http://speedy.sh/xCXN8/Count-for-Kids.zip) – Ali

+0

難道有所作爲,如果你更換了'physicsBody ''用'physicsBody!' – penatheboss

回答

0

你的一個物體相撞的dynamic財產應設置爲true。否則,碰撞將被忽略。在設置dynamic後,您還需要將affectedByGravity設置爲false,因爲球不應受重力的影響。

ball1.physicsBody?.dynamic = true 
ball1.physicsBody?.affectedByGravity = false 
+0

謝謝你,你的回答解決了我的問題 – Ali