本节学习目标
如何将屏幕2D坐标转换至3D游戏场景中去
oc 源码
代码语言:javascript复制- (SCNVector3)convertToScenOfPoint:(CGPoint)point
{
CGFloat Z_Far = 0.1;
CGFloat Screen_Aspect = [UIScreen mainScreen].bounds.size.width > 400 ? 0.3 : 0.0;
double Y = tan((double)(self.sceneView.pointOfView.camera.fieldOfView/180/2)*M_PI) * (double)(Z_Far-Screen_Aspect);
double X = tan((double)(self.sceneView.pointOfView.camera.fieldOfView/2/180)*M_PI) * (double)(Z_Far-Screen_Aspect) * (double)(self.view.bounds.size.width/self.view.bounds.size.height);
CGFloat alphaX = 2 * X / self.view.bounds.size.width;
CGFloat alphaY = 2 * Y / self.view.bounds.size.height;
float x = -(CGFloat)X point.x * alphaX;
float y = (CGFloat)Y - point.y * alphaY;
SCNVector3 target = SCNVector3Make((float)(x), (float)(y),(float)(-Z_Far));
SCNVector3 convertPoint = [self.sceneView.pointOfView convertVector:target toNode:self.sceneView.scene.rootNode];
NSLog(@"convertPoint X: %f,Y:%f,Z:%f", convertPoint.x, convertPoint.y, convertPoint.z);
return convertPoint;
}
swift
代码语言:javascript复制 /// 将屏幕上的点转化到3D场景中去
func convertToScenOf(point: CGPoint) -> SCNVector3{
let Z_Far:CGFloat = 0.1
var Screen_Aspect : CGFloat = UIScreen.main.bounds.size.width > 400 ? 0.3 : 0.0
// 计算屏幕边缘的距离
let Y = tan(Double(self.pointOfView!.camera!.fieldOfView/180/2)*Double.pi) * Double(Z_Far-Screen_Aspect)
let X = tan(Double(self.pointOfView!.camera!.fieldOfView/2/180)*Double.pi) * Double(Z_Far-Screen_Aspect) * Double(self.bounds.size.width/self.bounds.size.height)
let alphaX = 2 * CGFloat(X) / self.bounds.size.width
let alphaY = 2 * CGFloat(Y) / self.bounds.size.height
let x = -CGFloat(X) point.x * alphaX
let y = CGFloat(Y) - point.y * alphaY
let target = SCNVector3Make(Float(x), Float(y), Float(-Z_Far))
return self.pointOfView!.convertPosition(target, to:scene.rootNode)
}
注意
Z_Far:是要放置在屏幕后面多远的距离
上线应用ARFinger 即使用了此方式,欢迎各位下载试玩!