The plumps - a small RTS game in Lazarus lazarus / 74-Games ---------------------------------------------------------------------- Tomi · 2022-03-06 10:27 Hello everybody! I have started to make a small RTS game in Lazarus. It is not finished yet, but I can present some stuff about it for you. For example a picture at least, but I will publish the source code soon. Its title is "The plumps" (maybe "Puffancsok" in hungarian) and you can control the little cute creatures of an alien planet in its fight against enemy. So, what I completed till now with the game? - Scrollable game field, - A simple own algorithm to move units and avoid obstacles, - Player can build some basic buildings. I make the game purely in Lazarus, so nothing special like game engines or similar tools. Graphics made with Anim8or. Now, I would like present you my first steps with this topic. If you can recommend me similar Lazarus games, so don't hesitate because I need all kinds of knowledge. ---------------------------------------------------------------------- Tomi · 2022-03-19 16:14 And ladies and gentelmen, here is the source code from my website: http://www.programozzunk.ucoz.hu/lazjatekok/puffancsok.zip Note that this game are in very early version, so this is a beta version. But try it; I hope, you will like my work and I hope, I can inspire you if you plan to make similar games. ---------------------------------------------------------------------- Handoko · 2022-03-19 16:49 Great! It works, even on Linux too. Many things are still missing, but you made a good step. I can move the creatures and create buildings. Unfortunately it run too fast on my PC. You can use a TTimer or run some codes to check the computer speed and do necessary delay. Also, I guess you have a large monitor. All the sprites seemed very large on my 1600x900 resolution monitor. Just to warn you, using TCanvas to create games ... you will have performance issue later. ---------------------------------------------------------------------- flowCRANE · 2022-03-19 17:59 Use SDL — it is super simple to use and quite powerful. Dealing with LCL limitations in the terms of creating game is a waste of time. ---------------------------------------------------------------------- Tomi · 2022-03-20 08:27 Quote from: Handoko on March 19, 2022, 05:49:33 pm"it run too fast on my PC. You can use a TTimer or run some codes to check the computer speed and do necessary delay." Hello Handoko! Setting of correct game speed is always a big problem for me if there is no basic tools for this. But in this game I used TTimer at lines 1374-1376: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i palyafrissito:=TTimer.Create(nil);  palyafrissito.interval:=10;  palyafrissito.ontimer:=@palyafrissites;Maybe value 10 for interval is too small and the game is too fast because of it? Is there an optimal value to correct speed at all computers? ---------------------------------------------------------------------- Tomi · 2022-03-20 08:34 Quote from: furious programming on March 19, 2022, 06:59:30 pmUse SDL — it is super simple to use and quite powerful. Dealing with LCL limitations in the terms of creating game is a waste of time. Hello Furious! Yes, SDL and similar tools makes game developing easier, but I'm still too green for this and I just use basic Lazarus possibilities for games in first times. Then I will try Allegro and Castle Game Engine if necessary. ---------------------------------------------------------------------- Seenkao · 2022-03-20 10:35 Quote from: Tomi on March 20, 2022, 09:27:49 amIs there an optimal value to correct speed at all computers? Для этого каждый "шаг" основного процесса проводят соответственно прошедшего времени. Вычисляют deltaTime прошедшего времени данного цикла и герой (и всё окружение) двигаются соответственно данного deltaTime. И тогда на разных компьютерах это будет работать примерно одинаково. google translate: To do this, each "step" of the main process is carried out according to the elapsed time. The deltaTime of the elapsed time of the given cycle is calculated and the hero (and the whole environment) move according to the given deltaTime. And then on different computers it will work approximately the same. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i prcedure proc(dt: double);begin  Heroes.X :=  Heroes.X + Heroes.Speed * dt / 1000;    // 1000 msend; ---------------------------------------------------------------------- flowCRANE · 2022-03-20 10:44 Quote from: Tomi on March 20, 2022, 09:34:09 amYes, SDL and similar tools makes game developing easier, but I'm still too green for this and I just use basic Lazarus possibilities for games in first times. You will always be ”to green” for this until you finally try — nobody was born with such knowledge and skill. When I decided to make a game using SDL myself, I didn't really know how to use this library either. However, it is so easy to use that I had no problems programming other things. At most once in a while, by trial and error, I slowly came to a solution. I suggest not to waste your time on LCL to build games, because it is not suitable for creating games for many reasons, including the most important: no Direct3D and OpenGL supportunable to use GPU for rendering texturesno exclusive video mode support and available screen resolutionsabsolutely no support for sound mixer and playing multiple sounds at the same timelack of support for game controllers and their full functionalitylack o V-Sync supportWhat I mentioned above are the basics, without which creating even a simple game will be inconvenient, the game itself will be very limited, and its performance will be very low (software rendering is horribly slow in compare to GPU rendering). As you can see, it doesn't make much sense. Whether you want to make a tiny game or a bigger one, use the library dedicated to their creation. It does not have to be SDL, but it is important that it has all the functionality to create full-fledged video games. However, if you are interested in creating a 2D game, I strongly advise you not to use 3D engines for this purpose, because it will significantly complicate the implementation, and you will get discouraged very quickly. Use something small, light, functional and, above all, supported at all times. I suggest SDL because it meets all the requirements and is great, but it can also be Allegro, because it's the same shelf. In case you ever get tempted by SDL and have questions, I will be happy to help. I've learned a lot over the last year so I'll be able to help a bit, especially when it comes to basic (key) issues. Quote from: Tomi on March 20, 2022, 09:27:49 amIs there an optimal value to correct speed at all computers? You have several solutions. The first is to use delta to calculate motion using interpolation. Thanks to this, the game will run at the same speed on every computer, but the very big downside is that it will eat up all the available power of the CPU core. In the case of small games that do not have complicated logic and long-lasting frame rendering, this solution is weak. The second way is a constant framerate and pauses between generating frames. The current time is taken, the frame is generated along with the rendering, and the time is retrieved again. Based on the two times, the number of milliseconds it took to generate the frame is calculated, the waiting time for the next frame is calculated and the function is called, which freezes the thread (Windows.Sleep, FPNanoSleep, SDL_Delay, etc.). This allows you to easily handle logic (no delta), frames are generated at regular intervals, and the process only uses as much power as it needs. It is a simple, energy-saving solution, but not very precise. The third solution is V-Sync support, i.e. generating and displaying frames in accordance with the screen refresh rate. In this case, you also need to use delta-time, but timing and waiting for the generation of next frames is implemented on the API side of the GPU, so you do not have to program anything yourself — the intervals will be performed automatically. The solution is easy to implement (e.g. using SDL) and energy-saving and solves the screen tearing problem. The fourth solution is a constant framerate (independent of the screen refresh rate), no delta-time, but precise measurement of the time between generating frames. Similar to the first one given, but the difference is that the intervals should be performed with more precision than the millisecond. After measuring the waiting time between frames, a larger portion is waited first using eg SDL_Delay (milliseconds) and the remainder waited using busy waiting. Thanks to this, the framerate will always be what we want (super-precise), no matter how little time you have to wait between frames. If you need inspiration, I implemented such a clock in my game called Fairtris (unit Fairtris.Clock.pp). This solution is also simple and energy- saving. Of course, there are more ways and it all depends on what we really care about. It should be noted that no matter if we want a constant framerate or a variable (matched to screen refresh rate or completely dynamic), using delta is a good idea if we want to use the slow motion (or accelerated motion) effect in the game. Without delta, it cannot be done other than changing the game framerate or doing strenge things with game logic, which is a very poor solution. The playback speed of the game should be independent of the framerate and programmed in such a way that it is easy to manipulate it. ---------------------------------------------------------------------- AlexTP · 2022-03-20 12:11 Copied the good comment to the Wiki, https://wiki.freepascal.org/Game_ framework#Using_LCL_for_game_development ---------------------------------------------------------------------- Seenkao · 2022-03-20 12:17 Quote from: furious programming on March 20, 2022, 11:44:41 amI suggest not to waste your time on LCL to build games, because it is not suitable for creating games for many reasons, including the most important: no Direct3D and OpenGL supportunable to use GPU for rendering texturesno exclusive video mode support and available screen resolutionsabsolutely no support for sound mixer and playing multiple sounds at the same timelack of support for game controllers and their full functionalitylack o V-Sync supportНе надо путать людей. Есть очень немало решений для одновременного использования и LCL и OpenGL/DX. Их можно увидеть в соседних топиках и на вики Freepascal. На немецком форуме почти все уроки по OpenGL сделаны под LCL. dglOpenGL.pas - позволяет работать с LCL в Windows без особых знаний создания окна/контекста OpenGL. google translate: Don't confuse people. There are quite a few solutions for using both LCL and OpenGL/DX at the same time. They can be seen in neighboring topics and on the Freepascal wiki. In the German forum, almost all OpenGL tutorials are made under LCL. dglOpenGL.pas - allows you to work with LCL on Windows without much knowledge of creating an OpenGL window/context. tutorial wiki eng.dglOpenGL tutorial DeutschMetal, OpenGL demosGLSceneGLEngine2D - based on dglOpenGL. Deprecated. But it works.Free Pascal Game EnginesДумаю я даже не смогу полностью осветить эту тему. И большой шанс, что я что-нибудь упущу. LCL так же можно использовать и с SDL, Castle Game Engine, PGF, Apus Game Engine, ZenGL и многими другими движками. Подключение контроллеров, вообще не зависит от того что мы используем. Для этого надо просто использовать нужные библиотеки. Зачастую, которые уже идут с игровыми движками. И так же можно использовать в LCL. Со звуком так же, ни кто не запрещает использовать одноканальный/многоканальный звук. Всё это предоставлено в соответствующих библиотеках. И так же можно использовать в LCL. Вы очень сильно вводите в заблуждение людей!!! google translate: I don't even think I can fully cover this topic. And there's a good chance I'll miss something. LCL can also be used with SDL, Castle Game Engine, PGF, Apus Game Engine, ZenGL and many other engines. Connecting controllers does not depend at all on what we use. To do this, you just need to use the necessary libraries. Often that already come with game engines. And it can also be used in LCL. With sound, no one forbids the use of single-channel / multi-channel sound. All this is provided in the respective libraries. And it can also be used in LCL. You are very misleading people!!! Quote from: furious programming on March 20, 2022, 11:44:41 amWhat I mentioned above are the basics, without which creating even a simple game will be inconvenient, the game itself will be very limited, and its performance will be very low (software rendering is horribly slow in compare to GPU rendering). Единственно по какой причине это не подходящий вариант, это если у вас высоконагруженное приложение. Тут я частично согласен! На простых играх это практически ни как не скажется. google translate: The only reason this is not a suitable option is if you have a highly loaded application. Here I partly agree! In simple games, this has almost no effect. ---------------------------------------------------------------------- Seenkao · 2022-03-20 12:20 Quote from: AlexTP on March 20, 2022, 01:11:43 pmCopied the good comment to the Wiki, https://wiki.freepascal.org/Game_framework#Using_ LCL_for_game_development Вы зря это сделали. По большей части заходят смотреть такие вещи новички. А LCL намного удобнее и быстрее для понимания, чем разбор каких-либо движков. И, увы, не соответствует действительности. Выше всё описал. google translate: You did it in vain. For the most part, beginners come to see such things. And LCL is much more convenient and faster to understand than parsing any engines. And, alas, it is not true. All described above. ---------------------------------------------------------------------- AlexTP · 2022-03-20 12:44 @Seenkao, please point me to your detailed answer, and I will add it to the same wiki part. ---------------------------------------------------------------------- Seenkao · 2022-03-20 13:02 Quote from: AlexTP on March 20, 2022, 01:44:17 pm@Seenkao, please point me to your detailed answer, and I will add it to the same wiki part. Пост №9. Я не думаю, что это нужно вообще выкладывать на вики. Это обсуждения. Но думаю на вики были бы полезны именно ссылки на эти обсуждения. google translate: Post number 9. I don't think this should be posted on the wiki at all. These are discussions. But I think links to these discussions would be useful on the wiki. ---------------------------------------------------------------------- flowCRANE · 2022-03-20 14:55 Quote from: Seenkao on March 20, 2022, 01:17:40 pmDon't confuse people. There are quite a few solutions for using both LCL and OpenGL/DX at the same time. There are several solutions, but they all require a lot of knowledge and writing a lot of code, and besides, they only slightly cover what libraries such as SDL or Allegro offer. So what if you can create an OpenGL context, since rendering anything will require in-depth knowledge of this API? In addition, it will require writing code that someone has already written and tested on many operating systems and millions of devices. For the same reason, we use LCL to create window applications, rather than writing millions of lines of code in WinAPI. Also, even if you write a rendering code, it will still be a fraction of what is expected for game development. Where's the multiple displays and resolutions support? Where is the exclusive video mode support? Where is the sound mixer support? Where is the support for the keyboard, mouse, as well as controllers and their mapping? Do you want to write it yourself? Good luck. SDL has 300k+ LoC, I wonder how long it will take someone to do the same, who is just starting their adventure with game development. In short, if you are recommending anyone to use LCL to build a full- fledged game, then you have no idea what you are talking about. By doing this, you only do harm to others. QuoteConnecting controllers does not depend at all on what we use. To do this, you just need to use the necessary libraries. Often that already come with game engines. And it can also be used in LCL. What libraries? Why should I use separate libraries since SDL covers everything? QuoteWith sound, no one forbids the use of single-channel / multi- channel sound. All this is provided in the respective libraries. And it can also be used in LCL. More libraries? How many more will you need to search for and include in the project? Are you trolling or are you drunk? QuoteYou are very misleading people!!! You have no idea what you are writing about, your arguments are full of nonsense. I bet you have never created any more serious game, and you base your entire opinion on randomly found information in Google. You are the best teacher I have ever met. Coming back to the seriousness, without irony, everything that @Seenkao wrote is suitable for the trash and I advise everyone not to take his statements seriously. I advise against using LCL to create games, let alone looking for multiple libraries that support various aspects, since everything, absolutely EVERYTHING is supported by one meaningful library, such as SDL or Allegro (or entire engine like ZenGL or CGE). Not only is everything supported, but we also have one documentation describing everything, as well as one license (because the library is one). In this way, writing code for the game will be convenient, we will save a lot of time and we will not be limited in any way. And, at best, window applications and LCL with embedded OpenGL controls should be used to create editors and other tools for creating game content. Absolutely NOT for the game itself. QuoteIn simple games, this has almost no effect. I suggest you wake up, look at your calendar and understand that it's 2022, not 1980. We have great tools and libraries with powerful functionality that make game development very easy, and we have these tools for free. If you want to waste your time on LCL and millions of additional libraries, waste your time, but don't persuade others to do so. ---------------------------------------------------------------------- Seenkao · 2022-03-20 15:31 furious programming, как много эмоций...  Спокойнее молодой человек. Всё что вам нужно знать, это то, что рекламируемая вами библиотека SDL просто подключается к LCL и используется. Но видимо вам это невдомёк... И всё, что вы написали просто рушиться в крах, об ваши же утверждения. А о том, что другие движки так же спокойно подключаются к LCL и используются можно даже не говорить. А где-то это стоит по умолчанию.  google translate: how many emotions... Calm down the young man. All you need to know is that the SDL library you advertise is simply connected to the LCL and used. But apparently you don't know... And everything that you wrote just collapses into collapse, about your own statements. And the fact that other engines are just as easily connected to the LCL and used can not even be said. And somewhere it costs by default. Quote from: furious programming on March 20, 2022, 03:55:48 pmI bet you have never created any more serious game, and you base your entire opinion on randomly found information in Google. You are the best teacher I have ever met. Для таких утверждений, надо сначала самому что-то стоящее написать, а не повторить очередной тетрис. google translate: For such statements, you must first write something worthwhile yourself, and not repeat another Tetris. Ну и, ваши же эмоции вас и выдали. Я так понимаю что конкретного вам не чего сказать, просто очередная бравада. Думаю дальше спорить бесполезно, вы всё равно дальше своего носа не хотите видеть. Всего доброго! Google translate: Well, your own emotions betrayed you. I understand that there is nothing specific for you to say, just another bravado. I think it’s useless to argue further, you still don’t want to see beyond your nose. All the best! ---------------------------------------------------------------------- flowCRANE · 2022-03-20 16:08 Quote from: Seenkao on March 20, 2022, 04:31:15 pmAll you need to know is that the SDL library you advertise is simply connected to the LCL and used. But apparently you don't know... Great link — problem solved partially. As I wrote, random links from Google, no experience. QuoteAnd everything that you wrote just collapses into collapse, about your own statements. And the fact that other engines are just as easily connected to the LCL and used can not even be said. And somewhere it costs by default. If you still think that the placement of the visual engine component on the form is game development, then as I wrote, you have no clue about game development. This thread talks about using LCL content to build a game, not about using engine components for game development. Start reading comprehension. QuoteFor such statements, you must first write something worthwhile yourself, and not repeat another Tetris. At least I did something instead of just talking and pulling the wool over someone's eyes. And I will do a lot more — I am working on my own bigger game, my own IP. So, in summary, have fun putting the components on the form. EoT. ---------------------------------------------------------------------- Seenkao · 2022-03-20 16:23 furious programming есть какие-то конкретные факты, доказывающие что я не прав? Или просто голословность?  Возможно вы как раз не хотите понять, что вам пишут? Я ни где не утверждал, что использование LCL - это лучший способ для создания игр! Читайте не то что хотите прочитать, а то, что написано на самом деле. google translate: furious programming is there any concrete facts proving that I'm wrong? Or just gossip? Perhaps you just do not want to understand what they write to you? I have never claimed that using LCL is the best way to make games! Read not what you want to read, but what is actually written. ---------------------------------------------------------------------- Tomi · 2022-03-21 12:41 Quote from: Seenkao on March 20, 2022, 11:35:26 amQuote from: Tomi on March 20, 2022, 09:27:49 amIs there an optimal value to correct speed at all computers? each "step" of the main process is carried out according to the elapsed time. The deltaTime of the elapsed time of the given cycle is calculated and the hero (and the whole environment) move according to the given deltaTime. And then on different computers it will work approximately the same. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i prcedure proc(dt: double);begin  Heroes.X :=  Heroes.X + Heroes.Speed * dt / 1000;    // 1000 msend; Thanks, Seenkao, but what is the value of deltaTime (dt variable) in this case? Is this that value, what i set by interval of the Timer? ---------------------------------------------------------------------- Tomi · 2022-03-21 12:54 Quote from: furious programming on March 20, 2022, 11:44:41 amYou have several solutions. Thank you, Furious! I thought, SDL is a tool for C/C++ languages, not for Pascal. But I will look through it, just like your Tetris clone game, what I just downloaded. ---------------------------------------------------------------------- Seenkao · 2022-03-21 13:55 Quote from: Tomi on March 21, 2022, 01:41:26 pmThanks, Seenkao, but what is the value of deltaTime (dt variable) in this case? Is this that value, what i set by interval of the Timer? обычно это разница между текущим временем работы цикла с предыдущим временем цикла. В Windows есть функция GetTickCount. Для начала можно её использовать. google translate: Windows has a GetTickCount function. For starters, you can use it. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i begin  endTime := GetTickCount;  proc(endTime - begintime);  beginTime := endTime;end;В SDL есть свои функции для работы с таймером. Так же и большинство движков используют свои функции с таймером. Они зачастую внутри похожи, но наверняка называются по разному. google translte: SDL has its own functions for working with a timer. Likewise, most engines use their functions with a timer. They are often similar inside, but they are probably called differently. ---------------------------------------------------------------------- BeniBela · 2022-03-21 16:14 Quote from: Tomi on March 06, 2022, 11:27:26 amNow, I would like present you my first steps with this topic. If you can recommend me similar Lazarus games, so don't hesitate because I need all kinds of knowledge. I tried to make an RTS game 20 years ago: https://benibela.de/games_en.html#pbspiel There are units, buildings and resources. The units can move in a straight line and a worker unit can build buildings which cost resources. The buildings can build units or create resources. I used TCanvas in Delphi, so it should be mostly LCL compatible.  Then I abandoned it because TCanvas  was just too slow. I also became bored of games ---------------------------------------------------------------------- Tomi · 2022-03-22 08:29 Quote from: Seenkao on March 21, 2022, 02:55:31 pmWindows has a GetTickCount function. For starters, you can use it. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i begin  endTime := GetTickCount;  proc(endTime - begintime);  beginTime := endTime;end; A-ha! Thanks, Seenkao, it seems, there is hidden gems in Windows for a programmer - but, I think, if I use these, my program will not be platform independent(?). ---------------------------------------------------------------------- Tomi · 2022-03-22 08:40 Quote from: BeniBela on March 21, 2022, 05:14:46 pmI tried to make an RTS game 20 years ago: https://benibela.de/games_en.html#pbspiel Wow, you have great games on your website! I will look through these. I see, you also meet bad things during programming that interrupt your work, e.g. you can't find the source of an error or you get bored of yourself. Unfortunaltely these also happen to me, therefore I wish you all the best for your future works and plans! ---------------------------------------------------------------------- Seenkao · 2022-03-22 12:27 Quote from: Tomi on March 22, 2022, 09:29:07 amA-ha! Thanks, Seenkao, it seems, there is hidden gems in Windows for a programmer - but, I think, if I use these, my program will not be platform independent(?). Да, это подойдёт только для Windows. И это не лучшее решение для Windows. Если пользоваться кроссплатформенными решениями, то движки содержат в себе данные решения таймеров. Допустим в ZenGL с которым я работаю это timer_GetTicks. Для SDL вам надо найти самому, я с ним не работал. Но чаще этими решениями вообще пользоваться не приходится, а используют внутренние циклы движка, который предоставляем вам самому задать процедуру основного цикла, процедуру прорисовки и многие другие процедуры. Для этого надо изучать движки. А таймер уже уходит на второй план, движок решает всё сам за вас (но может и не решать, зависит от движка). google translate: Yes, this is only for Windows. And it's not the best solution for Windows. If you use cross-platform solutions, then the engines contain these timer solutions. Let's say the ZenGL I'm working with is timer_GetTicks. For SDL you have to find it yourself, I haven't worked with it. But more often you don’t have to use these solutions at all, but use the internal cycles of the engine, which we leave to you to set the main cycle procedure, the drawing procedure and many other procedures. To do this, you need to study engines. And the timer is already fading into the background, the engine decides everything for you (but it may not decide, it depends on the engine). ---------------------------------------------------------------------- flowCRANE · 2022-03-22 12:36 OnWindows, the GetTickCount and GetTickCount64 functions are completely useless in the terms of calculating delta. These functions are based on the system time which is refreshed only 60 times per second. This causes the delta calculated in this way: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i begin  endTime := GetTickCount;  proc(endTime - begintime);  beginTime := endTime;end; will always be 0, 16, or 17. I can see that it keeps repeating itself and suggests the same nonsense that these functions are supposed to be useful for game development. No, they are not — in absolute most cases they are useless (at least on Windows). Still don't believe me? Try this: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i uses  SysUtils;var  TicksOld, TicksNew: Int64;  Tries: Integer;begin  TicksNew := GetTickCount64();   for Tries := 0 to 19 do  begin    TicksOld := TicksNew;    WriteLn(TicksOld);     repeat      TicksNew := GetTickCount64();    until TicksOld <> TicksNew;  end;   ReadLn();end. The result in the console will be the following: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i 14945648414 9456500149456515149456531149456546149456562149456578149456593149456609 1494566251494566401494566561494566711494566871494567031494567181494567 34149456750149456765149456781 As you can clearly see, the value of the counter changes every 15-17 milliseconds. Bravo. If the main game loop is to freeze the thread between frames, no matter what framerate it has to keep (this can be a constant 25fps, 30fps, 60fps, 120fps or dynamic but limited), you need to calculate the freeze time with high precision and carry out the freezing with high accuracy. Some frames can be generated in 1ms and some in 15ms. At 60fps, in the first case you will have to wait a little over 15ms, and in the second only about 2ms. As I wrote, a little over, because at 60fps the time for one frame is 1000/60=16.667ms, so the calculations cannot be rounded to milliseconds. This type of computation is easily done — on Windows, you can determine counter resolution using QueryPerformanceFrequency function (precision is always nanosecond on Unix). To get the current counter status, use QueryPerformanceCounter on Windows and FPGetTimeOfDay on Unix-based systems. Take the time before and after generating the frame and then calculate their difference. Knowing the precision of the clock and how many ticks it took to generate the frame, it is easy to calculate how many nanoseconds to freeze the thread. It's easy on Unix-based systems to freeze the thread with high accuracy, because there is the FPNanoSleep function, which has a very high precision (microsecond, although the argument is the number of nanoseconds). It is more difficult on Windows, because Sleep works with millisecond precision. Therefore, in order to maintain a very high precision (more or less microseconds, which is enough for the needs of typical video games), you can divide the freezing into two stages — first, using Sleep, suspend the thread's work for a specified number of milliseconds, and the rest with busy waiting and especially for this purpose, the assembly instruction pause was designed. Important! If your game does not need super-high precision (you don't create e.g. an emulator), you can safely use only millisecond intervals. It is important not to round the time, but to keep it in a tank so that the remaining, less than a millisecond fraction, accumulates and is used in subsequent freezes. However, it is still necessary to rely on a high-precision counter (i.e. a hardware counter, not a shitty system clock) in order to be able to correctly calculate the waiting time and delta, as discussed below. Another bad example is delta usage in the form of elapsed milliseconds. This is wrong because such a value is unintuitive and very difficult to use. It is very good for delta to be a floating point number, representing a fraction of a second, in the range 0 to 1. Assuming the game is running at 60fps and there is no lag, the delta should be ~0.01667. At 100fps it should be 0.01 and at 187fps it should be around 0.005348. With a variable frame rate, the delta will contain different values, but still between 0 and 1. If there is a huge lag, for example 5 seconds, the delta will be 5 and still be able to be used in the calculations, so there is no problem. Given this delta, you determine the speed of each object and other element in the game in terms of units per second (e.g. 100px per second) and multiply it by the delta. No matter what the speed is, and no matter what the framerate (no matter if it's constant or dynamic), it's very easy to configure the behavior of objects. If your game is going to be able to manipulate the gameplay speed (i.e. support slow-motion or accelerated-motion), you can use the second floating point number, which is the speed of the game, and use it in the delta calculation. At normal speed, this number should be 1, at slow-motion the value should be in the range (0,1), and with accelerated motion in the range (1,n>, where n is any value greater than 1 (x=2 is an acceleration of 2x). Everything I wrote above will allow you to: keep any constant and any variable framerate (with the ability to change the behavior of the game while it is running),correctly calculate the waiting time between frames,correctly calculate the delta and keep it simple to use in your game engine,the mechanics are resistant to lags (the game does not slow down),maintain a very high precision of timing (depends of the needs and implementation),it is very easy to determine the speed of objects and elements in the game,it is very easy to support slow-motion and accelereted-motion regardless of the framerate.I know all of this can seem complicated, but it's all limited to using a few functions and performing very simple calculations. There is nothing to be afraid of, because such very simple calculations can create an incredibly functional game core mechanics, not only easy to use by the programmer, but also giving players the ability to adapt its behavior to their hardware (limit framerate, safe CPU power and so on). Everything I described will be implemented in the game I am currently working on, so if I have the timing module finished, I will gladly give you a demo for fun and source for analysis. ---------------------------------------------------------------------- Seenkao · 2022-03-22 13:02 furious programming, ты явно не далёкий человек! Не понимаешь что ты делаешь вообще! Не читаешь, то что пишут, видишь лишь что-то через строчку.  Даже читать не стану твои росписи, потому что новичку это вообще не нужно знать. Но ты об этом забыл и при чём совершенно! Ты просто не хочешь понимать, что люди совершенно разные и большинство из них даже программировать больше не будут, особенно после того, что ты им предлагаешь. Ты делаешь всё, чтобы у человека пропало желание что-то сделать. Заставляешь изучать движки, на которые нужно тратить дополнительное время, кроме самого программирования. И в итоге, человек просто забросит что-то делать. И можешь потом благодарить самого себя, за то, что он всё бросил. Либо дай нормальный цикл уроков, чтоб человек мог по этим урокам пройтись и изучать, либо не советуй человеку идти через горы информации! google translate: furious programming, you are clearly not a distant person! You don't understand what you are doing at all! You don’t read what they write, you only see something through the line. I won’t even read your paintings, because a beginner doesn’t need to know this at all. But you completely forgot about it! You just don't want to understand that people are different and most of them won't even program anymore, especially after what you offer them. You do everything to make a person lose the desire to do something. You make them learn engines that a person needs to spend extra time on, except for the programming itself. And in the end, a person will simply give up doing something. And then you can thank yourself for throwing everything away. Either give a normal cycle of lessons so that a person can go through these lessons and study, or do not advise a person to go through mountains of information! ---------------------------------------------------------------------- flowCRANE · 2022-03-22 13:07 No, you just write nonsense once again and pass on nonsensical knowledge that cannot be used in practice. You don't know what you are writing about, you don't check anything and instead of admitting your mistakes, you keep denying and blaming me. My above post clearly shows how much you have no idea what you are writing about, so stop confusing people and giving completely wrong solutions. Quote from: Seenkao on March 21, 2022, 02:55:31 pmWindows has a GetTickCount function. For starters, you can use it. GetTickCount is a total crap and cannot be used, so stop suggesting people to use it. ---------------------------------------------------------------------- Seenkao · 2022-03-22 13:20 Посмотрим сколько знаний у меня и сколько знаний у вас? Вы перебрали хоть один движок полностью? Хотя бы под одну систему? Вы знаете как работает движок? Вы смогли заставить работать движок под MacOS Cocoa? Вы знаете как нативно завести программу на андроид, со своими системными вызовами? Боюсь что нет. Ты просто пользователь движка, не зная как там внутри всё устроено. У тебя нет даже конкретных уроков по данному движку? У тебя нет примеров по данному движку? Всё что тут тобой написано, просто пустой звук без кода.  Всеми своими эмоциями ты показываешь, что ты явно не прав. (дак и я не прав, что позволяю эмоциям взять верх над собой  но мне просто смешно смотреть, как ты тут брызжешь слюной, вместо того, чтоб предоставить человеку ссылку на уроки). В чём ты меня обвиняешь? В том, что я предоставляю человеку информацию которою проще на данный момент усвоить? И показываю как это работает? google translate: Let's see how much knowledge I have and how much knowledge you have? Did you go through at least one engine completely? At least for one system? Do you know how the engine works? Were you able to get the engine working under macOS Cocoa? Do you know how to natively launch an Android program with your own system calls? I am afraid it is not. You are just a user of the engine, not knowing how everything works inside. Do you even have specific tutorials on this engine? Do you have any examples for this engine? Everything that you wrote here is just an empty phrase without code. With all your emotions you show that you are clearly wrong. (and I'm not right that I let my emotions get the best of me but it's just funny to me to see how you squirt saliva here, instead of providing a link to the lessons to a person). What are you accusing me of? The fact that I provide a person with information that is easier to assimilate at the moment? And show the person how it works? ---------------------------------------------------------------------- Seenkao · 2022-03-22 13:47 furious programming, ну и чтоб  не быть голословным, я скидываю код, который будет достаточно точно работать на Unix, ну а вы предоставьте подобный код только для Windows. Я не думаю что это будет сложно. Сложнее это если б я вас попросил нативный код для MacOS Cocoa показать для таймера. google translate: furious programming, well, not to be unfounded, I throw off the code that will work accurately enough on Unix, but you provide similar code only for Windows. I don't think it will be difficult. It's more difficult if I asked you to show the native code for MacOS Cocoa for the timer. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i implementationfunction fpGetTimeOfDay(val: PTimeVal; tzp: Pointer): Integer; cdecl; external 'libc' name 'gettimeofday';...function timerGetTicks: double;begin  fpGetTimeOfDay(@timerTimeVal, nil);  {$Q-}  Result := timerTimeVal.tv_sec * 1000 + timerTimeVal.tv_usec / 1000 - timerStart;  {$Q+}  end; ---------------------------------------------------------------------- flowCRANE · 2022-03-26 13:28 Quote from: Seenkao on March 22, 2022, 02:20:15 pmLet's see how much knowledge I have and how much knowledge you have? Did you go through at least one engine completely? At least for one system? Do you know how the engine works? Were you able to get the engine working under macOS Cocoa? Do you know how to natively launch an Android program with your own system calls? Oh, don't be a babycry. It puzzles me even more, since you claim that you have such a large track record and knowledge, and at the same time do not understand how such a basic function as GetTickCount works and how much it is useless for precise timing. QuoteI am afraid it is not. I didn't make any engine, I made two whole games — the Deep Platformer (almost finished but abandoned) to play with software rendering (LCL rendering sucks) and the Fairtris to learn SDL and to fix anything that broke the sloppy developers of the NES Tetris. For both of these games, I use my own timing implementation (in the first one the cross- platform implementation) and it works great. And now I'm working on a third game, this time big and serious one (commercial), built from scratch in Free Pascal and SDL with my own engine, which will take about 3-4 years to release the first game to the market. QuoteYou are just a user of the engine, not knowing how everything works inside. Don't measure other people by your own yard-stick, especially if you start the discussion by confusing users. Besides, that's why I chose Free Pascal and SDL to implement everything myself. Thanks to this, I can program every aspect in my own way and have full control over everything, without having to rely on someone else's engine and someone else's API to handle it. If I didn't know how it all works inside, this approach would be suicide. But since I know exactly what the engine should look like inside, I can do whatever I want and however I want, adjusting the implementation to the project requirements. QuoteWith all your emotions you show that you are clearly wrong. It is not the (supposed) emotions that prove the correctness of the argument, but the source code that I have provided, which clearly shows that GetTickCount cannot be used to measure time between frames and cannot be used to calculate delta properly. Deal with it. Everything I wrote in the previous post is enough to implement powerful timing — someone as experienced as you will surely have no problem writing ~50 lines of code for timing and delta calculation. And you certainly won't have a problem adding a second multiplier as well, which will come in handy for manipulating the speed of the gameplay. Not only to be able to take advantage of the slow-motion effect in several scenes, but also to be able to slow down the gameplay for the needs of players with motor and cognitive limitations (read the Game accessibility guidelines). Quote from: Seenkao on March 22, 2022, 02:47:11 pmIt's more difficult if I asked you to show the native code for MacOS Cocoa for the timer. No, it won't be harder. As I wrote, gettimeofday and nanosleep functions are available on all Unix-based systems, including macOS. You don't even need to import anything, because these functions are already implemented in the form of FPGetTimeOfDay and FPNanoSleep. ---------------------------------------------------------------------- Seenkao · 2022-03-27 11:08 Диалог в нормальном русле! Уже хорошо! google translate: Dialogue is on point! Already good! Quote from: furious programming on March 26, 2022, 02:28:11 pmOh, don't be a babycry. It puzzles me even more, since you claim that you have such a large track record and knowledge, and at the same time do not understand how such a basic function as GetTickCount works and how much it is useless for precise timing.Данная функция была дана для тренировки. Для не сильно точных игр её можно использовать. И для новичка вполне подойдёт её использование. Новичёк должен уметь решать проблему сам (желательно), и если он разберётся с GetTickCount, то дальше уже сам сможет выбрать более подходящий метод (функцию) для дальнейшего использования. Если данный метод не подходит. Саму задачу он уже (надеюсь) смог решить, на основе предоставляемой функции. google translate: This function was given for training. For not very accurate games, it can be used. And for a beginner, its use is quite suitable. A beginner should be able to solve the problem himself (preferably), and if he understands GetTickCount, then he will be able to choose a more appropriate method (function) for further use. If this method is not suitable. He already (I hope) was able to solve the problem itself, based on the provided function. QuoteNo, it won't be harder. As I wrote, gettimeofday and nanosleep functions are available on all Unix-based systems, including macOS. You don't even need to import anything, because these functions are already implemented in the form of FPGetTimeOfDay and FPNanoSleep. Но эти функции уже не нативные и вы не можете утверждать, что вы знаете как они работают! ))) А MacOS Cocoa больше стремиться к использованию своего NSTimer. Google trenslate: But these functions are no longer native and you can't claim to know how they work! ))) And MacOS Cocoa tends to use its own NSTimer more.