Advertisement
Guest User

Untitled

a guest
Dec 7th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System.Linq;
  5.  
  6. public class Snake : MonoBehaviour {
  7. //Current movement directions
  8. //(By default it moves to the right)
  9. Vector2 dir = Vector2.right;
  10. List<Transform> tail = new List <Transform>();
  11. //Did the snake eat something?
  12. bool ate = false;
  13.  
  14. // Tail prefab
  15. public GameObject tailPrefab;
  16.  
  17. void OnTriggerEnter2D(Collider2D coll)
  18. {
  19. //Food?
  20. if (coll.name.StartsWith ("FoodPrefab")) {
  21. //get longer in next Move call
  22. ate = true;
  23.  
  24. //Remove the food
  25. Destroy (coll.gameObject);
  26. }
  27. //Collided with Tail or Border
  28. else
  29. {
  30. //Todo you lose screen
  31. }
  32.  
  33. }
  34. // Use this for initialization
  35. void Start ()
  36. {
  37. InvokeRepeating ("Move", 0.3f, 0.3f);
  38. }
  39.  
  40. // Update is called once per frame
  41. void Update ()
  42. {
  43. Vector2 tempVector = new Vector2 (0, -90);
  44. transform.rotation += tempVector;
  45.  
  46. //Move in a new direction?
  47. if (Input.GetKey (KeyCode.RightArrow))
  48. dir = Vector2.right;
  49. else if (Input.GetKey (KeyCode.DownArrow))
  50. dir = Vector2.down;
  51. else if (Input.GetKey (KeyCode.LeftArrow))
  52. dir = Vector2.left;
  53. else if (Input.GetKey (KeyCode.UpArrow))
  54. dir = Vector2.up;
  55. }
  56.  
  57. void Move()
  58. {
  59. //Save current position (Gap will be here)
  60. Vector2 v = transform.position;
  61.  
  62. //Move head into new direction
  63. transform.Translate(dir);
  64.  
  65.  
  66.  
  67. //Ate something?
  68. if (ate)
  69. {
  70. //Load Prefab into the world
  71. GameObject g = (GameObject)Instantiate(tailPrefab, v, Quaternion.identity);
  72.  
  73. //Keep track of it in our tail list
  74. tail.Insert(0, g.transform);
  75.  
  76. //Reset the flag
  77. ate = false;
  78. }
  79.  
  80. //Do we have a tail?
  81. else if (tail.Count > 0)
  82. {
  83. //move Last tail element to where the head was
  84. tail.Last().position = v;
  85.  
  86. //Add to front of list, remove from back
  87. tail.Insert (0, tail.Last ());
  88. tail.RemoveAt(tail.Count-1);
  89. }
  90. }
  91.  
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement