How to move forward constantly and right left when it's necessary

Hello, I am developing an endless runner style game, the character will always go forward, there is no problem with this, I can do it as I want with addforce, but it does not go when it needs to go left and right. How can I do it using rigidbody and addforce.

rb.AddForce(new Vector3(Input.GetAxis("Horizontal"), transform.position.y, speed) * (Time.fixedDeltaTime * 2));

This is the last code I tried

Generally don’t write code like the above. This falls under “hairy lines of code” and since the entire piece of code is one statement, it isn’t possible to really reason about making meaningful changes to it, or even finding out why it isn’t working, or even printing any of the internal variables. It’s like giving a car to the mechanic and saying he can’t open the hood or change anything but he has to fix your car.

How to break down hairy lines of code:

http://plbm.com/?p=248

Instead, code it with many separate lines and steps, thinking like this, with LOTS of temporary variables:

  • gather input
  • condition that input, such as:
    ----- see if it is valid (won’t send you off the edge)
    ----- scale it to what you want
    ----- clamp it within what you desire
  • act upon the input

Using physics to move is going to be VERY tricky to get right, since it’s hard to know how much force will result in a given speed except by trial and error.

I suggest you perhaps work through two or three Youtube videos on endless runners. Few of them use physics to move and there is a real reason for that. Usually it is some other combination of explicit lane-based motion.