- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using System.Collections.Generic;
- using System.Linq;
- using System;
- using UnityEngine.UI;
- public class Snake : MonoBehaviour
- {
- public GameObject weiba;.//插入一个尾巴
- public float spead = 0.3f;//浮动时间值
- Vector2 dir = Vector2.right;//默认动方向
- List<Transform> tail = new List<Transform> ();
- public int Fenshudangqian;
- public Text Denfenkuang;
- public static bool eat =false ;
- public Action Onloss;
-
- // Start is called before the first frame update
- void Start()
- {
- InvokeRepeating("Move", spead, spead);
- }
- void Move()
- {
- Vector2 v = transform.position;
- transform.Translate(dir);
- if (eat)
- {
- GameObject g = (GameObject)Instantiate(weiba, v, Quaternion.identity);
- tail.Insert(0, g.transform);
- eat = false;
- }
- else if(tail.Count >0)
- {
- tail.Last().position = v;
- tail.Insert(0, tail.Last());
- tail.RemoveAt (tail.Count-1);
- }
- }
- // Update is called once per frame
- void Update()
- {
- //控制小蛇方向
- 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;
- }
- public void OnTriggerEnter2D(Collider2D coll)
- {
- //物体碰撞计算
- Debug .Log ("get血包");
- if (coll.name.StartsWith("food"))
- {
- eat = true;
- Destroy(coll.gameObject);
- Fenshudangqian++;
- Denfenkuang.text = Fenshudangqian.ToString();
- }
- else
- {
- //负责发送东西
- if (Onloss != null)
- Onloss();
- }
- }
- }