Hi all can some one please help me i want to make a camera recoil script which makes the camera go up and once the player lets go of the input key the camera goes back to its original position. Please someone help me thanks in advance
Attach this to the camera and press left ctrl ā¦ Iām sure there are better ways to do this ā¦
If you change the recoilSpeed value in the inspector the camera will slowly move to the new position.
#pragma strict
var recoilSpeed : float = 0.01; // Speed to move camera up / down
function Start () {
}
function Update () {
if (Input.GetKeyDown ("left ctrl")){
recoilBack();
}
if (Input.GetKeyUp ("left ctrl")){
recoilForward();
}
}
// Move camera to recoil position smoothly over time
function MoveToPosition(newPosition : Vector3, time : float){
var elapsedTime : float = 0;
var startingPos = transform.position;
while (elapsedTime < time){
transform.position = Vector3.Lerp(startingPos, newPosition, (elapsedTime / time));
elapsedTime += Time.deltaTime;
yield;
}
}
function recoilBack(){
// Start coroutine to move the camera back smoothly over time
var zoomOutOffset = Vector3(0.0, 0.5, 0);
var zoomOutWorldPosition = transform.TransformDirection( zoomOutOffset );
// Move the camera smoothly
StartCoroutine(MoveToPosition(transform.position + zoomOutWorldPosition, recoilSpeed));
}
function recoilForward(){
// Start coroutine to move the camera forward smoothly over time
var zoomInOffset = Vector3(0.0, -0.5, 0);
var zoomInWorldPosition = transform.TransformDirection( zoomInOffset );
// Move the camera smoothly
StartCoroutine(MoveToPosition(transform.position + zoomInWorldPosition, recoilSpeed));
}