Search code examples
c#unity-game-enginegame-engine

Input.GetKeyDown command doesn't work properly in Unity2D


I am very new to programming and game development so please be patient. I have been trying to make a script that would add a force to the player left or right depending on which direction he is facing in Unity2D.

I would make the script detect which direction he is facing depending on which button he pressed last(A/D). To do so I made two bools (IsFacingRight and IsFacingLeft) that would change accordingly if the player pressed "A" or "D".

IsFacingRight starts out true by default and Left starts false. The force would have been applied in the proper direction if I pressed the "S" button. My problem is that when I press the "S" button nothing happens. I have decided to turn both bools to public to see their state at all times and I notice that when I press the "S" button, both bools change to true. My guess is that the force is applied left and right and so the forces cancel each other out. Here is the code:

{
    public bool IsFacingR = true;
    public bool IsFacingL = false;
    public Rigidbody2D RB;
    private float thrust = 20f;
    void Update()

    {
        if (Input.GetKeyDown(KeyCode.D))
        {
            Debug.Log("Im R");
            IsFacingR = true;
            IsFacingL = false;
        }
        if (Input.GetKeyDown(KeyCode.A))
        {
            Debug.Log("Im L");
            IsFacingR = false;
            IsFacingL = true;
        }
        if (Input.GetKeyDown(KeyCode.S))
        {
            Slider();
        }
    }

    

    void Slider()
    {

        if (IsFacingR = true) 
        {
            RB.AddForce(Vector2.right * thrust);
        }
        if (IsFacingL = true) 
        {
            RB.AddForce(-Vector2.right * thrust);
        }
    }
}

Solution

  • You have a Typo :

    if (IsFacingR = true) 
        {
            RB.AddForce(Vector2.right * thrust);
        }
    if (IsFacingL = true) 
        {
            RB.AddForce(-Vector2.right * thrust);
        }
    

    you are not "asking" if IsfacingR is true you are setting IsFacingR to true, i dont even know how it even compiled (prob cause its a bool eitherway)

    c#'s = is not a comparator its setting a variable for comparing 2 things please use ==

    i hope this will solve your issue, but besides that please dont ask the same question every day. Greets.