- Home /
Find number of objects between two points
I am currently trying to write a simple AI and I need a quick way to find the number of objects between two points.
Little more details: It is something like a breakout game, but with tanks fighting each other, with destructible cover in between. Each of the tanks can only move along a vertical line and in order to find a valid attack position for the enemy I want to find a path between the player and a spot on the enemies 'homezone' that minimizes the number of obstacles between the two (with closer positions with slightly more obstacles would be preferred to further positions).
My first instinct would be to shoot some rays from a number of positions (slightly randomized) towards the player, but I have no idea if or how I could count the number of hits, since the Raycast only returns the first. Another idea might be to 'sweep' a collider in an arcing movement across the battlefield, pivot at the player's position and use OnTriggerEnter/Exit to increment/decrement a number and remember the angle when that number was smallest. But I would need many frames to make it work, instead of calculating the best position in a single frame.
Is there an existing function in Unity that would allow me to find the number of objects quickly and reliably, or alternatively a workaround/hack?
Not sure how well this would work since it depends on your setup, but you could raycast downwards multiple times along a path between source+Vector3(0,20,0) and dest+Vector3(0,20,0). You'd then store unique hits. Something like:
var objectsHit:Array=new Array();
for(var i:float=0;i<=1;i+=0.01){
var curPos:Vector3=Vector3.Lerp(source+Vector3(0,20,0),dest+Vector3(0,20,0),i);
if(Physics.Raycast(curPos,-Vector3.up,blah blah){
//if the hit object isn't on the objectsHit list, add it.
}
}
Answer by Kiloblargh · Nov 19, 2013 at 08:15 PM
Are you missing RaycastAll? That looks like just what you need here.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
AI Pathfinding using RayCast 0 Answers
2D Field of View 2 Answers
Best way to do an AI 1 Answer
AI line/field of sight with Raycast 0 Answers