0
votes

I want to be able to use joystick (left-right) to make the camera orbit around target. I have this handled with the code below:

using UnityEngine;
using System.Collections;
using UnityStandardAssets.CrossPlatformInput;

public class OrbitCamera : MonoBehaviour {

    public Transform target;

    public float turnSpeed;
    public float height;
    public float distance;

    private Vector3 offsetX;

    void Start()
    {
        offsetX = new Vector3 (0, height, distance);
    }

    void LateUpdate()
    {
        offsetX = Quaternion.AngleAxis (CrossPlatformInputManager.GetAxis ("hOrbit") * turnSpeed, Vector3.down) * offsetX;

        transform.position = target.position + offsetX;
        transform.LookAt (target.position);
    }
}

I need to extend this script so that the player can move camera also up and down using the same joystick. So what I want is the camera to be able to move around player in a shape of sphere, always looking at the player. Thanks in advance.

1

1 Answers

1
votes

Use a boom camera

A boom camera is wonderfully easy to setup and has a range of convenient cinematic controls:

Visualise a camera boom and things become much simpler

To set it up, you simply create a new game object which we'll call the dolly. You then simply parent the camera to the dolly and tidy up the positions and rotations:

Camera

  • Transform: 0,0,-distance
  • Rotation: 0,0,0

Dolly

  • Transform: 0,height,0
  • Rotation: 0,0,0

Why a boom camera is great

  • Rotate the dolly on x and y and you'll get the camera moving in a sphere. (Note that dragging the rotation gizmo in scene view doesn't show the effect properly because of axis alignment; edit the x/y rotation values in the inspector only).

  • That -distance z value is the zoom. Change the local position of the camera to zoom in/out.

  • Local rotating the camera gives interesting tilt/pan effects.

Making it work in your case

You'd attach the script to the dolly gameobject, then use the joystick input to rotate it on x/y:

using UnityEngine;
using System.Collections;
using UnityStandardAssets.CrossPlatformInput;

public class OrbitCamera : MonoBehaviour {
    // Height and distance are now set in the scene (by positioning the dolly and changing that camera z value).
    public float turnSpeed;
    private float horizontal;
    private float vertical;

    void LateUpdate()
    {
        // Update horizontal/ vertical angles:
        horizontal += CrossPlatformInputManager.GetAxis ("hOrbit") * turnSpeed;

        vertical += CrossPlatformInputManager.GetAxis ("vOrbit") * turnSpeed;

        // Update the rotation:
        transform.rotation = Quaternion.Euler(horizontal, vertical, 0f);
    }
}