I have a cage in my game hanging from the ceiling and I want it to dangle around. Therefor I wrote the following Script:
using UnityEngine;
using System.Collections;
public class Cage : MonoBehaviour {
private float xrot;
private float zrot;
private float time;
void Start()
{
xrot = (Random.Range (0, 1000) / 1000.0f) * 10f - 5f;
zrot = (Random.Range (0, 1000) / 1000.0f) * 10f - 5f;
time = (Random.Range (0, 1000) / 1000.0f) * Mathf.PI;
}
void Update () {
if(Time.time - time >= 0){
transform.RotateAround (new Vector3 (transform.position.x, 12, transform.position.z), new Vector3 (1, 0, 0), xrot * Time.deltaTime * Mathf.Cos (Time.time - time));
transform.RotateAround (new Vector3 (transform.position.x, 12, transform.position.z), new Vector3 (0, 0, 1), zrot * Time.deltaTime * Mathf.Cos (Time.time - time));
}
}
}
The Code choses a random x and z rotation speed (positive or negative) and uses a cosine to rotate the cage. When the cage is instantiated it has a rotation of 270 and hangs straight down from the ceiling which is the reason why is has to have full speed at the beginning since it starts a the lowest and fastest part of the swing motion.
The problem was all cages started swinging at the same time so I used “time” to start them at a different velocities. Now I do not know how to correct the start rotation of the cage. Having a random starting velocity demands the corresponding start rotation since those values are connected. I solved the poblem not very nice by letting them start to swing after the random delay but if you now look at the cage at the very beginning of the game they first do not move and then start abruptly which I do not want So is there any way how I can calculate the starting rotation for my cages with the value of “time”?
Thanks in advance!