What could I use if I want to add a feature that can determinate if the player is behind or in-front of the enemy? Is there any way of comparing if the players position is within or outside of 180-360 degrees? Or does anyone know any good script that tells this?
You can solve this easily with linear algebra. Basically you want to compare the vector from the enemy to the player and the vector that describes the direction the enemy is facing (the forward property of it’s transform) using a dot product which shows how similar two vectors are (Equivalent vectors will return a dot product of 1, perpendicular vectors will return 0, and opposite vectors will return -1. Everything in between returns some floating point value depending on how similar it is.). Here’s a script to demonstrate:
using UnityEngine;
using System.Collections;
public class FrontTest : MonoBehaviour {
public Transform target = null;
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.S)) {
Vector3 toTarget = (target.position - transform.position).normalized;
if (Vector3.Dot(toTarget, transform.forward) > 0) {
Debug.Log("Target is in front of this game object.");
} else {
Debug.Log("Target is not in front of this game object.");
}
}
}
}
Cant get this to work properly…I have modded it a bit to work for my project but it is basically switching from behind to in front of the target. (Im not using the Transform target, I am using the AI’s Base script and grabbing the transform.position from that)
public void OnTriggerEnter (Collider other)
{
// Player
if (UsedByPlayer) {
if (IsColliding) {
if (other.gameObject != User) {
if (other.tag == "Enemy") {
Target = other.GetComponent<AIBase> ();
target = other.transform;
if (MaxCrushingDamage > 0) {
Vector3 toTarget = (target.position - Char.transform.position).normalized;
if (Vector3.Dot(toTarget, Char.transform.forward) > 0) {
Debug.Log("Target is in front of this game object.");
}
else if (Vector3.Dot(toTarget, Char.transform.forward) < 0) {
Debug.Log("Target is not in front of this game object.");
}
}