简体   繁体   中英

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]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM