*
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
using System.Linq;
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
|
||||
|
||||
|
||||
public class AiFindEnemy : AiBehavior {
|
||||
|
||||
private GameObject obj;
|
||||
private PlayerSensor sensor;
|
||||
private HumanController selfController;
|
||||
public LayerMask skipMask;
|
||||
|
||||
protected override void OnBegin(AiBlackboard blackboard) {
|
||||
base.OnBegin(blackboard);
|
||||
if (obj == null) {
|
||||
obj = blackboard.Obj;
|
||||
sensor = obj.GetComponent<HumanoidAI>().viewSensor;
|
||||
selfController = obj.GetComponent<HumanController>();
|
||||
}
|
||||
}
|
||||
|
||||
protected override BehaviorStatus OnExecute(AiBlackboard blackboard) {
|
||||
|
||||
bool playerInCone = sensor.Player != null;
|
||||
if (playerInCone) {
|
||||
var enemyEyes = sensor.Player.eyes.transform.position;
|
||||
var selfEyes = selfController.eyes.transform.position;
|
||||
|
||||
var from = new Vector3[] { selfEyes, selfEyes };
|
||||
var to = new Vector3[] { enemyEyes, sensor.Player.transform.position };
|
||||
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
Debug.DrawLine(from[i], to[i], Color.gray);
|
||||
}
|
||||
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
if (RaycastEnemy(from[i], to[i])) {
|
||||
blackboard.SetValue(BlackboardVariables.Enemy, sensor.Player);
|
||||
blackboard.SetValue(BlackboardVariables.LastEnemyPosition, sensor.Player.transform.position);
|
||||
|
||||
//Debug.Log("Raycast OK");
|
||||
return BehaviorStatus.Success;
|
||||
}
|
||||
}
|
||||
// Debug.Log("Raycast FAIL");
|
||||
}
|
||||
|
||||
blackboard.SetValue(BlackboardVariables.Enemy, null);
|
||||
|
||||
return BehaviorStatus.Fail;
|
||||
}
|
||||
|
||||
private bool RaycastEnemy(Vector3 from, Vector3 to) {
|
||||
var hits = Physics2D.RaycastAll(from, (to - from).normalized, 100, (Physics2D.DefaultRaycastLayers & (~skipMask.value)));
|
||||
|
||||
//find first collision which is not inside player head
|
||||
int firstOutsideId = -1;
|
||||
for (int i = 0; i < hits.Length; ++i) {
|
||||
if (hits[i].fraction > 0.0f) {
|
||||
firstOutsideId = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (firstOutsideId >= 0) {
|
||||
var hit = hits[firstOutsideId];
|
||||
var g = hit.collider.GetComponent<PlayerController>();
|
||||
if (g != null) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user