Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi there, I've made a simple collision game, I have a spaceship and asteroids. Once there is a collision, the game is to reset, signalling a new game.

However, I am wanting to make a timer with a simple font to appear at the top corner, alongside a "Best time" high score.

To be more specific, I'm wanting a timer to start as soon as I start the game. But once a collision between the spaceship and asteroid happens, I want the time to stop, maybe keeping a record of the best time done so far.


Here is my code, code that can teach me would be helpful, if someone could tell me where to put the solution in my code too, that would be great.
C#
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using Intro2GD;

namespace AsteroidGame
{
   
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Sprite spaceship;

        //Texture2D starfield;

        //Sprite pickup;
        Sprite[] asteroid = new Sprite[10];
        Vector2[] AsteroidPosition = new Vector2[10];
        
        //Texture2D bullet;
        //Sprite[] bullets;

        float move = 0;

                
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }
      
        protected override void Initialize()
        {
            Components.Add(new Starfield(this));

            base.Initialize();
        }

         protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            spaceship = new Sprite(Content.Load<texture2d>("Spaceship3"),
                        new Vector2(graphics.PreferredBackBufferWidth/2,
                                    graphics.PreferredBackBufferHeight/2));

            //starfield = Content.Load<texture2d>("Starfield");

            
            
            //bullet = Content.Load<texture2d>("Bullet");

            //pickup = new Sprite(Content.Load<texture2d>("Pickup"),
                     //new Vector2(16,16));

            Random r = new Random();
            Vector2 randPos = new Vector2(r.Next(800), r.Next(600));
            float randRot = MathHelper.ToRadians(r.Next(360));

            for (int i = 0; i < 10; i++)
            {


                asteroid[i] = new Sprite(Content.Load<texture2d>("Asteroid2"), Vector2.Zero);
                asteroid[i].SetPosition(randPos * i);
                asteroid[i].SetRotation(randRot * i);

            }
            
        }

        protected override void UnloadContent()
        {
        }

        protected override void Update(GameTime gameTime)
        {
            float rotate = 0;
           
            if (Keyboard.GetState().IsKeyDown(Keys.Left) || Keyboard.GetState().IsKeyDown(Keys.A))
            {
                rotate = rotate - MathHelper.ToRadians(5);
            }

            if (Keyboard.GetState().IsKeyDown(Keys.Right) || Keyboard.GetState().IsKeyDown(Keys.D))
            {
                rotate = rotate + MathHelper.ToRadians(5);
            }

            if (Keyboard.GetState().IsKeyDown(Keys.Up) || Keyboard.GetState().IsKeyDown(Keys.W))
            {
                move = 4;
            }
            if (Keyboard.GetState().IsKeyDown(Keys.Down) || Keyboard.GetState().IsKeyDown(Keys.S))
            {
                move = -4;
            }
            if (move > 10)
            {
                move = 10;
            }
            if (move < -5)
            {
                move = -5;
            }

            move *= 0.97f;          
            

            spaceship.RotateBy(rotate);
            spaceship.MoveRelative(move);
            for (int i = 0; i < 10; i++)
            {
                asteroid[i].MoveRelative(4);
            }
            Vector2 position = spaceship.GetPosition();
            for (int i = 0; i < 10; i++)
            {
                AsteroidPosition[i] = asteroid[i].GetPosition();
            }
                                    
                for (int i = 0; i < 10; i++)
                {
                    if (Utils.CircToCircCollision(spaceship.GetPosition(), spaceship.GetRadius(),
                    asteroid[i].GetPosition(), asteroid[i].GetRadius()))
                    {
                        LoadContent();
                        Random r = new Random();
                        Vector2 randPos = new Vector2(r.Next(800), r.Next(600));
                        float randRot = MathHelper.ToRadians(r.Next(360));                      
                    }
                }
                if (position.X < 0 - spaceship.GetWidth())
                {
                    position.X = 800 + spaceship.GetWidth();
                }
                if (position.X > 800 + spaceship.GetWidth())
                {
                    position.X = 0 - spaceship.GetWidth();
                }

                if (position.Y < 0 - spaceship.GetHeight())
                {
                    position.Y = 600 + spaceship.GetHeight();
                }
                if (position.Y > 600 + spaceship.GetHeight())
                {
                    position.Y = 0 - spaceship.GetHeight();
                }

                spaceship.SetPosition(position);

                for (int i = 0; i < 10; i++)
                {
                    if (AsteroidPosition[i].X < 0 - asteroid[i].GetWidth())
                    {
                        AsteroidPosition[i].X = 800 + asteroid[i].GetWidth();
                    }
                    if (AsteroidPosition[i].X > 800 + asteroid[i].GetWidth())
                    {
                        AsteroidPosition[i].X = 0 - asteroid[i].GetWidth();
                    }
                    if (AsteroidPosition[i].Y < 0 - asteroid[i].GetHeight())
                    {
                        AsteroidPosition[i].Y = 600 + asteroid[i].GetHeight();
                    }
                    if (AsteroidPosition[i].Y > 600 + asteroid[i].GetHeight())
                    {
                        AsteroidPosition[i].Y = 0 - asteroid[i].GetHeight();
                    }                    

                    asteroid[i].SetPosition(AsteroidPosition[i]);
                    
                }                         
                        
           if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);

            spriteBatch.Begin();
            spaceship.Draw(spriteBatch);
            if (asteroid != null)
            
                for (int i = 0; i < 10; i++)
                {
                    asteroid[i].Draw(spriteBatch);
                }            
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}
</texture2d></texture2d></texture2d></texture2d></texture2d>
Posted
Updated 10-Jan-11 8:45am
v5
Comments
#realJSOP 10-Jan-11 13:53pm    
What have you tried? I also don't see the purpose of posting all that code when it doesn't really have anything to do with what you're asking us to help you with.
Elliot Harrison 10-Jan-11 14:02pm    
I've updated the question asking what I require help with.
Henry Minute 10-Jan-11 16:41pm    
Sorry for wasting your time. :) My eyes skipped right over the XNA Tag.

