我正在尝试在 SceneKit 中使用SCNCylinder
. 我希望将圆柱体放置在场景中用户点击屏幕的位置。
我目前的方法有效,但由于某种原因,圆柱体没有准确地放置在触摸位置。根据屏幕的不同部分,圆柱体有时位于触摸位置的中间,有时偏离很大。我希望屏幕截图能很好地说明问题。
我目前有一个SCNSphere
相机所在的位置。通过用球体对屏幕接触点进行命中测试,我检索到一条朝向命中测试的射线。然后我取光线的法线向量并将圆柱体沿乘以 6 的向量定位。
有谁知道这种方法的问题是什么以及为什么我会遇到这种偏移行为?
这就是我目前创建的方式SCNCylinder
:
- (IBAction)longPressGesture:(UILongPressGestureRecognizer *)sender {
if (sender.state == UIGestureRecognizerStateBegan) {
CGPoint location = [sender locationInView:self.sceneView];
NSArray *hitTestResult = [self.sceneView hitTest:location options:nil];
if (hitTestResult.count == 1) {
SCNHitTestResult *sphereHit = hitTestResult.firstObject;
// Get ray coordinates from local camera position
SCNVector3 localCoordinates = sphereHit.worldNormal;
localCoordinates = SCNVector3Make(localCoordinates.x * 6, localCoordinates.y * 6, localCoordinates.z * 6);
[self addCylinder:SCNVector3Make(localCoordinates.x, localCoordinates.y, localCoordinates.z)];
}
}
}
- (void)addCylinder:(SCNVector3)position {
SCNCylinder *cylinder = [SCNCylinder cylinderWithRadius:0.5 height:0.01];
SCNNode *cylinderNode = [SCNNode nodeWithGeometry:cylinder];
// Create LookAt Contstraint
NSMutableArray *constraints = [NSMutableArray new];
SCNLookAtConstraint *lookAtCameraConstraint = [SCNLookAtConstraint lookAtConstraintWithTarget:cameraNode];
lookAtCameraConstraint.gimbalLockEnabled = YES;
[constraints addObject:lookAtCameraConstraint];
// Turn 90° Constraint
SCNTransformConstraint *turnConstraint = [SCNTransformConstraint transformConstraintInWorldSpace:NO withBlock:^SCNMatrix4(SCNNode * _Nonnull node, SCNMatrix4 transform) {
transform = SCNMatrix4Mult(SCNMatrix4MakeRotation(M_PI_2, 1, 0, 0), transform);
return transform;
}];
[constraints addObject:turnConstraint];
cylinderNode.constraints = constraints;
cylinderNode.position = position;
SCNNode *rootNode = self.sceneView.scene.rootNode;
[rootNode addChildNode:cylinderNode];
}