To find half of the screen bounds use the code below. Setting your sprite to these will put the center of your sprite right on the edge.
float HalfScreenWidth = camera.orthographicSize * Screen.width / Screen.height;
float HalfScreenHeight = camera.orthographicSize;
Now to get sprite size.
Vector3 SpriteSize = SpriteRenderer.bounds.max-SpriteRenderer.bounds.min;
If your sprite’s pivot is in the center then all you have to do is subtract 1/2 the SpriteSize width (or height) from the HalfScreenWidth or HalfScreenHeight values.
Hope this helps, anyone searching.
One option is to size and position colliders around the edge of the screen so you can use the physics simulation to bounce.
You can get the worldspace position of the screen edges using Camera.main.ViewportToWorldPoint, giving values where 0,0 is the bottom left corner, and 1,1 is the top right corner. The Z value is worldspace distance from the camera.
That’s the no brainer I’d go with.
If you’re somehow reluctant to do that, you could check whether your sprite is to check, on your ball’s Update(), if you’re off the limits with something like
if (position + spriteWidth/2 > cameraLeftLimit)
// Reflect velocity vector
and so on.
Oh, I’m sorry.
Here’s all you need then:
- http://bfy.tw/DBia
- http://bfy.tw/DBij
These are the answers to your two questions.
Find screen edges:
Get sprite size:
You need to search before you post. These are questions that have been answered probably hundreds of times.
Setting up colliders around the edge of the screen will not only take care of any math you need to do to prevent the sprite from moving outside the screen, but it will also take care of the bouncing response to collisions. Save yourself the work, you’re reinventing the wheel here.