- Home /
Adding 1 to a float over time to increase difficulty?
so I have an object that moves back and forth at a speed and will change directions at random times, but I want it to increase in speed over time and increase from 1 to 16 in 96 seconds (or 1 every 6 seconds). Here's my script:
var blockSpeed : float = 1;
function Awake()
{
rigidbody.AddForce(blockSpeed, 0, 0, ForceMode.Impulse);
}
Invoke( "NewFunDirection", Random.Range(0.5,0.8) );
function NewFunDirection()
{
rigidbody.velocity = -rigidbody.velocity;
Invoke( "NewFunDirection", Random.Range(0.5,1.4) );
}
I tried something like this but i'm unaware of how to format it
function Update(){
yield WaitForSeconds (6);
if (blockSpeed <= 16){
blockSpeed =+1;
}
When I use this last bit of coding Unity tells me it the + is an unexpected token.
That code increases the speed every 6 seconds so the speed increases in steps. Is that what you want or do you want a smooth ramp in speed?
Answer by Bunny83 · Jun 25, 2014 at 12:39 AM
First of all you only apply a force in Awake. So changing "blockSpeed" afterwards doesn't do anything to the velocity of the rigidbody.
Apart from the fact that changing blockSpeed doesn't do anything, if you want to gradually increase the blockSpeed by 1 every 6 seconds you can do this:
function Update()
{
if (blockSpeed <= 16)
{
blockSpeed += Time.deltaTime / 6;
}
}
This will add a small fraction each frame so it gradually increases. Without the "/6" it would increase by 1 every second. By dividing by 6 the increase is 6 times slower, so it takes 6 seconds to increase blockSpeed by 1.
ps: If you want to set the speed of your rigidbody you can do this:
function Update()
{
if (blockSpeed <= 16)
{
blockSpeed += Time.deltaTime / 6;
var dir = rigidbody.velocity.normalized;
rigidbody.velocity = dir * blockSpeed;
}
}
Thank you, works perfectly! And smoother than it would be automatically changing the speed every 6 seconds. Boneheaded mistake on my part not realizing it was in the awake function haha.
Answer by Okari-Draconis · Jun 24, 2014 at 10:41 PM
Dont use update. From ur awake or start function do an InvokeRepeating(6,6,"increaseDifficulty"), make sure u have a function called increaseDifficulty() and put ur float++ in there
I totally missed the yield return in the Update() function. duh.
WaitForSeconds() can only be used in coroutines.
Thank you, that is probably a better way to do it! Unity is giving me an error though because apparently InvokeRepeating is supposed to be (string, float, float) and not (int, int, string). Why a float if it's function is to wait for seconds?
Answer by jefjohms · Jun 24, 2014 at 10:30 PM
put the '+' before the equals. This is shorthand for: blockSpeed = blockSpeed + 1; Your line says blockSpeed is equal to +1;
I tried it, and it doesn't turn an error now, but it doesn't increase the float speed of the block.