- Home /
Change the FOV from "60" to "90" smoothly when pressing "W" (C#, first time posting, beginner)
Hey, i am new to programming so my question might be really stupid and the answer really simple, but i can't get it to work, anyway, here is my script.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerFighterMovement : MonoBehaviour
{
[SerializeField]float movementSpeed = 60f;
[SerializeField]float turnSpeed = 100f;
[SerializeField]float pitchSpeed = 50f;
[SerializeField]float rollSpeed = 100f;
public float startFOV = 60f;
public float maxFOV = 90f;
public Camera myCamera;
Transform myT;
void Awake()
{
myT = transform;
}
void Update()
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
Turn();
Thrust();
if (Input.GetKeyDown("up"))
{
myCamera.fieldOfView = maxFOV;
}
else myCamera.fieldOfView = startFOV;
}
void Turn()
{
float yaw = turnSpeed * Time.deltaTime * Input.GetAxis("Mouse X");
float pitch = pitchSpeed * Time.deltaTime * Input.GetAxis("Mouse Y");
float roll = rollSpeed * Time.deltaTime * Input.GetAxis("Roll");
myT.Rotate(-pitch, yaw, roll);
}
void Thrust()
{
if (Input.GetAxis("Vertical") > 0)
myT.position += myT.forward* movementSpeed * Time.deltaTime* Input.GetAxis("Vertical");
}
}
I am doing a space game and i want to create an "speed effect" by changing the FOV. (Sorry for my english)
Answer by nt314p · Jul 31, 2017 at 10:35 PM
Put this as your new update function:
void Update() {
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
Turn();
Thrust();
if (Input.GetKeyDown("up")) {
myCamera.fieldOfView = Mathf.Lerp(myCamera.fieldOfView, maxFOV, t);
} else
myCamera.fieldOfView = Mathf.Lerp(myCamera.fieldOfView, startFOV, t);
}
}
And at the top where you define all your variables, write:
public float t = 0.5f;
To increase the speed of the camera transition, increase t (but not past 1).
To decrease the speed of the camera transition, decrease t (but not past 0).
The code is basically slowly but smoothly changing the camera's FOV to the desired value.
If you have any questions, please do not hesitate to ask.
At first it didn't work, but i changed (Input.Get$$anonymous$$eyDown("up")) to (Input.Get$$anonymous$$ey("w")) and it worked flawlessly. Thank you very much!
Answer by tommy166 · Feb 08, 2021 at 04:43 PM
Hi i gave a look at this conversation, and by trying the code i noticed that: if you wanna make it real smooth, chage the code a bit like this: oid Update() { Cursor.visible = false; Cursor.lockState = CursorLockMode.Locked; Turn(); Thrust(); if (Input.GetKeyDown("up")) { myCamera.fieldOfView = Mathf.Lerp(myCamera.fieldOfView, maxFOV, t Time.deltaTime); } else myCamera.fieldOfView = Mathf.Lerp(myCamera.fieldOfView, startFOV, t Time.deltaTime); } }