Hot answers tagged

41

Use a boolean flag. In the example shown, you'd modify the code to be something like the following: //a boolean flag that lets us "remember" if this thing has happened already bool thatThingHappened = false; void Update() { if(!thatThingHappened && mousebuttonpressed) { //if that thing hasn't happened yet and the mouse is pressed ...


21

Should bool flag not suffice or you wanted to improve readability* of the code in void Update() method, you could consider using delegates (function pointers): public class InputController { //declare delegate type: //<accessbility> delegate <return type> <name> ( <parameter1>, <paramteter2>, ...) public delegate void ...


11

An SDL_KEYDOWN event is only sent when the key is first pressed. You will receive an SDL_KEYUP event when it's released. You'll want to handle moving in code which gets called every frame, not in response to an event. Inside Avatar::handle_input, you'll instead want to set variables to tell you whether each key is up or down, and update those variables as ...


11

TL;DR The author is not suggesting you implement this in your game. He's telling you that the precision will be slow changing, but bad. This means the float you're using to track your game time would start at 2^32. Because setting the number that large to start with, whatever you add on to it in the next 136 years, won't change the exponent. Though, the ...


10

This looks like you could solve it with a priority queue or min-heap. The code to process the queue would look something like this: while(eventQueue.Count > 0 && eventQueue.Peek().executionTime <= Time.time) { eventQueue.Dequeue().action(); } This means you have only one check to do on frames when no events happen - you don't have to scan ...


9

I have not seen an else being used in this instance (the Rastertek tutorial you mentioned does not use an else). My guess would be if that you tried to resize your window the game rendering would freeze proving that the else part is never executed, as the resize message would be constantly sent. A common loop would have this structure. while (true) { ...


8

Most games have a function that calculates the current time -- perhaps using QueryPerformanceCounter(), perhaps using GetTickCount64(), perhaps using something else. Normally this function is designed so that it initially returns zero, and then gradually returns larger numbers. What the author is saying (and I can be definitive about this because I am the ...


7

Merging systems, such as collision and collision response, is a bad idea. The reason being that there can be many different responses to collisions: Physics based, and game-logic based. In most game engines I have seen (ECS and non-ECS and all the greys in-between), there is some kind of inter-system communication system, because this is what makes the ...


6

Just separate the events from the drawing. The normal method is to redraw all the time, not to wait for something to change. Normally your loop should be like this: while loop: check events: # find routes, block path, whatever update things: # change the state of the game draw() You shouldn't be thinking in terms of drawing one ...


6

The general solution to this problem is to have an update function with a completely fixed timestep. Unity calls this FixedUpdate, in physics engines you can run the simulation several times before updating the world, etc. but it's all the same concept. While this fixed update function will always be slightly out of sync with everything else in your world, ...


6

Although you can use the existing event model in C#, it might not always give you the flexibility that you require. You can for instance not sort events based on their priority, clear events of a specific type or add a queued/delayed event. Example) To signup for an event the object needs a method with the same signature as the CallbackMethod delegate. ...


6

There's no built-in way to do that. If you prefer an event based solution you can wrap all input polling inside a component and expose the relative and subscribe for them. Some like: public EventHandler : MonoBehaviour { public event Action<Vector2> mouseCliked; void Update() { if (Input.GetMouseButtonDown(0)) { mouseCliked(...


5

For synchronisation, you need to decide who (your code, animations, or neither) is the timing authority—the "beat" that everyone else "dances" to. Different arrangements suit different games: Animations are the timing authority (your current setup) The game code may trigger animations. When animations reach certain points, they raise events (e.g. ...


4

Whether you need a publish/subscribe pattern or not depends on when your data changes. If it does so during the lifetime of the interested objects, and if those objects need to know (and react) immediately, then publish/subscribe certainly is the right thing to do. If you do not need immediate notification, just store a direct or indirect reference to the ...


4

An event is simply that - an event, and tells you when something has happened, not what the current state is. So you only get one keydown event, when the key first goes down, then a key up event when the key is released again. For continuous motion, you have 2 choices: Use the events to set your game's internal state. This is the example that Petr Abdulin ...


4

Trevor is correct, you actually need something like this: // define vars somewhere bool left_down; bool right_down; void Avatar::handle_input(SDL_Event keyInput) { //If a key was pressed if( keyInput.type == SDL_KEYDOWN ) { //Adjust the velocity switch( keyInput.key.keysym.sym ) { case SDLK_LEFT: left_down = true;...


4

You know when each individual explosion is done. You know how many explosions there will be. Just make whatever is in control of your explosions (random event handler?) trigger an event saying the explosions are finished. If you don't have a separate object controlling your explosions, make one. A global event handler will likely be very useful to you. Any ...


4

This is just another category of collision detection. Your server needs to be able to tell if two bounding shapes are colliding for any number of reasons and this needs to be efficient; there are many ways to achieve this. The world is then capable of having thousands of entities (including triggers) and information about which ones are currently in ...


4

I think the thing you need to grasp is that the message processing will run much faster than the rate at which messages are sent. For the example code you've provided, here's an estimate of timings: while (msg != WM_QUIT) // { if (PeekMessage(&msg,0,0,0,PM_REMOVE) { // Translate and dispatch message // [A] --> This takes a ...


4

There isn't going to be something "faster" than Update(reference), that runs once per frame: Update is called every frame, if the MonoBehaviour is enabled. If your frame rate is half a second per frame, then you'll get a half second delay. You'll need to perform some optimizations if you want faster response. Make sure your MonoBehaviour is enabled, and ...


4

I often see people over-engineering event systems, my advice would be to keep it simple. For a simple game an enum suffices to identify events. For games with a large amount of events from different code modules and scripting functionality it will become a burden because it is not extendable (and increases compile time). Imagine you added a script system ...


4

Instead of completely refilling all players action points at a fixed time, you could instead give them a small amount of action points every few minutes and allow them to safe up action points up to one or a couple days worth of points. A player who wants to do something big will have to safe their action points for about a day. Afterwards they will be ...


4

Don't shove all the events into one type. You are using C++, a language that supports Abstract Data Types. Use them! Inheritance/Interfaces struct Event { TYPE type; virtual void Handle() = 0; }; struct DamageEvent : Event { float damage; int target; void Handle() final { FindTarget(target).TakeDamage(damage); } }; void ...


4

I see that the backward image is turned around 180 degrees to make it face opposite the direction of the forward image. This means that its front side is facing away from the camera. By default, this will cause the event system to ignore it. There are three easy fixes for this. 1. Make a copy of the arrow texture and use your image editor to reverse it. Use ...


4

This looks like a situation you can tackle with the curiously recurring template pattern. First, we'll define a generic GameEvent, that could work on payloads of some unknown type, with static methods to register/unregister listeners who care about events of that type, and broadcast the event to all listeners: public abstract class GameEvent<T> { ...


3

You need to redraw every time in your main loop (even if no event has occurred), don't wait for any event or change to occur. Don't make your draw functionality dependent on events. In your main loop Check for events and make changes Draw (even if nothing is changed)


3

I would check if the player moved, and call an event to handle all the checks for new tiles. Something like: ... if(playerX != oldPlayerX || playerY != oldPlayerY) { onTileChange(player); } ... onTileChange(Character character) { int characterTile = getTileAt(character.positionX, character.positionY); switch(characterTile) { case 3: ...


3

To do this, you need to sample the state of the mouse regularly, and when it's clicked, check the coordinates against the button and see how that goes. Usually, I write something like this in Button: public void Update() { // called every tick var mouseState = Mouse.GetState(); if (this.OnClick != null && mouseState.LeftButton == ButtonState....


3

If you have VSYNC on, and if you handle windows events in the same thread where you handle rendering, you will experience some small but noticeable input lag. The SwapBuffers() function will wait for vertical sync, which slows down main loop, which again slows down recieving of windows events. There are several different solutions. The easiest one would ...


3

Yes. It is a very efficient way for game systems to communicate with each other. Events help you decouple many systems and make it possible to even compile things separately without knowing of each others' existence. This means your classes can be more easily prototyped and the compilation times are faster. More importantly, you end up with a flat code ...


Only top voted, non community-wiki answers of a minimum length are eligible