Wednesday, October 9, 2013

2D Character Controller

A simple character control script I wrote, which allows movement, jump, and wall jumping.


var speed : int = 1;
var isGrounded : boolean;
var isWalled : boolean;
var horizontal : float;
var vertical : float;
var directional : boolean;

function Start () {

}

function Update () {
horizontal = Input.GetAxis("Horizontal");
vertical = Input.GetAxis("Vertical");
if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))
directional = true;
else
directional = false;
if (isGrounded)
{
if (Input.GetKeyDown(KeyCode.Space))
{
rigidbody.AddForce(Vector3.up * 5, ForceMode.Impulse);
}
if (Input.GetAxis("Horizontal"))
{
rigidbody.AddForce(Vector3(horizontal * (speed * 2), 0, 0), ForceMode.Acceleration);
}
}
if (isWalled)
{
rigidbody.drag = 6;
if (Input.GetAxis("Horizontal") && Input.GetKeyDown(KeyCode.Space))
{
rigidbody.AddForce(Vector3(horizontal * (speed * 10), 5, 0), ForceMode.Impulse);
}
if (Input.GetKeyDown(KeyCode.Space) && !directional)
{
isWalled = false;
}
}
if (!isWalled)
{
rigidbody.drag = 1;
}
}

function OnCollisionEnter (Col : Collision) {

if (Col.gameObject.tag == "Floor")
{
isGrounded = true;
isWalled = false;
}
if (Col.gameObject.tag == "Wall")
{
isWalled = true;
horizontal = 0;
}

}

function OnCollisionExit (Col : Collision) {

if (Col.gameObject.tag == "Floor")
isGrounded = false;
if (Col.gameObject.tag == "Wall")
isWalled = false;
}

The above script allows the arrow keys, as well as spacebar, to control a character on the X axis, and jump using the Y axis. When used with the following camera script, it can be used to control a 2D platformer character with no additional code.



//The target is the character you want to follow. 
var target : Transform;


function Start () {

}

function Update () {

gameObject.transform.position.x = target.transform.position.x;
gameObject.transform.position.y = target.transform.position.y;
}


No comments:

Post a Comment