两个物体之间的碰撞

Collision between two objects

我创建了一个简单的项目,但我遇到了冲突问题。

很简单(球移动和垂直线)但是没搞清楚球碰到线了怎么停

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

}

您的一个碰撞对象的 dynamic 属性 应设置为 true。否则碰撞将被忽略。设置好dynamic后,还需要设置affectedByGravityfalse,因为小球应该不会受到重力的影响。

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