How to implement scripted events for videogame design? - c++

I'm building a game in C++ (using SDL) for a college project, I'm trying to figure out how to script events that happens when a player does something, or some time passes etc.
I have a and idea of how to do it but I don't want to go against how it's commonly done.
Right now I have a class called Obj from where enemies, items and the player are child classes, my idea is to add 3 public variables to it like this:
class Obj{
int eventDeath,eventTouch,eventTalk,eventMeet;
}
Then I could create an Obj with eventDeath=1 and when it died it would fire event(1). event() would be something like this:
void event(int n){
switch(n){
case 1:
dialog("I'm dying");
break;
}
}
I could also add invisible "Obj" in specific places for when a player walks over a certain place. I don't know if this is a good idea but I can't think of other means to do it. How is it commonly done? Also how do I keep track of events that already happened?

An age old question to which there is probably no truely 'correct' answer. It is whatever works best for you. Take a look at the following links for information
Why embed lua into a game engine?
How do you add a scripting language to a game?

Related

Do people use classes as their "game loop?"

So I've been learning how to program so I can make games, and, therefor, I've been reading and watching many tutorials. Every once in a while, I'll come across code (c++) that uses a class to handle game events, but nobody has explained why they do this.
It also seems like some programming languages, like C#, automatically use a class for the program's "main."
So what I want to know is if I should be using a class for my game. Why and/or why not?
Here's an example of what this might look like:
class GAME
{
public:
void load_resources();
bool input();
void update();
void draw();
};
int main ()
{
GAME game;
while (!quit)
{
quit = game.input();
game.update();
game.draw();
}
return 0;
}
Thanks for reading.
In terms of game engine design we have something called a Scene system.
A scene normally hold all the GameObjects.
When you send the scene an event it should iterate on the gameObjects and update them all with events (update start end render postrender keyboard mouse scroll resize etch).
But in a much much simpler form of the system we at least want a game class so we can reload the level.
For example when the user enters the game it may take us a min to load all the models and textures and scripts from memory so we dont want it on our main loop we may want to load async and show a loading screen in this case we'll construct the game on another thread.
Or when the user wins and go to the next level we can unload the last level so we simply destroy the Game/Scene and create a new one of the new level.
In short: this kind of approach is used to define states of our application and manage them easily

Raycasting from player, hitting object and setting off custom event C++ UE4

I've been going in circles for a day now trying to get this going and I'm just getting nowhere. I'm trying to have multiple objects in the scene with individual animations and when I fire a raycast from my player and it hits one, have the UFunction(blueprintimplementableevent) go off on the object that it hits. Please help me this is absolutely stumping me.
What I would do is use a BlueprintNativeEvent. This will allow you to create an Implementation function of the stuff you want to happen in C++, as well as a blueprint implementation, which can be different for each blueprint of that object type.
It is quite simple to use as well, for example, in your character's header file:
/** Called when the player presses the fire key */
UFUNCTION(BlueprintNativeEvent, Category = "Shooting")
void OnHit();
virtual void OnHit_Implementation();
And now your Cpp:
void AMyGameCharacter::OnHit_Implementation()
{
UE_LOG(LogTemp, Warning, TEXT("OnHit_Implementation!"));
// Do whatever stuff you want to do in C++ here
}
Now over in your character / actor blueprint, just go to the event graph, right click, and add the event of type OnHit. Make sure that you make a callback to the parent OnHit event though (right click on the event and hit "Add Call to Parent Function")
If you want an example of this you can look at the C++ Battery Collector series or the docs.

How to alternate between two scenes in cocos2d-x?

