Reputation: 9561
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
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:
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:
CameraHolder.position += camera.transform.forward
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
.
Upvotes: 1