Skip to content

Instantly share code, notes, and snippets.

@MrLotU
Last active June 26, 2020 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MrLotU/a682443ffae1e2ac6055c3b1ffefc196 to your computer and use it in GitHub Desktop.
Save MrLotU/a682443ffae1e2ac6055c3b1ffefc196 to your computer and use it in GitHub Desktop.
import SceneKit
// Part 1: Distance
extension SCNVector3 {
func distance(to vector: SCNVector3) -> Float {
return simd_distance(simd_float3(self), simd_float3(vector))
}
}
import SceneKit
// Part 2: Angle
extension SCNVector3 {
/// Calculate the magnitude of this vector
var magnitude:SCNFloat {
get {
return sqrt(dotProduct(self))
}
}
/**
Calculate the dot product of two vectors
- parameter vectorB: Other vector in the calculation
*/
func dotProduct(_ vectorB:SCNVector3) -> SCNFloat {
return (x * vectorB.x) + (y * vectorB.y) + (z * vectorB.z)
}
/**
Calculate the angle between two vectors
- parameter vectorB: Other vector in the calculation
*/
func angleBetweenVectors(_ vectorB:SCNVector3) -> SCNFloat {
//cos(angle) = (A.B)/(|A||B|)
let cosineAngle = (dotProduct(vectorB) / (magnitude * vectorB.magnitude))
return SCNFloat(acos(cosineAngle))
}
}
import SceneKit
// Part 3: Rotating weapons
/// Changes the node's orientation so that its local forward vector points toward the specified location.
myWeapon.look(at: targetLocationVector)
// https://developer.apple.com/documentation/scenekit/scnnode/2867394-look
/// Changes the node's orientation so that the specified forward vector points toward the specified location.
myWeapon.look(at: targetLocationVector, up: upLocationVector, localFront: localFrontVector)
// https://developer.apple.com/documentation/scenekit/scnnode/2867396-look
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment