Recommand · June 3, 2021 0

Why won't my character move left when i press A?

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.


Want to improve this question? Update the question so it's on-topic for Stack Overflow.

Closed 54 mins ago.

Improve this question

I am new to Unity and coding in C#, so just any help would be nice.

In my program I have a game object with a controller; it can jump (With space) and go right (With D).
My problem is that when I press A, the game object don’t really move.

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

public class PlayerWalk: MonoBehaviour
{

    [SerializeField]
    private LayerMask groundLayerMask;

    private Rigidbody2D rigidbody2d;
    private BoxCollider2D boxcollider2d;

    

    private void Awake()
    {
        rigidbody2d = transform.GetComponent<Rigidbody2D>();
        boxcollider2d = transform.GetComponent<BoxCollider2D>();
    }

    void Update()
    {

    }
    void FixedUpdate()
    {
        float moveSpeed = 5;
        if (Input.GetKeyDown(KeyCode.A))
        {
            rigidbody2d.velocity = new Vector2(-moveSpeed, rigidbody2d.velocity.y);
        } else
        {
            if (Input.GetKey(KeyCode.D))
            {
                rigidbody2d.velocity = new Vector2(+moveSpeed, rigidbody2d.velocity.y);
            } else
            {
                rigidbody2d.velocity = new Vector2(0, rigidbody2d.velocity.y);

            }
        }
    }
}

this problem fixed by using GetKeyDown
but for better and simpler code you can use Input.GetAxis("Horizontal")
like this :

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

public class PlayerWalk: MonoBehaviour
{

    [SerializeField]
    private LayerMask groundLayerMask;

    private Rigidbody2D rigidbody2d;
    private BoxCollider2D boxcollider2d;

    

    private void Awake()
    {
        rigidbody2d = transform.GetComponent<Rigidbody2D>();
        boxcollider2d = transform.GetComponent<BoxCollider2D>();
    }

    void Update()
    {

    }
    float moveSpeed = 5;
    void FixedUpdate()
    {
         float hor = Input.GetAxis("Horizontal") * moveSpeed; 
         // GetAxis will return a float with value thats is between 1 and -1 
         // for right(D) greater than 0 for left(A) less than 0 ( you can set this your self in input manager )
         // if you dont want have soft move when character start moveing you can use Input.GetAxisRaw
         rigidbody2d.velocity = new Vector2(hor, rigidbody2d.velocity.y);
    }
}

I believe the reason you’re seeing that behavior is you’re using the GetKeyDown function. It only returns true on the frame that the key is pressed. In your other conditionals you’re using GetKey.enter image description here