Pendulum in Unity, sync with system clock (seconds)

48 Views Asked by At

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);
        }
    }
}
1

There are 1 best solutions below

0
derHugo On

As was mentioned Time.time

This is the time in seconds since the start of the application, which Time.timeScale scales and Time.maximumDeltaTime adjusts.

In order to access your actual system time instead you could use DateTime.Now

private Quaternion initialRotation;

private void Start()
{
    initialRotation = pendulum.rotation;
}

private void Update()
{
    var now = DateTime.Now;

    // increases from 0 up to 2 (exclusive)
    // instead of reaching 2 restarts from 0
    var currentTime = now.Second % 2 + now.Millisecond / 1000f;

    // is 0 for exact seconds (0 and 1)
    // is 1 for 0.5 seconds
    // is -1 for 1.5 seconds
    var angle = Mathf.Sin(currentTime * 180f * Mathf.Deg2Rad) * amplitude;

    // Rotate pendulum in local Z
    pendulum.rotation = initialRotation * Quaternion.Euler(0f, 0f, angle);
}