struggling with enemy AI
My enemy dodges an incoming projectile by detecting if its aimed to its head (the top) or the bottom torso (the bottom). If it is heading to the top then the enemy moves down and if its heading to the bottom it moves upwards to dodge it, It works fine except the enemy is colliding with the ground or "ceiling" of the scene it cannot go any further and so it stays where it is and carries on getting shot. How can I overcome this and make the enemy move downwards if its stuck at the top and vice versa. Thanks
if (GameObject.Find("Laser(Clone)") != null){
float topProjectileDistance = Vector2.Distance(topHalf.transform.position, GameObject.Find("Laser(Clone)").transform.position);
float bottomProjectileDistance = Vector2.Distance(bottomHalf.transform.position, GameObject.Find("Laser(Clone)").transform.position);
if(topProjectileDistance <= 10 && bottomProjectileDistance <= 10){
rb.AddForce(Vector3.right * speed/2 * Time.deltaTime);
if(topProjectileDistance < bottomProjectileDistance)
{
rb.AddForce(Vector3.down * speed * Time.deltaTime);
}else{
rb.AddForce(Vector3.up * speed * Time.deltaTime);
}
}
}
you can always try to disable the rigidbody when you move, and use the prefab's position ins$$anonymous$$d of addforce and then re-enable it after its done dodging. Just an idea.
Answer by callen · Dec 31, 2015 at 05:15 PM
You want the enemy to move...
Down when its top half is shot at
Up when its bottom half is shot at
Down when it's at the top of the screen
Up when it's at the bottom of the screen
Currently, your code only handles the first two. You should modify your 2nd if-statement to include the other cases. Something like...
public float avoidBoundsDistance = 5;
...
// calc these the same way as top/bottomProjectileDistance
float distanceToCeiling, distanceToFloor;
if(distanceToCeiling < avoidBoundsDistance)
// add force down
else if(distanceToFloor < avoidBoundsDistance)
// add force up
else if(topProjectileDistance < bottomProjectileDistance)
// add force down
else
// add force up
Answer by Elier · Jan 02, 2016 at 08:17 AM
It's not very complicated, you already have most of the work done:
First create a bool variable that will indicate if the enemy will dodge moving up or moving down (true = up, false = down).
Instead of applying the forces inmediatly, just set the variable using the calculations that you already have for the projectile targeting the head or torso.
Now, before trying to move up or down, check how close the enemy is to the floor or ceiling using Raycast. If the enemy is too close and can't dodge in the direccion it should, reverse the boolean.
Finally if the boolean is true apply the force upwards, or else apply the force downwards.
Your answer
Follow this Question
Related Questions
Turret AI Script - one way detection 0 Answers
Rain AI follow path and detect 0 Answers
How to keep an array of targets in detection radius? 0 Answers
How would I Move a rigidbody towards another object? 3 Answers