Steve
Steve

Reputation: 9561

Orbiting camera around center of screen

I'm trying to setup my camera to orbit around the center of the screen, rather than just rotating the camera itself, and without having a target game object.

I'm able to orbit around a game object very easily using:

float rotationAmount = Input.GetAxis("Mouse X") * RotateAmount;
transform.RotateAround(target, Vector3.up, rotationAmount);

However I want to have a similar orbit mechanic without a target. For an example, see the Planet Coaster camera controls.

I have tried using ScreenToWorldPoint to try and get the middle of the screen but that seems to still just rotate the camera:

camera.ScreenToWorldPoint(new Vector3(Screen.width / 2, Screen.height / 2, camera.nearClipPlane));

One thing that did work is using Vector3.zero as a target. However, if I translate the camera this vector still points to (0,0,0) and so the camera moves in a strange way.

Is there any way to orbit around the center of the screen without a target?

Upvotes: 0

Views: 2480

Answers (1)

AVAVT
AVAVT

Reputation: 7133

Put camera inside a GameObject (let's call it CameraHolder), offset the camera back a bit (just make sure CameraHolder is on the camera's forward positive axis). Now use your controls to control the CameraHolder instead of the camera:

  1. If you want to move the camera around, move the CameraHolder's position instead. Because the camera is a child of CameraHolder, it will keep its localPosition and move along. The trick though, is to move using camera.transform's vectors:

    • To move forward: CameraHolder.position += camera.transform.forward
    • To move right: CameraHolder.position += camera.transform.right

This way you always move relative to the camera's view.

Furthermore, if you want an RTS control just like Planet Coaster (slide along a plane - in this case, the ground), you will need to limit CameraHolder.transform.position.y to the ground. You can either set y to a fixed value after each movement or just remove the y part from camera.transform.forward/right.

  1. If you want to rotate the camera around, simply change CameraHolder's rotation, the camera will rotate along. For this case, you will need to limit max-min angle (most likely between 0 and -90 degree)

Upvotes: 1

Related Questions