Reverse Gravity for a period of time

Hey,

I’m looking to reverse gravity for a period of time, like 2 second then reverse it back

Below is what I am using, but its not working… if it was I wouldn’t be here haha. My thought is that when space is pressed the run time plus 2 is saved as startTime and gravity is flipped. When the 2 seconds has elapsed it will enter the if statement and flip gravity back. Currently it seems to just be a flip gravity button.

Also just as a side point to save posting two questions, how would I make sure if space is pressed during those 2 seconds, that it would do nothing

Thanks a lot

if (Input.GetKeyDown("space"))
	{ 
		startTime = Time.time + 2;
		gravity = -gravity;
        curVel.y = 0;
		
	    if (startTime == Time.time) {
        gravity = -gravity;
	    curVel.y = 0; 
        }
    }

var notAgain =true;
if (Input.GetKeyDown(“space”)&& notAgain){
gravity = -gravity;
curVel.y = 0;
notAgain = false;
Invoke(“Revert”,2.0f);
}

function Revert(){
     gravity = -gravity;
     curVel.y = 0;  
     notAgain = true;
}

The notAgain variable ensures that you do not press twice the space bar and invoke the revert function twice. Only once the gravity is back that you can press again.

Edit: I modify the declaration of the notAgain and the function.

For a detailed explanation on timers you can check there unitygems.com and check the “Make something happens in the future” section

EDIT (again): just another way to write the same snippet and make you look more “Pro” :slight_smile:

var notAgain = true;
if (Input.GetKeyDown("space")&& notAgain){ 
       Revert();
       Invoke("Revert",2.0f);
}

function Revert(){
     gravity = -gravity;
     curVel.y = 0;  
     notAgain = !notAgain;
}

Since you do the same thing twice you might as well make it a function. Though, I would say that slightly goes against my personal rule on function which is “Less than 5 lines of codes → not a function”. And do not try to put the Invoke in the function, you would end up in an endless recursion.