Camera zoom has a yo-yo effect
I'm trying to make a camera with a scroll wheel zoom. I have it nearly complete, but whenever I zoom in, and then try to zoom out the camera bounces back in a few times before moving outwards. I think it's the value of the scroll wheel axis not resetting so it's still reporting a positive input? I'm not sure where I've gone wrong. Here's my code.
Any help would be greatly appreciated!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ZoomController : MonoBehaviour
{
[SerializeField] Transform parentObject;
float zoomLevel;
[SerializeField] float sensitivity = 10f;
[SerializeField] float speed = 30f;
float maxZoom = 30f;
float zoomPosition;
void Update()
{
if(Input.GetAxis("Mouse ScrollWheel") != 0)
{
zoomLevel += Input.GetAxis("Mouse ScrollWheel") * sensitivity;
zoomLevel = Mathf.Clamp(zoomLevel, -maxZoom, maxZoom);
zoomPosition = Mathf.MoveTowards(zoomPosition, zoomLevel, speed * Time.deltaTime);
transform.position = parentObject.position + (transform.forward * zoomPosition);
}
else zoomLevel = 0;
}
Answer by jitterywriter · Mar 24 at 07:02 PM
Solved! New code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ZoomController : MonoBehaviour
{
[SerializeField] Transform parentObject;
float zoomLevel;
[SerializeField] float sensitivity = 10f;
[SerializeField] float speed = 30f;
float maxZoom = 30f;
float zoomPosition;
void Update()
{
if(Input.GetAxis("Mouse ScrollWheel") != 0)
{
zoomLevel += Input.GetAxis("Mouse ScrollWheel") * sensitivity;
zoomLevel = Mathf.Clamp(zoomLevel, -maxZoom, maxZoom);
zoomPosition = Mathf.MoveTowards(zoomPosition, zoomLevel, speed * Time.deltaTime);
transform.position = parentObject.position + (transform.forward * zoomPosition);
}
else zoomLevel = 0;
}
Big problem I have now is gett the zoomLevel to clamp. The change in value feels arbitrary to me. I can zoom in for a bit and then it'll suddenly give a negative value, or increase the value as I'm zooming out. Back to the drawing board.
Your answer
Follow this Question
Related Questions
Exponential Zoom Equation Not Working 0 Answers
Camera Controller default position? 0 Answers
Simple FPS camera zoom not working as intended because of the boolean. 1 Answer
Change Camera's size relative to player's speed 0 Answers
How to zoom in a game that happens within the canvas only? 2 Answers