SKPhysicsBody没有在碰撞上弹跳

时间:2017-06-23 11:26:56

标签: swift3 sprite-kit skphysicsbody

我最初在屏幕上显示了一堆圆形节点。我希望圆圈在触摸屏幕边界时反转方向。然而,他们直接通过。这是我到目前为止的代码:

import Foundation
import GameKit

class CircleHolder : SKNode {
    private var myScene:SKScene?
    private var circles:[Circle] = [Circle]()

    init(scene:SKScene) {
        myScene = scene
        super.init()

        for _ in 1...100 {
            addCircle()
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func addCircle() {
        var circle = Circle()
        circle.position = self.randomPosition(circle: circle, size: myScene!.size)
        addChild(circle)
        circles.append(circle)
    }

    private func randomPosition(circle: Circle, size: CGSize) -> CGPoint {
        var point:CGPoint = CGPoint()
        point.x = randomRange(min: size.width / -2 + circle.getRadius(), max: size.width / 2 - circle.getRadius())
        point.y = randomRange(min: size.height / -2 + circle.getRadius(), max: size.height / 2 - circle.getRadius())

        return point
    }

    private func randomRange(min: CGFloat, max: CGFloat) -> CGFloat {
        assert(min < max)
        return CGFloat(arc4random()) / 0xFFFFFFFF * (max - min) + min
    }

    enum CollisionTypes: UInt32 {
        case circle = 1
        case wall = 2
    }

    func startPhysics() {
        self.physicsBody = SKPhysicsBody(edgeLoopFrom: myScene!.frame)
        self.physicsBody?.categoryBitMask = CollisionTypes.wall.rawValue
        self.physicsBody?.isDynamic = false

        for circle in circles {
            circle.physicsBody = SKPhysicsBody()
            circle.physicsBody?.affectedByGravity = false
            circle.physicsBody?.isDynamic = true

            circle.physicsBody?.friction = 0
            circle.physicsBody?.restitution = 1
            circle.physicsBody?.linearDamping = 0
            circle.physicsBody?.angularDamping = 0

            circle.physicsBody?.categoryBitMask = CollisionTypes.circle.rawValue
            circle.physicsBody?.collisionBitMask = CollisionTypes.wall.rawValue

            circle.physicsBody?.applyImpulse(CGVector(dx:100, dy:100))
        }
    }
}

0 个答案:

没有答案