- Home /
Rotate Object around point and move it along sine function
First off: I am very new to Unity, as in VERY new.
I want to do the following: I want to rotate a cube around a stationary point (in my case a camera) with a radius that is adjustable in the inspector. The cube should always have its Z-axis oriented towards the camera's position. While the cube is orbiting around the camera, it should additionally follow a sine function to move up and down with a magnitude of 2.
I have some working code, the only problem is an increase in distance over time. The longer the runtime, the higher the distance between the cube and the camera.
Here is what I currently have:
void Awake()
{
cameraPosition = GameObject.FindGameObjectWithTag("MainCamera").transform;
transform.position = new Vector3(x: transform.position.x,
y: transform.position.y,
z: cameraPosition.position.z + radius);
movement = transform.position;
}
I instantiate some variables in the Awake()-method and set the cube's position to where it should be (do you instantiate in Awake()?). I'll use the Vector3 movement later in my code for the "swinging" of the cube.
void Update()
{
transform.LookAt(cameraPosition);
transform.RotateAround(cameraPosition.position, cameraPosition.transform.up, 30 * Time.deltaTime * rotationSpeed);
MoveAndRotate();
}
Here I set the orientation of the cube's z-axis and rotate it around the camera. 30 is just a constant i am using for tests.
void MoveAndRotate()
{
movement += transform.right * Time.deltaTime * movementSpeed;
transform.position = movement + Vector3.up * Mathf.Sin(Time.time * frequency) * magnitude;
}
To be quite frank, I do not understand this bit of code completely. I do however understand that this includes a rotation as it moves the cube along it's x-axis as well as along the world's y-axis. I have yet to get into Vector and matrices, so if you could share your knowledge on that topic as well I'd be grateful for that.
One last question: Is this place more active than Unity answers is? It sure does seem so.
Answer by UnityedWeStand · Jun 24, 2020 at 10:43 PM
Welcome to Unity! It does take some time getting used to working with positions and rotations in Unity, but it is well worth the payoff down the line.
As for your problem, the observed behavior (cube getting farther away from the camera) is caused by the movement
variable in your code. This step is actually not necessary: transform.RotateAround()
takes care of the circular portion of movement by itself and keeps the cube at a constant distance from the camera since the rotation point/axis is the camera itself. What your code is doing every frame is both circling the cube around the camera and moving the cube along its local x-axis. That second transformation (movement along local x-axis) is causing the cube to deviate from a completely circular path.
tl;dr remove the movement
variable