- Home /
How to make a Raycast2D proportional to a CanvasScaler dynamic resizing?
I've been doing a puzzle game with a custom collision script for a while. In this project, I do everything inside of canvases in order to achieve to best fit the game pieces identically in all possible mobile resolutions.
To get the Raycast collisions working, first I retrieve half of the block height and divide it by the default PixelsPerUnit (which is 100):
blockHeight = (GetComponent<BoxCollider2D>().size.y / 2)/100;
Then at every Update I just raycast this height down and up to check whenever a block is hitting another from above or below. If it hits, I reposition the block so it won't sink in other blocks. Here's the "below" part:
RaycastHit2D downHit = Physics2D.Raycast(transform.position, Vector2.down, blockHeight);
if (downHit.collider != null)
{
GetComponent<BlockGravity>().enabled = false;
transform.Translate(Vector2.down * (downHit.distance - blockHeight));
}
There's a problem whenever I raycast block collisions after changing screen resolutions, however. It seems the regular PixelsPerUnit from Canvas internal systems increase or decrease depending on how the Scaler is dealing with readjusting the screen. In other words, while Image-component blocks still appear and fit perfectly between all resolutions, their raycasted collisions go beyond their original bounds.
So, under normal circunstances, such as with my Nexus 4 screen resolution, blocks are very tightly aligned:
But when selecting resolutions such as FWVGA Portrait (480x854), the raycasts bleed out the original sprite bounds and cause issues with fitting blocks inside the screen aswell as making them aligned:
So, what am I supposed to do in this situation? I've tried a lot of different calculations, in particular involving the Canvas spriteDPI value, which is the one that (seemingly) changes between resolutions, but I can't get to a point where raycasts resize correctly with Image graphics and BoxCollider scales. I need help!
Your answer
Follow this Question
Related Questions
How to make a crosshair move with the player 1 Answer
Raycast Not Working 3 Answers
My Raycasts seem to sometimes miss 0 Answers
Canvas Scaling! 0 Answers
Unity Dual Monitor Size Bug? 1 Answer