- Home /
rate of spawn based on speed of object
Hi i have a object that moves around in the scene with a velocity value. This object moves around and slows down over time, decreasing the velocity of its rigidbody. This object can instantiate objects, you can say its dropping things as its moving around. The spawn rate should function like a trail behind the object, spawning objects at an even rate even though the speed of the object varies. For example, when the object starts moving its really fast meaning that the spawn rate should be fast aswell. As the object slows down the spawn rate should slow down aswell.
I worked and tried many different solutions for this. I first tried doing a IEnumerator that is looped with a while loop, the spawn rate is indicated by the float value of WaitForSeconds. I also tried using InvokeRepeating where you can use a normal void function but both methods doesn't seem to cut it for me.
The most important part is that i want to have a float variable that indicates the spawn rate of objects and it should also be flexible. I tried creating a float property where its value should be affected by the objects velocity value.
private float _netSpawnRate;
public float netSpawnRate
{
get
{
return _netSpawnRate;
}
set
{
value = 1 - boatObj.GetComponent<Rigidbody2D>().velocity.magnitude;
_netSpawnRate = value;
}
}
This is the float property i tried doing. Im not really familiar with them so i believe im doing something wrong here. Once i can get a flexible float variable that changes depending on the objects velocity, i believe i'm set to try and fix this on my own.
I appreciate any type of help! Have a nice day
EDIT: Im considering using an IEnumerator with a while loop where the iteration is based on WaitForSeconds. In this case my float should increase while the velocity of my object decreases, because if the float value is larger then the iteration will be slower.
Answer by Masterio · Apr 18, 2017 at 07:22 PM
public boatObj;
public float spawnInterval = 1f; // default spawn interval [increase or decrease it if needed]
private float _t = 0f; // next spawn time
private Rigidbody2D _rb; // handle [dont use GetComponent in update methods]
void Start()
{
_rb = boatObj.GetComponent<Rigidbody2D>();
}
void Update()
{
if(_t < spawnInterval)
_t += Time.deltaTime * _rb.velocity.magnitude; // greater magnitude increase spawn speed
else
{
_t = 0f;
// spawn object:
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612120100im_/https://answers.unity.com/themes/thub/images/avi.jpg)