- Home /
Change view if key is pressed
I am trying to change Camera view if user presses down a key.
if (Input.GetKeyDown("z"))
{
// Change Camera fov to 20.
}
else if (Input.GetKeyUp("z"))
{
// Change Camera fov to 10.
}
The problem is that makes me hold down the z on the keyboard and once I let it go I have to go the "else if (Input.GetKeyUp("z"))" takes effect.
What I want is for the user to press z and until he presses it again the Camera stays with fov to 20.
How would I do this, I tried get key and it didnt work; almost like both if and else executed at the same time due to how fast the update method is being called.
Hi try this C# script i made, put this on your camera
//set this to your defualt / standard fov
private float FieldOfView = 80;
// Update is called once per frame
void Update () {
//when Z hey is pressed
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Z))
{
//change the fov to 20
gameObject.transform.camera.fieldOfView = 20;
}
//when Z key is released
if (Input.Get$$anonymous$$eyUp($$anonymous$$eyCode.Z))
{
//change the fov to 80
//(set the fov number here, to match the fov number in the private float)
gameObject.transform.camera.fieldOfView = 80;
}
}
Answer by Grady · Jan 02, 2012 at 01:41 AM
Hey,
Using Input.GetKey()
should work.....
Try this script:
function Update(){
if(Input.GetKey("z")){
//Change camera fov to 20
}
}
I hope I fully understood what you were trying to do, which was change the fov to something while the z key is held down, and then change it back/to something else, once the z key is released.....
Hope this helps you!!!!!!
Comment back if you need more help!!!!!!
-Grady
Answer by Cocotimba · Jan 02, 2012 at 01:53 AM
Hi Grady, thanks for your post. Your code doesn't work, because if GetKey is not "z" then the else will always execute.
I tried different variations of the else, such as
function Update()
{
if(Input.GetKey("z"))
{
//Change camera fov to 20
}
else if (Input.GetKeyDown("z"))
{
//Change camera fov to 10
}
}
That doesn't work either. Any ideas?
I updated my answer, so that it is just the same thing without the else, that might work....!!! Also, remember when you are going to commment back, to use the comment box underneath the answer!!!!!!!!!!!!!!!!!!! :D
You could maybe try your code just above, but chnageGet$$anonymous$$eyDown to Get$$anonymous$$eyUp.......!!!
Answer by djfunkey · Jun 29, 2012 at 07:49 AM
Hi i know the C# script for this
using UnityEngine; using System.Collections;
public class FieldOfViewChange : MonoBehaviour {
//set this to your defualt / standard fov
private float FieldOfView = 80;
// Update is called once per frame
void Update () {
//when Z hey is pressed
if (Input.GetKeyDown(KeyCode.Z))
{
//change the fov to 20
gameObject.transform.camera.fieldOfView = 20;
}
//when Z key is released
if (Input.GetKeyUp(KeyCode.Z))
{
//change the fov to 80
//(set the fov number here, to match the fov number in the private float)
gameObject.transform.camera.fieldOfView = 80;
}
}
}