- Home /
Preventing player from moving out of Camera Viewport
I thought I had this figured out, just use ViewportToWorldPoint to get the world coordinates of the edges of the screen, then compare the player's position to these points and move him if necessary ( you already have world coordinates necessary for moving the player).
However, this only works when the camera is directly overhead at 90 degrees. Changing the angle or FOV messes this up, especially on the sides of the sceens. So anyone know a better approach? If anyone is curious, this is for a top down shooter(SHMUP).
Answer by Eric5h5 · Mar 08, 2010 at 12:28 AM
I'd suggest trying WorldToViewportPoint instead, so you can see if you're trying to move < 0 or > 1.
O$$anonymous$$, I tried that and it works, but how do you know where to move the player to after confir$$anonymous$$g they left the screen?
I'd probably save the position from the previous frame, and if an attempt is made to move off the screen, restore the saved position.
Answer by dhendrix · Mar 08, 2010 at 03:29 AM
OK, here is what I managed to come up with, hopefully this will help someone out. This assumes you are moving with a Character Controller. Vector3 moveDirection = (calculate where to move based on axis movement and such)
var viewPos = camera.WorldToViewportPoint (transform.position + moveDirection);
if( viewPos.x < 0 ) { viewPos.x = 0; boolBackToScreen = true; } else if( viewPos.x > 1 ) { viewPos.x = 1; boolBackToScreen = true; } if( viewPos.y < 0 ) { viewPos.y = 0; boolBackToScreen = true; } else if( viewPos.y > 1 ) { viewPos.y = 1; boolBackToScreen = true; }
if(boolBackToScreen) { movBackToScreen = camera.ViewportToWorldPoint(Vector3(viewPos.x,viewPos.y,viewPos.z)); moveDirection = movBackToScreen - transform.position; boolBackToScreen = false; }
controller.Move(moveDirection );
Only problem with it is the player.y coordinate goes wonky when the camera is tilted back at a 60 degree angle with 30 degree FOV. Not sure how to fix that.