Game Development Community

Best way to check if an object exists at clicked position?

by Rich Hudson · in Torque X 2D · 10/27/2007 (6:50 pm) · 1 replies

Anyone know what the best method is to do this is?

Right now I am doing this:

private T2DSceneObject GetNearestEnemy(float from, float to)
{
T2DSceneObject closestEnemy = null;
float closestDistance = to;
TorqueObjectType enemy = TorqueObjectDatabase.Instance.GetObjectType("enemy");
List enemies = new List();
T2DSceneGraph.Instance.FindObjects(_sceneObject.Position, to, enemy, (uint)0xFFFFFFFF, enemies);

//Iterate through the List and get their distance from Aidan, then return the closest enemy
foreach (ISceneContainerObject obj in enemies)
{
float DistX = _sceneObject.Position.X - ((T2DSceneObject)obj).Position.X;
float DistY = _sceneObject.Position.Y - ((T2DSceneObject)obj).Position.Y;

//Get Tangent Distance
float _distance = (float)Math.Abs(Math.Sqrt(Math.Pow((double)DistX, 2) + Math.Pow((double)DistY, 2)));

if (_distance < closestDistance && _distance > from)
{
closestDistance = _distance;
closestEnemy = (T2DSceneObject)obj;
}
}
return closestEnemy;
}

to get the closest enemy to a point clicked..

-J

#1
11/06/2007 (11:52 pm)
With the position of the click you could just iterate over the list of enemies an check if the mouse is inside the bounds:

// something like this
if (clickPos.X >= enemyPos.X - (enemyWidth / 2) && clickPos.X <= enemyPos.X + (enemyWidth / 2) 
    && clickPos.Y >= enemyPos.Y - (enemyHeight / 2) && clickPos.Y <= enemyPos.Y + (enemyHeight/ 2))
{
    // the given position is within the bounds of this enemy...
    // add it to a result list or just return it now if we only want one or whatever.
}

EDIT: Fixed my [ code ] tags.