Last active
December 22, 2015 11:58
-
-
Save StefanoFiumara/6468920 to your computer and use it in GitHub Desktop.
Movement Code v2.0!
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 System.Collections; | |
using UnityEngine; | |
class GridMove : MonoBehaviour { | |
public float moveSpeed; | |
public float gridSize; | |
public enum PlayerState {MOVING, STOPPED}; | |
public enum Direction {UP, DOWN, LEFT, RIGHT}; | |
public Vector2 input; | |
private Vector3 startPosition; | |
private Vector3 endPosition; | |
private float t; | |
public PlayerState state; | |
public Direction facing; | |
void Start() { | |
state = PlayerState.STOPPED; | |
facing = Direction.RIGHT; | |
input = new Vector2(0,0); | |
} | |
public void Update() { | |
getInput(); | |
if (state != PlayerState.MOVING) { | |
if (input != Vector2.zero) { | |
StartCoroutine(move()); | |
} | |
} | |
} | |
public IEnumerator move() { | |
state = PlayerState.MOVING; | |
startPosition = transform.position; | |
t = 0; | |
float endPosX = startPosition.x + System.Math.Sign(input.x) * gridSize; | |
float endPosZ = startPosition.z + System.Math.Sign(input.y) * gridSize; | |
//Check bounds | |
if(endPosX > 13 || endPosX < 0 || endPosZ > 13 || endPosZ < 0) { | |
endPosition = startPosition; //No movement or we go off the board | |
//state = PlayerState.STOPPED; | |
} | |
else { | |
endPosition = new Vector3(endPosX, startPosition.y, endPosZ); | |
} | |
while (t < 1f) { | |
t += Time.deltaTime * (moveSpeed/gridSize); | |
transform.position = Vector3.Lerp(startPosition, endPosition, t); | |
yield return null; | |
} | |
state = PlayerState.STOPPED; | |
yield return null; | |
} | |
void getInput() { | |
//set facing direction on getKeyDown | |
if(Input.GetKeyDown("up")) { | |
if(facing != Direction.DOWN) { | |
facing = Direction.UP; | |
input.y = 1; | |
input.x = 0; | |
} | |
} else if(Input.GetKeyDown("left")) { | |
if(facing != Direction.RIGHT) { | |
facing = Direction.LEFT; | |
input.y = 0; | |
input.x = -1; | |
} | |
} else if(Input.GetKeyDown("down")) { | |
if(facing != Direction.UP) { | |
facing = Direction.DOWN; | |
input.y = -1; | |
input.x = 0; | |
} | |
} else if(Input.GetKeyDown("right")) { | |
if(facing != Direction.LEFT) { | |
facing = Direction.RIGHT; | |
input.y = 0; | |
input.x = 1; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment