【问题标题】:Collision between two objects两个物体之间的碰撞
【发布时间】:2015-12-15 06:36:59
【问题描述】:

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

这很简单(球移动和垂直线),但不知道如果球碰到线如何停止。

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

}

【问题讨论】:

  • 所附链接中的项目供您参考:link
  • 如果您将physicsBody? 替换为physicsBody! 会有所不同

标签: ios swift sprite-kit skphysicsbody skscene


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    相关资源
    最近更新 更多