I'm creating a game using Cocos2d-x. I'm currently creating a gameover menu, in that menu I need to be able to switch to both my menuscene and my gamescene (When I say switch to gamescene I only really only mean "to restart" the game). But circular dependencies stop me from being able to do this.
MenuScene needs to be able to useGameScene::create() in order to switch to the gamescene and the gameover menu needs to be able to use both of GameScene::create() or its restart funtion and MenuScene::create() which is giving me circular dependency problems
I can't separate my gameover menu to it's own file as I still need the GameScene dependency and GameScene would need gameover.
I can't combine them as GameScene then needs to depend on MenuScene
So my question is: How do I alternate between two scenes in cocos2d-x c++.
I read somewhere about pushing and popnig scenes in Director, but I don't really understand how that works, or if I could use that for my purpose.
Thank you in advance!
EDIT:
Now that I think about it, could I not just push mMenuScene to Director before switching to GameScene? That should work if I understand that push/pop mechanic correctly.
I think you might have a misconception of how complex this is, using the way I provided below you can and should definitely split your game over scene into its own file.
The scene replace is easy enough, just use the code below:
Including your file:
#include "MainGameScene.h"
Creating and switching scenes in your onClickListener:
auto gameOverScene = GameOverScene::createScene();
// use code below for hard replace
Director::getInstance()->replaceScene(gameOverScene );
// or use code below for transition fade replace
Director::getInstance()->replaceScene(TransitionFade::create(1, gameOverScene , Color3B(255, 255, 255)));
As for the restart functionality. I usually provide a callback to my game over scene that I call when the restart button has been clicked. Not that I ever swap out my scene completely for a mobile game over scene, but I still do it the same way regardless. So lets do steps (This assumes you seperated your game over scene into it's own file named GameOverScene :) ).
Store a function pointer in your GameOverScene.h to your reset method in MainGameScene:
std::function<void()> _resetCallback;
Set your function pointer from the main game scene, before running with the GameOverScene.
auto gameOverScene = GameOverScene::createGameOverScene();
gameOverScene->setResetCallback(std::bind(&MainGameScene::reset, this));
When your reset button is clicked, call the _resetCallback
void GameOverScene::onResetClicked(Ref* sender)
{
_resetCallback();
}
This should provide you with all the functionality you need to set up a what you want as well as remove the circular dependency that you have. I have used this way many times before and it always works. Let me know if this solution works for you.

Making a GUI using Qt for a text-based game

Me and my fellow classmates decided to make a game over the summer. At first we decided to make it a text-based console app, but then I though that it would be possible to create a GUI for the game using Qt. I played around with it a bit, being able to create widgets and what-not, but was unable to do one thing. For an example, our game contains a Player class. I created a dummy player in the main.cpp and afterwards tried to make the players info to display on a label on a press of a button. After numerous attempts, the only way I was able to do it is by making the player in the mainwindow.cpp . Is there a way to display the info of a player made in the main.cpp? How would it be possible to make the data accessible by different windows, such as the battle window, inventory window, etc.
It's a good thing to let the main.cpp as lean as possible, it should not contain much code in your case.
If I understand correctly you have several windows (could be simple QWidgets with no parent or QMainWindows) running on the same QApplication and your want to share data between them ? Why not just share a Player pointer in both your windows ?
Your main.cpp will look like this:
QApplication app(argc,argv);
YourWindows1 mw1;
YourWindows2 mw2;
Player player;
mw1.setPlayer(&player);
mv2.setPlayer(&player);
mw1.show();
mw2.show();
app.exec();
A more fancy way, could be to use a singleton. This singleton could own and hold your Player instance, every windows can access this singleton statically anytime to fetch Player information. It could be something useful for you to learn.
NOTE: I don't see exactly what is the problem here, perhaps you could share more details about what's causing you trouble ...
In a typical Qt app, main.cpp is only there to start the single application UI object and then turn control over to Qt's event handler. It's possible to deviate from that model, but unless you're quite experienced with Qt it's not something that would be recommended.
I agree with the other posters in this thread in that your main function should be kept absolutely as lean as possible. You want it simply to spawn a new instance of your game, and the let the game loop or state control manager take care of the rest. It basically boils down to something like this:
class Game{
Game();
~Game();
int OnExecute();
};
int Game::OnExecute(){
while(running){
// do game stuff
}
return 0; // No errors, game closed correctly.
}
int main(int argc, char* argv[]){
Game myGame;
myGame.OnExecute();
}
All of your initialization methods/code is contained within the OnExecute function, prior to the game entering its main loop. Within that main while(running) loop, you put your calls to your per-frame Update and Rendering functions which control logic calculations like entity position, physics updating, AI updating, etc and then you render everything for that frame. This is obviously an ultra-simplistic strategy, but it definitely helped me grasp exactly how it is that game engines work.
Now, as far as Qt is concerned, I've tried exactly what you are trying and it is not easy. Qt, though it can be rigged to work for in-game interfaces and the like, seems to me to be primarily intended for use in applications more than games. It provides excellent functionality if you need simple forms and buttons in your program, but as far as custom-designed HUDs and such, you're going to want to look somewhere else in order to save yourself a great deal of hassle. There are, however, a huge number of extensible GUI libraries specifically meant for games. I would suggest looking for one based simply on OpenGL since most graphics/game engines are built upon it and would integrate quite nicely.

How to efficiently render different things at different times in a game?

Sorry for the ambiguous title. What I am wondering is what is an efficient way to alternate rendering between lets say a main menu, options menu, and "in the game."
The only two ways I've come up with so far are to have 1 render function, with code for each part (menu, ...) and a variable to control what gets drawn, or to have multiple render functions, and use a function pointer to point to the appropriate one, and then just call the function pointer.
I always wonder how more professional games do it.
Try to use state-machine / strategy OOP pattern. Game application is in different states and renders different things and reacts on keyboard/mouse input differently when you are playing and when you are interacting with menu.
Well this is a bit more complicated if you want to do it right.
First I create a CScreen class that's the base class for all the screens. It's an abstract class( use pure virtual functions) that has 2 functions: Render and Update. Then I derive it in more screens that I need such as CMainMenuScreen, COptionsScreen, CCreditsScreen, CGameScreen etc. Let each of these classes take care of their own stuff. In each of them you have the interface and then when press for instance the options button in the main menu screen then you change the screen to COptionsScreen. For that you have to just keep one variable CScreen screen somewhere and on every frame call screen->Update() and screen->Draw() remeber to adjust if you do not use pointers(tough I'd recommend this)
If your controls are represented as classes then a polymorhic API render would solve the problem. Depending on the object ( menu types) the corresponding rendering happens.
class UIObject
{
public:
virtual bool render() = 0;
~UIObject(){}
};
class MainMenu : pu{
public:
virtual bool render()
{ //rendering for main menu
}
};
class OptuionMenu
{
public:
virtual bool render() { //render for option menu}
};
Games that I've shipped, that have sold lots of copies, have had a state machine and used switch statements to choose the appropriate functionality. While ostensibly less flexible than an "OOP" state machine, it was far easier to work with than the OOP designs I've subsequently been subjected to.
It actually may be appropriate to have only one render function, but that function shouldn't know specifics about what it's doing. It'll have 3D and 2D passes (at least, for a 3D game, since even those often have 2D UI elements), but it doesn't need to know what "mode" the game is in.
The magic happens in the UpdateMainMenu or UpdateGame or UpdateInGameMenu functions, as well as the Start and Stop functions associated with switching states. Choose which with a switch statement on an enum and use it two places, switching states (one switch to stop the old state, one more to start the new one) and updating.
As I write that my alarm bells go off that this is a perfect opportunity to use OOP, but from experience I would advise against that. You don't want to end up in the situation where you have a million little states that are coming and going; you want to constrain it to the major "run modes," and each of those modes should be able to operate on data that tells it what to display. E.g. one state for the entire in-game menu, which "loads" data (usually, "updates its pointer to the data") to indicate what the behavior of the current screen is. There is nothing worse than having a hundred micro classes and not knowing which one triggers when, not to mention the duplicated logic that often arises from such a design (game developers are very bad at reducing duplication through refactoring).