在我的游戏中,我需要比较碰撞时的2种速度。两种速度都采用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
}
由于
答案 0 :(得分:4)
矢量的“速度”实际上是矢量描述的三角形的斜边。试试这个:
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
想象为直角三角形的两边,则向量的长度是斜边(记住Pythagorus) - 这就是hypot
返回的内容。
通过上面的扩展程序,<
和>
运算符现在比较CGVector
对象的速度(您可以愉快地重命名length
)。