// 这段代码用于导弹之类的发射,自动寻找目标等等 |
public Vector3 Noise = new Vector3 (20, 20, 20); |
public float Damping = 3; |
public float TargetLockDirection = 0.5f; |
public int DistanceLock = 70; |
public int DurationLock = 40; |
private bool locked; |
private void FixedUpdate() { |
// 给物体一个速度向量(去掉重力) |
rigidbody.velocity = new Vector3(transform.forward.x * Speed * Time.fixedDeltaTime, transform.forward.y * Speed * Time.fixedDeltaTime, transform.forward.z * Speed * Time.fixedDeltaTime); |
rigidbody.velcoity += new Vector3 (Random.Range (-Noise.x, Noise.x), Random.Range (-Noise.y, Noise.y), Random.Range (-Noise.z, Noise.z)); |
// 若不给予一个速度,则物体将会匀速运动 |
if (Speed < SpeedMax) { |
Speed += SpeedMult * Time.fixedDeltaTime; |
} |
} |
// 在Update里,所要做的是1.寻找并锁定目标 2.旋转角色,使得其向着目标前进 |
private void Update() { |
if (Target) { |
// 获取目标与角色之间的角度差,以四元数的形式返回 |
// 这里是使角色的z轴正方向对着目标 |
Quaternion rotation = Quaternion.LookRation(Target.transform.position - transform.transform.position); |
// 平滑地转向目标 |
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * Damping); |
// 计算目标与角色之间的余弦值,判断目标是否仍在范围内 |
Vector3 dir = (Target.transform.position - transform.position).normalized; |
float direction = Vector3.Dot (dir, transform.forward); |
// 不在范围内就重置目标 |
if (direction < TargetLockDirection) { |
Target = null ; |
} |
} |
// 是否启动锁定器? |
if (Seeker) { |
// 延迟锁定的时间 |
if (timeToLock > DurationLock) { |
// 没有锁定并且没有找到目标 |
if (!locked && !Target) { |
float distance = int .MaxValue; |
// 遍历所有目标对象 |
for ( int t = 0; t < TargetTag.Length; t++) { |
if (GameObject.FindGameObjectsWithTag(TargetTag[t].Length > 0)) { |
GameObject[] objs = GameObject.FindGameObjectsWithTag(TargetTag[t]); |
for ( int i = 0; i < objs.Length; i++) { |
if (objs[i]) { |
// 这两段代码的作用是用于计算对象与角色之间夹角的余弦值,再根据余弦值来判断对象是否在目标范围内 |
// 这里应用到的数学知识是两个向量a,b的点乘相当于a,b的模相乘,再与它们之间的余弦值相乘。 |
// 先求出对象与角色之间的方向向量,再单位化,则它的模就为1了 |
// transform.forward相对于角色前进方向(z轴)的方向向量,它的模是1 |
// 因此变量direction就是它们两个方向向量的余弦值了。 |
Vector3 dir = (objs[i].transform.position - transform.position.normalized); |
float direction = Vector3.Dot(dir, transform.forward); |
// 求得两个对象之间的距离 |
float dis = Vector3.Distance(objs[i].transform.position, transform.position); |
// 若果对象在目标范围之内, 记得direction是余弦值, |
if (direction >= TargetLockDirection) { |
// 若果对象在目标距离之内 |
if (DistanceLock > dis) { |
// 选择距离最近的 |
if (distance > dis) { |
distance = dis; |
Target = objs[i]; |
} |
locked = true ; |
} |
} |
} |
} |
} |
} |
} |
} else { |
timeToLock += 1; |
} |
if (Target) { |
} else { |
locked = false ; |
} |
} |
} |
by: 发表于:2018-01-08 10:20:28 顶(0) | 踩(0) 回复
??
回复评论