An odd bug

In the ‘Improved Targeting Selection’ lecture of the Unity 3rd Person Combat & Traversal:

I’ve found that when the camera faces directly away from a target, it will return a value for viewPos which bypasses the if statement meant to ignore targets that aren’t in the camera’s view:

Vector2 viewPos = mainCamera.WorldToViewportPoint(target.transform.position);

if(viewPos.x < 0 || viewPos.x > 1 || viewPos.y < 0 || viewPos.y > 1) { continue; }

I’m not sure if this is true for everyone or if I’ve changed something somewhere which causes this.

I wonder if this is a function of back face culling…

I used a different method of filtering for this:

Vector3 lookDirection = target.transform.position - transform.position;
if(Vector3.Angle(lookDirection, transform.forward) >90) continue;
2 Likes

Your method absolutely works for targeting something the player model is facing, and it won’t target something directly behind the player model. So it does solve or avoid the bug.

After testing that out, which meant changing viewPos (or lookDirection in your example) to a Vector3, I realized I could now add a condition for the .z in the original if statement:

Vector3 viewPos = mainCamera.WorldToViewportPoint(target.transform.position);

if(viewPos.x < 0 || viewPos.x > 1 || viewPos.y < 0 || viewPos.y > 1 || viewPos.z < 0) { continue; }

This also fixes the issue and preserves targeting with the camera.

(As a note for anyone who might do that, the toCenter variable will need to be changed to a Vector3):

Vector3 toCenter = viewPos - new Vector3(0.5f, 0.5f, 0);

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms