简体   繁体   中英

Unity lerp remove gaps

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.

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);
}

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM