Can you please tell me how to implement the movement of the character in a 2D game on unity?

I threw back and forth buttons onto the scene and added Event Trigger components with Pointer Down and Pointer Up events.

From the lesson https://www.youtube.com/watch?v=xZdCKgp-xd4 tried to take the information to realize the movement back and forth, but it does not work

public void BackButtonDown() { speedX = -horizontalSpeed; sprite.flipX = true; } public void ForwardButtonDown() { speedX = horizontalSpeed; sprite.flipX = false; } public void BackOrForwardButtonUp() { speedX = 0; } public void UpButton() { if (isGrounded) { rigidbody.AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse); } } private void FixedUpdate() { transform.Translate(speedX, 0, 0); } 

Because of transform.Translate(speedX, 0, 0); the character flies away as soon as I launch the game.

  • And what is the speedX speed initially - at the start of the game, before the first click on any button? If initially the speed is not initialized and is set only for actions related to pressing buttons, then try something like this: private void Start() { speedX = 0; } private void Start() { speedX = 0; } - Alexander Danilovsky
  • [SerializeField] private float speedX = 0.0F; // Player speed - Kolhoznik
  • Thanks, helped - Kolhoznik
  • then I will draw in the form of an answer - Alexander Danilovsky

1 answer 1

If initially the speed is not initialized and is set only for actions related to pressing buttons, then try something like this:

 private void Start() { speedX = 0; } 
  • The bad way, if you only need to initialize a variable, is easier to set the default value for it, rather than overriding Start (). - RiotBr3aker pm