- Home /
how to let user only have one go at moving?
so I'm creating a 2d game where there is a ball on top of a box, the idea is to drop the box and ball down as low as possible without it dropping below the bottom of the screen or the closest to a point or something. The box and ball will spawn mid screen, and you hold click (mouse button) to move the box downwards with the ball falling on top of it. So far i have got the movement of the box working with this code:
public Rigidbody2D rb;
public Vector2 moveVelocity;
public float speed;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
public void Update()
{
Vector2 moveInput = new Vector2(0, -Input.GetAxisRaw("Fire1"));
moveVelocity = moveInput.normalized * speed;
}
void FixedUpdate()
{
rb.MovePosition(rb.position + moveVelocity * Time.fixedDeltaTime);
}
however this allows you to move the box whenever you would like. What i want it to do is that you will start the game have one go at moving the box down and then you cannot move the box anymore after that first go. i believe that the problem is in the update function and the fact that it moves the box down by -1 every frame rather than once for the duration of your click. if there were some way of making it move the box down for the duration of your click, then setting a variable such as HasTried = true, then i could stop them from being able to move again. but the fact it moves the box frame by frame i cannot "instance" the click/hold in any way. Hope you understand what i am trying to do!
Answer by MrRightclick · Apr 11, 2019 at 12:45 PM
Just make a boolean check for when the box should move, and use Input.GetMouseButtonUp event to check when the player releases the button for the first time.
public bool hasTried = false;
void Update () {
if (!hasTried) {
// Your input & movement code here
}
if (Input.GetMouseButtonUp(0)) hasTried = true;
}
Also if you're using velocity to move the box, you should probably set the rigidbody's velocity to zero once you want the box to stop moving.
Hey, glad to be of help. Please remember to set the working answer as Best Answer so the question can be closed. Happy coding!
Your answer
Follow this Question
Related Questions
,Spawning snow or changing tilesets to snow as the player walks past them 0 Answers
how to do an hot update of android and ios build 0 Answers
Adding knockback to a 2D game (in C#) 2 Answers
How can I stop hurt animation and bounce the player when hit by an enemy? 0 Answers
2d Iteam respawn in Spawn point 0 Answers