Crane
unknown
csharp
10 months ago
2.0 kB
8
Indexable
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Crane : MonoBehaviour
{
[SerializeField] private GameObject chain;
[SerializeField] private Rigidbody startPoint;
[SerializeField] private Rigidbody endPoint;
[SerializeField] private float linkLength = 1.0f; // Length of each chain link
private List<GameObject> chains = new List<GameObject>();
private void Awake()
{
GreateChains();
}
void GreateChains()
{
Vector3 direction = (endPoint.position - startPoint.position).normalized;
float distanceToEndPoint = Vector3.Distance(startPoint.position, endPoint.position);
int linkCount = Mathf.CeilToInt(distanceToEndPoint / linkLength);
Rigidbody previousLink = null;
for (int i = 0; i < linkCount; i++)
{
// Calculate position for the current link
Vector3 linkPosition = startPoint.position + direction * linkLength * i;
// Instantiate the link
GameObject currentLink = Instantiate(chain, linkPosition, Quaternion.identity);
//Add it to list
chains.Add(currentLink);
// Get the Rigidbody of the current link
Rigidbody currentRigidbody = currentLink.GetComponent<Rigidbody>();
// Connect the current link to the previous one
HingeJoint hingeJoint = currentLink.GetComponent<HingeJoint>();
hingeJoint.connectedBody = previousLink;
// Save the current link as the previous for the next iteration
previousLink = currentRigidbody;
}
//Connect the last link to the endPoint
HingeJoint pot = endPoint.GetComponent<HingeJoint>();
pot.connectedBody = previousLink;
//Connect the first chain to startPoint
chains[0].GetComponent<HingeJoint>().connectedBody = startPoint;
}
}
Editor is loading...
Leave a Comment