Skip to content

Instantly share code, notes, and snippets.

@Templar2020
Last active November 17, 2015 01:26
Show Gist options
  • Save Templar2020/9a2d2386543ae5706ace to your computer and use it in GitHub Desktop.
Save Templar2020/9a2d2386543ae5706ace to your computer and use it in GitHub Desktop.
Basic 2D Controller
using UnityEngine;
using System.Collections;
public class Controller2D : MonoBehaviour {
// Player Movement
public float moveSpeed;
public float jumpHeight;
// No Stick
private float moveVelocity;
//Ground Check
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask whatIsGround;
private bool grounded;
// Double Jump Variables
private bool doubleJumped;
//Player Animation
private Animator anim;
void Start(){
anim = GetComponent<Animator>();
}
void FixedUpdate(){
grounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
}
void Update() {
//No Stick
moveVelocity = 0f;
// Move Right
if(Input.GetKey(KeyCode.D)){
//GetComponent<Rigidbody2D>().velocity = new Vector2(moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
moveVelocity = moveSpeed;
}
// Move Left
if(Input.GetKey(KeyCode.A) ){
//GetComponent<Rigidbody2D>().velocity = new Vector2(-moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
moveVelocity = -moveSpeed;
}
// No Stick Player
GetComponent<Rigidbody2D>().velocity = new Vector2(moveVelocity, GetComponent<Rigidbody2D>().velocity.y);
//Player walk animation
anim.SetFloat("Speed",Mathf.Abs(GetComponent<Rigidbody2D>().velocity.x));
//Player flip
if(GetComponent<Rigidbody2D>().velocity.x > 0)
transform.localScale = new Vector3(1f,1f,1f);
else if (GetComponent<Rigidbody2D>().velocity.x < 0)
transform.localScale = new Vector3(-1f,1f,1f);
// Jump
if(Input.GetKeyDown (KeyCode.Space)&& grounded){
GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jumpHeight);
}
// Double Jump
if(grounded)
doubleJumped = false;
//Player Jump Animation
anim.SetBool("Grounded",grounded);
if(Input.GetKeyDown (KeyCode.Space)&& !doubleJumped && !grounded ){
GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jumpHeight);
doubleJumped = true;
}
}
}
@Templar2020
Copy link
Author

For all the Unity5 users, you can Get rid of typing GetComponent() every time by declaring it as a private Var.so in my script Ive got:
private Rigidbody2D rBody;

then in void start ; rBody = GetComponent();

and then Finally you can reference it like the anim.

rBody.velocity = new Vector2 (moveSpeed, rBody.velocity.y);

@Templar2020
Copy link
Author

Note: Add Physics2D Material and reduce friction to 0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment