Advertisement
jairogv98

grid movement

Dec 15th, 2019
514
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.53 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public enum Direction
  6. {
  7. up, down, right, left
  8. }
  9. public class Movement : MonoBehaviour
  10. {
  11. Animator anim;
  12. Vector2 targetPosition;
  13. Direction direction;
  14.  
  15. public float speed = 5f;
  16. public LayerMask obstacle;
  17. private void Start()
  18. {
  19. anim = GetComponent<Animator>();
  20. targetPosition = transform.position;
  21. direction = Direction.down;
  22. }
  23. void Update()
  24. {
  25. Vector2 axisDirection = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
  26. anim.SetInteger("Direccion", (int)direction);
  27. if (axisDirection != Vector2.zero && targetPosition == (Vector2)transform.position)
  28. {
  29. if (Mathf.Abs(axisDirection.x) > Mathf.Abs(axisDirection.y))
  30. {
  31. if (axisDirection.x > 0)
  32. {
  33. direction = Direction.right;
  34. if (!CheckCollision)
  35. targetPosition += Vector2.right;
  36. }
  37. else
  38. {
  39. direction = Direction.left;
  40. if (!CheckCollision)
  41. targetPosition -= Vector2.right;
  42. }
  43. }
  44. else
  45. {
  46. if (axisDirection.y > 0)
  47. {
  48. direction = Direction.up;
  49. if (!CheckCollision)
  50. targetPosition += Vector2.up;
  51. }
  52. else
  53. {
  54. direction = Direction.down;
  55. if (!CheckCollision)
  56. targetPosition -= Vector2.up;
  57. }
  58. }
  59. }
  60.  
  61. transform.position = Vector2.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
  62.  
  63. }
  64.  
  65. bool CheckCollision
  66. {
  67. get
  68. {
  69. bool col = true;
  70. RaycastHit2D rh;
  71.  
  72. Vector2 dir = Vector2.zero;
  73. if (direction == Direction.down)
  74. dir = Vector2.down;
  75. if (direction == Direction.up)
  76. dir = Vector2.up;
  77. if (direction == Direction.left)
  78. dir = Vector2.left;
  79. if (direction == Direction.right)
  80. dir = Vector2.right;
  81.  
  82.  
  83. rh = Physics2D.Raycast(transform.position, dir, 1, obstacle);
  84. return rh.collider != null;
  85.  
  86.  
  87.  
  88. return col;
  89. }
  90. }
  91.  
  92.  
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement