简体   繁体   中英

Unity - Change direction along x-axis when GetMouseButtonDown

I'm making a wall-runner type of game, where I need my character to change walls when the mouse button is clicked. I made it work with gravity, but it gave undesired effects. Therefore I'm now working with transform.position, but now the character only moves for a split second (I assume the transform.position only activates while the mouse button is actually clicked).

How do I make it change direction on the mouseclick, instead of it just moving a bit? Do I need some kind of while loop, or where am I at?

My class:

//Variables used by the Player
public int flyingSpeed;
bool rightWall = true;
bool inAir = false;

// Use this for initialization
void Start () {
}

// Update is called once per frame
void Update () {
//Constantly moves the Players position along the Y-axis
    if (inAir == false) {
        if (Input.GetMouseButtonDown (0) && rightWall == true) {
            transform.position += Vector3.left * flyingSpeed * Time.deltaTime;
            rightWall = false;
            inAir = true;
        } else if (Input.GetMouseButtonDown (0) && rightWall == false) {
            transform.position += Vector3.right * flyingSpeed * Time.deltaTime;
            rightWall = true;
            inAir = true;
        }
    }
}

void OnCollisionEnter2D(Collision2D coll) {
    inAir = false;
}

The Input.GetMouseButtonDown method only returns true on the first frame that the button is clicked, so your moving operations are only executed once, which is not enough to switch the walls.

To switch between the walls, you can do one of the following:

  1. Move the player immediately when the mouse is clicked by setting transform.position
  2. Make a function that checks if the player is on the right or left wall (let's call is WallCheck ). Then change the rightWall value every time the mouse is clicked.And then add this to your Update method

    if (WallCheck() != rightWall) transform.position += rightWall ? Vector3.left : Vector3.right * flyingSpeed * Time.deltaTime;

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