两个物体之间的碰撞

时间:2015-12-15 06:37:00

标签: ios swift sprite-kit skphysicsbody skscene

我创建了一个简单的项目但碰撞中遇到了问题。

这很简单(球移动和垂直线),但如果碰到线就没有弄清楚如何停球。

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")

}

1 个答案:

答案 0 :(得分:0)

您的一个碰撞对象dynamic属性应设置为true。否则将忽略碰撞。设置dynamic后,您还需要将affectedByGravity设置为false,因为球不应受重力影响。

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