- Home /
Question by
XTRA_THICC · Mar 09, 2020 at 02:52 PM ·
c#rotate objectsphereworldspace
How do I rotate an object around a certain point?
I have this piece of code:
if (Input.GetMouseButton(2))
{
float mouseInput = Input.GetAxisRaw("Mouse X");
angle += mouseInput;
Vector3 offset = new Vector3(Mathf.Sin(angle), 0, Mathf.Cos(angle));
transform.position = offset;
}
It reads my mouse movements and then moves a sphere in a circle around the center of the worldspace.
The problem is, it doesn't matter where I put the sphere before starting the game, it always snaps back to rotate around the worldspace center. I can't figure out how to fix it.
Could anybody help me?
Comment
Answer by unity_ek98vnTRplGj8Q · Mar 09, 2020 at 03:00 PM
This is because you are setting the position to just your offset, if you want to rotate it around a set point you need to tell it what that point is and also what radius you want it to rotate at.
public Transform rotationCenter;
public float radius;
Update () {
if (Input.GetMouseButton (2)) {
float mouseInput = Input.GetAxisRaw ("Mouse X");
angle += mouseInput;
Vector3 offset = new Vector3 (Mathf.Sin (angle) * radius, 0, Mathf.Cos (angle) * radius);
transform.position = offset + rotationCenter.position;
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Rotate gameobject by mouse at constant speed? 2 Answers