我想覆盖 SpriteKit 中的碰撞。
这个想法是我有一个在场景中弹跳的球。当 didBeginContact 检测到边缘和球之间的接触时,我希望球以随机的方向和速度反弹。
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
let kEdgeCollisionCategory:UInt32 = 0x1 << 1
let kSquareCollisionCategory:UInt32 = 0x1 << 2
override func didMoveToView(view: SKView) {
/* Setup your scene here */
// Physics world
self.physicsWorld.gravity = CGVectorMake(0.0, 0.0)
self.physicsWorld.contactDelegate = self
// Edge
let frameEdges = SKNode()
frameEdges.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
frameEdges.physicsBody?.categoryBitMask = kEdgeCollisionCategory
self.addChild(frameEdges)
// Sprite
var sprite = SKSpriteNode(imageNamed: "blue")
sprite.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(sprite.size.width, sprite.size.height))
sprite.physicsBody?.restitution = 1.0
sprite.physicsBody?.linearDamping = 0.0
sprite.physicsBody?.angularDamping = 0.0
sprite.physicsBody?.friction = 0.0
sprite.physicsBody?.dynamic = true
sprite.physicsBody?.categoryBitMask = kSquareCollisionCategory
sprite.physicsBody?.collisionBitMask = kEdgeCollisionCategory
sprite.physicsBody?.contactTestBitMask = kEdgeCollisionCategory
self.addChild(sprite)
}
func didBeginContact(contact: SKPhysicsContact) {
var firstBody:SKPhysicsBody?
var second:SKPhysicsBody?
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask) {
firstBody = contact.bodyA
secondBody = contact.bodyB
}
else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
var randomX = CGFloat(arc4random_uniform(UInt32(4))))
var randomY = CGFloat(arc4random_uniform(UInt32(4))))
if firstBody!.categoryBitMask == kSquareCollisionCategory && secondBody!.categoryBitMask == kEdgeCollisionCategory {
firstBody!.velocity = (CGVectorMake(firstBody!.velocity.dx * randomX, firstBody!.velocity.dy * randomY))
}
}
}