Skip to content

Instantly share code, notes, and snippets.

@defektive
Created May 26, 2014 03:40
Show Gist options
  • Save defektive/b5c543a4b5ad3f7b4a1b to your computer and use it in GitHub Desktop.
Save defektive/b5c543a4b5ad3f7b4a1b to your computer and use it in GitHub Desktop.
Character Controller for unity
using UnityEngine;
using System.Collections;
public class ControllerScript : MonoBehaviour {
CharacterController controller;
public float speed = 5.0f;
public float jumpSpeed = 8.0f;
public float pushPower = 3.0f;
bool airJumpReleased = false;
bool hasDoubleJumped = false;
Vector3 movement = Vector3.zero;
// Use this for initialization
void Start () {
controller = GetComponent<CharacterController> ();
}
// Update is called once per frame
void Update () {
movement.x = Input.GetAxis ("Horizontal") * speed;
if(controller.isGrounded == false) {
movement.y += Physics.gravity.y * Time.deltaTime;
}
if (Input.GetButton ("Jump") && (controller.isGrounded == true || (airJumpReleased == true && hasDoubleJumped == false))) {
movement.y = jumpSpeed;
hasDoubleJumped = airJumpReleased;
}
if (controller.isGrounded == false && Input.GetButtonUp ("Jump")) {
airJumpReleased = true;
}
if (controller.isGrounded && (airJumpReleased || hasDoubleJumped)) {
airJumpReleased = hasDoubleJumped = false;
}
controller.Move (movement * Time.deltaTime);
}
void OnControllerColliderHit (ControllerColliderHit hit) {
Rigidbody body = hit.collider.attachedRigidbody;
if(body == null || body.isKinematic) {
return;
}
if (hit.moveDirection.y < -0.3f) {
return;
}
Vector3 pushdir = new Vector3 (hit.moveDirection.x, 0f, 0f);
body.velocity = pushdir * pushPower;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment