简体   繁体   中英

Character not moving in horizontal axis

I'm writing a 2D platform game with Visual Studio Code and Unity . So far, I have established the animations that I will use later in the main character and the enemy. With the main character I have defined the "horizontal move" and the "vertical move". However when I run the game, the character moves up, but it doesn't move left or right.

This is the code that I have for the main character:

public class Hero : Monobehaviour 
 
 { 
    public float vel =10f;
    public Animator anim;
    private Vector2 moveVelocity; 
    float horizontalMove = 0f; 

    private Rigidbody2D rb; 

  void Start()
  {
     rb = GetComponent<Rigidbody2D>();
  }

  void Update() 
  {
   horizontalMove = Input.GetAxisRaw("Horizontal") * vel;
   Vector2 moveInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
   moveVelocity = moveInput.normalized * vel;
  }

  void FixedUpdate()
  {
    Vector2 v = new Vector2 (vel, 0);
    rb.velocity = v;
    rb.MovePosition(rb.position + moveVelocity * Time.fixedDeltaTime);       
  }

}

Can someone please tell me what I'm missing?

It should work if you change your code to this:

    void Update() 
      {
       if(Input.GetKeyDown(KeyCode.D))
          {
          rb.AddRelativeForce(Vector2.right * (vel*Time.deltaTime));
          }
           else if(Input.GetKeyDown(KeyCode.A))
              {
              rb.AddRelativeForce(Vector2.left * (vel*Time.deltaTime));
              }
      }

Since you have a rigidbody attached to your game object, it would make sense to add relative force to the object when a user presses D/A instead of just changing the object's transform position. This should work.

Essentially, you can set the horizontal move up in the input manager under Edit > project settings > input. Double-check if the horizontal axis is set up to the left and right button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM