- Home /
 
               Question by 
               NikolaStoilkovic · Feb 27 at 10:26 AM · 
                2dmovement2d gameunity 2dmovement script  
              
 
              How do i make a cube move (Continuosly without stopping) when i press a button once in unity 2D
how do i make a cube move without stopping when i press a button in unity (2D)
               Comment
              
 
               
              Answer by V_0_1_D_ · Feb 27 at 11:46 AM
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();
 }
Answer by JdeHaan · Feb 27 at 11:48 AM
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;
 }
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                