Simple FPS camera zoom not working as intended because of the boolean.
Here is the code that deals with the zoom. When I press mouse1 which is right mouse button, the camera zooms in. However after releasing the mouse1, camera stays at the zoomed in view, and doesn't reset to it's default position. In other words, Boolean stays "true" long after releasing the mouse1. Are there any workarounds for this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraZoom : MonoBehaviour
{
public float zoom;
public float normal;
public float smooth;
private bool isZoomed = false;
private void Update()
{
if (Input.GetMouseButton(1))
{
isZoomed = true;
if (isZoomed)
{
GetComponent<Camera>().fieldOfView = Mathf.Lerp(GetComponent<Camera>().fieldOfView, zoom, Time.deltaTime * smooth);
}
else
{
GetComponent<Camera>().fieldOfView = Mathf.Lerp(GetComponent<Camera>().fieldOfView, normal, Time.deltaTime * smooth);
}
}
}
}
Answer by nilozeribinate · Oct 08, 2020 at 07:50 PM
@SollerEtFortis What is happening is that your code is only being activated when you are holding the mouse button and the variable "isZoomed" is becoming true and not coming back, to solve this I did this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class scr_Mira : MonoBehaviour
{
public float zoom;
public float normal;
public float smooth;
private bool isZoomed = false;
void Update(){
if(Input.GetMouseButtonDown(1)){
isZoomed = true;
}
if(Input.GetMouseButtonUp(1)){
isZoomed = false;
}
if(isZoomed){
GetComponent<Camera>().fieldOfView = Mathf.Lerp(GetComponent<Camera>().fieldOfView, zoom, Time.deltaTime * smooth);
}
if(!isZoomed){
GetComponent<Camera>().fieldOfView = Mathf.Lerp(GetComponent<Camera>().fieldOfView, normal, Time.deltaTime * smooth);
}
}
}
I hope I helped because you helped me.
Your answer
Follow this Question
Related Questions
Recoil system 0 Answers
Camera distance affects FPS, FPS grows as the camera moves away 0 Answers
FPS shader fixing 1 Answer
Parented Object moves weirdly in FPS Standard Asset Camera 0 Answers
How to change camera's zoom? 0 Answers