Gene M.
Gene M.

Reputation: 130

SceneKit: Using pan gesture to move a node that's not at origin

I have a SCNNode that I've set at a position of SCNVector3(0,0,-1). The following code moves the node forward or backward along the Z-axis, however, the initial pan gesture moves the node to (0,0,0) and then moves the node in line with the pan gesture.

let currentPositionDepth = CGPoint()

@objc func handlePan(sender: UIPanGestureRecognizer) {    
    let translation = sender.translation(in: sceneView)
    var newPos = CGPoint(x: CGFloat(translation.x), y: CGFloat(translation.y))
    newPos.x += currentPositionDepth.x
    newPos.y += currentPositionDepth.y

    node.position.x = Float(newPos.x)
    node.position.z = Float(newPos.y)

    if(sender.state == .ended) { currentPositionDepth = newPos }
}

I'd like the node to move from it's set position of (0,0,-1). I've tried setting currentPositionDepth.y to -1, however it does not achieve the desired effect. How can I achieve this?

Upvotes: 0

Views: 1669

Answers (1)

SWAT
SWAT

Reputation: 1158

Try something like this:

var previousLoc = CGPoint.init(x: 0, y: 0)

@objc func panAirShip(sender: UIPanGestureRecognizer){
    var delta = sender.translation(in: self.view)
    let loc = sender.location(in: self.view)

    if sender.state == .changed {
        delta = CGPoint.init(x: 2 * (loc.x - previousLoc.x), y: 2 * (loc.y - previousLoc.y))
        airshipNode.position = SCNVector3.init(airshipNode.position.x + Float(delta.x * 0.02), airshipNode.position.y + Float(-delta.y * (0.02)), 0)
        previousLoc = loc
    }
previousLoc = loc


}

I have multiplied the 0.02 factor to make the translation smoother and in turn easier for the end user. You may change that factor to anything else you like.

Upvotes: 3

Related Questions