Search code examples
unity-game-engineequationmotioneuler-angles

Unity 2D move and rotate issue


I am working on adding a helicopter to my 2d game and I need it to move in circular motion whilst moving on the x axis as well. Below you can find the code that I am using which uses the mathematical circle equation.

angle += speed * Time.deltaTime; //if you want to switch direction, use -= instead of +=
float x = startPoint.x + Mathf.Cos(angle) * radius;
float y = startPoint.y + Mathf.Sin(angle) * radius;
transform.position = new Vector2(x + 2, y);

The helicopter is rotating correctly but I can't figure out how I can make it move along the x axis. Concept image of how it should work below: enter image description here


Solution

  • 1) Make an empty game object

    2) Parent your box to the empty game object

    3) rotate the box around the empty game object

    4) move the empty game object to the side

    If you want to avoid adding an empty parent, you can keep track of the center of rotation separately, rotate around it, and move it over time.

    public class hello_rotate : MonoBehaviour
    {
        float angle = 0;
        float radius = 1;
        float speed = 10;
        float linear_speed = 1;
        Vector2 centerOfRotation;
        // Start is called before the first frame update
        void Start()
        {
            centerOfRotation = transform.position;
        }
    
        // Update is called once per frame
        void Update()
        {
            centerOfRotation.x = centerOfRotation.x + linear_speed * Time.deltaTime;
    
            angle += speed * Time.deltaTime; //if you want to switch direction, use -= instead of +=
            float x = centerOfRotation.x + Mathf.Cos(angle) * radius;
            float y = centerOfRotation.y + Mathf.Sin(angle) * radius;
            transform.position = new Vector2(x + 2, y);
        }
    }