Home > OS >  Unity2D - Changing rotation direction using transform.RotateAround()
Unity2D - Changing rotation direction using transform.RotateAround()

Time:11-01

I am making a simple game where two moons orbit around a planet. I want to make it so that with the press of a button:

    public KeyCode switch_rotation_moon_a;
    private bool rotating_left = false;
    private void Update()
    {
        if (Input.GetKeyDown(switch_rotation_moon_a))
        {
            rotating_left = !rotating_left;
        }
    }

where rotating_left is what decides the rotation direction. I then have this for the actual implementation of the rotation:

    private void FixedUpdate()
    {
        planet_position = radius * Vector3.Normalize(this.transform.position - planet.transform.position)   planet.transform.position;
        this.transform.position = planet_position;
        if (rotating_left)
        {
            transform.RotateAround(planet.transform.position, new Vector3(0, 0, 1),  rotation_speed);
        }
        transform.RotateAround(planet.transform.position, new Vector3(0, 0, -1), rotation_speed);
    }

When starting the game, the planet seems to rotate just fine in one direction, but inverting the z-axis just stops the rotation.

I've looked into transform.RotateAround(), but I have a hard time understanding the exact math behind it. I would also appreciate a simple explanation of the math behind it, I don't expect ready-to-copy code! Thank you! :)

CodePudding user response:

You're missing an else, i.e.:

if (rotating_left)
{
    transform.RotateAround(planet.transform.position, new Vector3(0, 0, 1), rotation_speed);
}
else
{
    transform.RotateAround(planet.transform.position, new Vector3(0, 0, -1), rotation_speed);
}

Your current code is running both rotations at the same time when rotating_left is true, causing them to cancel each other out.

  • Related