Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert between vector_float2 and CGPoint*?

What's the easiest/fastest way to convert between vector_float2 and CGPoint* in Objective-C?

Does Apple provide any built-in functionality for this kind of type conversion? I noticed in 2-3 places in sample apps they just call CGPointMake() etc. to make the conversion

Is it possible to simply cast a CGPoint* to vector_float2 and vice versa? Is it safe to do so?


Update: obviously the solution is:

vector_float2 v = (vector_float2){(float)point.x, (float)point.y};
CGPoint p = CGPointMake(v.x, v.y);

But this is cumbersome if you need to do so frequently, and more so if there's a C array of either vector_float2* or CGPoint*. So I'm looking for already-existing solutions or very simple alternatives that I may be overlooking.

like image 226
LearnCocos2D Avatar asked Jul 10 '15 14:07

LearnCocos2D


2 Answers

Example:

CGPoint p                   = CGPointMake(1.0f, 1.0f);
vector_float2 v             = simd_make_float2(p.x, p.y);
CGPoint x                   = CGPointMake(v[0], v[1]);
like image 36
Mojo66 Avatar answered Nov 10 '22 21:11

Mojo66


I tried to simply extend CGPoint but couldnt seem to import vector_float2; not even with the bridging header file.

// Doesn't work!!
extension CGPoint {
    init(vector: vector_float2)
    {
        self.x = CGFloat(vector.x)
        self.y = CGFloat(vector.y)
    }
}

You do have several options though. You can extend Float with a calculated var that returns a CGFloat and extend GKAgent2D to convert it's position to a CGPoint:

extension Float {
    var f: CGFloat { return CGFloat(self) }
}

extension GKAgent2D {
    var cgposition: CGPoint {
        return CGPoint(x: self.position.x.f, y: self.position.y.f)
    }
}

You can also extend CGPoint itself to accept two Float's:

extension CGPoint {
    init(x: Float, y: Float) {
        self.x = CGFloat(x)
        self.y = CGFloat(y)
    }
}

extension GKAgent2D {
    var cgposition: CGPoint {
         // Note that the ".f" is gone from the example above
        return CGPoint(x: self.position.x, y: self.position.y)
    }
}

In both cases, you can use it like this:

let agent = GKAgent2D()
let point = agent.cgposition
like image 86
Renan Paul Blanco Avatar answered Nov 10 '22 22:11

Renan Paul Blanco