Advertisement
Guest User

Untitled

a guest
Apr 27th, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5.  
  6. public class PlayerController : MonoBehaviour
  7. {
  8.  
  9. public float Speed = 1.0f;
  10. public float MoveDistance = 2.0f;
  11.  
  12. public enum MOVEMENTTYPE
  13. {
  14. MOVING,
  15. PUSHING,
  16. IDLE
  17. };
  18.  
  19. public MOVEMENTTYPE MovementState;
  20.  
  21. // public Transform transform;
  22.  
  23. // Use this for initialization
  24. void Start()
  25. {
  26. MovementState = MOVEMENTTYPE.IDLE;
  27. }
  28.  
  29. // Update is called once per frame
  30. void Update()
  31. {
  32. switch (MovementState)
  33. {
  34. case MOVEMENTTYPE.IDLE:
  35. HandleInput();
  36. break;
  37. case MOVEMENTTYPE.MOVING:
  38.  
  39. break;
  40. case MOVEMENTTYPE.PUSHING:
  41.  
  42. break;
  43. }
  44.  
  45. }
  46.  
  47. public void HandleInput()
  48. {
  49. Vector3 movement_vector = new Vector3(0f, 0f, 0f);
  50.  
  51. if (MovementState == MOVEMENTTYPE.MOVING) return;
  52.  
  53. if (Input.GetAxis("Horizontal") > 0f)
  54. {
  55. movement_vector = new Vector3(MoveDistance, 0f, 0f);
  56.  
  57. }
  58. else if (Input.GetAxis("Horizontal") < 0f)
  59. {
  60. movement_vector = new Vector3(-MoveDistance, 0f, 0f);
  61.  
  62. }
  63. else if (Input.GetAxis("Vertical") > 0f)
  64. {
  65. movement_vector = new Vector3(0f, 0f, MoveDistance);
  66.  
  67. }
  68. else if (Input.GetAxis("Vertical") < 0f)
  69. {
  70. movement_vector = new Vector3(0f, 0f, -MoveDistance);
  71. }
  72. if (movement_vector.magnitude != MoveDistance) return;
  73.  
  74. StartCoroutine(Move(FixToGrid(transform.position + movement_vector)));
  75. }
  76.  
  77. private IEnumerator Move(Vector3 targetPos)
  78. {
  79. MovementState = MOVEMENTTYPE.MOVING;
  80.  
  81. var dir = Vector3.Normalize(targetPos - transform.position);
  82. while(Vector3.Distance(transform.position,targetPos) > 0.1f)
  83. {
  84. transform.position += dir * Time.deltaTime * Speed;
  85. yield return null;
  86. }
  87. MovementState = MOVEMENTTYPE.IDLE;
  88. }
  89.  
  90. public Vector3 FixToGrid(Vector3 _vector)
  91. {
  92. return new Vector3(
  93. Mathf.Round(_vector.x),
  94. Mathf.Round(_vector.y),
  95. Mathf.Round(_vector.z));
  96. }
  97.  
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement