Main Camera transform position or localPosition is not working
I made an crouch script, but i have a problem at camera change y position:
public float CameraCrouched = 0.414f;
public float CameraUnCrouched = 0.914f;
Crouched/UnCrouched part:
void Crouched()
{
controller.height = 1.45f;
controller.center = new Vector3(0, -0.5f, 0);
Camera main = GameObject.Find("FirstPersonCharacter").GetComponent<Camera>();
main.transform.localPosition = new Vector3(0, CameraCrouched, 0);
Crouch = true;
}
void UnCrouched()
{
controller.height = standardHeight;
controller.center = new Vector3(0, 0, 0);
Camera main = GameObject.Find("FirstPersonCharacter").GetComponent<Camera>();
main.transform.localPosition = new Vector3(0, CameraUnCrouched, 0);
Crouch = false;
}
I need to move the FirstPersonCharacter camera at: 0.414f, the original position si: 0.914f, I tried this what you see in code, but nothing.
hmm.. You must need to check that this method is calling well and camera's position is assigning or not by placing the Debug.Log()
or by breakpoints. if logs are printing in the console there might be possibilities that any Update()/FixesUpdate()/LateUpdate()
is re-setting camera's position back again in any script like CameraCaontroller.cs
Answer by Rares15 · Dec 24, 2016 at 06:49 PM
I Solved :D
I made a new Object, i put camera in that object and i put that line at the object:
cameraGroup.transform.localPosition = new Vector3( 0, CameraUnCrouched, 0);
Answer by Nick15104 · Jun 16, 2018 at 04:52 AM
Yes for first person crouching as Rares15 has figured out. You can create from the first person character and add an empty game object. Then put the character camera into the empty game object and apply this script to the empty game object. I have made the numbers a public float so you can play around with the standing height and the crouched height.
using UnityEngine;
public class Crouch : MonoBehaviour
{
public float playerCrouched = -0.75f;
public float playerUncrouched = 0f;
private void Update()
{
if (Input.GetKeyDown(KeyCode.LeftControl))
{
transform.localPosition = new Vector3(0, playerCrouched, 0);
}
if(Input.GetKeyUp(KeyCode.LeftControl))
{
transform.localPosition = new Vector3(0, playerUncrouched, 0);
}
}
}