Created
December 29, 2015 09:17
-
-
Save ahmadnaser/3a048ef5510e2f65c1a6 to your computer and use it in GitHub Desktop.
Allow player to move and jump based on keyboard arrows and space jump
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
public class PlayerKeyboardController : MonoBehaviour | |
{ | |
//to make movement more smoother | |
//Change Mass to 0.1f | |
//Linear Drag to 0.4f | |
//Andgular Drag to 0.05f | |
//Gravity Scale to 0.2 | |
public float speed = 8f, maxVelocity = 4f; | |
public float jumpSpeed = 25.0F; | |
public float gravity = 5.0F; | |
private Rigidbody2D myBody; | |
private Animator anim; | |
private bool moveLeft, moveRight; | |
private bool flippedToLeft; | |
void Awake () | |
{ | |
myBody = GetComponent<Rigidbody2D> (); | |
anim = GetComponent<Animator> (); | |
} | |
//if we have 50 frame, this method will be called 50 time | |
void Update () | |
{ | |
} | |
//every couple of frames, used to deal with physics | |
void FixedUpdate () | |
{ | |
if (Input.GetKeyDown (KeyCode.Space)) { | |
myBody.AddForce (Vector3.up * jumpSpeed); | |
} | |
PlayerKeyboardMovement (); | |
} | |
void PlayerKeyboardMovement () | |
{ | |
float forceX = 0f; | |
float vel = Mathf.Abs (myBody.velocity.x); | |
float inp = Input.GetAxisRaw ("Horizontal"); | |
//-1 left, 0 no movement, 1 right | |
if (inp > 0) { | |
if (vel < maxVelocity) | |
forceX = speed; | |
//reflect the player | |
Vector3 temp = transform.localScale; | |
temp.x = Mathf.Abs (transform.localScale.x) * 1f; | |
temp.y = Mathf.Abs (transform.localScale.y); | |
transform.localScale = temp; | |
flippedToLeft = false; | |
} else if (inp < 0) { | |
if (vel < maxVelocity) | |
forceX = -speed; | |
Vector3 temp = transform.localScale; | |
if (!flippedToLeft) { | |
temp.x = Mathf.Abs (transform.localScale.x) * -1f; | |
flippedToLeft = true; | |
} | |
temp.y = Mathf.Abs (transform.localScale.y); | |
transform.localScale = temp; | |
//anim.SetBool ("walk", true); | |
} else { | |
//stop animating | |
} | |
myBody.AddForce (new Vector2 (forceX, 0)); | |
} | |
} // PlayerKeyboardController | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment