我想在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))
}
}
}
答案 0 :(得分:0)
接触后,您可以根据球的当前矢量向球施加力或冲击力。例如,在接触球时,球的矢量是(30,-20)。此示例向量转换为向右和向下移动的球。然后,您可以应用一个新的矢量,使球向左和向上移动(-20,25)。您可以使用arc4random
设置新值或设置静态值。
如果您需要,请阅读物理机构using vectors。
答案 1 :(得分:0)
你的问题在这里,
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask) {
firstBody = contact.bodyA
secondBody = contact.bodyB
}
else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
这意味着第一个主体具有kEdgeCollisionCategory的categoryBitMask,第二个主体具有kSquareCollisionCategory的categoryBitMask。所以改成这个,
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask) {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
else {
firstBody = contact.bodyA
secondBody = contact.bodyB
}
要获得随机数,请使用
int minSpeed = 1;
int maxSpeed = 20;
int randNum = rand() % (max-min) + min;
然后对所需的身体施加冲动。