[SUGGESTION] I thought I would have a go at avoiding magic numbers with this. The following code seems to do the job of calculating clamp limits using Unity variables, thereby eliminating the need to serialize or hardcode the limits or the screenwidth.
Any feedback would be appreciated.
using UnityEngine;
public class Paddle : MonoBehaviour {
//config parameters
float screenWidthInUnits;
[SerializeField] Camera mainCamera;
float minX;
float maxX;
// Use this for initialization
void Start ()
{
GetScreenWidth();
SetPaddleBoundaries();
}
private void GetScreenWidth()
{
float screenX = Screen.width;
float screenY = Screen.height;
float resolutionFactor = screenX / screenY;
float cameraSizeInUnits = mainCamera.GetComponent<Camera>().orthographicSize;
screenWidthInUnits = 2 * cameraSizeInUnits * resolutionFactor;
}
// Update is called once per frame
void Update () {
float mousePosInUnits = Input.mousePosition.x * screenWidthInUnits / Screen.width;
Vector2 paddlePos = new Vector2(transform.position.x, transform.position.y);
paddlePos.x = Mathf.Clamp(mousePosInUnits, minX, maxX);
transform.position = paddlePos;
}
private void SetPaddleBoundaries()
{
float paddleHalfWidth = GetComponent<Collider2D>().bounds.extents.x;
minX = paddleHalfWidth;
maxX = screenWidthInUnits - paddleHalfWidth;
}
}
Maybe paramaterize something for gameplay value, such as allowing a variable percentage of the paddle to disappear off screen (to compensate for the oddly-shaped paddle)?
Is there a tidier way of using 2 integers to calculate a float? It didn’t seem to work too well for me when i tried
float resolutionFactor = Screen.width / Screen.height;
as it seems the screen dimensions needed to be cast as floats first?