Hi. So I am trying to do something like a game of snake. And I want to try using the Animation Rigging package, with RigBuilder and DampedTransform. My snake is currently composed of multiple spheres, and if I create them in the editor, they work as expected.
My use case is that when I pick a fruit from the ground, I want to instantiate a new sphere (body part) and append it to the snake.
I was able to instantiate the objects, and then did the Build() on the rig builder; by default, the distance between each body part is 1, but when I’m moving, the distance and rotation aren’t constant, so if I pick a new fruit while I am turning, the new body part won’t be instantiated in the right place (will have a weird offset).
Is there a good fix for that, or should I drop using the Animation Rigging part on things like this?
In case it helps, this is how the code I got looks like:
public class SnakeManager : MonoBehaviour {
private RigBuilder rigBuilder;
[Header("Size Flow Components")]
[SerializeField] private Transform bodyContainer;
[SerializeField] private Transform rigContainer;
[SerializeField] private Transform head;
[SerializeField] private GameObject bodyPartPrefab;
[SerializeField] private GameObject bodyRigPrefab;
[SerializeField] private int initialBodySize = 3;
private void Awake() {
rigBuilder = GetComponent<RigBuilder>();
for (int i = 0; i < initialBodySize; i++) { CreateBodyPart(); }
}
public void CreateBodyPart() {
Transform lastBodyPart;
if (bodyContainer.childCount == 0) {
lastBodyPart = head;
} else {
lastBodyPart = bodyContainer.GetChild(bodyContainer.childCount - 1);
}
GameObject newBodyPart = Instantiate(bodyPartPrefab, bodyContainer);
newBodyPart.transform.localPosition = new Vector3(0, 1, lastBodyPart.localPosition.z - 1);
newBodyPart.transform.localRotation = lastBodyPart.localRotation;
newBodyPart.name = $"Body{bodyContainer.childCount}";
GameObject newBodyRig = Instantiate(bodyRigPrefab, rigContainer);
newBodyRig.transform.localPosition = newBodyPart.transform.localPosition;
newBodyRig.transform.localRotation = newBodyPart.transform.localRotation;
newBodyRig.name = $"Body{rigContainer.childCount} Rig";
DampedTransform dampedTransform = newBodyRig.GetComponent<DampedTransform>();
dampedTransform.data.constrainedObject = newBodyPart.transform;
dampedTransform.data.sourceObject = lastBodyPart.transform;
dampedTransform.data.dampPosition = 0.05f;
dampedTransform.data.dampRotation = 0.35f;
dampedTransform.data.maintainAim = true;
rigBuilder.Build();
}
}