Friday, October 11, 2013

First Person Character Controller; no head movement.

I love how this one works. It's a first person character controller, that jumps. However, it has support for footsteps, and running, (though I haven't put in the footsteps when running yet, but I will be). I'm using this for a game I'm working on, and it works great. Here is the character controller script, ready to be implemented.


var speed : float = 1;
var rotSpeed : float = 1;
var jumpStrength : float = 5;
var isGrounded : boolean;
var horizontal : float;
var vertical : float;
var leftFoot : AudioClip;
var left : boolean;
var right : boolean;
var rightFoot : AudioClip;
var steps : float;

function Start () {

}

function Update () {
horizontal = Input.GetAxis("Horizontal");
vertical = Input.GetAxis("Vertical");
if (Input.GetAxis("Horizontal"))
transform.Rotate(Vector3(0, horizontal * rotSpeed, 0));
if (isGrounded)
{
if (Input.GetAxis("Vertical"))
{
rigidbody.AddRelativeForce(Vector3(0, 0, vertical * speed), ForceMode.VelocityChange);
steps += Time.deltaTime;

if (steps >= .5 && steps < .8 && !left)
{
audio.PlayOneShot(leftFoot);
left = true;
right = false;
}
if (steps >=1 && steps < 1.3 && !right)
{
audio.PlayOneShot(rightFoot);
steps = 0;
right = true;
left = false;
}
if (steps >1.016)
steps = 0;
}
if (Input.GetButtonDown("Jump"))
rigidbody.AddRelativeForce(Vector3(0, 1 * jumpStrength,0), ForceMode.Impulse);
if (Input.GetAxis("Vertical") && Input.GetKey(KeyCode.LeftShift))
rigidbody.AddRelativeForce(Vector3(0, 0, vertical * speed*1.5), ForceMode.VelocityChange);
if (vertical == 0)
{
steps = 0;
left = false;
right = false;
}
}
if (!isGrounded)
{
if (Input.GetAxis("Vertical"))
rigidbody.AddRelativeForce(Vector3(0, 0, vertical * speed/3), ForceMode.VelocityChange);
}
}

function OnCollisionEnter (Col : Collision) {
if (Col.gameObject.tag == "Floor")
isGrounded = true;
}

function OnCollisionExit (Col : Collision) {
if (Col.gameObject.tag == "Floor")
isGrounded = false;
}

No comments:

Post a Comment