C - Moving Obstacle?

Soldato
Joined
4 Mar 2008
Posts
2,563
Location
Guildford
Hi all,

I'm currently trying to write a program in C. It is basically a game where you throw something and get a score from where it lands.

Now what I want to be able to do is to have a moving obstacle in the way (basically a vertical line moving up and down the screen)

and I cant for the life of me work out how to get the line to move slowly up and down (the user chooses the speed it moves up and down at)

Is this possible? (I am using a graphics library compiled by a professor at uni)

Sorry if I'm being too vague, let me know what other information you need.

Drowning in code here :(
 
Associate
Joined
10 Nov 2013
Posts
1,808
I may have misunderstood, but don't you just need to add a timer to move the y-position of your object at a given interval. The 'speed' that the user chooses can either determine the interval time or the height that the object moves at each interval.

You'd just have to keep tabs on when the y-position reaches the height of the playing area, and then start moving the object down instead.
 
Associate
Joined
7 Nov 2013
Posts
255
Location
Kent, England
This is entirely possible, as planty says, you may use a timer, but this will most likely involve use of a separate thread (which isn't too simple in C).

The other alternative which is utilised by the majority of games is to keep track of the time elapsed between each game loop, and perform the movements based on the elapsed time.

It's been a while since I have done any C, but here is some pseudo-code to give you some thoughts:

Code:
time previousTime = // Get the current time
while(gameInProgress)
{
    time currentTime = // Get the current time

    // How long did the previous animations/logic take?
    duration elapsed = currentTime - previousTime;     

   // TODO Move the line based on the elapsed amount of time
   // E.g. 20 pixels per second

    previousTime = currentTime;
}
 
Soldato
Joined
1 Feb 2006
Posts
3,480
Hi,
Look up State Machines. I have done a few games over the years and most books I have used State Machines to control things.
Basically you have a main loop like the timer example shown and you will have a function: UpdateFrame(Time). In the function you just go through your items and update their positions based on the time value. The time value is the elapsed time between frames.
For the objects you will need to store:
Last Position
Current Position
Speed
Direction
How you work out your new current Position will depend on if you are using 2d/3d vectors.
After you have updated your object position values just render them.
 
Back
Top Bottom