I am trying to make the camera zoom in or out when I press the arrow up and down keys. What have I done wrong?
void Update()
{
transform.position = Player.position + Offset;
if (Input.GetKeyDown(KeyCode.DownArrow))
{
Offset.y += 1;
Offset.z += 1;
Debug.Log(Offset);
}
if (Input.GetKeyDown(KeyCode.UpArrow))
{
Offset.y -= 1;
Offset.z -= 1;
Debug.Log(Offset);
}
}
All you are doing there is moving the offset y and z values. That may end up being further away from the player depending on the direction from the camera to the player. You can either calc the direction to the player and move closer or change the field of view/orthographic size depending on if it is a 3D or 2D setup.
I want to change the offset so that the camera is further away from the player when I press the ArrowDown Key. But it won’t work. Not even the Debug.Log works…
Is that code on the camera and is it enabled?
yes, it is. I get the camera to follow an object as I want but still can’t zoom in or out
Try this, it’s a simple script for moving your camera towards/away from your player.
public class CameraZoom : MonoBehaviour
{
public Transform Player;
public float ZoomSpeed = 3f;
private Transform _transform;
private Vector3 _offSet;
private void Start ()
{
_transform = transform;
_offSet = Player.position - _transform.position;
}
private void Update ()
{
_transform.position = Player.position - _offSet;
if(Input.GetKey(KeyCode.DownArrow))
{
var dir = Player.position - transform.position;
_offSet += dir.normalized * ZoomSpeed * Time.deltaTime;
}
else if (Input.GetKey(KeyCode.UpArrow))
{
var dir = Player.position - transform.position;
_offSet -= dir.normalized * ZoomSpeed * Time.deltaTime;
}
}
}
Thanks, dude! With a few changes it worked perfect, thx again and have a good day =)