作业需求
前置作业
请先完成上课的贪食蛇:贪食蛇
素材下载
STARTO!
先将开头的音效档案放到 Assets 底下
将 Head 物件新增元件 > 音讯 > 音讯源,并将 AudioClip 选择为刚刚新增的音效
并且将 “唤醒时播放” 取消打勾
在阶层视窗按下滑鼠右键 > UI > 文字
修改 Canvas 物件的属性,渲染模式为萤幕空间 – 摄影机,将渲染摄影机改为 MainCamera
修改 Text 物件的属性,颜色为白色,大小30,水平与垂直溢出改为 Overflow,文字改成”请开始游戏”
画面完成

再次新增一个 Text (阶层视窗滑鼠右键 > UI > 文字)
将第二次新增的 Text 更名为 “Score_Display”
修改 Score_Display 物件的属性,文字颜色白色,大小 35,水平垂直溢出设定为 Overflow
文字设定为 “Game Over 换行 please press ‘R’ to try again!”
将物件移动到画面中央位置

画面完成

修改 Snake.cs 脚本为以下程式码
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
public class Snake : MonoBehaviour
{
// Start is called before the first frame update
bool ate = false;
bool isDied = false;
public GameObject tailPrefab;
Vector2 dir = Vector2.right;
List<Transform> tail = new List<Transform>();
private Text Score_display;
private int Score;
private GameObject gameover_text;
void Start()
{
InvokeRepeating("Move", 0.1f, 0.1f);
Score_display = GameObject.Find("Text").GetComponent<Text>();
gameover_text = GameObject.Find("Score_Display").GetComponent<Transform>().gameObject;
gameover_text.SetActive(false);
}
// Update is called once per frame
void Update()
{
if (!isDied)
{
if (Input.GetKey(KeyCode.RightArrow))
dir = Vector2.right;
else if (Input.GetKey(KeyCode.DownArrow))
dir = -Vector2.up;
else if (Input.GetKey(KeyCode.LeftArrow))
dir = -Vector2.right;
else if (Input.GetKey(KeyCode.UpArrow))
dir = Vector2.up;
}
else
{
if (Input.GetKey(KeyCode.R))
{
for (int i = 0; i < tail.Count; i++)
tail[i].gameObject.SetActive(false);
tail.Clear();
transform.position = new Vector3(0, 0, 0);
isDied = false;
gameover_text.SetActive(false);
Score = 0;
Score_display.text = "现在分数:\n" + Score;
}
}
}
void Move()
{
if (!isDied)
{
Vector2 v = transform.position;
transform.Translate(dir);
if (ate)
{
GameObject g = (GameObject)Instantiate(tailPrefab, v, Quaternion.identity);
tail.Insert(0, g.transform);
ate = false;
}
else if (tail.Count > 0)
{
tail.Last().position = v;
tail.Insert(0, tail.Last());
tail.RemoveAt(tail.Count - 1);
}
}
}
void OnTriggerEnter2D(Collider2D coll)
{
if (coll.name.StartsWith("Food"))
{
ate = true;
GetComponent<AudioSource>().Play();
Score_display.text = "现在分数:\n" + ++Score;
Destroy(coll.gameObject);
}
else
{
isDied = true;
gameover_text.SetActive(true);
}
}
}
完成
Latest posts by SHXJ (see all)
- 受保护的内容: NAS 版 Mathbot 管理网站与 Linebot 启动方法 - 2024 年 11 月 15 日
- Realtime 啥鬼的 - 2021 年 6 月 15 日
- nodejs 数学游戏 - 2021 年 6 月 8 日









