how do i make a cube move without stopping when i press a button in unity (2D)
Declare a bool variable and initially assign it to false. When you press the button, change its value to true. Move character only if the bool is true.
private bool isAllowed = false;
private void AllowState()
{
if (isAllowed == true)
{
return;
}
if (Input.GetKeyDown(KeyCode.Space))
{
isAllowed = true;
}
}
private void MoveObject()
{
if (isAllowed == true)
{
// Move code in here
}
}
private void Update()
{
AllowState();
MoveObject();
}
In the update loop, you can continuously update the position of the cube by a certain speed. So something like this
public int speed = 5;
Vector2 velocity;
private void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
velocity.x = 1;
transform.position += velocity * speed * Time.deltaTime;
}