Unity 2D switch direction in a autor runner

I’m new to unity and I’m trying to make a 2d endless runner(something like super meat boy forever), and one idea was that when the player touches a wall he would change direction, I tried to implement the mecanic, but in game is very strange and buggy, if someone can help me, the idea was to change the speed value from positive to negative and vice versa when the character collides to a wall(I used a layer mask for that). If someone could help me I would be very grateful.
Here u have the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
public float speed;
public float jumpForce;
private Rigidbody2D rb;
public bool grounded;
public bool walled;
public LayerMask whatIsGround;
public LayerMask whatIsWall;
private Collider2D myCollider;

// Start is called before the first frame update
void Start()

// Update is called once per frame
void Update()
    grounded = Physics2D.IsTouchingLayers(myCollider, whatIsGround);
    walled = Physics2D.IsTouchingLayers(myCollider, whatIsWall);
    rb.velocity = new Vector2(speed, rb.velocity.y);
    if(Input.GetKeyDown(KeyCode.Space) ||Input.GetMouseButtonDown(0) )
        rb.velocity = new Vector2(rb.velocity.x, jumpForce);

       speed = -speed;