简体   繁体   中英

Collision between two objects

I have created a simple project but I have a problem in the collisions.

It's simple (ball moving and vertical line) but didn't figure out how to stop the ball if it is touched the line.

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

}

One of your collided objects's dynamic property should be set to true . Otherwise the collision will be ignored. After setting dynamic , you also need to set affectedByGravity to false because the ball should not be affected by the gravity.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM