- Home /
Detect whenever the player is near the edges of the screen
Hi!
I need to detect whenever my player is near the screen edge of my 2D game. I got some code but that only works for the left side and for the bottom. I need to be able to detect for all of the edges. How can I do such a thing?
Here's my code so far:
void Update()
{
Vector3 screenPos = Camera.main.WorldToScreenPoint(this.transform.position);
if (transform.position.x > screenPos.x || transform.position.y > screenPos.y)
{
gc.PlayerDie();
}
}
I know there's a problem with it but I can't not solve it.
Any help is appreciated! Also, please try and post code in C# if code is necessary.
Thanks in advance!
If you want to detect camera corners or edges in 2D May be this video will be helpful for you it solved my issue https://www.youtube.com/watch?v=-SlN5ekMLR8
Answer by Jessespike · May 11, 2015 at 04:41 PM
Vector3 screenPos = Camera.main.WorldToScreenPoint(this.transform.position);
if (screenPos.x < 0 || screenPos.y < 0 ||
screenPos.x > Screen.width || screenPos.y > Screen.height)
{
gc.PlayerDie();
}
Thank you! It worked perfectly! I didn't realize it was that simple...
Answer by aakashsolanki890 · Feb 19, 2021 at 04:55 PM
If you want to detect camera corners or edges in 2D May be this video will be helpful for you it solved my issue :- https://www.youtube.com/watch?v=-SlN5ekMLR8