Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections.Generic;
- using System.Linq;
- using UnityEngine;
- public class Snake : MonoBehaviour
- {
- // Panel for gameover
- public RectTransform GameOver_m;
- //text game over
- public Text eGameSmore;
- // Snake ate the food
- bool ate = false;
- // Tail Prefab
- public GameObject tailPrefab;
- // Current Movement Direction
- Vector2 dir = Vector2.right;
- private List<Transform> tail = new List<Transform>();
- // initialization
- void Start()
- {
- // Move the Snake every second
- InvokeRepeating("Move", 0.1f, 0.1f);
- }
- // Update is called once per Frame
- void Update()
- {
- // Move in a new Direction?
- if (Input.GetKey(KeyCode.RightArrow))
- dir = Vector2.right;
- else if (Input.GetKey(KeyCode.DownArrow))
- dir = -Vector2.up; // -up means down -- who made these rules up....
- else if (Input.GetKey(KeyCode.LeftArrow))
- dir = -Vector2.right; // -right means left -- who made these rules up....
- else if (Input.GetKey(KeyCode.UpArrow))
- dir = Vector2.up;
- }
- void Move()
- {
- // Save current position (gap will be here)
- Vector2 v = transform.position;
- // Move head into new direction (now there is a gap)
- transform.Translate(dir);
- // Ate something? Then insert new Element into gap
- if (ate)
- {
- // Load Prefab into the world
- GameObject g = (GameObject) Instantiate(tailPrefab,
- v,
- Quaternion.identity);
- // Keep track of it in our tail list
- tail.Insert(0, g.transform);
- // Reset the flag
- ate = false;
- }
- //Does have a Tail?
- else if (tail.Count > 0)
- {
- // Move last Tail Element to where the Head was
- tail.Last().position = v;
- // Add to front of list, remove from the back
- tail.Insert(0, tail.Last());
- tail.RemoveAt(tail.Count - 1);
- }
- }
- void OnTriggerEnter2D(Collider2D coll)
- {
- // Food?
- if (coll.name.StartsWith("FoodPrefab"))
- {
- // Get longer in next Move call
- ate = true;
- // Remove the Food
- Destroy(coll.gameObject);
- }
- // Collided with Tail or Border
- else Destroy(gameObject);
- {
- // 'You lose' - Game over.
- else private void OnEnable()
- {
- StartCoroutine(Co_ReloadScene(3f));
- }
- private IEnumerator Co_ReloadScene(float delay)
- {
- yield return new WaitForSeconds(delay);
- //load scene code here. Game Over
- int scene = SceneManager.GetActiveScene().buildIndex;
- SceneManager.LoadScene(scene, LoadSceneMode.Single);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement