【发布时间】:2017-06-30 09:10:02
【问题描述】:
所以我正在制作 Spectrum 游戏“Snake Pit”的复制品。你可以作为你的玩家移动,并且有多个 AI 控制的蛇。我正试图弄清楚当蛇头就在你旁边时,如何让它们移动到你的位置。这是我想要实现的代码。
public class SnakeController : MonoBehaviour {
public int maxSize;
public int currentSize;
public GameObject snakePrefab;
public Snake Head;
public Snake Tail;
public Vector2 nextPos;
public int NESW;
int Random;
float lineTimer;
int NESWTemp;
// Use this for initialization
void Start () {
InvokeRepeating("TimerInvoke", 0, .3f);
lineTimer = UnityEngine.Random.Range(0, 2.5f);
currentSize = 1;
}
// Update is called once per frame
void Update () {
lineTimer -= Time.deltaTime;
if (lineTimer <= 0)
{
ComChangeD();
lineTimer = UnityEngine.Random.Range(0, 2.5f);
}
}
void TimerInvoke()
{
Movement();
if(currentSize >= maxSize)
{
TailFunction();
}
else
{
currentSize++;
}
}
void Movement()
{
GameObject temp;
nextPos = Head.transform.position;
if(nextPos.y > 3.22)
{
NESW = 2;
}
else if (nextPos.y < -4.42)
{
NESW = 0;
}
else if (nextPos.x < -8.2)
{
NESW = 1;
}
else if (nextPos.x > 7.7)
{
NESW = 3;
}
switch (NESW)
{
case 0:
nextPos = new Vector2(nextPos.x, nextPos.y + 0.32f);
break;
case 1:
nextPos = new Vector2(nextPos.x + 0.32f, nextPos.y);
break;
case 2:
nextPos = new Vector2(nextPos.x, nextPos.y - 0.32f);
break;
case 3:
nextPos = new Vector2(nextPos.x - 0.32f, nextPos.y);
break;
}
temp = (GameObject)Instantiate(snakePrefab, nextPos, transform.rotation);
Head.SetNext(temp.GetComponent<Snake>());
Head = temp.GetComponent<Snake>();
return;
}
void ComChangeD()
{
NESWTemp = UnityEngine.Random.Range(0, 3);
if (NESW == 0)
{
switch (NESWTemp)
{
case 0:
NESW = 1;
break;
case 1:
NESW = 2;
break;
case 2:
NESW = 3;
break;
}
}
else if (NESW == 1)
{
switch (NESWTemp)
{
case 0:
NESW = 0;
break;
case 1:
NESW = 2;
break;
case 2:
NESW = 3;
break;
}
}
else if (NESW == 2)
{
switch (NESWTemp)
{
case 0:
NESW = 0;
break;
case 1:
NESW = 1;
break;
case 2:
NESW = 3;
break;
}
}
else if (NESW == 3)
{
switch (NESWTemp)
{
case 0:
NESW = 0;
break;
case 1:
NESW = 1;
break;
case 2:
NESW = 2;
break;
}
}
}
【问题讨论】:
-
通常这些游戏的逻辑是无论AI在哪里,离玩家角色近1步......无论它在哪里......
-
@BugFinder 好吧,有多个蛇,这会使游戏变得太难,不过我不介意测试和调整。你能帮我吗?但除此之外,这个功能就在那里,如果蛇在玩家旁边,它们会杀死玩家。现在他们只是去一些地方,并不真正关心玩家。
-
我不知道蛇游戏是什么,但为什么不使用对撞机?
-
@AleksaRistic 就像用触发器在蛇头周围制作一个盒子对撞机一样?
-
是的。是 2d 还是 3d 游戏?
标签: c# artificial-intelligence unity5 detection