Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using System.Linq;
- public class Snake : MonoBehaviour {
- //Current movement directions
- //(By default it moves to the right)
- Vector2 dir = Vector2.right;
- List<Transform> tail = new List <Transform>();
- //Did the snake eat something?
- bool ate = false;
- // Tail prefab
- public GameObject tailPrefab;
- 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
- {
- //Todo you lose screen
- }
- }
- // Use this for initialization
- void Start ()
- {
- InvokeRepeating ("Move", 0.3f, 0.3f);
- }
- // Update is called once per frame
- void Update ()
- {
- Vector2 tempVector = new Vector2 (0, -90);
- transform.rotation += tempVector;
- //Move in a new direction?
- if (Input.GetKey (KeyCode.RightArrow))
- dir = Vector2.right;
- else if (Input.GetKey (KeyCode.DownArrow))
- dir = Vector2.down;
- else if (Input.GetKey (KeyCode.LeftArrow))
- dir = Vector2.left;
- 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
- transform.Translate(dir);
- //Ate something?
- 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;
- }
- //Do we 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 back
- tail.Insert (0, tail.Last ());
- tail.RemoveAt(tail.Count-1);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement