- Home /
InvokeRepeating faster if the rigidBody is moving faster?
Hi, I have this:
var spawnRate = 0.5;
InvokeRepeating("makeAsteroid", 0, spawnRate);
I want 'spawnRate' to be faster the faster my object is moving and slower the slower it is moving. Eg, if the object is moving really fast 'spawnRate' will be 0.1 and if its not moving at all 'spawnRate' will be 1.0. How can I do this?
Not with InvokeRepeating. Sorry. You'll have to do it manually- try using a Coroutine with a yield WaitForSeconds(spawnRate) in the middle of a while loop.
Answer by syclamoth · Oct 27, 2011 at 10:07 AM
var spawnRate = 0.5;
function SpawnAsteroids() { yield WaitForSeconds(); while(true) { MakeAsteroid(); yield WaitForSeconds(spawnRate); } }
Start it using
StartCoroutine(SpawnAsteroids());
then you can modify spawnRate as you like, and it will change the number of asteroids accordingly. Do it in FixedUpdate, if there's a rigidbody involved.
If you need it to stop, use
StopCoroutine("SpawnAsteroids");
To spawn lots of things as it speeds up, have something like this-
function FixedUpdate () {
// This will make the spawn delay decrease from 2 seconds when
// the object is stationary, 0.1 seconds when it is moving at
// someMultiplier units per second.
spawnRate = Mathf.Lerp(2, 0.1, rigidbody.velocity.magnitude * someMultiplier);
}
Sorry I don't think you understood my question, I need spawnRate to decrease as the object accelerates and increase as it slows down if that makes any sense?
Seriously, I understood your question perfectly! I never specified any implementation, I expected you to do that yourself (since that's what you would have done anyway). I've given you some anyway because I'm nice.