Skip to content

Instantly share code, notes, and snippets.

@Templar2020
Created September 14, 2015 23:53
Show Gist options
  • Save Templar2020/7f1ad17035aef176ae4c to your computer and use it in GitHub Desktop.
Save Templar2020/7f1ad17035aef176ae4c to your computer and use it in GitHub Desktop.
2D Player Controller
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
//Player movement variables
public float moveSpeed;
public float jumpHeight;
private bool doubleJump;
//Player grounded variables
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask whatIsGround;
private bool grounded;
//Non-Stick Player
private float moveVelocity;
// Use this for initialization
void Start () {
}
void FixedUpdate () {
grounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
}
// Update is called once per frame
void Update () {
// This code makes the character jump
if(Input.GetKeyDown (KeyCode.Space)&& grounded){
Jump();
}
// Double jump code
if(grounded)
doubleJump = false;
if(Input.GetKeyDown (KeyCode.Space)&& !doubleJump && !grounded){
Jump();
doubleJump = true;
}
//Non-Stick Player
moveVelocity = 0f;
// This code makes the character move from side to side using the A&D keys
if(Input.GetKey (KeyCode.D)){
//GetComponent<Rigidbody2D>().velocity = new Vector2(moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
moveVelocity = moveSpeed;
}
if(Input.GetKey (KeyCode.A)){
//GetComponent<Rigidbody2D>().velocity = new Vector2(-moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
moveVelocity = -moveSpeed;
}
GetComponent<Rigidbody2D>().velocity = new Vector2(moveVelocity, GetComponent<Rigidbody2D>().velocity.y);
}
public void Jump(){
GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jumpHeight);
}
}
@JGiles93
Copy link

void FixedUpdate() {

    move = Input.GetAxis ("Horizontal");
    grounded = Physics2D.OverlapCircle (groundCheck.position, groundCheckRadius, whatIsGround);
    player.velocity = new Vector2 (move * moveSpeed, player.velocity.y);
}

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