A quick guide on how to move an object with Rigidbody velocity. The movement will be Clamped() to predifined values.
float speed; Rigidbody2D rb; void Start() { speed = 20f; rb = GetComponent<Rigidbody2D>(); } private void FixedUpdate() { float moveHorizontal = Input.GetAxis("Horizontal"); float moveVertical = Input.GetAxis("Vertical"); Vector2 movement = new Vector2(moveHorizontal, moveVertical); rb.position = new Vector2(Mathf.Clamp(rb.position.x, -8, 4), Mathf.Clamp(rb.position.y, -4, 4)); rb.velocity = movement * speed; }
Slightly different example with jumping and no Clamp option:
float speed = 5; float jumpSpeed = 600; Rigidbody2D rb; void Start() { rb = GetComponent<Rigidbody2D>(); } void FixedUpdate() { float playerVelocity = Input.GetAxisRaw("Horizontal"); playerVelocity *= speed; rb.velocity = new Vector2(playerVelocity, rb.velocity.y); if (Input.GetButtonDown("Jump")) { Jump(); } } void Jump() { rb.AddForce(new Vector2(0, jumpSpeed)); }