Moon
Moon

Reputation: 20002

C# XNA Matrices - Calculate moon rotation around axis with matrices

I am building a 3D simulation.

I am using one class to display sun, planets & moon with different size, texture, speed and orbit. Here's my code which does the magic job of calculating rotation + revolution

world = Matrix.CreateScale(size,size,size) * Matrix.CreateTranslation(0,0,0) * 
 Matrix.CreateRotationY(rotation) * 
 Matrix.CreateTranslation(position) * 
 Matrix.CreateRotationY(revolution); 

now i want the display the moons around earth and around other planets but i just can't figure out how to do it. In terms of Matrix Multiplication.

The complication is the moon's revolution is around a planet which is not on origin and is always changing.

How to do it ?

Upvotes: 1

Views: 2390

Answers (2)

Moon
Moon

Reputation: 20002

i figured it out...

Translate The Origin to the Parent planet's Current Location

and keep doing it in the update method

world = Matrix.CreateScale(size,size,size)
        * Matrix.CreateTranslation(0,0,0) 
        * Matrix.CreateRotationY(rotation)
        * Matrix.CreateTranslation(position)
        * Matrix.CreateRotationY(revolution); 

world *= Matrix.CreateTranslation( parent.getPosition() );

what i am doing here is that i m revolving the moon around the origin (Sun) but i translate its origin to any planet's current location... this worked for me.

Upvotes: 0

Neil Knight
Neil Knight

Reputation: 48537

In your Draw method, after you've drawn the planet/moon that you want to orbit around:

Matrix satellite = Matrix.Identity
                 * Matrix.CreateScale(orbitScale)
                 * Matrix.CreateRotationY(orbitSpin)
                 * Matrix.CreateTranslation(0f, orbitDistance, 0f)
                 * Matrix.CreateFromAxisAngle(orbitAxis, orbitRotation);
effect.View = satellite * camera.View;

So, in your Update method, you can then do:

orbitRotation += MathHelper.PiOver2 * (float)gameTime.ElapsedGameTime.TotalSeconds;
orbitRotation = MathHelper.WrapAngle(orbitRotation);
orbitSpin += MathHelper.TwoPi * (float)gameTime.ElapsedGameTime.TotalSeconds;
orbitSpin = MathHelper.WrapAngle(orbitSpin);

I've defined orbitAxis as a Vector3. orbitDistance, orbitRotation, orbitScale and orbitSpin as float's.

Upvotes: 2

Related Questions