我做了一个基本上有一个球和几个目标和桨的游戏。然而,我需要根据球碰撞的目标来做到这一点,只要速度不低于最低速度或高于最高速度,速度就会增加三倍,加倍或减半。
为此,我一起使用了didBegin(联系人)功能并设置了不同的速度,如下面的代码所示:
extension CGVector {
var speed: CGFloat {
return hypot(dx, dy)
}
static func > (lhs: CGVector, rhs: CGVector) -> Bool {
return lhs.speed > rhs.speed
}
static func < (lhs: CGVector, rhs: CGVector) -> Bool {
return lhs.speed < rhs.speed
}
static func * (vector: CGVector, multiplier: CGFloat) -> CGVector {
return CGVector(dx: vector.dx * multiplier, dy: vector.dy * multiplier)
}
static func / (vector:CGVector, divider:CGFloat) -> CGVector {
return CGVector(dx: vector.dx / divider, dy: vector.dy / divider)
}
}
func didBegin(_ contact: SKPhysicsContact) {
var firstBody = SKPhysicsBody()
var secondBody = SKPhysicsBody()
let ballNode = self.childNode(withName: ballName)
let minSpeed = self.initialSpeed / 2
let maxSpeed = self.initialSpeed * 3
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if firstBody.categoryBitMask == ballBitmask && secondBody.categoryBitMask == drainBitmask {
endGame()
Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(GameScene.showLeaderboard), userInfo: nil, repeats: false)
} else if firstBody.categoryBitMask == ballBitmask && secondBody.categoryBitMask == target1Bitmask {
let currentSpeed = ballNode?.physicsBody?.velocity
score += 20
self.vc.scoreLabel.text = "Score: \(score)"
if currentSpeed == maxSpeed {
ballNode?.physicsBody?.velocity = currentSpeed!
} else if (currentSpeed! * 2) > maxSpeed {
ballNode?.physicsBody?.velocity = maxSpeed
} else if (currentSpeed! * 2) < maxSpeed {
ballNode?.physicsBody?.velocity = currentSpeed! * 2
}
} else if firstBody.categoryBitMask == ballBitmask && secondBody.categoryBitMask == target2Bitmask {
let currentSpeed = ballNode?.physicsBody?.velocity
score += 10
self.vc.scoreLabel.text = "Score: \(score)"
if currentSpeed == minSpeed {
ballNode?.physicsBody?.velocity = currentSpeed!
} else if (currentSpeed! / 2) > minSpeed {
ballNode?.physicsBody?.velocity = currentSpeed! / 2
} else if (currentSpeed! / 2) < minSpeed {
ballNode?.physicsBody?.velocity = minSpeed
}
} else if firstBody.categoryBitMask == ballBitmask && secondBody.categoryBitMask == target3Bitmask {
let currentSpeed = ballNode?.physicsBody?.velocity
score += 30
self.vc.scoreLabel.text = "Score: \(score)"
if currentSpeed == maxSpeed {
ballNode?.physicsBody?.velocity = currentSpeed!
} else if (currentSpeed! * 3) > maxSpeed {
ballNode?.physicsBody?.velocity = maxSpeed
} else if (currentSpeed! * 3) < maxSpeed {
ballNode?.physicsBody?.velocity = currentSpeed! * 3
}
}
我的问题是有时候当球与目标碰撞时会以一种非常奇怪和不切实际的方式反弹,有时只会出现故障(请查看下面的链接,看一下显示我的意思的短片)
注意:进入视频后2/3秒就是一个奇怪的反弹发生的例子
https://drive.google.com/open?id=0BxgQmn_JruJ_aUU2dVBoVlprV0k
为什么会发生这种情况,更重要的是我该如何解决?
PS:我认为可能造成这种情况的一个建议是,速度矢量控制球的角度(方向)和速度(我认为),因此当我设定速度时,方向是'n'考虑到了。如果这是原因,是否可以将速度增加三倍/两倍/一半,同时仍能使反弹变得逼真?