Im working on enemy AI for my game and I have a problem. The enemy has a collider on it and I want it to check for another objects distance (projectile). If the projectile is aimed towards the top of the enemy object, then the enemy should move downwards and if the projectile is aimed at the bottom the enemy should move upwards. I have got a vector2.distance method setup to measure the distance between the enemy and projectile but I want to check if the projectile is aimed at the top or bottom and if the distance of the projectile to the top for example is less than the distance to the bottom then let the enemy AddForce(transform.down * 800 * Time.deltaTime);
So its like dodging the projectile.
Dot products will be super useful here! Here’s an example of how to use them in this situation, though I highly recommend reading up on them, they are infinitely useful in game programming.
// Assuming projectile.transform.forward is the direction of the projectile...
float upperDot = Vector3.Dot(projectile.transform.forward, ((AI.transform.position + AI.transform.up) - projectile.transform.position).normalized);
float lowerDot = Vector3.Dot(projectile.transform.forward, ((AI.transform.position - AI.transform.up) - projectile.transform.position).normalized);
if (upperDot > lowerDot)
{
// Projectile is aimed more towards top
}
if (lowerDot > upperDot)
{
// Projectile is aimed more towards bottom
}
if (lowerDot == upperDot)
{
// Projectile is aimed at the center of the AI hitbox
}
That object has a collider and there is a simple trick and it might work
ColliderCenterY = GetComponent.<BoxCollider>().bounds.center.y;
//now you can find where the projectile in respective to object in Y axis
if ( ProjectileA.transform.position.y > ColliderCenterY) {
//move the object down
}
if ( ProjectileB.transform.position.y <= ColliderCenterY) {
//move the object Up
}
you can also use this code to find the max and min Y points like this
ColliderTopY = GetComponent.<BoxCollider>().bounds.max.y;
ColliderBottomY = GetComponent.<BoxCollider>().bounds.min.y;
and with it you can calculate the distance to top and bottom Y points. As long as you know the Vectors for your objects then you can get what you want.
for more info read this