What's the best way to handle 2D platformer movement - I thought two different methods

What technique is better to handle control inputs?
Almost every 2D platform game you move through X axis (left and right). I’ve noticed in Unity you can handle it by two ways:

a) Using Input.GetAxis("Horizontal")

It will returns a float to indicate char position, you can modify the char’s transform component to walk right or left side.

So you have:

transform.Translate() to pass a modified Vector3 object.

b) Using Input.GetKey(KeyCode.)

You personally handle the key event. I.E: “A” and “D” keys or “left” and “right” arrows keys.

So you can have:

rigidbody.AddForce() to pass the char transform component.


So, my question is: what is the best way to accomplish it or is there somehow one method can be better than other in some circumstances?

Thanks in advance!

A lot of people ask “what is the best way to”. There are many many ways to solve a problem, and what may be the best way to solve it for a particular problem may be one of the worst ways to solve it for another. I think you should be content with getting an answer rather than a universal best answer. If there was a truly universal way to provide the best approach for all cases, it would have been the standard by a long time ago.

You are discussing four possibilities here.

For one problem (input) you offered two solutions; Use Axis or use Keys. Well, if you were going to go multi platform, keys might be a bad choice. However, it may be simple for you to use right now and you want to be productive in your comfortable level, so maybe it makes sense for you to use keys. What is best? I don’t know. You should know where you are going with your game.

For another problem (movement) you offered two solutions. One is changing the position via the objects transform, another is relying on physics to allow the player to push objects around most likely. If you are going to use physics, it sounds like you want to use rigidbody.AddForce rather than transform.Translate. If you don’t bother about physics, it makes more sense to use transform.Translate. Again, I don’t know how your game is meant to behave so it’s hard to tell what to suggest.

You already discarded two possibilities for reasons I have no idea why (why couldn’t you use transform.Translate with Input.GetKey and why couldn’t you use rigidbody.AddForce with Input.GetAxis?)

Only because you use Input.GetKey doesn’t mean that you can’t use floating point curves to drive your behaviour. You can easily do something like:

acceleration.y = 0;
if (Input.GetKey(KeyCode.W))
    acceleration.y += 1;
if (Input.GetKey(KeyCode.S))
    acceleration.y -= 1;
velocity += acceleration * Time.deltaTime;
transform.Translate(velocity * Time.deltaTime);