在我的游戏中,我需要比较碰撞时的两种速度。两种速度均为CGVector(dx:,dy :)格式。但是Swift 3不允许我使用'>'和'
func didBegin(_ contact: SKPhysicsContact) {
var firstBody = SKPhysicsBody()
var secondBody = SKPhysicsBody()
let ballNode = self.childNode(withName: ballName)
let defaultSpeedX:CGFloat = 100
let defaultSpeedY:CGFloat = -100
let maxSpeed = CGVector(dx: defaultSpeedX * 3, dy: defaultSpeedY * 3)
let minSpeed = CGVector(dx: defaultSpeedX / 2 , dy: defaultSpeedY / 2)
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()
} else if firstBody.categoryBitMask == ballBitmask && secondBody.categoryBitMask == target1Bitmask {
score += 20
self.vc.scoreLabel.text = "Score: \(score)"
let currentSpeedX = ballNode?.physicsBody?.velocity.dx
let currentSpeedY = ballNode?.physicsBody?.velocity.dy
let speedDouble = CGVector(dx: currentSpeedX! * 2, dy: currentSpeedY! * 2)
if ballNode?.physicsBody?.velocity == maxSpeed {
ballNode?.physicsBody?.velocity = maxSpeed
} else if speedDouble < maxSpeed {
ballNode?.physicsBody?.velocity = speedDouble
} else if speedDouble > maxSpeed {
ballNode?.physicsBody?.velocity = maxSpeed
}
谢谢
最佳答案
向量的“速度”实际上是向量描述的三角形的斜边。试试这个:
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
}
}
let aaa = CGVector(dx: 10, dy: 10)
let bbb = CGVector(dx: 13, dy: 12)
print(aaa > bbb)
有了此扩展名后,您会发现现有代码
} else if speedDouble < maxSpeed {
将会编译。它是如何工作的?嗯,作为矢量的速度由两个部分定义-水平速度
dx
和垂直速度dy
。如果您将dx
和dy
想象为一个直角三角形的两侧,则向量的长度就是斜边(记住毕达哥拉斯)-这就是hypot
返回的内容。通过上面的扩展,
<
和>
运算符现在可以比较CGVector
对象的速度(您可以很高兴地重命名length
)。