- Home /
Get the gameobject to the left/right of current target, in field of vision?
I'm trying to write the math to cycle between lockon targets. Basically the player is currently locked onto one target (looking at them, the target has an eye over its head etc etc etc). If the player hits left on rightHorizontalStick, it should switch to the next viable target to the left of the current one, and same for if they hit right. The problem is that rather than just being left/right on one axis, it's relative to the curve that is made up by the camera's vision. Depth does not matter at all, only left/right position along this curve
Here are two picture to better communicate what I mean (the black dots are other enemies):
http://i.imgur.com/vqA3a6S.png
http://i.imgur.com/7f0keyD.png
How could I get the next dot to the left/right of the blue dot?
Here is the code from my attempt. Idk if I just need to tweak the math or if there is an entirely different, much better approach, but just in case, I figured I should post what I did myself
private void changeLockOnTarget(direction d)
{
float yRot = player.transform.eulerAngles.y;
float distanceFromCurrLockOn = Mathf.Infinity;
GameObject newTarget = null;
GameObject[] allEnemies = GameObject.FindGameObjectsWithTag("Enemy");
foreach(GameObject enemy in allEnemies)
{
//if not current target && enemy is in camera view
if(enemy != lockOnTarget && GeometryUtility.TestPlanesAABB(GeometryUtility.CalculateFrustumPlanes(mainCam), enemy.collider.bounds))
{
float distance;
if(d == direction.left)
{
float xAmount = (lockOnTarget.transform.position.x - enemy.transform.position.x) * Mathf.Cos(yRot * Mathf.Deg2Rad);
float zAmount = Mathf.Abs(lockOnTarget.transform.position.z - enemy.transform.position.z) * Mathf.Sin(yRot * Mathf.Deg2Rad);
distance = xAmount + zAmount;
}
else if(d == direction.right)
{
float xAmount = (enemy.transform.position.x - lockOnTarget.transform.position.x) * Mathf.Cos(yRot * Mathf.Deg2Rad);
float zAmount = Mathf.Abs(enemy.transform.position.z - lockOnTarget.transform.position.z) * Mathf.Sin(yRot * Mathf.Deg2Rad);
distance = xAmount + zAmount;
}
else distance = 0; //this will never happen
if(distance < distanceFromCurrLockOn && distance > 0)
{
Debug.Log("newTarget is now " + enemy.name);
distanceFromCurrLockOn = distance;
newTarget = enemy;
}
}
}
Your answer
Follow this Question
Related Questions
Instantiate cube on network 0 Answers
Given a position, how do I figure out Pixel's Per Unit? 1 Answer
Please help, bullet drop is wrong at certain angles ? 0 Answers
Transform.RotateAround(Vector3 axis, float angle) - what happens with only two arguments? 3 Answers
How to calculate the angle of a trajectory to hit the target 1 Answer