2016-09-17 23 views
0

您好我是swift和OpenGL的新手。我以书面目标C以下的教程,我将其转换为雨燕2.0Swift - 如何更改只读属性的值

下面是代码

float radius = self.view.bounds.size.width/3; 
GLKVector3 center = GLKVector3Make(self.view.bounds.size.width/2, self.view.bounds.size.height/2, 0); 
GLKVector3 P = GLKVector3Subtract(touchPoint, center); 

P = GLKVector3Make(P.x, P.y * -1, P.z); 

float radius2 = radius * radius; 
float length2 = P.x*P.x + P.y*P.y; 

if (length2 <= radius2) 
    P.z = sqrt(radius2 - length2); 
else 
{ 
    P.z = radius2/(2.0 * sqrt(length2)); 
    float length = sqrt(length2 + P.z * P.z); 
    P = GLKVector3DivideScalar(P, length); 
} 

这是我的银行代码

let radius: CGFloat = self.view.bounds.size.width/3 
    let center: GLKVector3 = GLKVector3Make(Float(self.view.bounds.size.width/2), Float(self.view.bounds.size.height/2), 0.0) 
    var P: GLKVector3 = GLKVector3Subtract(touchPoint, center) 

    P = GLKVector3Make(P.x, P.y * -1, P.z) 

    let radius2 = radius * radius 
    let length = P.x * P.x + P.y * P.y 

    if(Float(length) <= Float(radius2)){ 
     P.z = sqrt(Float(radius2) - Float(length)) //the error is here 
    } else { 
     //other code 
    } 

我不能改变Pz的值,它表示

“不能分配属性:'z'是只能得到的属性”

预先感谢您

回答

0

你需要创建一个新的GLK3DVectorMake。似乎它被桥接在Swift中使用Struct。

结构是不可变的,除非它们在内部实现中发生变异。要克服的一个方法是创建一个具有正确属性的新GLK3DVectorMake。它是一个广泛使用的技术,用于修改CGRect,CGPoint和任何结构类型。

if(Float(length) <= Float(radius2)){ 
    let newz = sqrt(Float(radius2) - Float(length)) 
    P = GLKVector3Make(P.x, P.y * -1, newz) 
} 
+0

非常感谢 –