I have to make a Pendulum sync with system time. It has to be right in the middle of the swing when the second ticks in the clock.
I made this script, but its not sync.. it swings ok, but it depends on when I click play if its sync or not, and thats not ok. It has to be with the system clock:
using UnityEngine;
public class SwingPendulo : MonoBehaviour
{
public Transform pendulum;
public float amplitude = 45f;
public float speed = 180f;
private float initialAngle; // Start angle
private void Start()
{
initialAngle = pendulum.rotation.eulerAngles.z;
}
private void Update()
{
// Obtain actual time in seconds
float currentTime = Time.time;
// calculate actual pendulum angle
float angle = initialAngle + Mathf.Sin(currentTime * speed * Mathf.Deg2Rad) * amplitude;
// Rotate pendulum in Z
pendulum.rotation = Quaternion.Euler(0f, 0f, angle);
// If we are between seconds, adjunst angle to half
if (Mathf.Abs(angle - initialAngle) < 0.1f)
{
float halfAmplitude = amplitude / 2f;
pendulum.rotation = Quaternion.Euler(0f, 0f, initialAngle + halfAmplitude);
}
}
}
As was mentioned
Time.timeIn order to access your actual system time instead you could use
DateTime.Now