2015-09-30 59 views
4

Here是我遇到的問題的視頻。正如你在視頻中看到的那樣,我移動一個灰色的球試圖碰撞一個紅色的球。當兩個物體發生碰撞時不會發生彈跳,紅色球就會移動。我試着玩弄紅球的密度,比如使紅球密度爲0.00001。碰撞行爲沒有區別。當拖動一個對象與Sprite Kit中的另一個對象發生衝突時,不會發生彈跳

如何更改碰撞行爲以便彈跳?

這裏是灰球的特性:

func propertiesGrayBall() { 
    gray = SKShapeNode(circleOfRadius: frame.width/10) 
    gray.physicsBody = SKPhysicsBody(circleOfRadius: frame.width/10) 
    gray.physicsBody?.affectedByGravity = false 
    gray.physicsBody?.dynamic = true 
    gray.physicsBody?.allowsRotation = false 
    gray.physicsBody?.restitution = 1 
} 

這裏是紅球的特性:

func propertiesRedBall { 
    let redBall = SKShapeNode(circleOfRadius: self.size.width/20 
    redBall.physicsBody = SKPhysicsBody(self.size.width/20) 
    redBall.physicsBody?.affectedByGravity = false 
    redBall.physicsBody?.dynamic = true 
    redBall.physicsBody?.density = redBall.physicsBody!.density * 0.000001 
    redBall.physicsBody?.allowsRotation = false 
    redBall.physicsBody?.restitution = 1 
} 

這裏是我移動灰球。

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { 
    if fingerIsOnGrayBall { 
     let touch = touches.first 
     var position = touch!.locationInView(self.view) 
     position = self.convertPointFromView(position) 
     grayBall.position = position 
    } 
} 

主要編輯 球原本附件。我刪除了它們來簡化問題。這就是爲什麼這些評論可能與代碼無關。

+1

您能告訴我們灰色bal我和黑人?那裏可能有東西不允許它響應物理碰撞。 – Gliderman

+0

@Gliderman我剛剛更新了代碼!感謝您的答覆。 – Sami

+1

有趣的是,你說把賠償金改爲1並沒有什麼不同。您是否嘗試將恢復原狀設置爲true,然後執行blackBall.physicsBody?.usePreciseCollisionDetection = true?你很快移動球,所以也許可以解決這個問題。 – theprole

回答

3

如果通過直接或用SKAction設置其位置來移動節點(帶有物理體),該節點將不會成爲物理模擬的一部分。相反,您應該通過施加力/衝動或設置其速度來移動節點。下面是如何做到這一點的例子:

首先,定義一個變量來存儲觸摸的位置

class GameScene: SKScene { 
    var point:CGPoint? 

然後,從您的代碼刪除下面的語句

redBall.physicsBody?.density = redBall.physicsBody!.density * 0.000001 

最後,添加以下觸摸處理程序

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

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

     let node = nodeAtPoint(location) 
     if (node.name == "RedBall") { 
      point = location 
     } 
    } 
} 

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

    for touch in touches { 
     let location = touch.locationInNode(self) 
     if point != nil { 
      point = location 
     } 
    } 
} 

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { 
    point = nil 
} 

override func update(currentTime: CFTimeInterval) { 
    if let location = point { 
     let dx = location.x - redBall.position.x 
     let dy = location.y - redBall.position.y 
     let vector = CGVector(dx: dx*100, dy: dy*100) 
     redBall.physicsBody?.velocity = vector 
    } 
} 
相關問題