Created
September 5, 2013 17:57
-
-
Save StefanoFiumara/6453747 to your computer and use it in GitHub Desktop.
A small example of using player states to handle movement.
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 Player : MonoBehaviour { | |
public enum PlayerState {MOVING_UP, MOVING_DOWN, MOVING_LEFT, MOVING_RIGHT}; | |
public PlayerState state; | |
public float speed; | |
// Use this for initialization | |
void Start () { | |
//must assign an initial state | |
state = PlayerState.MOVING_RIGHT; | |
} | |
// Update is called once per frame | |
void Update () { | |
//Input only affects the state | |
if(Input.GetKeyDown("up")) { | |
if(state != PlayerState.MOVING_DOWN) { | |
state = PlayerState.MOVING_UP; | |
} | |
} else if(Input.GetKeyDown("left")) { | |
if(state != PlayerState.MOVING_RIGHT) { | |
state = PlayerState.MOVING_LEFT; | |
} | |
} else if(Input.GetKeyDown("down")) { | |
if(state != PlayerState.MOVING_UP) { | |
state = PlayerState.MOVING_DOWN; | |
} | |
} else if(Input.GetKeyDown("right")) { | |
if(state != PlayerState.MOVING_LEFT) { | |
state = PlayerState.MOVING_RIGHT; | |
} | |
} | |
//After Input, we decide what the player should do this frame, based on his state. | |
switch(state) { | |
case PlayerState.MOVING_LEFT: | |
rigidbody.velocity = new Vector3(-speed,0,0); | |
break; | |
case PlayerState.MOVING_RIGHT: | |
rigidbody.velocity = new Vector3(speed,0,0); | |
break; | |
case PlayerState.MOVING_UP: | |
rigidbody.velocity = new Vector3(0,0,speed); | |
break; | |
case PlayerState.MOVING_DOWN: | |
rigidbody.velocity = new Vector3(0,0,-speed); | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment