As the title says, I have a scene with three objects, a cube, a sphere, and a cylinder-like you can see in the image below.
What I'm trying to achieve is that when I press the "Rotate" button, the three objects rotate in an anti-clockwise direction, so the cylinder goes where the cube was, the cube goes where the sphere was, and the sphere goes where the cylinder was. If I click the button again, they rotate once again and so on. So far, I managed to make them rotate around an empty object at the center of the "triangle" they form with their initial position.
This is what happens when I first click the "Rotate" button:
As you can see, the object rotates, but they don't keep the same coordinate of the object that was previously in that position, so I was thinking of having them exchange coordinates. How can I achieve that or making them rotate how I want to?
Here is the code I wrote so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RotateObject : MonoBehaviour {
//rotating objects
[SerializeField]
private GameObject cube;
[SerializeField]
private GameObject sphere;
[SerializeField]
private GameObject cylinder;
private Renderer cubeRenderer;
private Renderer sphereRenderer;
private Renderer cylinderRenderer;
//rotation target
public GameObject target;
private void Start() {
cubeRenderer = cube.GetComponent<Renderer>();
sphereRenderer = sphere.GetComponent<Renderer>();
cylinderRenderer = cylinder.GetComponent<Renderer>();
gameObject.GetComponent<Button>().onClick.AddListener(Rotate);
}
void Rotate() {
//rotate objects by 120 degrees
cube.transform.RotateAround(target.transform.position, Vector3.up, -120);
sphere.transform.RotateAround(target.transform.position, Vector3.up, -120);
cylinder.transform.RotateAround(target.transform.position, Vector3.up, -120);
}
}
Thanks in advance for helping me!
The easiest way to make an object(s) rotate around a point is to have it/them as a child of the point then rotate the point itself.
Rotator Script to be put on the parent object:
public class RotateObjects : MonoBehaviour
{
[SerializeField] Button rotateButton;
// Start is called before the first frame update
void Start()
{
rotateButton.onClick.RemoveAllListeners();
rotateButton.onClick.AddListener(RotateClockwise);
}
void RotateClockwise()
{
float newRotation = (360 / transform.childCount);
transform.Rotate(new Vector3(0, newRotation, 0));
}
}
You are rotating around an object. Like the earth rotates around the sun; that means it will change its position. Use
transform.rotation = new Quaternion(rotx, roty, rotz, rotw);
or
transform.Rotate(rotx, roty, rotz);
Instead of rotating about a point rotate the shape, it's self.