如何将碰撞检测设置到我想要的位置?

时间:2018-01-17 02:06:36

标签: ios swift collision-detection game-physics

我正在制作一个游戏,其中一个球(人)必须通过旋转圆圈(圆圈)中的一个开口并击中目标。我将碰撞检测设置到旋转圆圈然后我尝试让球(人)通过它不通过开口。我知道它与碰撞检测有关。另外我将circleOfRadius设置为半径,但我似乎无法为球传球打开。如果你能提供帮助,我很乐意听取你的意见。这是我的代码,它不是全部,它的重要性是什么。

import SpriteKit
import GameplayKit

class GameScene: SKScene, SKPhysicsContactDelegate {

    var circle  = SKSpriteNode()
    var guy     = SKSpriteNode()
    let guyCategory     :UInt32 = 0x1 << 0
    let circleCategory  :UInt32 = 0x1 << 1

    override func didMove(to view: SKView) {


        self.physicsWorld.contactDelegate = self

        scene?.anchorPoint = CGPoint(x: 0, y: 0)
        backgroundColor = UIColor.lightGray

        circle = SKSpriteNode(imageNamed: "Circle1")
        circle.position = CGPoint(x: self.frame.size.width / 2, y: 
        self.frame.size.height / 2)
        circle.physicsBody = SKPhysicsBody(circleOfRadius: 298 )
        circle.physicsBody?.isDynamic = false
        circle.physicsBody?.allowsRotation = true
        circle.physicsBody?.affectedByGravity = false
        circle.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat.pi * 2.0, duration: 7.0)), withKey: "rotatecircle")
self.addChild(circle)

        guy = SKSpriteNode(imageNamed: "Guy")
        guy.position = CGPoint(x: self.frame.size.width/2 , y:40)
        guy.name = "guy"
        guy.physicsBody = SKPhysicsBody(circleOfRadius: guy.size.width/2)
        guy.physicsBody?.isDynamic = false
        guy.physicsBody?.affectedByGravity = false
        self.addChild(guy)

        circle.physicsBody?.categoryBitMask = circleCategory
        circle.physicsBody?.collisionBitMask = targetCategory
        circle.physicsBody?.contactTestBitMask = targetCategory

        guy.physicsBody?.categoryBitMask = guyCategory
        guy.physicsBody?.collisionBitMask = targetCategory
        guy.physicsBody?.contactTestBitMask = targetCategory
    }

    func didBegin(_ contact: SKPhysicsContact) {
        let collision1:UInt32 = contact.bodyA.categoryBitMask

        if collision1 == targetCategory {
            backgroundColor = UIColor.green
        }
        else {
            backgroundColor = UIColor.red
        }
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        self.physicsWorld.gravity = CGVector(dx: 0 ,dy: 10);
        guy.physicsBody = SKPhysicsBody(circleOfRadius: guy.size.width / 2)
    }
    override func update(_ currentTime: TimeInterval) {

    }
}

1 个答案:

答案 0 :(得分:0)

这里的问题是您使用SKPhysicsBody(circleOfRadius: 298 )为整个圈子指定物理实体。这也包括你在圆圈中的洞,以便没有任何东西可以通过。您应该使用SKPhysicsbody类的纹理初始化器来复制圆形的形状并让孔不受影响。以下内容适合您:

circle = SKSpriteNode(texture: SKTexture(imageNamed: "Circle1"))
circle.physicsbody = SKPhysicsbody(texture: circle.texture!, size: CGSize(width: circle.frame.width, height: circle.frame.height))