貪食蛇加強版 (作業十)

作業需求

前置作業

請先完成上課的貪食蛇:貪食蛇

素材下載

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);
}
}
}

完成

SHXJ
Latest posts by SHXJ (see all)

發佈留言