1
votes

I have code that lerps Sphere instance positions from the vertices of a 1st mesh, to the vertices of a 2nd mesh.

The sphere instances are moved via a Lerp that uses transform data positions. The problem is that apparently moving the instances this way does not work with Unity's Physics very well, so other objects that collide with the sphere instances don't collide with them properly.

How can I change the code to correctly make the Sphere instances move with maybe Vector3 velocity (or whatever would make Unity physics work right), rather than just moving via setting explicit transform positions?

here is the code. I have these variables:

public List<TransformData> meshVertices1 = new List<TransformData>();
public List<TransformData> meshVertices2 = new List<TransformData>();

which are then being filled later with data like:

meshVertices1.Add(new TransformData(position, rotation, scaleVector));
meshVertices2.Add(new TransformData(position, rotation, scaleVector));

then I instantiate sphere instances based on above data:

spheres = new GameObject[24]; 
for (int i = 0; i < mesh.vertexCount; i++)
{
    spheres[i] = Instantiate(spherePrefab, meshVertices1[i].position, Quaternion.identity, transform);
}

and lastly put a Lerp for the sphere instance positions in Update method:

for (int i = 0; i < 24; i++)
{
    spheres[i].transform.localPosition = Vector3.Lerp(meshVertices1[i].position, meshVertices2[i].position, t);
}

Thanks. One of the things I tried was changing the Update method to say

Vector3 convert = spheres[i].transform.InverseTransformPoint(transform.localPosition); convert = Vector3.Lerp(meshVertices1[i], meshVertices2[i].position, t);

but upon hitting play it just made the sphere instances all drop to the floor and roll around. Whereas I want the instances to move and stay in the formation of the 2nd Mesh vertices.

1

1 Answers

0
votes

One approach is getting a reference to the Rigidbody of each sphere and calling Rigidbody.MovePosition (make sure this is done in FixedUpdate):

for (int i = 0; i < 24; i++)
{
    Rigidbody rb = spheres[i].GetComponent<Rigidbody>();
    rb.MovePosition(Vector3.Lerp(meshVertices1[i].position, meshVertices2[i].position, t));
}

In the interest of performance, you may want to create a list of each sphere's Rigidbody once, and then loop through that list so you don't have to call GetComponent 24 times every frame.