Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

A problem about Update function

Discussion in '2D' started by akkayaozi44, Apr 18, 2020.

  1. akkayaozi44

    akkayaozi44

    Joined:
    Apr 18, 2020
    Posts:
    11
    Hello i hava a little problem about my code.

    if (Sitution == "To Right")
    {
    Boomerang.transform.position += new Vector3(1, 0.5f, 0) * Time.deltaTime * Speed;
    Boomerang.transform.Rotate(0, 0, -5 * Speed);
    if (Input.GetMouseButton(0))
    {
    Sitution = "To Left";
    }
    }
    if (Sitution == "To Left")
    {

    Boomerang.transform.position += new Vector3(-1, 0.5f, 0) * Time.deltaTime * Speed;
    Boomerang.transform.Rotate(0, 0, 5 * Speed);
    if (Input.GetMouseButton(0))
    {
    Sitution = "To Right";
    }
    }

    This is my code. Code is doing if sitution is equal to "To right" boomerang going to right,if sitution is equal to "To left" boomerang going to left. If the player click to button, boomerang changing direction.

    The problem is sometimes when i click to button boomerang direction is not changing. What is the problem?
     
  2. Deshalsky

    Deshalsky

    Joined:
    Nov 16, 2013
    Posts:
    57
    I made something that works, there are better ways to do this however.
    Code (CSharp):
    1.  
    2. // Check for input
    3. if (Input.GetMouseButtonDown(0)) {
    4.        if(Sitution == "To Right") {
    5.             Sitution = "To Left";
    6.        } else if(Sitution == "To Left") {
    7.             Sitution = "To Right";
    8.        }
    9. }
    10.  
    11. // Apply speed and rotation depending on Sitution
    12. if (Sitution == "To Right") {
    13.        Boomerang.transform.position += new Vector3(1, 0.5f, 0) * Time.deltaTime * Speed;
    14.        Boomerang.transform.Rotate(0, 0, -5 * Speed);
    15. } else if (Sitution == "To Left") {
    16.        Boomerang.transform.position += new Vector3(-1, 0.5f, 0) * Time.deltaTime * Speed;
    17.        Boomerang.transform.Rotate(0, 0, 5 * Speed);
    18. }
    I moved the input out from the if-statements and changed GetMouseButton to GetMouseButtonDown to check for button presses instead of button holds. I also joined the two if-statements with an 'else' so it can only either go right or left.
     
    Last edited: Apr 18, 2020
  3. akkayaozi44

    akkayaozi44

    Joined:
    Apr 18, 2020
    Posts:
    11
    Problem is fixed. Thanks you very much !!