Last active
June 26, 2020 12:49
-
-
Save MrLotU/a682443ffae1e2ac6055c3b1ffefc196 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SceneKit | |
// Part 1: Distance | |
extension SCNVector3 { | |
func distance(to vector: SCNVector3) -> Float { | |
return simd_distance(simd_float3(self), simd_float3(vector)) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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