Tuesday, 12 November 2013

Sprint and Crouch

var walkSpeed: float = 7;
var crchSpeed: float = 3;
var runSpeed: float = 20;

private var chMotor: CharacterMotor;
private var ch: CharacterController;
private var tr: Transform;
private var height: float; // initial height

function Start(){
  chMotor = GetComponent(CharacterMotor);
  tr = transform;
  ch = GetComponent(CharacterController);
  height = ch.height;
 
  }
 
  function Update(){
 
  var h = height;
  var speed = walkSpeed;
  if (ch.isGrounded && Input.GetKey("left shift") || Input.GetKey("right shift")){
  speed = runSpeed;
 
  }
  if (Input.GetKey("c")){ // press C to crouch
  h = 0.3 * height;
  speed = crchSpeed; // slow down when crouching
 
  }
  chMotor.movement.maxForwardSpeed = speed; // set max speed
  var lastHeight = ch.height; // crouch/stand up smoothly
  ch.height = Mathf.Lerp(ch.height, h, 5*Time.deltaTime);
  tr.position.y += (ch.height-lastHeight)/2; // fix vertical position
 
}
 


This is the sprint and crouch script that I found and used, once applied to the first person controller you can edit the walk speed, crouch speed and run speed.
One problem I face is getting the headbob of the character the change when the players speed changes.

No comments:

Post a Comment