我正在编写我的第一个SceneKit项目,尝试使用Pan手势来旋转场景中的简单对象(对象是从.dae文件导入的简单L立方体形状,枢轴点已正确设置)。
我查看了多个SO解决方案和教程,并组合了一些代码,但旋转不正确。如果我反复尝试沿一个轴旋转对象,则可以正常工作,但是当我尝试另一个方向时,在pan的开始时,对象会重置到其初始位置。有时旋转也会随机出现问题或跳跃。我不确定是否使用了正确的方法,请指导...这是我的代码:
func handlePan(sender: UIPanGestureRecognizer){
// determine pan direction
let velocity: CGPoint = sender.velocity(in: sender.view!)
if self.panDirection == nil {
if velocity.x > 0 && velocity.x > abs(velocity.y) { self.panDirection = "right" }
if velocity.x < 0 && abs(velocity.x) > abs(velocity.y) { self.panDirection = "left" }
if velocity.y < 0 && abs(velocity.y) > abs(velocity.x) { self.panDirection = "up" }
if velocity.y > 0 && velocity.y > abs(velocity.x) { self.panDirection = "down" }
}
// do rotation only on selected SCNNode
if self.selectedBrickNode != nil {
// start of pan gesture
if sender.state == UIGestureRecognizerState.began{
// remember initial rotation angle
self.initRot = self.selectedBrickNode.rotation.w
}
let translation = sender.translation(in: sender.view!)
let pan_x = Float(translation.x)
let pan_y = Float(-translation.y)
// add rotation angle to initial rotation
var anglePan = self.initRot + (Float)(sqrt(pow(pan_x,2)+pow(pan_y,2)))*(Float)(Double.pi)/180.0
var rotVector = SCNVector4()
// if left/right, rotate on Y axis
rotVector.x = (self.panDirection == "left" || self.panDirection == "right" ) ? 0 : -pan_y
// if up/down, rotate on X axis
rotVector.y = (self.panDirection == "up" || self.panDirection == "down" ) ? 0 : pan_x
rotVector.z = 0
rotVector.w = anglePan
// set SCNNode's rotation
self.selectedBrickNode.rotation = rotVector
// end of pan gesture
if(sender.state == UIGestureRecognizerState.ended) {
// reset initial rotation
self.initRot = 0.0
// calculate degrees so we can snap to 90deg increments
var angle = anglePan * (Float) (180.0 / Double.pi)
// snap to 90deg increments
let diff = angle.truncatingRemainder(dividingBy: 90.0)
if diff <= 45 {
angle = angle - diff
}else{
angle = (angle - diff ) + 90
}
// set new rotation to snap
rotVector.w = angle * (Float)(Double.pi)/180.0
self.selectedBrickNode.rotation = rotVector
self.selectedBrickNode = nil
}
}
}