- Home /
Check whether objects are within a sphere of influence
I'm creating an explosive weapon, and I need to be able to tell if enemies are inside of a sphere of influence. The issue I have is that I also need to be able to stop enemies who are behind walls from being hit by this sphere.
Right now I have an idea in my head that I can create a sphereOverlay, and for every single collider it touches, excluding walls, raycast towards the enemy in order to make sure it isn't going to hit a wall. Is there a more efficient way to get a list of every single enemy within a radius and only damage the enemy if they are not behind walls?
Answer by Kim-Nobre · May 16, 2019 at 09:52 PM
You can try something like this:
private void DamageNearbyEnemies()
{
Collider[] enemies = Physics.OverlapSphere(transform.position, sphereRadius);
for (int i = 0; i < enemies.Length; i++)
{
Ray ray = new Ray(transform.position, enemies[i].transform.position - transform.position);
if (Physics.Raycast(ray, out RaycastHit hit))
{
Enemy damageableEnemy = hit.collider.GetComponent<Enemy>();
if (damageableEnemy)
{
damageableEnemy.ApplyDamage();
}
}
}
}
Your answer
Follow this Question
Related Questions
Check whether objects are within a sphere of influence 0 Answers
Physics.Boxcast not working with mesh collider 1 Answer
Rotation is coming back way higher than random maximum 0 Answers
Non-convex mesh for ray-casting only as child of object with rigid body 0 Answers
How do i make a simple grappling hook? 0 Answers