|
using UnityEngine;
using System.Collections;
public class NPC : MonoBehaviour {
GameObject tank;
public Transform target;
public Transform targetRotation1;
public Transform targetRotation2;
int cun_time;
void Start()
{
cun_time = 0;
if (target == null && GameObject.Find("NPC"))
{
target = GameObject.Find("NPC").transform;
}
}
void Update()
{
tank = GameObject.Find("Player");//实例化
if (target == null)
return;
Vector3 relativePos1 = target.position - tank.transform.position;
Quaternion targetRotation1 = Quaternion.LookRotation(relativePos1);//求出与目标之间的角度
tank.transform.rotation = Quaternion.Slerp(tank.transform.rotation, targetRotation1, Time.deltaTime * 2.0f);//旋转之角度与目标对齐
Vector3 forward = tank.transform.TransformDirection(Vector3.forward);
Vector3 targetDir =tank.transform.position-target.position;//求出2者之间的距离
if((Vector3.Angle(forward, targetDir) <10.0)||((Vector3.Angle(forward, targetDir) >-10.0))) //这边是自动开炮的效果
{
cun_time++;
if(cun_time==260)
{
fire ();
cun_time=0;
}
}
if((Vector3.Distance(transform.position, this.transform.position) < 50))//发现目标而且在范围之内,开始追击目标
{
Vector3 relativePos2 = target.position - tank.transform.position;
Quaternion targetRotation2 = Quaternion.LookRotation (relativePos2);
tank.transform.rotation = Quaternion.Slerp(tank.transform.rotation, targetRotation2, Time.deltaTime * 1.0f);
tank.transform.Translate(Vector3.forward*0.05f);
}
}
void fire()
{
GameObject obj=GameObject.CreatePrimitive(PrimitiveType.Sphere);
obj.transform.localScale=new Vector3(0.5f,0.5f,0.5f);
obj.transform.position=this.transform.position;
obj.transform.rotation=this.transform.rotation;
obj.AddComponent<Rigidbody>();
obj.AddComponent<Bullet>();
Physics.IgnoreCollision(obj.collider, collider);
}
}
效果好像差的蛮远,拜托各位大大指点指点
|
|