今天介绍第一种只靠 c# 代码的 简单 AI 敌人 追踪方法:
简单粗暴 ,上代码
1,新建对象
2,代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AI : MonoBehaviour
{
public GameObject player;
public float attackrange;
public float movespeed;
// Start is called before the first frame update
// Update is called once per frame
void FixedUpdate()
{
float dist = Vector3.Distance(player.transform.position, transform.position);
if (dist > attackrange)
{
transform.Translate(Vector3.right * movespeed * Time.deltaTime);
}
Vector2 direction = player.transform.position - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
ps,此方法只能用于一般低智商ai,全程 面对着 player,在进入攻击范围之后,延x/y轴 向前。
若 3d 游戏 可用 lookat 函数,but 该函数之作用于y轴。