Xcode Swift Collision无法正常工作

时间:2015-04-07 21:34:13

标签: ios swift sprite-kit skphysicsbody

我试图获得"英雄"与#34; wallGenerator"碰撞(生成墙壁)

但无论我做什么,它都不会发生碰撞。英雄将与地面发生碰撞,但不会碰撞墙壁,因为它会穿过它们。

以下是Hero和WallGenerator的代码

    hero.position = CGPointMake(70, movingGround.position.y + movingGround.frame.size.height/2 + hero.frame.size.height/2)
    hero.physicsBody = SKPhysicsBody(rectangleOfSize: hero.size)
    hero.physicsBody!.dynamic = true
    hero.physicsBody!.allowsRotation = false
    hero.physicsBody!.categoryBitMask = heroCategory
    hero.physicsBody!.collisionBitMask = heroCategory | wallCategory
    hero.physicsBody!.contactTestBitMask = wallCategory | heroCategory | groundCategory

    wallGenerator = CSWallGenerator(color: UIColor.clearColor(), size: view.frame.size)
    wallGenerator.position = view.center
    wallGenerator.physicsBody = SKPhysicsBody(edgeLoopFromRect : wallGenerator.frame)
    wallGenerator.physicsBody!.dynamic = false
    wallGenerator.physicsBody!.categoryBitMask = wallCategory
    wallGenerator.physicsBody!.collisionBitMask = wallCategory | heroCategory

CSWallGenerator代码

class CSWallGenerator: SKSpriteNode {

var generationTimer: NSTimer?

func startGeneratingWallsEvery(seconds: NSTimeInterval) {
    generationTimer = NSTimer.scheduledTimerWithTimeInterval(seconds, target: self, selector: "generateWall", userInfo: nil, repeats: true)


}

func generateWall() {
    var scale: CGFloat
    let rand = arc4random_uniform(2)
    if rand == 0 {
        scale = -1.0
    } else {
        scale = 1.0
    }

    let wall = CSWall()
    wall.position.x = size.width/2 + wall.size.width/2
    wall.position.y = scale * (kCSGroundHeight/2 + wall.size.height/2)
    addChild(wall)

}

}

1 个答案:

答案 0 :(得分:0)

您正在为wallgenerator设置物理主体,但实际添加到场景中的是cswall。 Cswall没有设置物理体。

尝试类似

的内容
wall.physicsBody = SKPhysicsBody(edgeLoopFromRect : wall.frame)

在generateWall函数中