PSPTorchinim
PSPTorchinim

Reputation: 13

Unity3D c# change rotation of object

I'm trying to do Day/Night Cycle in my game... there is a server sending me the azimuth of sun, and using that azimuth i want to change rotation of the directional light, there is my code:

public static Sun instance;
    public GameObject gameObject;

    public Vector3 SunRot;
    private bool rotate;

    void FixedUpdate()
    {
        ///Rotate gameObject with SunRot values
    }

    internal void UpdateRotation(double altitude, double azimuth)
    {
        Debug.Log(azimuth);
        SunRot = new Vector3((float)azimuth, (float)altitude, 0);
        rotate = true;
    }

and my logic is:

  1. Call UpdateRotation
  2. ooo... SunRot changed... so copy SunRot values to Sun gameobject

When i use EulerAngles it's copying azimuth like [from server: 304.00075, in transform.rotation: 65.99825]... i want do it like [from server: 304.00075, in transform.rotation: 304.00075]

Upvotes: 1

Views: 164

Answers (1)

Yamuk
Yamuk

Reputation: 769

It could be better to keep the previous value from the server, and use Transform.Rotate(deltaRotation) when it changes. You need to be careful for boundary 0-360 case though.

public static Sun instance;
    public GameObject gameObject;
    private Transform sunTransform = gameObject.Transform;
    private Vector3 previousServerValues;
    private bool rotate;

    void FixedUpdate()
    {
        ///Rotate gameObject with SunRot values
    }

    internal void UpdateRotation(double altitude, double azimuth)
    {
        var newServerVals = new Vector3((float)azimuth, (float)altitude, 0); 
        Vector3 deltaRotation = newServerRot - previousServerRot ;
        if (deltaRotation.x < 0)   //boundary case, may need it for altitude as well
            deltaRotation.x += 360;
        sunTransform.Rotate (deltaRotation);
        rotate = true;
    }

You might need to use Transform.RotateAround by the way, unless you offset the center of the sun object, which may or may not be ideal depending on your case.

Upvotes: 1

Related Questions