Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Resolved changing referencePixelsPerUnit and referenceResolution for more accurate physics

Discussion in 'Physics' started by dynamicbutter, Nov 15, 2022.

  1. dynamicbutter

    dynamicbutter

    Joined:
    Jun 11, 2021
    Posts:
    61
    I am trying to set the initial velocity of a rigid body in such a way that it crosses its rect transform x axis in 10 seconds. I am using the equation below (where timeWidth=10). What I'm observing with a stop watch is the rigid body crosses the rect transform in about 8.75 seconds. I have also observed that increasing the pixels per unit of the main canvas causes the rigid body to slow down. Any idea what this could be? I am using a camera set to Screen Space - camera. Could it be related to the camera distance from the plane?

    Code (CSharp):
    1. initialVelocityX = (rectTransform.rect.xMin - rectTransform.rect.xMax) /
    2.                 canvas.referencePixelsPerUnit /
    3.                 timeWidth;
     
    Last edited: Nov 15, 2022
  2. dynamicbutter

    dynamicbutter

    Joined:
    Jun 11, 2021
    Posts:
    61
    Partly Resolved. Part of the issue seems to be not accounting for the relationship of the orthographic camera. I was using the reference pixels per unit from my canvas scaler. Turns out blindly using the reference value is no good for this. By computing pixels per unit and then set the canvas referencePixelsPerUnit value (as shown below), setting the initial velocity as shown above now works (sometimes). While this did the trick for some of the different resolutions I've tested on, I have found some that it doesn't seem to work on. So still looking into this.

    Code (CSharp):
    1. canvas.referencePixelsPerUnit = canvas.pixelRect.height / (Camera.main.orthographicSize * 2);
    2.  
     
    Last edited: Nov 15, 2022
  3. dynamicbutter

    dynamicbutter

    Joined:
    Jun 11, 2021
    Posts:
    61
    Resolved. In addition to adjusting the referencePixelsPerUnit, I found it necessary to adjust the referenceResolution of the canvas scaler to match the current device resolution. So I do this every time the resolution changes...

    Code (CSharp):
    1. var canvasScaler = canvas.GetComponent<CanvasScaler>();
    2. canvasScaler.referenceResolution = new Vector2(canvas.renderingDisplaySize.x, canvas.renderingDisplaySize.y);
    3. canvas.referencePixelsPerUnit = canvas.renderingDisplaySize.y / (Camera.main.orthographicSize * 2);
    4.