So I have had to come back to this course as I have not touched Unity for a long while, back in the pre-Rick days. So this solution might require some knowledge touched on further in the course, but wanted to share it anyway.
public class PaddleController : MonoBehaviour
{
float screenWidthSizeMod, screenHeightSizeMod;
float leftClamp, rightClamp;
[SerializeField] int paddleSize;private void Start() { screenHeightSizeMod = FindObjectOfType<Camera>().orthographicSize * 2f; screenWidthSizeMod = FindObjectOfType<Camera>().aspect * screenHeightSizeMod; leftClamp = 0f + (float)paddleSize / 2; rightClamp = screenWidthSizeMod - (float)paddleSize / 2; } // Update is called once per frame void Update() { float mousePosition = Input.mousePosition.x / Screen.width * screenWidthSizeMod; Vector2 paddlePosition = new Vector2(transform.position.x,transform.position.y); paddlePosition.x = Mathf.Clamp(mousePosition, leftClamp, rightClamp); transform.position = paddlePosition; }
}
So that is a whole lot of code, but here is the break down of what you need to be able to get out of using constants (even serialised fields).
By finding the camera, then finding the orthographic size (as a float) and multiplying that by two, you get your height (which in Rick’s case, he said was 12, as in 6 x 2). Taking that height value and multiplying it by the camera’s aspect float then gives you the width.
This will allow the clamp function, which as you can see above has a leftClamp and rightClamp set based upon the screen width (in units) and half the size of the paddle.
It might seem like a lot of coding for very little gain, but if you decide to change your game’s aspect ratio at a later date, it recalculates those things at run time, rather than relying on serialised fields.
Cheers
Moose