Finally completed the character controller for the char. At the moment we have a black box but I hope to change that later. It reacts to gravity, can jump and move left and right. It took forever with endless bugs along the way for example when you use the velocity on a rigidbody2D in unity it completely overrides the inbuilt gravity so you have to put your own in. Never the less it is working and here is the code if anyone else wants to know what I did. Feel free to use some of it in your own code
:
using UnityEngine;
using System.Collections;
public class CC : MonoBehaviour {
//Rigidbody and falling
private Rigidbody2D rigid;
public bool falling = false;
public bool jumping = false;
//Keys
public KeyCode jump = KeyCode.W;
public KeyCode left = KeyCode.A;
public KeyCode right = KeyCode.D;
//Speed at which to do things
public float walkSpeed = 6;
public float jumpSpeed = 5;
//Sorting out gravity
public Vector3 gravity;
public Vector2 gravityToAdd = new Vector2();
//Falling calculation variables
public Transform lineStart;
//Get the rigidbody from char and gravity ammount from physics
void Start () {
rigid = this.GetComponent<Rigidbody2D>();
gravity = Physics2D.gravity;
}
//Actually move stuff WHAT?!?!?!?!
void Update () {
//Check if we are still jumping
if (gravityToAdd.y < 0) {
jumping = false;
}
//The force that we will move
Vector2 force = new Vector2();
//Walk left
if (Input.GetKey(left)) {
force.x = -walkSpeed;
}
//Walk right
if (Input.GetKey(right)) {
force.x = walkSpeed;
}
//Landing detection
if (!Physics2D.Linecast(new Vector2 (this.transform.position.x, this.transform.position.y), new Vector2 (this.transform.position.x, this.transform.position.y – 1.22f), 1 << LayerMask.NameToLayer(“Ground”))) {
falling = true;
} else {
falling = false;
}
//Show a line in the editor
Debug.DrawLine (lineStart.localPosition, new Vector3(this.transform.position.x , this.transform.position.y -1.22f, this.transform.position.z), Color.cyan);
//If falling apply gravity if not gravity = 0
if (falling == false && jumping != true) {
gravityToAdd.y = 0;
} else {
gravityToAdd.y += gravity.y * Time.deltaTime;
}
//Add jump force
if (Input.GetKeyDown (jump) && falling == false) {
jumping = true;
gravityToAdd.y = jumpSpeed;
}
//Apply gravity to force
force.y = gravityToAdd.y;
rigid.velocity = force; //Apply force to rigidbody
}
}
I expect people are pretty flexible with the ‘entire game on one screen’ thing.