Sunday, 3 April 2016

Pendulum Test



Inspired by https://github.com/KatsuomiK/Rope

Whole Pendulum created by C# script without any prefab. Code as below, just need to attach to camera.


using UnityEngine;
using System.Collections;

public class CreateRope : MonoBehaviour {

int fragmentNum = 20;
GameObject[] fragments;
GameObject parentOfAllObjs;

Vector3 interval = new Vector3(0f, 0f, 0f);

void Start () {

parentOfAllObjs = new GameObject("Pendulum");
parentOfAllObjs.transform.position = new Vector3 (10f, 0f, 10f);

GameObject chainObj = GameObject.CreatePrimitive(PrimitiveType.Sphere);
chainObj.transform.localScale = new Vector3 (0.25f, 1.0f, 0.25f);
Rigidbody rb = chainObj.AddComponent<Rigidbody>(); // Add the rigidbody.

fragments = new GameObject[fragmentNum];

Vector3 position = parentOfAllObjs.transform.position;

for (int i = 0; i < fragmentNum; i++) {
fragments[i] = (GameObject) Instantiate(chainObj, position, Quaternion.identity);
fragments[i].transform.parent = parentOfAllObjs.transform;
fragments[i].name = "fragment-" + i.ToString ();
fragments [i].transform.localPosition = i*interval;

HingeJoint joint = fragments[i].AddComponent<HingeJoint>();
joint.autoConfigureConnectedAnchor = false;
joint.connectedAnchor = new Vector3 (0f, 0f, 0f);

if (i > 0)
{
joint.connectedBody = fragments [i - 1].GetComponent<Rigidbody> ();
}
}

GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
sphere.name = "Ball";
sphere.transform.parent = parentOfAllObjs.transform;
Rigidbody gameObjectsRigidBody = sphere.AddComponent<Rigidbody>(); // Add the rigidbody.
gameObjectsRigidBody.mass = 50;

HingeJoint fj = sphere.AddComponent<HingeJoint> ();
fj.autoConfigureConnectedAnchor = false;
fj.connectedAnchor = new Vector3 (0f, 0f, 0f);
fj.connectedBody = fragments [fragmentNum - 1].GetComponent<Rigidbody> ();

Destroy (chainObj);

}
}

No comments:

Post a Comment