Skip to content

Instantly share code, notes, and snippets.

@ahmadnaser
Created December 29, 2015 06:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmadnaser/a46353ad0854816ffb0f to your computer and use it in GitHub Desktop.
Save ahmadnaser/a46353ad0854816ffb0f to your computer and use it in GitHub Desktop.
Allow player to move based on three buttons - left,right,jump
using UnityEngine;
using System.Collections;
public class PlayerJoystick : MonoBehaviour
{
public float speed = 0.1f, maxVelocity = 0.05f;
private Rigidbody2D myBody;
private Animator anim;
private bool moveLeft, moveRight;
private bool flippedToLeft;
void Awake ()
{
myBody = GetComponent<Rigidbody2D> ();
anim = GetComponent<Animator> ();
}
void FixedUpdate ()
{
if (moveLeft) {
MoveLeft ();
}
if (moveRight) {
MoveRight ();
}
}
public void SetMoveLeft (bool moveLeft)
{
this.moveLeft = moveLeft;
this.moveRight = !moveLeft;
flippedToLeft = !moveLeft;
}
public void StopMoving ()
{
moveLeft = moveRight = false;
anim.SetBool ("walk", false);
}
void MoveLeft ()
{
float forceX = 0f;
float vel = Mathf.Abs (myBody.velocity.x);
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);
transform.position += new Vector3 (forceX, 0, 0);
}
void MoveRight ()
{
float forceX = 0f;
float vel = Mathf.Abs (myBody.velocity.x);
if (vel < maxVelocity)
forceX = speed;
Vector3 temp = transform.localScale;
temp.x = Mathf.Abs (transform.localScale.x) * 1f;
temp.y = Mathf.Abs (transform.localScale.y);
transform.localScale = temp;
anim.SetBool ("walk", true);
transform.position += new Vector3 (forceX, 0, 0);
}
} // PlayerJoystick
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment