我是SpriteKit和Swift的新手。花了太多时间尝试将位置/速度变化应用于didBeginContact中的主体,只读取Apple文档中的联系是只读的。修改碰撞中涉及的物体有什么好办法?
struct PhysicsCategory
{
static let None: UInt32 = 0
static let All: UInt32 = UInt32.max
static let LeftWall: UInt32 = 0b1
static let Food: UInt32 = 0b10
}
override func didMoveToView(view: SKView)
{
for(var i = 0; i < 10; ++i)
{
var temp = SKSpriteNode(color: UIColor(red: 0.0, green: 0.7, blue: 0.0, alpha: 1.0), size: CGSizeMake(size, size))
temp.position.x = self.scene!.size.width/2.0
temp.position.y = self.scene!.size.height/2.0
temp.physicsBody = SKPhysicsBody(rectangleOfSize: temp.size)
temp.physicsBody!.categoryBitMask = PhysicsCategory.Food
temp.physicsBody!.contactTestBitMask = PhysicsCategory.LeftWall
temp.physicsBody!.collisionBitMask = PhysicsCategory.None
temp.physicsBody!.velocity.dx = self.randomBetweenNumbers(0.0, secondNum: 0.5) - 0.25
temp.physicsBody!.velocity.dy = self.randomBetweenNumbers(0.0, secondNum: 0.5) - 0.25
self.addChild(temp)
}
}
func didBeginContact(contact: SKPhysicsContact)
{
if (contact.bodyA.categoryBitMask & PhysicsCategory.Food != 0) && (contact.bodyB.categoryBitMask & PhysicsCategory.LeftWall != 0)
{
contact.bodyA!.velocity.dx = 0.0
println("\(contact.bodyA.velocity.dx)") //isn't 0.0
}
}
答案 0 :(得分:0)
课外
let firstObjectCategory:UInt32 = 0x1 << 0
let secondObjectCategory:UInt32 = 0x1 << 1
var marker:Int= 0
在你的DidMoveToView
中 node1.physicsBody?.categoryBitMask = firstObjectCategory
node1.physicsBody?.contactTestBitMask = secondObjectCategory
if marker=1
{
node1.velocity.dx = 0.0
}else{
node1.velocity.dx = what you want
}
node2.physicsBody?.categoryBitMask = secondObjectCategory
node2.physicsBody?.contactTestBitMask = firstObjectCategory
测试两个物理机构之间的接触:
func didBeginContact(contact: SKPhysicsContact!)
{
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 & firstObjectCategory) != 0 && (secondBody.categoryBitMask & secondObjectCategory) != 0)
{
marker=1
}
}
我希望它能帮到你