Daniel Lip
Daniel Lip

Reputation: 11321

How can I move some object in circle around another object?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TargetBehaviour : MonoBehaviour
{
    // Add this script to Cube(2)
    [Header("Add your turret")]
    public GameObject Turret;//to get the position in worldspace to which this gameObject will rotate around.

    [Header("The axis by which it will rotate around")]
    public Vector3 axis;//by which axis it will rotate. x,y or z.

    [Header("Angle covered per update")]
    public float angle; //or the speed of rotation.

    public float upperLimit, lowerLimit, delay;// upperLimit & lowerLimit: heighest & lowest height; 
    private float height, prevHeight, time;//height:height it is trying to reach(randomly generated); prevHeight:stores last value of height;delay in radomness; 

    // Update is called once per frame
    void Update()
    {
        //Gets the position of your 'Turret' and rotates this gameObject around it by the 'axis' provided at speed 'angle' in degrees per update 
        transform.RotateAround(Turret.transform.position, axis, angle);
        time += Time.deltaTime;
        //Sets value of 'height' randomly within 'upperLimit' & 'lowerLimit' after delay 
        if (time > delay)
        {
            prevHeight = height;
            height = Random.Range(lowerLimit, upperLimit);
            time = 0;
        }
        //Mathf.Lerp changes height from 'prevHeight' to 'height' gradually (smooth transition)  
        transform.position = new Vector3(transform.position.x, Mathf.Lerp(prevHeight, height, time), transform.position.z);
    }
}

In general it's working the problem is for example if I set the axis x,y,z to 1,1,1 on the variable: axis

And Angle set to 1 Upper limit to 50 Lower limit to 2 and delay to 2.

Then the object is making a circle around the other object but sometimes when the object is getting higher the most he get higher the object making a bigger circle and then when the object is getting lower the circle is smaller.

How can I make it to keep the circle radius static ?

The main goal is to move the object in circles around another object in random highs limits for example 2 and 50 but I want to keep the same radius all the time. Now the radius is changing by depending on the height.

Upvotes: 1

Views: 696

Answers (1)

lockstock
lockstock

Reputation: 2427

As you are constantly moving the object upwards, if you want the radius of rotation to remain constant then the axis of rotation must veertical ie - Vector3.up or new Vector3(0, 1, 0)

Upvotes: 2

Related Questions