简体   繁体   中英

How to change the horizontal movement direction of the player in Unity2D?

I am trying to make a 2D game in Unity and I am using in FixedUpdate() function the Input.GetMouseButtonDown() method. I want my player to change the horizontal direction, so for this I have the below code.

 if (Input.GetMouseButtonDown(0))
             {
                 if(change == true)
                 {
                     rb.velocity = new Vector2(-12,rb.velocity.y);
                     change=!change;
                 }
                 else if(change == false)
                 {
                     change=!change;
                     rb.velocity = new Vector2(12,rb.velocity.y);
                 }
     }

At the beginning, first 3-6 clicks, works fine (one click change direction, another click the other direction) but afterwards I have to press 2 or 3 times to change the actual direction.

What should I do to increase the accuracy, quality of changing directions?

Thank you very much for your patience and attention!

The Unity Documentation states that you have to use GetMouseButtonDown() in the Update function.

You probably should create a global boolean to save the value and reset it in the FixedUpdate(). Something like this:

boolean MouseButtonDown=false;
void Update(){
if(Input.GetMouseButtonDown(0)){
MouseButtonDown=true;
}
}

void FixedUpdate(){
if (MouseButtonDown)
             {
                 if(change == true)
                 {
                     rb.velocity = new Vector2(-12,rb.velocity.y);
                     change=!change;
                 }
                 else if(change == false)
                 {
                     change=!change;
                     rb.velocity = new Vector2(12,rb.velocity.y);
                 }
     }
}

The FixedUpdate() function runs after a fixed interval of time, if you click the mouse button at the time when if(Input.GetMouseButtonDown(0) is executing then your input is taken into account. The Update() function runs for every frame that is being displayed on the screen, if your fps (frame rate) is 60fps it means that the Update() function runs 60 times per second so there's a very low possibility that your input isn't recorded. Hope that answers why your code isn't working.

What you can do is:

bool btnPressed = false;
void Update(){

    if(Input.GetMouseButton(0) && !btnPressed){
        btnPressed = true;
    }

}

void FixedUpdate(){

    if(btnPressed){

        if(change == true){
            rb.velocity = new Vector2(-12,rb.velocity.y);
            change=!change;
        }
        else if(change == false){
            change=!change;
            rb.velocity = new Vector2(12,rb.velocity.y);
        }

        btnPressed = false;
    }
}

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