0
\$\begingroup\$

This is the script I've written so far which makes the block move from the left of the screen to the right on a mouse click. What I want to achieve is for the block to move back to the left when I click the mouse again. So I can have a back and forth movement with each mouse click. Thank you for any help it's much appreciated.

public class PlayerControls1 : MonoBehaviour  {

private bool hasBeenTapped = false;
private bool control = false;
public float speed = 20f;

void Update () {
    if (Input.GetMouseButtonDown (0)) {
        hasBeenTapped = true;
            }

    if (hasBeenTapped && transform.position.x < 4 && control == false){
        transform.Translate (Vector2.right * speed * Time.deltaTime);
    }

    if(transform.position.x > 4.0f) {

        control = true;

        hasBeenTapped = false;
    }

    if(hasBeenTapped && transform.position.x == 4 || transform.position.x < 4 && control == true) {
        transform.Translate (-Vector2.right * speed * Time.deltaTime);

    if(transform.position.x < -4){

            control = false;

            hasBeenTapped = false;
        }
    }
  }
}
\$\endgroup\$
1
\$\begingroup\$

Here is a generic answer

public class PlayerControls1 : MonoBehaviour  {

private bool hasBeenTapped = false;
private bool shouldMoveLeft = false;
private bool control = false;
public float speed = 20f;

void Update () {
    if (Input.GetMouseButtonDown (0)) {
        hasBeenTapped = true;
            }

    if (hasBeenTapped && !shouldMoveLeft && transform.position.x < 4 && control == false){
        transform.Translate (Vector2.right * speed * Time.deltaTime);
    }

    if (hasBeenTapped && shouldMoveLeft && transform.position.x > 0 && control == false){
        transform.Translate (Vector2.left * speed * Time.deltaTime);
    }

    if(transform.position.x > 4.0f) {
        transform.position.x = 4.0f;
        control = true;
        shouldMoveLeft = true;
        hasBeenTapped = false;
    }

    if(transform.position.x <= 0.0f) {
        transform.position.x = 0.0f;
        control = true;
        shouldMoveLeft = false;
        hasBeenTapped = false;
    }

    if(hasBeenTapped && transform.position.x == 4 || transform.position.x < 4 && control == true) {
        transform.Translate (-Vector2.right * speed * Time.deltaTime);

    if(transform.position.x < -4){

            control = false;

            hasBeenTapped = false;
        }
    }
  }
}

You would be wise to keep a state of this object. Then decide on the behavior based on the state and the input from the user.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.