Created
December 29, 2015 06:57
-
-
Save ahmadnaser/a46353ad0854816ffb0f to your computer and use it in GitHub Desktop.
Allow player to move based on three buttons - left,right,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 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