菜鸡代码,大佬勿喷
矩形的两个对角可以确定矩形大小
如图a,b两点确定一个矩形范围,或者一个空间范围;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AiMove : MonoBehaviour
{
private GameObject End;
private Transform Db3;
bool suo = false;
//时间容器
float time = 0;
//时间范围我这里是随机的,也可以改为动值
int time1;
//v1,v2确定矩形范围
Vector3 v1;
Vector3 v2;
//目标点
Vector3 pos;
// Start is called before the first frame update
void Start()
{
End = PlayGame.Ins.End.gameObject;
Db3 = End.transform.GetChild(End.transform.childCount - 1);
v1 = Db3.GetChild(Db3.childCount-1).position;
v2 = Db3.GetChild(Db3.childCount-1).GetChild(0).position;
pos=RendV3(v1,v2);
var a = Instantiate(Resources.Load("dian"));
a.transform.position = pos;
suo = true;
}
// Update is called once per frame
void Update()
{
if (suo)
{
transform.position = Vector3.MoveTowards(transform.position, pos, Time.deltaTime*2);
}
else
{
time += 0.01f;
}
//冷却时间过time1秒后再次行动;
if (time>time1)
{
pos = RendV3(v1, v2);
//刷新时利用lookat转向
transform.LookAt(pos);
//这里需要在目标点生成一个碰撞体以便判断到点
var a = Instantiate(Resources.Load("dian"));
a.transform.position = pos;
time = 0;
suo = true;
}
}
//根据两点在范围内随机坐标
Vector3 RendV3(Vector3 a,Vector3 b)
{
print(a);
print(b);
Vector3 x = new Vector3(Random.Range(a.x,b.x),a.y,Random.Range(a.z,b.z));
print(x);
return x;
}
private void OnCollisionEnter(Collision col)
{
if (col.transform.name=="dian")
{
print(1);
suo = false;
time1 = Random.Range(3,6);
Destroy(col.transform.parent.gameObject);
}
}
}
最后把脚本放在需要移动的ai上,记得加刚体和碰撞;
触发器用的是OnCollisionEnter,不要勾选isTrigger
这个是平面移动,如果是3D空间内随机移动只需要修改返回的坐标就可以
把函数替换即可
Vector3 RendV3(Vector3 a,Vector3 b)
{
//print(a);
//print(b);
Vector3 x = new Vector3(Random.Range(a.x,b.x), Random.Range(a.y, b.y),
Random.Range(a.z,b.z));
//print(x);
num++;
return x;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)