iosmacosglkit

GLKit. How do I assign to a component of a GLKVector3


What is the correct way to assign to a field of a GLKVector3 (or 4)?

This fails: enter image description here

Which makes sense since .x and .z are getters. What is the workaround?


Solution

  • I believe that in Swift GLKVector3s are immutable, whether a var or a let. Use GLKVector3Make to create one with arbitrary Float values; subsequently generate new results to new instances.

    So:

    let ballLocation = GLKVector3Make(
         (locationInBallCoordinates.x - ballCentre.x) / ballRadius,
         0.0,
         (locationInBallCoordinates.y - ballCentre.y) / ballRadius)
    

    Or, if locationInBallCoordinates and ballCentre were already instances of GLKVector3 — and the y-to-z component switch that I hadn't noticed when I first wrote this answer weren't there — then:

    let ballLocation = 
        GLKVector3DivideScalar(
            GLKVector3Subtract(locationInBallCoordinates, ballCentre),
            ballRadius)
    

    It's probably easiest to unpack and repack to move ys into zs but you could also use a matrix multiply if you were desperate to keep it high level.