1

I'm currently instantiating some objects in a row using Vector3.Lerp. This is working, however it's also creating some gaps between the objects. This happens if the distance between the start and end isn't big enough to insert a new object, but it's big enough that they can slide around a bit. They need to run end-to-end, butted up directly against each other.

Code is:

Vector3 startPosition= blah.transform.position.
Vector3 endPosition = getCurrentMousePosition();
Vector3 size = ObjectToSpawn.GetComponent<Renderer>().bounds.size;
fillCount = Mathf.RoundToInt(Vector3.Distance(startPosition, endPosition) / size.z);

float distance = 1.0f / fillCount;
float lerpValue = 0;

for (int i = 0; i < fillCount; i++)
 {
   lerpValue += distance;
   nextPosition = Vector3.Lerp(startPosition, endPosition, lerpValue);
   Instantiate(ObjectToSpawn, nextPosition, Quaternion.identify);
 }

Part of me thinks that it might just be worth trying to instantiate the objects in a row just based on their size / distance, but I can't seem to get that quite right either. Although this system is being used for something else, and I'd rather not rewrite entirely new code, if this can be modified slightly to work. I'm guessing that rounding the Lerp value would be the way to go, possibly?

Any input or advice would be greatly appreciated.

Programmer
  • 121,791
  • 22
  • 236
  • 328
Tony
  • 3,587
  • 8
  • 44
  • 77

2 Answers2

1

You can use a threshold. When it's position is very close to endPosition, you can clamp it to endposition directly like this:

if(Vector3.Distance(nextPosition,endPosition)<threshold){
  nextPosition = endPosition;
}else{
  nextPosition = Vector3.Lerp(startPosition, endPosition, lerpValue);
}
ZayedUpal
  • 1,603
  • 11
  • 12
1

If you want the objects to exactly touch with no gaps, the distance between the start and end positions has to be an integer multiple of their size.

Try adding the following line just before your loop:

endPosition = Vector3.Lerp(startPosition, endPosition, (fillCount * size.z) / Vector3.Distance(startPosition, endPosition));
David Oliver
  • 2,251
  • 12
  • 12
  • That's done it. Just had to tweak the code a bit, ((i+1) * size.z) has them all placed in a line, with no overlaps. Thanks!! – Tony Aug 19 '17 at 20:45