trying to make 2d bouncing square

I’m trying to make a top down 2d bouncing square. when it hits a wall it should not rotate and should bounce in a v shape. But my code doesn’t do that and I’m not sure how I can do that

using UnityEngine;

public class EnemyXYULaxis : MonoBehaviour
{
    public float speed = 2.0f; 
    public float shmovinUpLeft = 1;

    void Update () {
        if(shmovinUpLeft == -1){
            transform.position += transform.up * -1 *speed * Time.deltaTime;
            transform.position += transform.right * speed * Time.deltaTime;
        }

        if(shmovinUpLeft == 1){
            transform.position += transform.up * speed * Time.deltaTime;
            transform.position += transform.right * -1 * speed * Time.deltaTime;
        }
    }
    //hitting wall
    private void OnCollisionEnter2D(Collision2D collision){
        if(collision.gameObject.CompareTag("Wall")){
        //bouncing    
        shmovinUpLeft = -1 * shmovinUpLeft;
        }
    }
}

I’ve look for other guides but couldn’t find one for squares and they had gravity

You’re stomping over the Transform which is the whole point of using a Rigidbody2D. It writes to the Transform, you use its API.

Also note, you’re modifying the Transform per-frame when physics doesn’t run per-frame by-default. It runs during the FixedUpdate.

You can set the rotation constraint on the Rigidbody2D in the inspector to stop it rotating upon collision.

There are hundreds of tutorials showing how to drive a Rigidbody2D and use 2D physics though.

You may not even need to write any code for the bounce behavior. You can create a physics material with “Bounciness” set to 1 and apply it to your Rigidbody2D. Also set Freeze Rotation for Z if you don’t want it to rotate.

This suggestion assumes that you set the Rigidbody2D velocity rather than translating the object directly with transform.position.

9788922--1404711--upload_2024-4-23_10-0-19.png

9788922--1404714--upload_2024-4-23_10-0-39.png