• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Sythical

Few questions about fix timestep for physics

2 posts in this topic

Hello, I've been trying to implement the fix time-step technique and I'm having trouble understanding a couple of thing. I've listed the two issues separately so that they make more sense.

i) To interpolate between the old and the new state, I'm using two variables called old_pos_x and new_pos_x. Originally, I would copy new_pos_x to old_pos_x after rendering each time. This makes more sense to me since I want to interpolate between the circle on the screen and the one I'll be drawing next. However, this makes the animation stutter if I don't update the physics at 60 or 120 hertz (multiples of my refresh rate).

When I moved the copy statement inside the physics loop, the stutter goes away and I have no idea why. I would have thought that this will make the game stutter a lot more, especially when the the frame rate is lower than the update rate. Why does this work?

ii) I added Sleep(5) after the render bit in order to decrease the FPS to about 200 so that I can see how it works at low rates. The animation becomes very jumpy and not smooth at all. I understand that Sleep() isn't accurate but surely that shouldn't matter as long as the frame rate is above 60 FPS because of the monitor's refresh rate.

I've written a smaller version of the program which replicates the issue(s) so that it's easier to read. It's just a circle that moves horizontally. The code is still a bit long, sorry about that.
 

unsigned screen_width = 1200, screen_height = 800;
int old_pos_x = 100, new_pos_x = 100, velocity_x = 0;
LARGE_INTEGER counter, frequency;

LONGLONG
    accumulator = 0, accumulator_max, physics_delta,
    time_difference, new_time, previous_time;

sf::RenderWindow window(sf::VideoMode(screen_width, screen_height), "Example", sf::Style::Titlebar | sf::Style::Close);

sf::CircleShape graphics(15.f);
graphics.setFillColor(sf::Color(255, 255, 255));

QueryPerformanceFrequency(&frequency);
physics_delta = frequency.QuadPart / 50;
accumulator_max = physics_delta * 5;

QueryPerformanceCounter(&counter);
previous_time = counter.QuadPart;

while(window.isOpen()) {
    QueryPerformanceCounter(&counter);

    new_time = counter.QuadPart;
    time_difference = new_time - previous_time;
    previous_time = new_time;
    accumulator += time_difference;

    if(accumulator > accumulator_max) {
        accumulator = accumulator_max;
    }

    while(accumulator >= physics_delta) {
        if(new_pos_x > 1000) velocity_x = -8;
        else if(new_pos_x < 200) velocity_x = 8;

        // if I copy the new state (position) to the old state here instead the animation is much more smooth
        // but I don't understand why this is the case, I would have thought that this is more likely to cause stutter
        // especially if the frame rate is lower than the game update rate

        // old_pos_x = new_pos_x; // copy the current state to the old one
        new_pos_x += velocity_x; // update the current state

        accumulator -= physics_delta;
    }

    double interpolation_val = accumulator / (double) physics_delta;
    graphics.setPosition(new_pos_x * interpolation_val + old_pos_x * (1 - interpolation_val), 400.f);

    window.clear();
    window.draw(graphics);
    window.display();

    // this is where I was originally copying the new state (position) to the old state
    // this makes more sense to be because I want to interpolate between the last drawn circle
    // and the current circle

    old_pos_x = new_pos_x;

    // Sleep(5);
}

 
I'd be very grateful if someone can have a read through the code. Thank you smile.png

 

Edit: I think I've figured out the reason for the first part. The game renders quicker than it updates so if I copy the states after rendering, the position will not be interpolated properly until it updates again. Still not sure about the second part.

Edited by Sythical
0

Share this post


Link to post
Share on other sites

i think this may be the basic algo you're looking for:

 

 

game loop:

{

startimer(0)

drawscreen()

ET=elapsedtime(0)      // hi-res in ms or perhaps even ticks

update(ET)

}

 

 

update(ET):

numsteps=ET/stepsize

for (a=0; a<numsteps; a++)

    update_by_one_step()

accumulator = ET-numsteps*stepsize

 

 

update_by_one_step():

last_position=current_position

// then calc new current position here

 

render:

render_position=lerp(from last_position, to current_position, by accumulator fraction)

draw using render_position.

1

Share this post


Link to post
Share on other sites

Thank you for the reply smile.png

 

I tried my code with Allegro (made a couple of small changes) and it's now very smooth. Here is the code so that others may find it useful, I haven't refactored it:

#include <allegro5\allegro.h>
#include <allegro5\allegro_font.h>
#include <allegro5\allegro_primitives.h>
#include <allegro5\allegro_ttf.h>

#include <iostream>

#include <windows.h>

using namespace std;

int main(int argc, char *argv[]) {

	if(!al_init()) return -1;

	ALLEGRO_DISPLAY *display = al_create_display(1400, 800);

	if(!display) return -1;

	al_init_font_addon();
	al_init_primitives_addon();
	al_init_ttf_addon();

	ALLEGRO_FONT *font = al_load_font("terminalscope.ttf", 16, 0);

	// ------------------------------------------------------------

	LARGE_INTEGER
		counter, frequency;

	double
		interpolation_val = 0, counter_old_time = al_get_time();;

	QueryPerformanceFrequency(&frequency);

	unsigned
		screen_width = 1200, screen_height = 800, frame_counter = 0, current_fps = 0;

	int
		old_pos_x = 100, new_pos_x = 100, velocity_x = 15;

	LONGLONG
		accumulator = 0, delta_time = 0, previous_time;

	const unsigned
		physics_rate = 80, max_step_count = 5;

	const LONGLONG
		step_duration = frequency.QuadPart / physics_rate,
		accumulator_max = step_duration * max_step_count;

	// ------------------------------------------------------------

	QueryPerformanceCounter(&counter);
	previous_time = counter.QuadPart;

	// ------------------------------------------------------------

	ALLEGRO_EVENT event;
	ALLEGRO_EVENT_QUEUE *event_queue;
	ALLEGRO_TIMER *timer;

	event_queue = al_create_event_queue();
	timer = al_create_timer(1.0 / 60.0);

	al_register_event_source(event_queue, al_get_timer_event_source(timer));
	al_start_timer(timer);

	while(true) {
		QueryPerformanceCounter(&counter);

		delta_time = counter.QuadPart - previous_time;
		previous_time = counter.QuadPart;
		accumulator += delta_time;

		// ------------------------------------------------------------

		if(accumulator > accumulator_max) {
			accumulator = accumulator_max;
		}

		while(accumulator >= step_duration) {
			if(new_pos_x > 1330) velocity_x = -15;
			else if(new_pos_x < 70) velocity_x = 15;

			old_pos_x = new_pos_x;
			new_pos_x += velocity_x;
			accumulator -= step_duration;
		}

		interpolation_val = accumulator / (double) step_duration;
		double render_pos_x = old_pos_x + (new_pos_x - old_pos_x) * interpolation_val;

		// ------------------------------------------------------------

		al_clear_to_color(al_map_rgb(20, 20, 40));
		al_draw_textf(font, al_map_rgb(255, 255, 255), 20, 20, 0, "current_fps: %i", current_fps);
		al_draw_filled_circle(render_pos_x, 400, 15, al_map_rgb(255, 255, 255));
		
		al_wait_for_event(event_queue, &event);

		al_flip_display();

		frame_counter++;

		if(al_get_time() - counter_old_time >= 1) {
			current_fps = frame_counter;
			frame_counter = 0;
			counter_old_time = al_get_time();
		}
	}

	return 0;
}

Edited by Sythical
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0