Chandan Shetty SP - 1 year ago 90
iOS Question

# Maths formula of cleaner way for bounding box logic?

Below I have written some bounding box logic which is a bit verbose. Is there a way to make it more readable, so the check looks cleaner and more concise?

func validatePosition(position:SCNVector3, forNode node:SCNNode) -> SCNVector3 {
var newPosition = position
var maxVector = SCNVector3Zero
var minVector = SCNVector3Zero

let success = self.actionDelegate?.getBoundingBox(&minVector, max: &maxVector)
guard success == true else {
return newPosition
}

if newPosition.x < minVector.x && newPosition.x < 0 {
newPosition.x = minVector.x
}

if newPosition.y < minVector.y && newPosition.y < 0 {
newPosition.y = minVector.y
}

if newPosition.z < minVector.z && newPosition.z < 0 {
newPosition.z = minVector.z
}

if newPosition.x > maxVector.x && newPosition.x > 0 {
newPosition.x = maxVector.x
}

if newPosition.y > maxVector.y && newPosition.y > 0 {
newPosition.y = maxVector.y
}

if newPosition.z > maxVector.z && newPosition.z > 0 {
newPosition.z = maxVector.z
}

return newPosition
}

Try this:

extension ClosedInterval {
func clamp(value : Bound) -> Bound {
return self.start > value ? self.start
: self.end < value ? self.end
: value
}
}

extension SCNVector3 {
func clamp(min min:SCNVector3, max: SCNVector3) -> SCNVector3 {
let x = (min.x...max.x).clamp(self.x)
let y = (min.y...max.y).clamp(self.y)
let z = (min.z...max.z).clamp(self.z)
return SCNVector3(x, y, z)
}
}

func validatePosition(position:SCNVector3, forNode node:SCNNode) -> SCNVector3 {
var newPosition = position
var maxVector = SCNVector3Zero
var minVector = SCNVector3Zero

let success = self.actionDelegate?.getBoundingBox(&minVector, max: &maxVector)
guard success == true else {
return newPosition
}

newPosition = position.clamp(min: minVector, max: maxVector)
return newPosition
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download