当我调用didbegincontact
函数时,此函数应按增量宽度增加蛇的大小。但是,当进行联系时,它会调用该函数一次,然后再也不会再调用它。我不确定为什么在接触时它不会继续增加我的蛇的大小
func increaseSnakeSize(increment: CGFloat){
snake.snake1.size = CGSizeMake(snake.size.width + increment, snake.size.height + increment)
snake.snake2.size = CGSizeMake(snake.size.width + increment, snake.size.height + increment)
snake.snake3.size = CGSizeMake(snake.size.width + increment, snake.size.height + increment)
print(snake.snake1.size)
}
// didBeginContact
if (firstBody.categoryBitMask & physicsCategory.snakeCategory == 0b1) && (secondBody.categoryBitMask & physicsCategory.foodCategory == 0b10 ){
score++
scoreLabel.text = "\(score)"
food.removeFromParent()
addFood()
increaseSnakeSize(2)
}
答案 0 :(得分:0)
看起来你没有增加你的蛇的PhysicsBody
。你的应用程序中是否有物理命中框?如果没有,我会建议打开它们,看看它是如何表现的。在您的查看代码中,执行:self.showsPhysics = true
答案 1 :(得分:0)
当初始接触时,蛇长到22x22,但其物理体的大小保持在20x20。一个解决方案是创建一个新的物理主体,其初始接触为22x22,下一次为24x24,之后为接触为26x26,...例如,
func increaseSnakeSize (increment: CGFloat) {
snake.snake1.size = CGSizeMake(snake.size.width + increment, snake.size.height + increment)
// Create a new, larger physics body that matches the size of the snake
snake.snake1.physicsBody = SKPhysicsBody(circleOfRadius:snake.size.width/2.0)
// Configure the physics body's property accordingly
snake.snake1.physicsBody?.affectedByGravity = false
...
}
另一个潜在问题是contact.bodyA
和contact.bodyB
的顺序可以在联系人之间切换。您将需要检查蛇是否是第一个身体,食物是第二个,食物是第一个身体和蛇是第二个身体。这是一个例子
func didBeginContact (contact: SKPhysicsContact) {
var firstBody, 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 == physicsCategory.snakeCategory) && (secondBody.categoryBitMask == physicsCategory.foodCategory ) {
// Increase size of the snake
}
或
let bitMask = contact.BodyA.categoryBitMask | contact.BodyB.categoryBitMask
if bitMask == physicsCategory.snakeCategory | physicsCategory.foodCategory {
// Increase size of the snake
}