场景中的节点旋转



im在弄清楚如何将我的播放器节点旋转到每个点击时都很难。IVE已经截取了单击X-Z平面并将节点移动到其上的截距,并且与角色移动的X和Z平面相比,我发现了点击的弧度。角色不在0 y旋转之后,我的方法不起作用。我猜想有一种更简单的方法可以做到这一点,只是希望有人可以将我指向一些文档,或者告诉我如何找出点击角度和当前玩家的当前方向之间的区别,并使他面对运动。<<<<<<<<

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if game.state == .tapToPlay {
        startGame()
    }
    if game.state == .playing {
        let touch = touches.first!
        let location = touch.location(in: scnView)
        let hitResults = scnView.hitTest(location, options: nil)
        if hitResults.first?.node.name == "Grass" {
            //pigNode.runAction(SCNAction.move(to: (hitResults.first?.localCoordinates)!, duration: 1.0))
            let moveAction = SCNAction.move(to: (hitResults.first?.localCoordinates)!, duration: 1.0)
            let location = hitResults.first?.localCoordinates
            /*
            pigNode.runAction(SCNAction.rotateTo(x: 0.0,
                                                 y: CGFloat(offset.y),
                                                 z: 0.0, duration: 1.0, usesShortestUnitArc: true))
            let rotateAction = SCNAction.rotateTo(x: CGFloat((locationOnPlane?.x)!),
                                                  y: CGFloat((locationOnPlane?.y)!),
                                                  z: CGFloat((locationOnPlane?.z)!),
                                                  duration: 1.0, usesShortestUnitArc: true)
            */
            let locationOnPlane = CGPoint(x: Double((location?.x)!), y: Double((location?.z)!))
            let offset = CGPoint(x: Double(locationOnPlane.x) - Double(pigNode.position.x), y: Double(locationOnPlane.y) - Double(pigNode.position.z))
            let length = sqrt(offset.x * offset.x + offset.y * offset.y)
            let direction = CGPoint(x: offset.x / length, y: offset.y / length)
            let rotationAngle = CGFloat(atan2(direction.y, direction.x))
            let rotateAction = SCNAction.rotate(by: rotationAngle, around: SCNVector3(x: 0.0, y: 1.0, z: 0.0), duration: 1.0)
            //let rotateAction = SCNAction.rotateBy(x: 0.0, y: rotationAngle, z: 0.0, duration: 1.0)
            //let rotateAction = SCNAction.rotateTo(x: 0.0, y: rotationAngle, z: 0.0, duration: 1.0, usesShortestUnitArc: true)
            print(rotationAngle)
            print(pigNode.eulerAngles.y)

            let groupAction = SCNAction.group([moveAction, rotateAction])
            pigNode.runAction(groupAction)
        }
    }
}

检查此答案在Swift中以SpriteKit在Spriitekit中旋转Sprite位置,这是旋转的代码

let angle = atan2(location.y - cannon.position.y , location.x - cannon.position.x)
 cannon.zRotation = angle - CGFloat(M_PI_2)

我希望这对您有帮助

最新更新