Swift 2 PhysicsBody不工作

时间:2016-06-23 22:25:01

标签: swift2 physics skphysicsbody

我有一个代码,我在屏幕上漂浮着两个太空飞船,但它们无法突破屏幕顶部和座右铭。但他们可以飞过我的身边。我看了无数的网站,并做了一些不同类型的skphysicsbodys但没有一个帮助。 代码示例。

class GameScene: SKScene, SKPhysicsContactDelegate {

var player = SKSpriteNode(imageNamed: "spaceship.png")
var player2 = SKSpriteNode(imageNamed: "spaceship.png")
var timer = NSTimer()
var tapsValid:Bool?
var playerRight:Bool?
var playerChange:Bool?

override func didMoveToView(view: SKView) {

    let sceneBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
    sceneBody.friction = 0
    self.physicsBody = sceneBody

    physicsWorld.gravity = CGVector(dx: 0.0, dy: 0.0)


    tapsValid = true
    playerRight = true

    self.scene?.backgroundColor = UIColor.whiteColor()

    player.position = CGPointMake(self.size.width / 2, self.size.height / 1.8 + 280)
    player.physicsBody = SKPhysicsBody(rectangleOfSize: player.size)
    player.physicsBody?.dynamic = false
    player.physicsBody?.affectedByGravity = false
    player.physicsBody?.restitution = 1
    player.physicsBody?.friction = 0
    player.physicsBody?.linearDamping = 0
    player.physicsBody?.angularDamping = 0

    player2.position = CGPointMake(self.size.width / 2, self.size.height / 14)
    player2.physicsBody = SKPhysicsBody(rectangleOfSize: player2.size)
    player2.physicsBody?.affectedByGravity = false
    player2.physicsBody?.dynamic = false
    player2.physicsBody?.restitution = 1
    player2.physicsBody?.friction = 0
    player.physicsBody?.linearDamping = 0
    player.physicsBody?.angularDamping = 0

    self.addChild(player)

    self.addChild(player2)

任何人都可以帮助我。我只是想在屏幕边缘添加物理。谢谢,

1 个答案:

答案 0 :(得分:0)

您应该为节点定义colliderTypes和类别。这样你可以检查看什么

enum ColliderType: UInt32 {
    case Spaceship = 0
    case CornerCategory = 1
}

self.physicsBody!.categoryBitMask = ColliderType.CornerCategory.rawValue


player.physicsBody?.contactTestBitMask =  ColliderType.CornerCategory.rawValue
player2.physicsBody?.contactTestBitMask = ColliderType.CornerCategory.rawValue

func didBeginContact(contact: SKPhysicsContact) {
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
        //If it is true. Means that bodyA is the spaceship. Because it's 0
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    }else{
        //Either way. firstBody will always be the spaceship
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }

    if firstBody.categoryBitMask == ColliderType. Spaceship.rawValue && secondBody.categoryBitMask == ColliderType.CornerCategory.rawValue{
        //means that Spaceship and wall touches
        print("Spaceship hits wall")

        }
}