简体   繁体   中英

C# compass rotation script in Unity3d

I have a compass object which rotates and moves along with the camera. Thus the rotation and position of the compass object is adjusted along with the player-controlled camera. Now, having attached a needle to my compass - I would like to have the needle point north.

That is easily done but having the needle point to a northern object. But the needle now doesn't follow the plate (compass object) it is placed on. I would thus like the needle to point accordingly. In other word, rotate singly along the y-axis.

I don't need code - I just need a broad idea of how to do that. I would really appreciate any help :)

I finally figured it out :D It was much easier than expected... Here is the code if anyone should ever need it:

using UnityEngine;
using System.Collections;

public class Compass : MonoBehaviour 
{
    void Update () 
    {
         transform.localRotation = Quaternion.Euler(0, 360-transform.root.rotation.eulerAngles.y, 0);
    }
}

I would try to project the vector pointing from compass location to target onto the plane where the needle should lay on. Vector.ProjectOnPlane might be helpful. Something like this should work (not yet tested):

Vector3 dir = compassPos - targetPos;
Vector3 needleDir = Vector3.ProjectOnPlane(dir, compassNormal);

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