I came up with a solution that finds the boundaries of the Paddle’s sprite and uses those to calculate the clamping values you need to use. This means you can update the clamping programmatically in Update() if, for example, you changed the size of the paddle Sprite with a power-up. I wondered if the way I’ve gone about this is the most efficient or if there’s a better way?
Code is below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PaddleController : MonoBehaviour
{
[SerializeField] private float screenWidthInWorldUnits = 16f;
private float xMin = 0f;
private float xMax = 16f;
private SpriteRenderer paddleSpriteRenderer;
// Start is called before the first frame update
void Start()
{
paddleSpriteRenderer = this.GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update()
{
// find the size of the paddle's sprite to determine screen clamping
// this is useful because if the sprite is updated (for example the paddle got bigger)
// it will still be properly clamped to the screen
xMin = 0f + paddleSpriteRenderer.sprite.bounds.size.x / 2;
xMax = screenWidthInWorldUnits - paddleSpriteRenderer.sprite.bounds.size.x / 2;
// work out mouse position to world position
float xMousePos = (Input.mousePosition.x / Screen.width) * screenWidthInWorldUnits;
Vector2 paddlePos = new Vector2(xMousePos, transform.position.y);
// clamp the paddle position to the screen
paddlePos.x = Mathf.Clamp(xMousePos, xMin, xMax);
transform.position = paddlePos;
}
}