2015-10-15 13 views
4

是否可以將一個物理體放置在精靈上?我只想要我的精靈節點的某個部分有碰撞檢測,而不是整個圖像。是否有可能將物理體定位到雪碧的一部分?

繼承人我的物理身體

physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: CGFloat(54.0), height: CGFloat(100.0))) 

,但我想在物理學體的節點,它通常被放置在節點的中間的頂部位置。

回答

4

您可以嘗試創建與SKPhysicsBody尺寸相同的較小SKSpriteNode,並將較大的SKSpriteNode作爲子項添加到較小的一個。根據需要更改較大的位置。例如

override func didMoveToView(view: SKView) { 

    let smallerSprite = SKSpriteNode(color: UIColor.redColor(), size: CGSizeMake(30, 30)) 
    smallerSprite.physicsBody = SKPhysicsBody(rectangleOfSize: smallerSprite.size) 
    smallerSprite.position = CGPointMake(100, 400) 
    self.addChild(smallerSprite) 

    let largerSprite = SKSpriteNode(color: UIColor(white: 0.5, alpha: 0.5), size: CGSizeMake(100, 100)) 
    largerSprite.position = CGPointMake(-10, -10) 
    smallerSprite.addChild(largerSprite) 

    self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame) 

} 
+1

這實際上對我來說是完美的:)因爲我的圖像物理體的變化取決於核心運動acceleration.x。所以根據位置我可以改變較大的精靈位置相對於我需要物理體的位置。 我想投這個答案,但目前還不足以做到這一點:( 但非常感謝你的快速反應rakeshbs,使我的一天減少很多壓力。希望你有一個很好的休息一天! Rachel –

3

作爲除了Rakesh的回答......不同的方法來得到相同的結果是使用 + bodyWithRectangleOfSize:center: method。就像這樣:

override func didMoveToView(view: SKView) { 

let sprite = SKSpriteNode(color: SKColor.whiteColor(), size: CGSize(width: 100.0, height: 100.0)) 

//I assume that you have initialized view and scene properly. If so, this will position a sprite in the middle of the screen. 
sprite.position = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame)) 
var physicsBodySize:CGSize = CGSize(width: sprite.size.width, height: 30.0) //Create a size here. You can play with height parameter. 

sprite.physicsBody = 
    SKPhysicsBody(rectangleOfSize: physicsBodySize, center: CGPoint(x: 0.0, y: sprite.size.height/2.0 - physicsBodySize.height/2.0)) 

//Not needed, just set to restrict that sprite can't off screen 
sprite.physicsBody?.affectedByGravity = false 
self .addChild(sprite) 

} 

結果:

enter image description here

如果試圖物理學體的高度變化到10.0,你會得到這樣的事情:

enter image description here

+0

謝謝你的迴應Whirlwind!rakeshbs答案對我來說最合適只是因爲我需要根據核心運動acceleration.x位置改變物理體的x和y位置,但是我知道我會最絕對需要在我的另一個項目。 希望你有一個偉大的休息一天,並再次感謝您花時間回答我的問題! Rachel –