Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.