这个view主要展示在ARKit中点击2d界面如何映射到3d空间。
ar空间中有一杯咖啡,点击屏幕如果点中咖啡杯,咖啡杯会变色,如果点中现实中的桌子,咖啡杯会移动到桌子上,如果点击的地方不是杯子又没有桌子这样的平面,杯子会漂浮在前方0.7米的空中。
我们将使用下面三个方法:
SCNSceneRenderer
- (NSArray<SCNHitTestResult *> *)hitTest:(CGPoint)point options:(NSDictionary<SCNHitTestOption, id> *)options;
//从屏幕中一点,视线方向发出一条射线,返回射线击中的所有3D对象
ARSCNView
- (NSArray<ARHitTestResult *> *)hitTest:(CGPoint)point types:(ARHitTestResultType)types;
//从屏幕中一点,视线方向发出一条射线,返回射线击中的AR锚
SCNSceneRenderer
- (SCNVector3)unprojectPoint:(SCNVector3)point;
//屏幕中一点在3D空间的映射
首先我们把咖啡杯加入场景并给这个节点起个名字
SCNScene *scene = [SCNScene sceneNamed:@"art.scnassets/cup/cup.scn"];
cupNode=scene.rootNode.childNodes[0];
cupNode.position = SCNVector3Make(0, -0.3,-0.5);
cupNode.name=@"cup";
[sceneView.scene.rootNode addChildNode:cupNode];
当点击屏幕的时候,我们首先检测是否点中咖啡杯。
UITouch *touch=[touches anyObject];
CGPoint point = [touch locationInView:[touch view]];
NSArray *arr=[sceneView hitTest:point options:nil];
if (arr.count>0) {
SCNHitTestResult *node=[arr objectAtIndex:0];
if ([node.node.name isEqualToString:@"cup"]) {
//点中咖啡执行变色
[self changeColor];
return;
}
}
我们通过加一个环境光的方式让咖啡杯变色
-(void)changeColor{
if (lightNode==nil) {
SCNLight *light=[SCNLight light];
light.type=SCNLightTypeOmni;
light.color=[UIColor blueColor];
lightNode=[SCNNode node];
lightNode.position=SCNVector3Make(0, 0, 100);
lightNode.light=light;
}
if (lightNode.parentNode==nil) {
[sceneView.scene.rootNode addChildNode:lightNode];
}else{
[lightNode removeFromParentNode];
}
}
如果没有击中咖啡杯,我们检测是否击中检测到的平面,比如桌面、地面等等。
NSArray *arr1=[sceneView hitTest:point types:ARHitTestResultTypeExistingPlane];
if (arr1.count>0) {
//击中一个平面,找到平面上击中点的坐标
ARHitTestResult *plane=[arr1 objectAtIndex:0];
SCNVector3 planePos=SCNVector3Make(plane.worldTransform.columns[3].x, plane.worldTransform.columns[3].y, plane.worldTransform.columns[3].z);
//让咖啡杯移动到那一点
[self cupMoveTo:planePos];
}
茶杯移动
-(void)cupMoveTo:(SCNVector3) position{
CABasicAnimation *animation=[CABasicAnimation animationWithKeyPath:@"transform.translation"];
animation.toValue=[NSValue valueWithSCNVector3:position];
animation.removedOnCompletion=NO;
animation.duration=2;
animation.fillMode=kCAFillModeForwards;
[cupNode addAnimation:animation forKey:@"move"];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
cupNode.position= position;
});
}
如果没有击中咖啡杯,也没有击中检测到的平面,我们让咖啡移动到,点击处前方0.7米的空中。
-(SCNVector3)worldPositionFromScreenPosition:(CGPoint)position{
ARFrame *frame = sceneView.session.currentFrame;
SCNVector3 cameraPos=SCNVector3Make(frame.camera.transform.columns[3].x, frame.camera.transform.columns[3].y, frame.camera.transform.columns[3].z);
SCNVector3 positionVec = SCNVector3Make(position.x, position.y,1.0);
SCNVector3 screenPosOnFarClippingPlane = [sceneView unprojectPoint:positionVec];
//rayDirection 为射线的方向向量
SCNVector3 rayDirection=SCNVector3Make(screenPosOnFarClippingPlane.x-cameraPos.x,screenPosOnFarClippingPlane.y-cameraPos.y,screenPosOnFarClippingPlane.z-cameraPos.z);
float leng=sqrtf(rayDirection.x * rayDirection.x + rayDirection.y * rayDirection.y + rayDirection.z * rayDirection.z);
rayDirection=SCNVector3Make(rayDirection.x/leng,rayDirection.y/leng,rayDirection.z/leng);
//返回 rayDirection方向上,相机前方0.7米处坐标
return [self getNewPointLinePoint:cameraPos lineVector:rayDirection distance:0.7];
}
getNewPointLinePoint 返回已知直线L过点m(m1,m2,m3),且方向向量为VL(v1,v2,v3)求与m距离d的点n的坐标
-(SCNVector3)getNewPointLinePoint:(SCNVector3)linePoint
lineVector:(SCNVector3)lineVector
distance:(float)distance{
float vpt=(lineVector.x*lineVector.x+lineVector.y*lineVector.y+lineVector.z*lineVector.z);
if (vpt==0) {
return {FLT_MAX,FLT_MAX,FLT_MAX};
}
float t=pow(distance*distance/vpt,0.5);
float x=linePoint.x+lineVector.x*t;
float y=linePoint.y+lineVector.y*t;
float z=linePoint.z+lineVector.z*t;
return SCNVector3Make(x,y,z);
}
完整代码
#import "ARHitTestResultViewController.h"
@interface ARHitTestResultViewController ()<ARSCNViewDelegate>{
IBOutlet ARSCNView *sceneView;
SCNNode *lightNode;
SCNNode *cupNode;
BOOL isMoving;
}
@end
@implementation ARHitTestResultViewController
- (void)viewDidLoad {
[super viewDidLoad];
sceneView.delegate = self;
SCNScene *scene = [SCNScene sceneNamed:@"art.scnassets/candle/candle.scn"];
cupNode=scene.rootNode.childNodes[0];
cupNode.position = SCNVector3Make(0, -0.3,-0.5);
cupNode.name=@"cup";
// Set the scene to the view
[sceneView.scene.rootNode addChildNode:cupNode];
isMoving = false;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// Create a session configuration
ARWorldTrackingConfiguration *configuration = [ARWorldTrackingConfiguration new];
configuration.planeDetection = ARPlaneDetectionHorizontal;
// Run the view's session
[sceneView.session runWithConfiguration:configuration];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
// Pause the view's session
[sceneView.session pause];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// NSLog(@"touch the screen");
UITouch *touch=[touches anyObject];
CGPoint point = [touch locationInView:[touch view]];
NSArray *arr=[sceneView hitTest:point options:nil];
if (arr.count>0) {
SCNHitTestResult *node=[arr objectAtIndex:0];
NSLog(@"nodename %@",node.node.name);
if ([node.node.name isEqualToString:@"cup"]) {
[self changeColor];
return;
}
}
NSArray *arr1=[sceneView hitTest:point types:ARHitTestResultTypeExistingPlane];
if (arr1.count>0) {
NSLog(@"hit plane right");
ARHitTestResult *plane=[arr1 objectAtIndex:0];
SCNVector3 planePos=SCNVector3Make(plane.worldTransform.columns[3].x, plane.worldTransform.columns[3].y, plane.worldTransform.columns[3].z);
[self cupMoveTo:planePos];
return;
}
SCNVector3 planePos=[self worldPositionFromScreenPosition:point];
[self cupMoveTo:planePos];
}
-(void)changeColor{
if (lightNode==nil) {
SCNLight *light=[SCNLight light];
light.type=SCNLightTypeOmni;
light.color=[UIColor blueColor];
lightNode=[SCNNode node];
lightNode.position=SCNVector3Make(0, 0, 100);
lightNode.light=light;
}
if (lightNode.parentNode==nil) {
[sceneView.scene.rootNode addChildNode:lightNode];
}else{
[lightNode removeFromParentNode];
}
}
-(void)cupMoveTo:(SCNVector3) position{
if (isMoving){
return;
}
isMoving = true;
CABasicAnimation *animation=[CABasicAnimation animationWithKeyPath:@"transform.translation"];
animation.toValue=[NSValue valueWithSCNVector3:position];
animation.removedOnCompletion=NO;
animation.duration=2;
animation.fillMode=kCAFillModeForwards;
[cupNode addAnimation:animation forKey:@"move"];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
cupNode.position= position;
isMoving=false;
});
}
-(SCNVector3)worldPositionFromScreenPosition:(CGPoint)position{
ARFrame *frame = sceneView.session.currentFrame;
SCNVector3 cameraPos=SCNVector3Make(frame.camera.transform.columns[3].x, frame.camera.transform.columns[3].y, frame.camera.transform.columns[3].z);
SCNVector3 positionVec = SCNVector3Make(position.x, position.y,1.0);
SCNVector3 screenPosOnFarClippingPlane = [sceneView unprojectPoint:positionVec];
SCNVector3 rayDirection=SCNVector3Make(screenPosOnFarClippingPlane.x-cameraPos.x,screenPosOnFarClippingPlane.y-cameraPos.y,screenPosOnFarClippingPlane.z-cameraPos.z);
float leng=sqrtf(rayDirection.x * rayDirection.x + rayDirection.y * rayDirection.y + rayDirection.z * rayDirection.z);
rayDirection=SCNVector3Make(rayDirection.x/leng,rayDirection.y/leng,rayDirection.z/leng);
return [self getNewPointLinePoint:cameraPos lineVector:rayDirection distance:0.7];
}
//已知直线L过点m(m1,m2,m3),且方向向量为VL(v1,v2,v3)
//求与m距离d的点n
-(SCNVector3)getNewPointLinePoint:(SCNVector3)linePoint
lineVector:(SCNVector3)lineVector
distance:(float)distance{
float vpt=(lineVector.x*lineVector.x+lineVector.y*lineVector.y+lineVector.z*lineVector.z);
if (vpt==0) {
return {FLT_MAX,FLT_MAX,FLT_MAX};
}
float t=pow(distance*distance/vpt,0.5);
float x=linePoint.x+lineVector.x*t;
float y=linePoint.y+lineVector.y*t;
float z=linePoint.z+lineVector.z*t;
return SCNVector3Make(x,y,z);
}
@end
网友评论