user13082770
user13082770

Reputation:

Adding multiple box colliders between two points?

I have tried to add a line renderer between two points and that works. How do I add multiple small box colliders between two points? Lets say I want to add 10 small box colliders between these two points. The Box colliders should not overlap but the 1st box collider's end position can be touched with 2nd box collider's starting position. I hope I made it clear here.

I assume I would have to instantiate gameObjects with box colliders between two points, how do I achieve this?

public GameObject PointA;
public GameObject PointB;
public GameObject GameObjPrefab;
// Start is called before the first frame update
void Start()
{
    Instantiate(GameObjPrefab, Mathf.Lerp((float)PointA, (float)PointB, 0.5f), Quaternion.identity);
}

Upvotes: 0

Views: 265

Answers (1)

Philipp Lenssen
Philipp Lenssen

Reputation: 9218

Try

using UnityEngine;

public class CubeCreator : MonoBehaviour
{
    [SerializeField] Transform startPoint = null;
    [SerializeField] Transform endPoint = null;

    void Start()
    {
        AddCollidersBetween();
    }

    void AddCollidersBetween()
    {
        const int padding = 2;
        const int colliderCount = 10 + padding;
        const float cubeSize = 0.5f;

        const float lerpMultiplier = 1f / colliderCount;

        for (int i = 1; i < colliderCount; i++)
        {
            float lerpFactor = i * lerpMultiplier;

            GameObject cubeObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
            cubeObject.name = "Cube " + i;

            Transform cube = cubeObject.transform;
            cube.position = Vector3.Lerp(
                startPoint.position, endPoint.position, lerpFactor
            );
            cube.localScale = Vector3.one * cubeSize;
            cube.LookAt(endPoint);
        }
    }

}

Upvotes: 2

Related Questions