// GDnD wiki example // Demonstrates: horizontal player input clamped to the screen — the same input/clamp pattern as Pong, on the X axis // Related pages: [[overview-arcade-classics-as-learning-projects]], [[unity-input]], [[unity-transform]] using UnityEngine; // Player paddle. Reads a horizontal axis and clamps to the play area so it // cannot leave the screen. public class Paddle2D : MonoBehaviour { [SerializeField] private float speed = 14f; [SerializeField] private string horizontalAxis = "Horizontal"; private float halfWidth; private float halfSize; private Camera cachedCamera; private void Awake() { cachedCamera = Camera.main; halfSize = GetComponent().bounds.extents.x; } private void Update() { float move = Input.GetAxisRaw(horizontalAxis); Vector3 position = transform.position; position.x += move * speed * Time.deltaTime; halfWidth = cachedCamera.orthographicSize * cachedCamera.aspect - halfSize; position.x = Mathf.Clamp(position.x, -halfWidth, halfWidth); transform.position = position; } }