# Fixed camera rotate to follow character

I have a camera in a fixed position in the middle of a field, and I would like to rotate the camera to follow the character as it moves around. There is no point lower than the camera, but I would like it to follow vertically as well. Given the point/euler angle of the camera, and the point of the character, what math could I use to implement this?

• Should the camera follow the character or is the position fixed and it should only rotate to face the character? Sep 7 '17 at 10:32
• It should only rotate to face the character. Sorry if my English was unclear. Sep 8 '17 at 0:50
• Have you tried adding a constraint to the camera node using SCNLookAtConstraint(target: SCNNode) Sep 8 '17 at 7:55

(Since the question states only one angle this answer assumes rotation on one axis in 3D-space)

Given these inputs on a y-up coordinate system:

cameraPos    = (cx, cy, cz)
currentAngle = θ
playerPos    = (px, py, pz)


We can first calculate the vector pointing from the camera to the player position:

playerCamVector = playerPos.xz - cameraPos.xz = (px - cx, pz - cz)


We can then calculate the angle of this vector using atan (a.k.a. arc tan or tan-1):

playerCamAngle = atan(playerCamVector.y, playerCamVector.x)


We now calculate the difference between this angle and the current camera angle:

angleChange = playerCamAngle - currentAngle


Given this difference we can now rotate the camera by this much so we face the player:

// Rotate on the Y-vector (up)
camera.rotate(Vector.Y, angleChange)


If you want smoother movement you should probably use some sort of interpolation to gradually change the camera's rotation instead of instantly moving it.

A more compact version would be to just calculate the angle directly:

angle = atan(pz - cz, pz - cx)
angleChange = angle - currentAngle
camera.rotate(Vector.Y, delta)

• I am rotating on two axis, but I was able to solve it without too much extra work due to this answer. Thank you. Sep 11 '17 at 10:42