Controlling/moving an object in a circular motion in Unity

14.5k views Asked by At

Basically, I want it so I can move an object left or right, but in a circular motion, rather than a straight line. This is because the object is the child of another sphere, and I want to move the object around the sphere using the left/right arrowkey so a position around the sphere can be established.

I found some code that moves the circle in only one direction, and I cannot control it. Here it is:

float timeCounter = 0;

void Update () {
        timeCounter += Time.deltaTime;
        float x = Mathf.Cos (timeCounter);
        float y = Mathf.Sin (timeCounter);
        float z = 0;
        transform.position = new Vector3 (x, y, z);
}

If someone could try to "convert" this code into a code I can control with the left and right arrowkey and making it move both left and right, it would be great. Other submissions are also greatly appreciated

2

There are 2 answers

0
Nika Kasradze On BEST ANSWER
float timeCounter = 0;

void Update () {
    timeCounter += Input.GetAxis("Horizontal") * Time.deltaTime; // multiply all this with some speed variable (* speed);
    float x = Mathf.Cos (timeCounter);
    float y = Mathf.Sin (timeCounter);
    float z = 0;
    transform.position = new Vector3 (x, y, z);
}
0
dev-masih On

Here is a complete code for rotation with left and right arrow keys

float timeCounter = 0;
bool Direction = false;

void Update () {

    if(Input.GetKeyDown(KeyCode.LeftArrow))
    {
        Direction = false;
    }
    if(Input.GetKeyDown(KeyCode.RightArrow))
    {
        Direction = true;
    }
    if (Direction)
        timeCounter += Time.deltaTime;
    else
        timeCounter -= Time.deltaTime;
    float x = Mathf.Cos (timeCounter);
    float y = Mathf.Sin (timeCounter);
    float z = 0;
    transform.position = new Vector3 (x, y, z);
}