- Home /
How to make my object bounce off the screen bounds?
I have been trying my best to make a dynamic edge collider 2D that will resize to whatever the screen resolution of the mobile device to make my screen bounds as walls but I could not find the right script for it. I wanted to make my objects bounce off the screen size.
I tried using half of Screen.height
and half of Screen.width
as my vector points for my edge collider 2D but I kept on running on some issues if I change the resolution.
An overview of my problem:
If I use the resolution 1920x1080 Portrait (1080x1920), I get the exact vector points for y axis which is 960 and -960 and it fits perfectly with the display's height. But when I change it to iPadPro 2224x1668 Portrait (1668x2224), I get the exact vector points 1112 and -1112 but it doesn't fit perfectly with the display's height.
Any help would be greatly appreciated! Thanks!
Answer by Klarzahs · Oct 08, 2020 at 12:51 PM
Hi @zcndev,
did you try a raycast from all corner positions of the screen? If you have - as an example - a top-down 2d world, you could place a plane in the background. The ray would then hit the world-coordinates of this plane, giving you the corner stones of your screen bounds.
This will probably also work in 3d, but require more though :)
EDIT: You can probably also just use the camera translation, but im not sure about the resulting depth
Hello @Klarzahs,
I'm still new to game development and unity so I haven't tried raycast. I also don't know how that works and how to implement it on a 2D game :(
Have a look at this tutorial by brackeys, where they are using raycasts for shooting. Basically a raycast "shoots" a straight line from a point/direction. Unity then reports the first object it hits and its world position.
Implementing it in 2D isn't really different than in 3D, which is explained in the video.
Thank you for this! Hope this helps. Really appreaciate it! :D