Search code examples
c#xnaxna-4.0

Move a 2D sprite in a curved upward arc in XNA?


Alright, so here's my problem.

I've been trying to create a sort of a visual day/night cycle in XNA, where I have an underlying class that updates and holds time and a Sky class which outputs a background based on the time that the class updates.

What I can't figure out though is how to make the moon/sun move in a curved upward arc that spans the screen based on what time of the day it is. The most problematic part is getting the Y axis to curve while the X axis moves as the time progresses.

Anyone that could help me here?

EDIT: Alright, looks like Andrew Russels example helped me to do what I needed to do. Although I had to expermient for a bit, I finally reached a suitable solution: float Time = (float)Main.inGameTime.Seconds / (InGameTime.MaxGameHours * 60 * 60 / 2);

this.Position.X = Time * (Main.Viewport.X + Texture.Width * 2) - Texture.Width;
this.Position.Y = Main.Viewport.Y - (Main.Viewport.Y * (float)Math.Sin(Time * MathHelper.Pi) / 2) - (Main.Viewport.Y / 2) + 50;

Solution

  • Try looking at the Math.Sin or Math.Cos functions. These are the trigonometric functions you're looking for.

    Something like this (giving a position for SpriteBatch):

    float width = GraphicsDevice.Viewport.Width;
    float height = GraphicsDevice.Viewport.Height;
    float time = 0.5f; // assuming 0 to 1 is one day
    Vector2 sunPosition = new Vector2(time * width,
            height - height * (float)Math.Sin(time * width / MathHelper.TwoPi));
    

    (Disclaimer: I haven't tested this code.)