我一直在开发一款游戏,每当我的测试节点与我的检查节点接触时,都必须执行一次测试。由于这两个节点是唯一将在游戏中检查冲突的节点,我决定使用这种方法来启动我的测试。
问题是,当两个节点物理交叉时,我一直难以使冲突正常工作。
当前代码将移动测试方块,直到它到达检查方块,但现在当它们相遇时,什么都不会发生。
我是不是错过了什么?任何帮助都将不胜感激。谢谢
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var test:SKSpriteNode!
var testTexture = SKTexture(imageNamed: "redsquare.png")
var check:SKSpriteNode!
var checkTexture = SKTexture(imageNamed: "bluesquare.png")
var moving:SKNode!
let testCategory: UInt32 = 1 << 0
let checkCategory: UInt32 = 1 << 2
override func didMoveToView(view: SKView) {
/* Setup your scene here */
self.physicsWorld.gravity = CGVectorMake(0.0, 0.0)
self.physicsWorld.contactDelegate = self
moving = SKNode()
self.addChild(moving)
//create test block
test = SKSpriteNode(texture: testTexture)
test.xScale = 0.1
test.yScale = 0.1
test.position = CGPointMake(0, self.frame.height - test.size.height)
test.physicsBody = SKPhysicsBody(rectangleOfSize: test.size)
test.physicsBody?.dynamic = false
test.physicsBody?.categoryBitMask = testCategory
test.physicsBody?.collisionBitMask = checkCategory
test.physicsBody?.contactTestBitMask = checkCategory
self.addChild(test)
//creates check block
check = SKSpriteNode(texture: checkTexture)
check.xScale = 0.1
check.yScale = 0.1
check.position = CGPointMake(self.frame.width, self.frame.height - check.size.height)
check.physicsBody = SKPhysicsBody(rectangleOfSize: check.size)
check.physicsBody?.dynamic = false
check.physicsBody?.categoryBitMask = checkCategory
check.physicsBody?.collisionBitMask = testCategory
check.physicsBody?.contactTestBitMask = testCategory
self.addChild(check)
// move action
let actionMove = SKAction.moveToX(self.frame.width, duration: 1.5)
let actionMoveDone = SKAction.moveToX(0, duration: 0)
let moveForever = SKAction.repeatActionForever(SKAction.sequence([actionMove,actionMoveDone]))
test.runAction(moveForever)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch: AnyObject in touches {
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
func didBeginContact(contact: SKPhysicsContact) {
// help here!
var firstBody:SKPhysicsBody
var secondBody:SKPhysicsBody
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask){
firstBody = contact.bodyA
secondBody = contact.bodyB
}
else{
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if((firstBody.categoryBitMask & testCategory) != 0 && (secondBody.categoryBitMask & checkCategory) != 0){
println("contact!")
}
}
}
根据苹果的文档,dynamic
属性控制基于体积的物体是否受到重力、摩擦力、与其他物体的碰撞以及直接应用于物体的力或脉冲的影响。
动态属性:默认值为true。如果该值为false,则物理实体将忽略所有作用于它的力和脉冲。在基于边缘的实体;它们自动是静态的。
因此,将dynamic
属性设置为true。
node.physicsBody?.dynamic = true
有关详细信息:https://developer.apple.com/library/prerelease/ios/documentation/SpriteKit/Reference/SKPhysicsBody_Ref/index.html#//apple_ref/occ/instp/SKPhysicsBody/