To determine the elapsed time, create two DateTime variables - one called started, and called stopped.

When the players starts to play, set the started datetime with DateTime.Now, and when a collision occurs, set the stopped datetime.

Since you're only displaying time as it passes, create a Timer object and when the game starts, start the timer, and in the Tick event handler, set your visual display of elapsed time.

You can use the two datetime objects to calculate the total time played, or you can use the tracked elapsed time that was set by the timer.

EDIT (response to your first comment) ============

If you wrote that code, you'd be the best one to identify the correct place to put the functionality you need. I'm not emotionally invested in your project, so I don't feel compelled to write/test code for you, and your lack of initialitive to learn on your own further diminishes my level of caring. Lastly, you're not going to learn anything if I spoon-feed you, but here are some guidelines:

0) You need to add this to the top of your file:

C#
using System.Timers;


1) You need to define a Timer and two TimeSpan objects in your class:

C#
System.Timers.Timer m_timer = new Timer(1000);
TimeSpan m_elapsed = new TimeSpan();
TimeSpan m_oneSecond = new TimeSpan(0,0,0,1);


2) You need to create an event handler for the Timer.Elapsed event in your constructor:

C#
m_timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);


3) You need to add this method to your class:

C#
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
    if (m_elapsed != null)
    {
        m_timeSpan.Add(m_oneSecond);
        ... write some code to update the on-screen timer.
    }
}


You have to do other maintenance crap associated with the timer, but you'll discover that eventually. This is as far as I can (or want to) help you on this.

Asking a question is fine if you're truly stuck, but ALL of what I've given you is easily discoverable by the most miniscule amount of googling.

One last thing - don't forget to re-mark this as the answer.
 
Share this answer
 
v5
Comments
Elliot Harrison 10-Jan-11 14:33pm    
Your answer seems as if it is the way to go, however, as I'm a beginner, could you show me how I would put that into the code?

Thanks
ely_bob 10-Jan-11 16:27pm    
You want to use the GameTime class... NOT system.Time....!!! see bellow.

DO NOT USE EVENTS IN XNA!!!!!!!!!!!
If you search on the internet for any of the c# digital clock implementations, that should give you enough to get started.

When you have at least a partial solution you can ask again about the specific problem you are having.
 
Share this answer
 
Comments
ely_bob 10-Jan-11 16:39pm    
not for XNA...
As John says, you can use a DateTime.Now to also run a time elapsed.
Use this as a metric at the end of the game to show points per minute etc.

Just set several variables and you can run events off them without using a timer.
 
Share this answer
 
Comments
ely_bob 10-Jan-11 16:39pm    
don't use events in XNA ...
John Simmons / outlaw programmer
is mostly correct...

Your in a XNA environment, that means you don't want to use the system clock.. because what happens when you go to add {pause} capabilities to the game? And you MUST NOT use the events name space.. because that will really mess with your game loop.

You want to look at the GameTime and use the style of XNA timer that works for you. easiest way is to use the gameTime from Update... and just display the elapsed game time.

the system timer is different, and will only cause headaches when it comes to elapsed time and elapsed game time... which are different..!!!

you may want to look at setting yout gamestep to a static ammount and just using that as a score keeper...
 
Share this answer
 
v2
Comments
#realJSOP 10-Jan-11 17:12pm    
Like I said, Ive never done XNA and am not familiar with what should and shouldn't be done. Read the whole answer.
ely_bob 10-Jan-11 17:15pm    
Well for almost any other circumstance I can think of you are correct, but XNA is a different beasty. .. and yes I'm sorry I saw the namespace you were using and I freaked out... my bad...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900