# Axial tilt and moons

I found a script that makes an object spin and orbit the origin.

``````#pragma strict

function Start () {

}

var PlanetRotateSpeed : float = -25.0;
var OrbitSpeed : float = 10.0;

function Update() {
// planet to spin on it's own axis
transform.Rotate(transform.up * PlanetRotateSpeed * Time.deltaTime);

// planet to travel along a path that rotates around the sun
transform.RotateAround (Vector3.zero, Vector3.up, OrbitSpeed * Time.deltaTime);

}
``````

What I’d like to do is have moons orbit moving planets and tilt the planets’ Y axes. When I try tilting a planet that uses this script, it rotates chaotically. Does anyone have a script that allows axial tilt and orbiting moving objects?

The documentation on RotateAround() states that it affects both the position and rotation of the object that it is used on in world coordinates. Rotate(), on the other hand, rotates the object around its center on local coordinates by default. Therefore, this script is rotating the object in two different directions and by different coordinate systems.

The real problem, though, is that Transform.up is in world coordinates, yet its being used to transform in local coordinates. You don’t notice anything when the moon is upright in the world, because Vector.up and transform.up are both (0, 1, 0) in this state. Therefore, the orbit’s rotation axis doesn’t transform the direction of transform.up to anything other than (0, 1, 0). The transform.up is then used as a local coordinate, which also conveniently happens to be the local vector for up (0, 1, 0). So the result appears that the moon’s rotation axis is fine.

However, the moment you tilt it, the bad logic becomes apparent because the orbit 's rotation axis modifies the direction of transform.up to something that is not (0, 1, 0). Since it no longer happens to be the local vector for up, its now rotating the moon on a new axis every frame; hence, your chaotic movement.

There are two ways to solve this. First one is to bring the moon rotation to world coordinates as well, so that it uses transform.up in the proper coordinates:

``````// planet to spin on it's own axis
transform.Rotate(transform.up * PlanetRotateSpeed * Time.deltaTime, Space.World);
``````

or, you can keep the moon rotation in local corrdinates, and just change the axis to the local vector for up:

``````// Vector.up in local *is always* transform.up in world
transform.Rotate(Vector.up * PlanetRotateSpeed * Time.deltaTime);
``````

Both of them give the same output, but one fix does it in reference to local coordinates, the other in world coordinates.

Hope that helps!