08-08-2022, 03:21 PM
(This post was last modified: 08-08-2022, 03:45 PM by josemendez.)
(08-08-2022, 02:56 PM)landosilva Wrote: The attachment, position and motion are now fine, but, for some reason, the end point is sometimes being dettached.
When you change the length of a rope using a cursor, particles might be removed from/added to it (for obvious reasons). So existing attachments can go "outside scope" so to speak, referencing particles that no longer exist (or rather, are inactive): because they were removed when reducing the length of the rope, and replaced by other particles when increasing the length again.
There's no guarantee that the particles that were removed when decreasing the length of a rope are added in the exact same order they were removed, since particles are pooled. This is what's causing the end attachment to stop working: after you shorten the rope, the end attachment references a particle that no longer exists.
The way to do this is to update the attachment's particle group to reference the new particle at the end of the rope:
Code:
public void Connect(Transform origin, Transform end)
{
cursor.ChangeLength((end.position - origin.position).magnitude);
for (var i = 0; i < rope.elements.Count; i++)
{
ObiStructuralElement element = rope.elements[i];
float t = i / (float)rope.elements.Count;
Vector3 position = Vector3.Lerp(origin.position, end.position, t);
int particleIndex1 = element.particle1;
int particleIndex2 = element.particle2;
rope.solver.positions[particleIndex1] = position;
rope.solver.positions[particleIndex2] = position;
rope.solver.velocities[particleIndex1] = Vector4.zero;
rope.solver.velocities[particleIndex2] = Vector4.zero;
}
// Update the attachments to reference whichever particles are now at the ends of the rope, after changing its length:
int firstParticle = rope.elements[0].particle1;
int lastParticle = rope.elements[rope.elements.Count - 1].particle2;
attachment1.particleGroup.particleIndices[0] = rope.solver.particleToActor[firstParticle].indexInActor;
attachment2.particleGroup.particleIndices[0] = rope.solver.particleToActor[lastParticle].indexInActor;
attachment1.target = origin;
attachment2.target = end;
attachment1.enabled = true;
attachment2.enabled = true;
}
Note that depending on where you place the cursor and which side of the rope it is facing, both the end and start attachments might be affected (since the rope can also grow/shrink from the start), so it's safer to update both attachments. This prevents issues if you later flip the cursor to face the start of the rope instead.
kind regards,