Hot answers tagged

43

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 ...


22

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 ...


12

The second solution will perform slightly less ticks than expected over time, because when tickTimer is slightly larger than tickTimerMax (which is almost always going to happen due to floating point inaccuracies), then the remaining time gets discarded. Those differences accumulate. So when your game runs for a minute and you check how many 0.2 second ticks ...


10

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) { ...


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 ...


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

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

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.message != WM_QUIT) // { if (PeekMessage(&msg,0,0,0,PM_REMOVE) { // Translate and dispatch message // [A] --> This ...


4

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 ...


4

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 ...


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> { ...


4

Abstract Should the connection be persisted? No: Connect from code. Should the connection happen on load? No: Connect from code. Should the connection be removed on runtime? Yes: Connect from code. Should the connection include a node made on runtime? Yes: Connect from code. Are you writing GDScript? No: Connect from code, or use GDScript as glue. On a ...


4

Unity already has a built-in event for doing exactly what you want: EditorSceneManager.sceneSaving Usage: EditorSceneManager.sceneSaving += OnSavingScene; private void OnSavingScene(UnityEngine.SceneManagement.Scene scene, string path) { //do some stuff here }


3

One important point - when you're using eg. DirectX, you really, really don't care about the main thread. Let it be as free as possible, it doesn't do anything. All the inputs and outputs are processed separately from the UI thread, so why tie them to it? That's only going your window to stop responding if your rendering / updating is too busy. Also, yes, ...


3

The computer graphics term for what you're trying to do is picking. The issue with picking from an HTML canvas is that the canvas doesn't understand anything about sprites -- all it knows about is pixels. In more general terms, canvas is a purely graphical representation -- it stores no semantic information. It has no idea what you wanted those pixels to ...


3

You might want to look at internet Diplomacy, which takes the simultaneous moves approach. Diplomacy assumes you will be discussing moves with other players, so you have some idea of what is going on even though you can't see actual moves (and other players may be lying to you about their plans). I'm not sure whether this helps, but it's at least an ...


3

I managed to figure this out. You need to manually tell the EventSystem that the object has been selected. On a method such as OnPointerDown() you need to call the EventSystem.current.SetSelectedGameObject() method and pass in the event data and your gameobject. public class SelectableText : MonoBehaviour, IEventSystemHandler, ISelectHandler, ...


3

I would personally use the keyboard class that allows you to query the state of keys instead of waiting for an event. The documentation is here One of the reasons I prefer this method is that you can check the status of the key from almost anywhere in the code, and you don't have to store the state of the keys yourself. f::Keyboard can retrieve the ...


3

The DieOnCollision event couples behavior to an event. This causes tight coupling and could be why you're having trouble deciding how to handle these use cases. Instead I would concentrate on the fact you want to perform some behavior when a collision occurs, therefore it makes logical sense to expose some way to know when a collision has happened. Since ...


3

TL,DR: The SDL2 event/render system is not yet thread-safe, but you can overcome this limitation by using OpenGL to decouple the renderer system from your application (and then perform all rendering in a separate thread using only OpenGL functions). In this method, you still have a single event queue. Another way is to use multiple processes (e.g. using ...


3

The event "A unit owned by player 12 dies" implies the "A unit dies" event. So there is no reason to have two different events. You should only need a single "Unit death" event, but have that event include all the relevant information like which unit exactly got killed and what killed it. You can then have the event receivers inspect that information ...


3

For completeness (Not actually recommending that you do this as it's actually pretty straightforward to just write something like if(!already_called), but it would be "correct" to do it.) Unsurprisingly, the C++11 standard has idiomized the rather trivial problem of calling a function once, and made it super explicit: #include <mutex> void ...


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