- Home /
Camera Height-based crouch script
Hi, I want an way to make this: When I press CTRL, the Camera height decrease smoothly, and when I release, it increase smoothly too, because I have tools in front of the camera, and when I use other scripts, it deforms the tools.
Answer by ScroodgeM · Aug 01, 2012 at 09:20 PM
left/right shift - run, C - crouch
should be attached to FPC
RunAndCrouch.cs
using UnityEngine; using System.Collections; public class RunAndCrouch : MonoBehaviour { public float walkSpeed = 3; // regular speed public float crchSpeed = 1; // crouching speed public float runSpeed = 6; // run speed public float crchDeltaHeight = 1f; // height that crouched down public AnimationCurve crchHeightAnimation = new AnimationCurve(new Keyframe[] { new Keyframe(0f, 0f), new Keyframe(0.5f, 0.3f), new Keyframe(1f, 1f) });
private CharacterMotor charMotor;
private CharacterController charContr;
private Transform _transform;
private float crouchPhase;
private float initHeight;
void Start()
{
_transform = transform;
charMotor = GetComponent();
charContr = GetComponent();
initHeight = charContr.height;
}
void FixedUpdate()
{
float crouchHeightOld01 = crchHeightAnimation.Evaluate(crouchPhase);
crouchPhase = Mathf.MoveTowards(crouchPhase, Input.GetKey(KeyCode.C) ? 1f : 0f, Time.fixedDeltaTime);
float crouchHeightNew01 = crchHeightAnimation.Evaluate(crouchPhase);
float speed = Input.GetKey(KeyCode.C) ? crchSpeed : ((Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) && charMotor.grounded) ? runSpeed : walkSpeed;
charMotor.movement.maxForwardSpeed = speed; // set max speed
charMotor.movement.maxSidewaysSpeed = speed;
charMotor.movement.maxBackwardsSpeed = speed;
charContr.height = initHeight - crouchHeightNew01 * crchDeltaHeight;
charContr.center = Vector3.Lerp(Vector3.zero, Vector3.up * crchDeltaHeight * 0.5f, crouchHeightNew01);
transform.position -= Vector3.up * (crouchHeightNew01 - crouchHeightOld01) * crchDeltaHeight;
}
}
But this is Zoom, I want to make the FPS character crouch, not the character itself, just change the "height" of the camera, something like moving it Y axis.
Answer by midomido · Aug 01, 2012 at 11:02 PM
var speed: float = 2.5;
var cameraPos: Vector3; //this is the target position
var cameraOldPos = transform.position //this is the old position or the current
function Update () {
if (Input.GetButtonDown ("Fire1")) {
transform.position = Vector3.Lerp(cameraOldPos, cameraPos, speed*Time.deltaTime);
}
}
and you can use GetButtonUp to restore it
Your answer
Follow this Question
Related Questions
how can i make my character jump? 5 Answers
Camera Bobbing and Stairs 4 Answers
FPS camera script - keeps reverting to 0,0,0 rotation 1 Answer
I need help with my script 3 Answers