I’ve built a simple 3D scene and put some 2D sprites in the scene. I have a camera that overlooks all 8 sprites. There are 4 close to the camera and 4 far away in the distance. I’m trying to programmatically manipulate the camera as the player interacts with the game. I have spent about 4 hours on this and have learned a lot about it but I am still unable to get it to work correctly. I would appreciate some help.
Here are the two things I want the camera to be able to do:
- When one of the four characters in the foreground are clicked I want the camera to rotate towards the character and zoom to a certain distance away from the selected character.
- I want to at some point zoom the camera in on the 4 characters in the distance.
Both of these things need to be interpolated so that the camera repositions itself over maybe 500 ms.
I can quite easily make the camera look at the selected character with this code:
Camera.main.transform.LookAt(transform.position);
but this doesn’t result in the camera being animated to the new “look at” rotation. The other thing I can’t figure out is how to translate the camera along a line that runs both through it and a target object.
Here is a screenshot of the scene. for reference.
Appreciate any help!
I think what you are after are tweening functions. These allow you to move from one point to another over time and specify the curve/path. I highly recommend HOTween. There is a free version for download and you can create tweens on objects with one line of code.
I got it!
Camera.main.GetComponent<CameraScript>().Rotate(transform.position - Camera.main.transform.position);
Camera.main.GetComponent<CameraScript>().Reposition(transform.position + (transform.forward * -20));
and
using UnityEngine;
using System.Collections;
public class CameraScript : MonoBehaviour {
private Vector3? _targetPosition;
private Vector3? _targetRotation;
private float _damping = 5.0f;
// Use this for initialization
void Start () {
_targetPosition = null;
_targetRotation = null;
}
// Update is called once per frame
void Update () {
if (_targetRotation != null)
{
var newRotation = Quaternion.Slerp(this.transform.rotation, Quaternion.LookRotation(_targetRotation.Value), _damping * Time.deltaTime);
if (newRotation == this.transform.rotation)
{
_targetRotation = null;
}
else
{
this.transform.rotation = newRotation;
}
}
if (_targetPosition != null)
{
var newPosition = Vector3.MoveTowards(transform.position, _targetPosition.Value, 50 * Time.deltaTime);
if (newPosition == transform.position)
{
_targetPosition = null;
}
else
{
transform.position = newPosition;
}
}
}
public void Reposition(Vector3 newPosition)
{
_targetPosition = newPosition;
}
public void Rotate(Vector3 newRotation)
{
_targetRotation = newRotation;
}
}