我做了一个游戏,它基本上有一个球、几个目标和桨。但是,我需要根据球与哪个目标相撞,只要它不低于最小速度或不超过最大速度,速度就会增加三倍、两倍或减半。
为此,我一起使用了 didBegin(contact) 函数并设置了不同的速度,如下面的代码所示:
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:我认为可能导致这种情况的一个建议是,速度矢量同时控制了球的角度(方向)和速度(我认为),因此当我设置速度时,没有考虑方向。如果这是原因,是否有可能在使弹跳逼真的同时将速度增加三倍/两倍/减半?