Unity和C#-游戏开发-贪吃蛇+源代码工程
2021/8/1 9:35:52
本文主要是介绍Unity和C#-游戏开发-贪吃蛇+源代码工程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.UI;
using System;
public class Snake : MonoBehaviour
{
// Current Movement Direction
// (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;
public Action OnLose;
// Use this for initialization
void Start()
{
// Move the Snake every 300ms
InvokeRepeating("Move", 0.3f, 0.3f);
}
void OnTriggerEnter2D(Collider2D coll)
{
// Food?
if (coll.name.StartsWith("food"))
{
// Get longer in next Move call
ate = true;
// Remove the Food
Destroy(coll.gameObject);
}
// Collided with Tail or Border
else
{
OnLose();
}
}
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'
else if (Input.GetKey(KeyCode.LeftArrow))
dir = -Vector2.right; // '-right' means 'left'
else if (Input.GetKey(KeyCode.UpArrow))
dir = Vector2.up;
}
void Move()
{
// Move head into new direction
Vector2 v = transform.position;
transform.Translate(dir);
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 the back
tail.Insert(0, tail.Last());
tail.RemoveAt(tail.Count - 1);
}
}
}
https://item.taobao.com/item.htm?ft=t&id=652525567349
这篇关于Unity和C#-游戏开发-贪吃蛇+源代码工程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具
- 2024-01-24.NET集成IdGenerator生成分布式全局唯一ID