Rotate SCNNode to a Point

I am trying to rotate my object (SCNNode) to see the point at which it is moving. I am only moving along the x and y axis, so far I tried:

    // Action to move node
    let action1 = SCNAction.moveTo(SCNVector3(x: 4.0, y: 0.0, z: 6.0), duration: 3)
    // Get the tan angle:
    let angle = CGFloat(atan2(z, x))
    if angle - previousAngle > Pi {
        playerAngle += 2 * Pi
    } else if previousAngle - angle > Pi {
        playerAngle -= 2 * Pi
    }
    previousAngle = angle
    playerAngle = angle * RotationBlendFactor + playerAngle * (1 - RotationBlendFactor)
    let rot = playerAngle - 90 * DegreesToRadians
    flyNode.rotation = SCNVector4(x: 0, y: 1, z: 0, w: Float(rot))

It works for some target points, but not for all.

I am also trying to add SCNLookAtConstraint to the constraint array, it changes my node perfectly, but stops my transition to animation:

    let targerNode = SCNNode()
    targerNode.position = SCNVector3(x: -4.0, y: 0.0, z: -2.0)
    let con = SCNLookAtConstraint(target: targerNode)
    flyNode.constraints = [con]        
    let action1 = SCNAction.moveTo(SCNVector3(x: 4.0, y: 0.0, z: -2.0), duration: 3)

Can you help me please?

+4
source share
2 answers

The simplest solution, although perhaps not the most elegant, is to apply moveTo SCNActionto the node and apply yours SCNLookAtConstraintto the child of that node. This should allow both to work without conflict.

0
source

: ( C, )

float x, z;// these are your vars you assign these so you can delete this line


float offset = 0; // use this to offset your final output
                  // because your output might be off by 
                  // a quarter of a turn or so, or more
                  // but once you got the offset right
                  // than it will stay right
float aQuarterOfAturn = 1.570795;// since scenekit uses radians
                                 // this needs to be pi/2
                                 // if it was degrees it would be 90


if (x < 0) {
    offset += aQuarterOfAturn;// turn it to compensate for the lack of negetive x
    x *= -1;// convert x to positive so we can calculate it
}
if (z < 0) {
    offset += aQuarterOfAturn;// turn it to compensate for the lack of negetive z
    z *= -1;// convert z to positive so we can calculate it
}

xzDelta = x + z// add x and z

zPercent = z * 100 / xzDelta // so we can calculate how much percent z is

yRot = aQuarterOfAturn * zPercent / 100 // and finally convert it to a rotation

yRot += offset // add the offset and you can implement the rotation now
// a note, this code has not been tested you may need to offset it (above)
// and possibly multiply it by negitive 1

// if it works fine but the rotation is off by however many degrees than just offset it

// if it works fine but your move up and it rotates down than multiply it by -1

, !

0

All Articles