dugla dugla - 7 months ago 51
iOS Question

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

are getters. What is the workaround?


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.


let ballLocation = GLKVector3Make(
     (locationInBallCoordinates.x - ballCentre.x) / ballRadius,
     (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 = 
        GLKVector3Subtract(locationInBallCoordinates, ballCentre),

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.