Move an Object until it touches wall?

Hi.
Im making my first unity game and I have a problem.
I have a cube that can move with the arrow keys.
The cube is in a simple room.
The cube spawns at the right at the top in the room.
If I press down and then I immediately press up the cube turns around at the half of his way.
I don’t want this to be possible.
if I press the down key, I want the cube to go down until he touches the wall.
I’m not good at coding so i don’t know how to do this.

this is my Code now:

Code (CSharp):
using UnityEngine;

public class MoveWithForceARROWS : MonoBehaviour
{
private Rigidbody _rigidbody;

[SerializeField] private float _movementForce = 10f;

private void Awake() => _rigidbody = GetComponent<Rigidbody>();

private void FixedUpdate()
{
    if (Input.GetKey(KeyCode.UpArrow))
        _rigidbody.AddForce(_movementForce * Vector3.forward);
   


    if (Input.GetKey(KeyCode.DownArrow))
        _rigidbody.AddForce(_movementForce * Vector3.back);
 

    if (Input.GetKey(KeyCode.RightArrow))
        _rigidbody.AddForce(_movementForce * Vector3.right);
   

    if (Input.GetKey(KeyCode.LeftArrow))
        _rigidbody.AddForce(_movementForce * Vector3.left);
 
}

}

You need a way to check if the cube is on the ground. Create an empty that is a child of the cube, and put it at the bottom of the cube in the middle. Add this code to your movement script. Then assign the groundcheck as that empty. You will also need to make the ground mask variable whatever the surface is that your cube is on. I think this is correct, but like you I am also new to coding. If this doesn’t work, you can use a tutorial on youtube. That is where I got this code.

public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
bool isGrounded;

   if (Input.GetKey(KeyCode.UpArrow) && isGrounded)

{
_rigidbody.AddForce(_movementForce * Vector3.forward);
}

  • You can check the Freeze Rotation boxes in your Rigidbody component to prevent your cube from rotating.

  • Use Vector3.down and Vector3.up to move the cube on the global y-axis.