SFML community forums

Help => General => Topic started by: Serapth on September 09, 2011, 12:09:46 am

Title: SFML Complete Game Tutorial
Post by: Serapth on September 09, 2011, 12:09:46 am
I have been working on a tutorial series (http://www.gamefromscratch.com/page/Game-From-Scratch-CPP-Edition.aspx) on using SFML 1.6 with Visual Studio 2010 to create a complete game from scratch.

One of the things I often see is when new developers share their code, the structure is absolutely horrible.  Part of this is as a result of learning from code samples that are meant to concisely demonstrate the usage of the library involved, not how to make an actual game.  Many other beginner samples are from books, where being concise is one of the most important aspects. There seem to be very few examples out there that actually explain how to bridge the gap between various library features and an creating an actual game.

That is what I am trying to provide with this example.  It is long, 5 chapters already and frankly nowhere near complete and the end result is going to be a glorified pong clone.  That said, along the process I try to teach the basics of object oriented programming.  Additionally, initial setup and configuration seems to be one of the major stumbling blocks for new developers in C++, so I spend a good deal of time focusing on that in detail.


Anyways, if you are new to SFML and are just learning C++, you are my target audience.

If you are a C++ expert and see a glaring flaw in what I have written, let me know!

Hopefully this series is useful to new developers.  Please let me know what you think.

A Game From Scratch: C++ Edition (http://www.gamefromscratch.com/page/Game-From-Scratch-CPP-Edition.aspx)
Title: SFML Complete Game Tutorial
Post by: Serapth on September 09, 2011, 12:16:26 am
One of the tenants I am working upon is to write code that initially fits, but in later chapters revist it to fit changing circumstances.  This is meant more as a learning exercise than as a coding template.

For example, in Part 4, I introduce the VisibleGameObject class, which owns an sf::Image class.  Then I present a PlayerPaddle class, which loads an image to represent the player's paddle.  In a future chapter, I will present an AI Paddle class, which will result in the duplicate loading of the same Image file, and will then present a class to rectify this inefficiency.

I hope that made sense.


I also should have named Gameloop() as GameloopIteration() or something similar, as the current name is misleading.  I regret how I structured that aspect of the code for clarities sake and will probably refine it.  Making the initial Game class static also probably introduced a level of complexity that could have been avoided, although by the end of the process, I think it will still prove to be the right decision.
Title: SFML Complete Game Tutorial
Post by: Lo-X on September 09, 2011, 07:18:31 am
Clicking on the title of an article on the main page is not working. The link is broken.

I don't have the time to read all the tuto, later =)
Title: SFML Complete Game Tutorial
Post by: Serapth on September 09, 2011, 02:47:10 pm
Thanks for pointing that out, it has been fixed now.

Windows Live Writer, which is otherwise a very nice blogging tool, has this horrible glitch where it will attempt to turn a + in the title into a URL.  So every post with forbidden characters in the title I need to manually edit the page name.  I missed that one. :(
Title: SFML Complete Game Tutorial
Post by: easy on September 10, 2011, 03:38:02 pm
This is nice! That was my problem too, SFML does not provide complete examples, rather snippets.

I think you should rather put this topic to 'Project Announcements'!

Keep it up! :D
Title: SFML Complete Game Tutorial
Post by: Jove on September 10, 2011, 08:18:29 pm
Indeed this is good, looking forward to the next installment.
Title: SFML Complete Game Tutorial
Post by: ephaitch on September 10, 2011, 09:20:40 pm
Is Part 5 not written yet or is the link broken?
Title: SFML Complete Game Tutorial
Post by: easy on September 10, 2011, 11:36:25 pm
I believe it's not written yet.
Title: SFML Complete Game Tutorial
Post by: ephaitch on September 11, 2011, 12:54:58 am
Bummer.. I'm trying to continue on my own to finish the game, but I'm probably noting doing things correctly. =(
Title: SFML Complete Game Tutorial
Post by: Serapth on September 11, 2011, 01:04:55 am
Hi everybody,

Thanks for the kind words.  Section 5 is being written as we speak ( all sample code for 5 & 6 is complete ).  I am currently doing a bit of a revision based on some feedback I've received so that distracted things a bit.

Also, death nearly laid her hands on me  ( Ok... I got a flu ), so writing cohesively hasn't been my strong suit the last couple days.  Should have part 5 up very soon, most likely Monday at the latest, perhaps tomorrow if my immune system decides to stop sucking.  It's kinda funny, I am able to code sick, but stringing two cohesive sentences together seems to be beyond me!


EDIT: BTW, did I post this thread to the wrong forum?  If so, sorry.  I didn't post to Announcements based on the fact it's not "done" per say.
Title: SFML Complete Game Tutorial
Post by: Azurus on September 11, 2011, 08:43:31 pm
I have a little problem. In part 1, you mention a "sfml_main-d.dll" that you're supposed to copy to the debug folder. However, this dll doesn't exist. For me, anyway.

Also, in Part 2, in game.cpp, you call sf::color twice on line 38, why would that be? Also, a little matter of consistency, in line 6 you just have Uninitialized, but in line 52 you have Game::Uninitialized.
Title: SFML Complete Game Tutorial
Post by: Laurent on September 11, 2011, 08:57:49 pm
It has never existed, sfml-main is always a static library.
Title: SFML Complete Game Tutorial
Post by: Serapth on September 11, 2011, 10:23:28 pm
Yeah, my bad.  It should have been sfml-main-d.lib not sfml-main.dll, fixed now.

As to the two other things, the double colour call was a cut and paste error that survived to live, while the fully resolved enum is the C# developer in me expressing himself! :)  I've fixed both now, thanks for the catch.

I actually allowed a ton of little errors to pop up between projects that I should have caught but didn't because I wrote the 5 source projects, then wrote the blogs to go with them, but in writing the blogs I found little glitches and errors, or decided I didn't like the way it was put together, resulting in a change having to be propagated across 5 separate projects.  

This...  was stupid. :)  Now, I am working to get everything at parity, then will keep the posts in closer sync to the code to prevent such problems.
Title: SFML Complete Game Tutorial
Post by: Serapth on September 14, 2011, 06:55:50 pm
Sorry for the delay, but Part Five is now completed (http://www.gamefromscratch.com/page/Game-From-Scratch-CPP-Edition-Part-5.aspx).


In this part we put together a very simple game object manager, it might be overkill in a pong clone, but if your game becomes any larger, a class like this is almost essential.  To a degree the complexity level of the code ramped up a bit from Part 4, so if I did a poor job explaining something or you see an error, please let me know!


Alright, off to work on Part 6.
Title: SFML Complete Game Tutorial
Post by: Serapth on September 25, 2011, 01:38:41 am
Took way longer than expected, but Part 6 is live (http://www.gamefromscratch.com/page/Game-From-Scratch-CPP-Edition-Part-6.aspx)


We are still in sub-game territory, but we are getting closer and closer!   In this part, we added a player controllable paddle and the game ball. Again, if you encounter and mistakes or have any questions, please let me know!

Next up, we will get the ball rolling ( sorry, bad pun ) and cover off collision detection.
Title: SFML Complete Game Tutorial
Post by: Azurus on September 29, 2011, 06:00:45 am
You should probably explain what the 'virtual' keyword is, how it works, etc. in part 6 too.
Title: SFML Complete Game Tutorial
Post by: Serapth on September 29, 2011, 05:18:44 pm
I covered off the virtual keyword in part 4 (http://www.gamefromscratch.com/page/Game-From-Scratch-CPP-Edition-Part-4.aspx) and mention it briefly ( about it's absence ) in part 5.  The series is meant to build off the previous part, or each part would go from being long to being enormously overwhelmingly hugely long!
Title: SFML Complete Game Tutorial
Post by: sbroadfoot90 on October 03, 2011, 12:22:14 pm
oh my god I can't wait for part 7. Any idea when it will be done?
Title: SFML Complete Game Tutorial
Post by: Serapth on October 04, 2011, 12:19:17 am
Soon (tm). :)


A bad case of the flu ripped its way through the Serapth household and I am just now regaining the ability to string a cognitive sentence together.

The code is written, just need to finish the write up.
Title: SFML Complete Game Tutorial
Post by: kolofsson on October 05, 2011, 04:57:25 pm
Dear Serapth, I have read your tutorial.

First of all, I would like to thank you for the hard work you put in this. It's really nice to see people dedicate their free time to help others.

I have to say, however, that your tutorial has made me more scared than eager to make a game. In the beginning of your tutorial you wrote:
Quote
I am writing it in C++ because regardless to all the people say “DON’T DO THAT IN C++!” the vast majority of people still do.

...people state things like “I hate OOP, I’ll just use functions”.

I have no academic programming experience, I'm more of a hobbyist programmer, so I'm not really aware of what people say. After reading your tutorial, I'm thinking they may have a point :). I tried writing stuff in a couple of programming languages and I have to say that the best memories come from writing in PHP. For me, PHP is very easy to use and the syntax is easy to understand. PHP is packed with useful functions and very well documented on the php.net website.

From the history of programming I know that OOP is a step forward in making programming more abstract and "human". However, for me, objects make the source code so difficult to understand/grasp. For me, OOP should give me a set of blocks to play with. That's what I like SFML for.

However, your tutorial shows the true face of the OOP. Public/ protected/ private/ virtual/ constructor/ destructor/ static class, put a tilde here, an asterisk there and a colon. All this stuff makes my head explode and I don't consider myself to be a dimwit.

To conclude, I have read your tutorial thoroughly and understood a portion of it. To me the most useful part is the final product, which is the attached project file. The tutorial itself is an explanation of how and why you made the source code look like that. I will try to fiddle with that source code, but it looks like ultra complex to me, and I would never ever come up with anything similar so I don't know if I will make big use of it. I understand that your tutorial was meant for us to take over at some point and create similar stuff to what you did, but I think it's too complex for me.

I attempted to make a game with SFML once, but had to focus on other stuff. Now I would like to start over, that's why I read your tutorial. My game can be found here:
http://grebocin.com/upload/screenway08.zip

I made this game after fiddling with with SFML Pong example, which is much less complex than what you're offering (without objects, private, public, virtual etc.). I don't know if it makes sense for me to make this game, as you clearly state in your tutorial that not following it will lead to a fail.
Title: SFML Complete Game Tutorial
Post by: Serapth on October 05, 2011, 06:55:11 pm
Hi kolofsson,

One thing to keep in mind, my tutorial is just one way of doing things and in many cases I absolutely overkill and that is on purpose.  There is nothing wrong with writing your code along the style of the SFML examples, doing things in that manner is much easier to get your head around.  

The problem is the examples are just that, examples.  They are meant to showcase how something works, not how to actually create a full game.  What you will find is once you start adding complexity to your game things are going to start turning into a mess really fast.  There aren't too many tutorials out there on actually laying out a game, so when I see beginners code it's often all in a single file with hundreds or thousands of lines of code all often in a single function.  Then again, this is a perfectly valid way to start.

This is what my tutorial is attempting to address.  There is a very good reason why there aren't many such tutorials and first off is they take a hell of a lot of space and time, look how long it is already and it's not even a functional game yet.  There often isn't space within a book, or in the case of SFML, it's well outside the scope of what should be documented. Again though, I am just showing one possible way of doing things and I am (hopefully) doing it in such a way that people walk away with a better concept of how to lay out a game and how OO programming works.  I am also over doing things, so although this is a simple pong game, you cant take the knowledge and some of the classes and apply them to any kind of game you wish to create.

However, there is nothing to say you need to make your game object oriented.  A great many games aren't programmed using objects, take a look sometime at the Doom/Quake source code that John Carmack released for an alternative approach.  It is simply one way to approach the problem of code complexity and there is no single "right" way.

All that said, judging by the comment  "Public/ protected/ private/ virtual/ constructor/ destructor/ static class, put a tilde here, an asterisk there and a colon" C++ is probably not the language for you, as these things are the bread and butter of C++ programming.  Compared to many other procedural programming langauges ( C#, Java, Python, Lua, Ruby, etc ) C++ has a downright byzantine syntax.

In all honesty, I don't really recommend C++ as a starter language, especially if you are approaching it from a hobbyist perspective.  If you are willing to do yet more reading this is my advice for beginning developers (http://www.gamefromscratch.com/post/2011/08/04/I-want-to-be-a-game-developer.aspx) that want to get into game programming.  It is a very long read and I tried to keep bias to a minimum, but a number of new game developers have told me they found it extremely useful, hopefully you will too.  At the very least when you are done reading you should be a little bit more knowledgeable! :)  If you are doing this as a hobby, it is something you should have fun doing!

One other thing though, what looks like a foreign language will in time become natural.  In some cases it is simply a matter of time and effort and what initially makes your head want to explode will eventually become second nature to you.  We all go through it to a certain degree.  I do however find many languages are much more intuitive than C++, which should make your learning process much cleaner.

Fortunately, SFML has bindings for just about every programming language you might consider working with.  It is a clean, well designed and mostly intuitive library which is very good for a beginner.  Therefore whatever language you go with, SFML is a very good choice to stick with.
Title: SFML Complete Game Tutorial
Post by: kolofsson on October 05, 2011, 07:47:09 pm
Allright, I'll follow your advice and read the guide. I like your writing style. You know a lot about making games, you write in an non-boring manner, which brings me to a question: who are you? :P Are you a professional developer?

When it comes to choosing programming language, I went with C++ because SFML is made in C++ and I knew C. I even tried reading books about programming in C++ but it was a few years ago and I forgot. Moreover a friend who is a professional programmer himself recommended C++ "as the pro choice" and told me not to fool around with C#. Finally, I don't fully understand the concept of bindings and how to make them work, they seem to me like another layer of complexity. And, as I fell in love with SFML, I did not want to use any other library.
Title: SFML Complete Game Tutorial
Post by: Serapth on October 05, 2011, 08:58:57 pm
Bindings are usally just an interface layer that makes a library available to other languages.  Languages are able to call code written in other languages, they just require a bit of translation in the middle, this is essentially what a binding provides.  In the end you are still using SFML, just through a translation layer that makes it work in another language.  Your friend did you a disservice, but his (bad) advice is all to common, generally among younger/newer developers sadly.

As to me, I was a professional developer, even worked in games when I first graduated, but now I created a start up (http://www.flexamail.com) and work for myself while raising my 3 year old.  Now that pretty much all the coding is complete on my other project, I am getting back into games and writing.  Now is perhaps the greatest time to be an indie developer, so I am rather enjoying it.
Title: SFML Complete Game Tutorial
Post by: Nexus on October 05, 2011, 10:18:49 pm
Very good tutorials! Good to see there are so many nice contributions to SFML :)

You have a clean code style: Clear identifiers, almost no manual memory management, good distribution of responsibilities to different classes, const correctness, use of the STL and constructor initializer lists. Many advanced C++ programmers still have problems with these things. Your explanations to new language features are clear and helpful.

I have however a few remarks, of which some are quite details, but I thought I'd mention them nevertheless:
Title: SFML Complete Game Tutorial
Post by: Serapth on October 06, 2011, 04:24:40 pm
Thanks for the excellent feedback Nexus!

I really wish you'd mentioned some earlier as some are a nightmare to change at this point! :)

I can and will edit in a blurb about the possible perils of globals, that is a very good idea.

The _ thing, I know I shouldn't do it, I really really really know I shouldn't do it, but I can't help myself :)  It's a coding habit I picked up a long time back and although its frowned upon I really find it intuitive, especially because it groups all private members together in intellisense which is handy.  I know prefixing with m would have the same effect, but I personally at least think the prefix alphabet soup makes things more difficult to read.  Granted, in a tutorial I really should have coded to the established norm, but in this case I couldn't help it.

On the coding changes, I will see what I can do about addressing each mistake in code.  In some cases it makes a massive amount of work because of the way my blogging software does code samples in the posts.  




The choice to use asserts was one of those things I went back and forth on, and made a point of addressing that it was just one option in the comment.  As much as anything, I wanted to present the concept of asserts because they aren't mentioned nearly enough.  I think I will go back and add a bit further detail about the behavior of asserts during release mode.  I still feel they are a valuable concept to introduce.


Instead of if(x) return true; else return false; you can write return x;
Where did I do this?





As to struct/class, when I started with C++, I was coming from C and I seem to remember there being some arcane rule that a C++ to be compatible with a C struct under certain circumstances  ( perhaps composed of entirely POCO types ) would not contain a v-table.  This is a very old and very vague memory, so I decided to cover my ass and use
"biggest difference" :)
Title: SFML Complete Game Tutorial
Post by: Nexus on October 06, 2011, 05:06:09 pm
Quote from: "Serapth"
I really wish you'd mentioned some earlier as some are a nightmare to change at this point! :)
Sorry, I haven't read the tutorial earlier :?

If I can be of help at changing a specific thing, just tell me :)


Quote from: "Serapth"
Instead of if(x) return true; else return false; you can write return x; Where did I do this?
For example here:
Code: [Select]
if(_gameState == Game::Exiting)
    return true;
else
    return false;

You could write
Code: [Select]
return _gameState == Game::Exiting;
But as mentioned, it's a detail. If you find the first variant more clear, use it. In my opinion, the second can be read faster if you understand boolean expressions ;)


Quote from: "Serapth"
As to struct/class [...]
Your description isn't wrong, it's even very good. I also use struct for PODs, simple data wrappers or functors and class for "real" classes. But technically, one could use both in every situation. I mentioned it because many beginners think the class keyword is somehow the mighty variant of struct (probably because it is taught like this in books).
Title: SFML Complete Game Tutorial
Post by: kolofsson on October 06, 2011, 05:22:51 pm
Hey Serapth :), I have read your introduction to becoming a game dev. From what you wrote I understand I should either choose C# or Python. The problem is, I would like to stick to SFML and would not like to start learning XNA (I also would like my game to run on Mac and Linux). So, would you approve of going with C# + Monodevelop + SFML? I should add I'm not a fan of Visual Studio cause its bloated, its like a swiss army knife when I just need a knife. Hence the monodevelop.

Regarding the bindings, I only see bindings for C# and Python for version 1.6. Is it possible to compile a fresh nighly build of SFML and use the bindings?

If I went with C# + SFML, would your game from scratch tutorial still be of use to me?

I also took some time to see the differences between programming languages. So, what I like in programming languages is: weak type strength, implicit types, dynamic type checking, failsafe i/o, easy implementation of associative arrays.

From what I've seen in comparisons, I should either go with Python or Lua. However, AFAIR there are no up to date bindings with SFML for these :(.

I do not see the big difference between C++ and C#. My friend told me, that if I used C++, I could still do a majority of what I need to achieve without getting into the complex stuff. For a hobbyist programmer, I don't see where is the simplicity that C# brings. I can see that there are more built-in functions and easier to use too.
Title: SFML Complete Game Tutorial
Post by: Serapth on October 07, 2011, 06:14:12 pm
I am not actually sure of the status of 2.0 .NET bindings, someone else will have to answer that question.  When just starting out though, I would recommend going with the stable supported version, that is why I based my tutorial around 1.6, although there aren't very many differences.

I don't really get the Visual Studio == bloated comments, but I see them all the time.  I absolutely love Visual Studio, I think it is one of the greatest pieces of software ever written and I am simple staggered by what it can accomplish.  There isn't even an ounce of hyperbole in that comment, I truly think its a wonderful piece of software and when recently using XCode or before that Eclipse it made me realize just how much I do love VS.  Now there is a ton of functionality in there that you don't need, which is why the Express versions are often a good place to start, but I don't really get that bloat part.  It loads in a matter of seconds, will open an exceptionally large project file in seconds, the compile times seem comparable to G++, the generated code is quite tight, the debugger is hands down the best debugger on any platform, ever.  About the only complaint I can think of is the few seconds of pause when running an application, but that's the price you pay for such amazing debugging.  Anyways, thats just my opinion on that subject.  Now the IDE vs text editor approach that has been argued since the first IDEs appeared, thats a different conversation.


But yeah, go ahead and use monodevelop, its a perfectly capable ide with the advantage of being able to work ( and consistently on ) on Windows, Mac and Linux, which is a nice perk.

As to if my tutorial would still be useful, thats a big fat sorta.  The setup portions obviously wouldn't be, but then .NET projects are a hell of a lot easier to configure than C++ so that is a lesser factor anyways.  The structure of my game however could be duplicated in C# and the code would look remarkably similar.  I actually code C++ in a very C#ish way, as that's been my primary language since it was released.  That said, there aren't too many tutorials out there on how to properly lay out a simple game, or design class hierarchies, etc... and that information will still be useful.  Additionally, the SFML calls will be nearly identical as well.  Obviously all the C++ specific bits will be mostly of no value if you go with C#.

Python or Lua are both perfectly valid options, although I would suggest Python over Lua simply because there is more documentation and help available for Python.  Lua was primarily created as a language to embed within other languages, although it has obviously grown beyond that purpose.  If it was me though, I would choose C#, but thats my personal bias again.  C# is the closest (mainstream) language to C++ but worlds more approachable.


As to the language differences, what you mentioned are some of the differences, but mostly as applied to Python/Lua vs C++.  C# is a strongly typed language, just like C++, although C# moved more towards weak typing with C# 4.  I personally think dynamic was a step in the wrong direction, but that's a argument well beyond the scope of this conversation.


The advantages to C# over C++ for a beginner are well beyond the scope of this conversation and a lot of it doesn't isn't necessarily core language features.  The C# build and configuration process is a world simpler than C++, there are no header files or preprocessor and the errors are a world easier to comprehend.  The first time you have to decode a C++ template error or warning, you will understand exactly what I mean.

Plus frankly the C# syntax, especially when dealing with templates vs generics, is a bunch easier to comprehend.  Plus the standard libraries are far superior, I don't think even the biggest C++ zealot would argue against that.  It also has a vastly run time support ( an advantage of running in a VM ), which benefits a developer in a number of ways, but the explanation of why are a bit premature.


I don't mean to make this into a C++ vs C# thread, by these are the reasons I think a programmer is better off learning with C#, especially if the syntax bothers you.
Title: SFML Complete Game Tutorial
Post by: kolofsson on October 22, 2011, 01:48:23 pm
Waiting for part 7, Serapth...  :wink:
Title: SFML Complete Game Tutorial
Post by: Serapth on October 24, 2011, 07:40:10 pm
Soon, soon I promise. ;)


I learned a valuable lesson to try and put this chapter together.

I can't teach math.  It simply can't be taught in a tutorial, the subject is too overwhelmingly massive and had I thought about this upfront I would have saved a ton of time! :)


Take for example this method ( from Pang7 )

float GameBall::LinearVelocityX(float angle)
{
   angle -= 90;
   if (angle < 0) angle = 360 + angle;
      return (float)std::cos( angle * ( 3.1415926 / 180.0f ));
}


It is straight forward enough, but seriously how the hell do you explain to someone WHY it works.  In order to do that you need to go waaaaayyyyyyyyyyyy back to early high school math and explain so many concepts.  You need to explain Radians, Cartesian coordinates, then you have to get into Pythagorean's theorem and work your way forward.  Simply put, it is wayyyy beyond the scope of a tutorial and I am frankly not expert enough in mathematics to do the subject justice.

Sadly I went looking for good resources to link on each specific subject ( velocity, rotation, etc... ) but couldn't find a consisive site, anyone have a good recommendation?


Anyways, I attempted to explain the math and well... that was not a very productive end.  The code is written though, just need to polish the much more stripped down blog post to go with it.  Again, soon.  I also took a brief detour to explore Google's recently released PlayN ( not ready for prime time ).  Unfortunately, I am easily distracted by shiny objects.

As I am operating on about 7 hours total sleep from all of last weekend, so soon is not today however. :)
Title: SFML Complete Game Tutorial
Post by: kolofsson on October 24, 2011, 09:09:44 pm
Ah, from your tutorial I just need the game framework. I'd like to write the engine myself, as I'm fairly good at maths. In my prior 2d racing project I had all the trigonometry and physics figured out. In fact, that is the most fun part of all, fiddling with the physical equations and then testing the effect it has on the car :D.

I don't know if you should teach maths in your tutorial. You don't teach general programming, do you? I like your tutorial, so far, because it's a missing ingredient of how to wrap SFML libs to make an organized game framework. But if you really wish to teach trigonometry, i think its not all that hard to comprehend. Seriously, what more needs to be said than this little infographic I made? :D

(http://grebocin.com/upload/trig.png)

By the way, I managed to compile PySFML2 and I'm overwhelmed by the simplicity of Python. For example, project is not kept in a file, you just open a folder and all files inside that folder are treated as part of the project. I love the language itself. In most cases there is only one right way of doing stuff, which is cool beacause understanding the code  is easier that way. The syntax is clean. I downloaded a PySFML asteroids game called Multitroids and the code looks really nice, I think the structure is similar to yours. I only hope that Python won't be too slow for the game I'm planning to make.
Title: SFML Complete Game Tutorial
Post by: Serapth on October 27, 2011, 05:46:02 pm
Ok, so I took my sweet time about it, but the next chapter is online.  The game ball is now animated and the game performs collisions and proper ricochets.  The chapter also discusses the topic of, and various types, of casts in C++.

Pang chapter 7 (http://www.gamefromscratch.com/page/Game-From-Scratch-CPP-Edition-Part-7.aspx)


Or if you are just starting out, start at the table of contents (http://www.gamefromscratch.com/page/Game-From-Scratch-CPP-Edition.aspx).

I promise the next chapter will be significantly quicker to be released! In fact a good portion of it is already done.
Title: SFML Complete Game Tutorial
Post by: ActionBoy on October 28, 2011, 08:58:34 pm
A great tutorial. Wish I found something like this 10 years ago. Keep up the great work and good luck to everything you do.
Title: SFML Complete Game Tutorial
Post by: Serapth on October 31, 2011, 05:53:43 pm
Oops, but of a bug crept in in PlayerPaddle, at the end change the "Bounce" test to :

Code: [Select]
if(pos.x  <= GetSprite().GetSize().x/2
|| pos.x >= (Game::SCREEN_WIDTH - GetSprite().GetSize().x/2))
{
_velocity = -_velocity; // Bounce by current velocity in opposite direction
}


It should have be <= and >=, otherwise on the condition of == 0, the paddle can get stuck to the wall.  Oops.[/code]
Title: I just wanted to say thank you.
Post by: sec_goat on November 10, 2011, 08:29:50 pm
This is an amazing tutorial that introduces the nuances of SFML as well as some really good (IMO) programming practices that I  have been trying to figure out for quite a while.

I am really learning a lot form this and have been looking for something like this for a long time. Can't wait for the next installments of this tutorial.
Title: SFML Complete Game Tutorial
Post by: Jany on November 11, 2011, 11:01:01 am
a really good tutorial! it helped me much to get into the SFML Library, and also i had fun reading and coding with it. =)

Waiting for Part 8 :)

Greetings Jany
Title: SFML Complete Game Tutorial
Post by: Serapth on November 11, 2011, 02:40:02 pm
Thanks for the kind words, they are very much appreciated.

The next two chapters are very much in the works and should be released soon.  To be completely honest I am not really sure how well the next chapter will be taken, as it goes off slightly into unexplored territory, which is why I am releasing two chapters at once... don't like it, skip it! ;)

I would have been done a while ago, but I got a bit distracted by PlayN (http://www.gamefromscratch.com/?tag=/PlayN), shiny new toys are always a major distraction for me!  All said though, I should have them up in the next couple days.  I have to, my Skyrim order arrives today...  ooooh Shiny!
Title: SFML Complete Game Tutorial
Post by: Serapth on November 14, 2011, 09:39:14 pm
Chapter 8 is now live and can be accessed here (http://www.gamefromscratch.com/page/Game-From-Scratch-CPP-Edition-Part-8.aspx) and the post summary is available here (http://www.gamefromscratch.com/post/2011/11/14/Game-From-Scratch-CPP-edition-chapter-8-is-now-live.aspx).


This chapter is a bit... different.  So far as I have ever seen, I have never really seen another game tutorial post like this one.  It covers using audio ( poorly ) and in fact shows how to use a library other than SFML ( sorry Laurent :) ) for audio, as an option anyways.  Most importantly, almost all of the code is absolute garbage.

Sound interesting? ;)


This chapter is more about design than code and if you are fairly new to programming in an OO style, I hope it is enlightening.

On the other hand, you may absoluely hate this chapter and want me to never go off track like this again.  Please read it and let me know which way you lean!


There is another post, one that shows how to more properly use SFML audio, so don't worry about that part.  It is nearly complete and should be live very shortly.
Title: SFML Complete Game Tutorial
Post by: P@u1 on November 14, 2011, 11:13:29 pm
I really like your tutorials.

In the last one I found a thing you should change:
Code: [Select]
#include <string.h>
should be
Code: [Select]
#include <string> instead.

If you include it with the .h it is not placed in the std:: namespace afaik.
Title: SFML Complete Game Tutorial
Post by: Serapth on November 15, 2011, 12:03:08 am
Quote from: "P@u1"
I really like your tutorials.

In the last one I found a thing you should change:
Code: [Select]
#include <string.h>
should be
Code: [Select]
#include <string> instead.

If you include it with the .h it is not placed in the std:: namespace afaik.




You are right, it should have been <string>, more to the matter, it shouldn't even be there.  I think its merely left overs from some code I was messing about with or possibly a code completion mistake...  I am a bit haphazard with my includes...  

Either way, its been updated.
Title: SFML Complete Game Tutorial
Post by: Laurent on November 15, 2011, 07:30:22 am
Quote
If you include it with the .h it is not placed in the std:: namespace afaik.

The C++ equivalent of a C header <xxx.h> is <cxxx>. So here, the C++ equivalent would be <cstring>, which includes functions such as memcpy, strcmp, strlen, etc.
<string> is totally different, it defines the std::string class.
Title: SFML Complete Game Tutorial
Post by: P@u1 on November 15, 2011, 05:17:23 pm
I know this, but in this case he wanted <string> and not <cstring>:
Code: [Select]

#pragma once

#include "stdafx.h"
#include <string.h>  //<----
#include "IAudioProvider.h"

class SFMLSoundProvider : public IAudioProvider
{
public:

  SFMLSoundProvider();

  void PlaySound(std::string filename);  //<----- here std::string is used
  void PlaySong(std::string filename, bool looping = false); //<----- here std::string is used
  ...
};


With <string.h> you probably get the completely wrong things (c-string utility function without std namespace, whereas you want std::string in std namespace), so you should #include <string>
It probably works anyway, because somewhere <string> is included, maybe even <string.h> includes it with msvc, although this would be quite strange.
Title: SFML Complete Game Tutorial
Post by: Serapth on January 01, 2012, 02:02:53 am
Part 9 is now online (http://www.gamefromscratch.com/page/Game-From-Scratch-CPP-Edition.aspx)


This part of the tutorial deals with playing sf::Music and sf::Sound objects using a (simple) caching system.  In addition it implements the AI paddle with some exceedingly stupid AI, although no collision detection.  Along the way it explores the C++ topics of exception handling and templates.



Next chapter we will be polishing things up a bit. fixing a flaw or two, adding a score board and will be much closer to a full game.  As always, any and all feedback appreciated.[/url]
Title: SFML Complete Game Tutorial
Post by: Neomex on January 01, 2012, 12:01:56 pm
Really nice job! I like it alot! :)
Title: SFML Complete Game Tutorial
Post by: Lee R on January 02, 2012, 12:47:27 am
Quote from: "Serapth"
Part 9 is now online (http://www.gamefromscratch.com/page/Game-From-Scratch-CPP-Edition.aspx)


I haven't looked at your code in any detail, but a quick look revealed at least four memory leaks. You're new'ing up exceptions (why?) but attempt to catch them by reference.
Title: SFML Complete Game Tutorial
Post by: Serapth on January 02, 2012, 02:17:44 am
Quote from: "Lee R"
Quote from: "Serapth"
Part 9 is now online (http://www.gamefromscratch.com/page/Game-From-Scratch-CPP-Edition.aspx)


I haven't looked at your code in any detail, but a quick look revealed at least four memory leaks. You're new'ing up exceptions (why?) but attempt to catch them by reference.




Oops.


The why is easy, it was a mistake.  :oops:


The why of the why is also easy, I've spent far too long using C#, and you develop a certain muscle memory when typing code...

Thanks for the catch, fixing.  One other potential leak was actually on purpose and will be resolved in the next chapter.
Title: State Machines
Post by: StormWingDelta on January 02, 2012, 05:53:53 am
I've got something useful for you Serapth if you can wrap your mind around what a state machine is.

http://
https://sites.google.com/site/onlinegameworkcjr/useful-things


The two things there those two files should help with the AI.
This code is from Digipen's game engine FunEditor1.5 so most of the codes in it are useless unless you know what you are doing.

The .txt file shows the code from the inside of a state machine I had to make for pong and I thought it might give you some ideas on how to fix up your AI in this game.

The other file is a code of the C# engine that they use in Microsoft Visual C++ 2010 Express and in mostly DirectX code if I remember right.  It has a few things that could be used to make a state machine in a compiler and has one already made and in use.  Just look for the state machine codes in these files and you should get some idea of how to make a state machine of some kind. :)


The only reason I have these things is because I'm in a game design class that has connections to Digipen. :)
Title: Re: State Machines
Post by: Serapth on January 02, 2012, 04:01:39 pm
Quote from: "StormWingDelta"
I've got something useful for you Serapth if you can wrap your mind around what a state machine is.

http://
https://sites.google.com/site/onlinegameworkcjr/useful-things


The two things there those two files should help with the AI.
This code is from Digipen's game engine FunEditor1.5 so most of the codes in it are useless unless you know what you are doing.

The .txt file shows the code from the inside of a state machine I had to make for pong and I thought it might give you some ideas on how to fix up your AI in this game.

The other file is a code of the C# engine that they use in Microsoft Visual C++ 2010 Express and in mostly DirectX code if I remember right.  It has a few things that could be used to make a state machine in a compiler and has one already made and in use.  Just look for the state machine codes in these files and you should get some idea of how to make a state machine of some kind. :)


The only reason I have these things is because I'm in a game design class that has connections to Digipen. :)


Thanks StormWingDelta, I will take a look.


It's not so much that AI is broken at this point; it simply hasn't been implemented.  At this point it is just a stub, I ran out of room.  Then again, in Pong, one of the keys to AI is actually making it stupid in believable ways, as frankly an AI controlled paddle will never miss.
Title: SFML Complete Game Tutorial
Post by: Razzeeyy on January 06, 2012, 04:38:11 pm
Hi guys (and girls if they are here :P).

First I want to thank the author for that perfectly done tutorial.

And also I want ask you about the collision detection? Is there any good tutorials and articles on that topic? I'm just starting to work on some simple but impressive (at least i think it is :P) 2D "racing - shooter" game, and I wonder how to detect collisions and build the interactions between more complicated objects.
But I'm only the beginner programmer and I have poor skills :P At least I'm trying to do something :D

(I will upload sources on github later, for now they are really butt-ugly :D)
Title: SFML Complete Game Tutorial
Post by: Serapth on January 06, 2012, 05:01:27 pm
Quote from: "Razzeeyy"
Hi guys (and girls if they are here :P).

First I want to thank the author for that perfectly done tutorial.

And also I want ask you about the collision detection? Is there any good tutorials and articles on that topic? I'm just starting to work on some simple but impressive (at least i think it is :P) 2D "racing - shooter" game, and I wonder how to detect collisions and build the interactions between more complicated objects.
But I'm only the beginner programmer and I have poor skills :P At least I'm trying to do something :D

(I will upload sources on github later, for now they are really butt-ugly :D)



It's not specifically a tutorial, but there is a code example for doing various collision tests, axis aligned bounding boxes and per pixel detection I believe, in this sites wiki ( EDIT: link (https://github.com/SFML/SFML/wiki/SourceSimpleCollisionDetection) ), that would probably be a good place to start.  That said, your game might be best served looking into Box2D (http://box2d.org/) for 2d physics.  Generally with the way graphics work these days, you never really want to work at the per-pixel level anymore.

Keep at it, we all start out lousy. :)


SOmetime in the future I may actually do a box2d/sfml tutorial.
Title: SFML Complete Game Tutorial
Post by: Razzeeyy on January 06, 2012, 05:41:39 pm
Quote from: "Serapth"
your game might be best served looking into Box2D (http://box2d.org/) for 2d physics


I don't want to use the box2d because I want to try writing physics and etc by myself.
And Thank You for that interesting link about  working with collisions in sfml! :)

Here is the current - draft state of my project: http://ompldr.org/vYzNvYw
It don't do much, but what it do for now is pretty interesting XD
I don't know if it works and compiles on windows (I'm develop on linux, and develop mainly for linux, coz I like linux :P).
But it should compile and run on windows due to SFML :)
Title: SFML Complete Game Tutorial
Post by: Nexus on January 07, 2012, 03:09:00 pm
Code: [Select]
sf::SoundBuffer mySound;
mySound.LoadFromFile("MySound.wav");
if(mySound)
  {
    sf::Sound sound;
    sound.SetBuffer(mySound);
    sound.Play();
  }
if (mySound) doesn't work, the loading statement should be inside the if. Furthermore, this code is problematic because the sound must be alive as long as it is played.

Maybe it's too advanced for that tutorial, but you could consider to use std::unique_ptr instead of manual memory management. That would often remove the need for destructors and deletes.
Title: SFML Complete Game Tutorial
Post by: StormWingDelta on January 07, 2012, 11:59:36 pm
Why not try a 3D form of Pong next with a third person view from just above and behind the player paddle? With a table and walls to make things interesting. :idea:


Just throwing out an idea where to go next when this one is done. :)
Title: SFML Complete Game Tutorial
Post by: Serapth on January 08, 2012, 12:12:51 am
Quote from: "Nexus"
Code: [Select]
sf::SoundBuffer mySound;
mySound.LoadFromFile("MySound.wav");
if(mySound)
  {
    sf::Sound sound;
    sound.SetBuffer(mySound);
    sound.Play();
  }
if (mySound) doesn't work, the loading statement should be inside the if. Furthermore, this code is problematic because the sound must be alive as long as it is played.

Maybe it's too advanced for that tutorial, but you could consider to use std::unique_ptr instead of manual memory management. That would often remove the need for destructors and deletes.



Truth told, I am not a big fan of how this section was done.  It was my intention to introduce the various pointer options at this point, but the chapter was already wayyyyyyyyy too long.   I intend to cover unique_ptr and auto_ptr, although it might be wise to skip auto_ptr completely with it's wonky as hell rules.


That's why I'm kinda looking forward to the next chapter, as I can use it to address various mistakes I've made, as well as cover a general mish mash of features.

Nice catch.
Title: SFML Complete Game Tutorial
Post by: Serapth on January 08, 2012, 12:13:27 am
Quote from: "StormWingDelta"
Why not try a 3D form of Pong next with a third person view from just above and behind the player paddle? With a table and walls to make things interesting. :idea:


Just throwing out an idea where to go next when this one is done. :)



Truth told, I am sooooooo sick of Pong at this point. ;)
Title: SFML Complete Game Tutorial
Post by: eot on January 10, 2012, 07:53:48 pm
I just found your tutorial and I'm going through it. It's been a while since I worked with C++ and I never really used static variables or functions much (well, at all really) so I'm just wondering about the use of the scope operator ("::"). You use it for the enum (GameState) that's defined inside the class (Game) even though the functions in which you use it belong to the very same class. Is that simply because those are static functions and they can be accessed without an instanced object of the class?

Maybe it's a dumb question but I've never seen that operator used like that before :P
Title: SFML Complete Game Tutorial
Post by: StormWingDelta on January 11, 2012, 03:43:05 am
I was going through part 6 and ended up with a strange error that I can't trace for some reason.



Code: [Select]

c:\documents and settings\roland.user-6fef0ae329\my documents\visual studio 2010\projects\sfml1p6testing\sfml1p6testing\game.h(31): error C2146: syntax error : missing ';' before identifier '_gameObjectManager'
c:\documents and settings\roland.user-6fef0ae329\my documents\visual studio 2010\projects\sfml1p6testing\sfml1p6testing\game.h(31): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
c:\documents and settings\roland.user-6fef0ae329\my documents\visual studio 2010\projects\sfml1p6testing\sfml1p6testing\game.h(31): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
c:\documents and settings\roland.user-6fef0ae329\my documents\visual studio 2010\projects\sfml1p6testing\sfml1p6testing\game.h(31): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int



I was going through the code and the only changes in mine are where I'm getting files from.
Title: SFML Complete Game Tutorial
Post by: FallenShard on January 11, 2012, 04:40:25 pm
I'm enjoying the tutorial, but I'm just wondering is there any difference between writing it starting from "Empty Project" rather than "Win32 Console Application"?
Title: SFML Complete Game Tutorial
Post by: Serapth on January 11, 2012, 11:08:53 pm
Without seeing your code, I'm willing to bet you have a rogue semicolon. Check each of your.h Files for a class definition closed with a semicolon. Sadly it could be any of them.


Quote from: "StormWingDelta"
I was going through part 6 and ended up with a strange error that I can't trace for some reason.



Code: [Select]

c:\documents and settings\roland.user-6fef0ae329\my documents\visual studio 2010\projects\sfml1p6testing\sfml1p6testing\game.h(31): error C2146: syntax error : missing ';' before identifier '_gameObjectManager'
c:\documents and settings\roland.user-6fef0ae329\my documents\visual studio 2010\projects\sfml1p6testing\sfml1p6testing\game.h(31): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
c:\documents and settings\roland.user-6fef0ae329\my documents\visual studio 2010\projects\sfml1p6testing\sfml1p6testing\game.h(31): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
c:\documents and settings\roland.user-6fef0ae329\my documents\visual studio 2010\projects\sfml1p6testing\sfml1p6testing\game.h(31): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int



I was going through the code and the only changes in mine are where I'm getting files from.
Title: SFML Complete Game Tutorial
Post by: Serapth on January 11, 2012, 11:11:00 pm
Quote from: "FallenShard"
I'm enjoying the tutorial, but I'm just wondering is there any difference between writing it starting from "Empty Project" rather than "Win32 Console Application"?


Not much. It creates a few files for you, main, stdafx and sets the subsystem to console.
Title: SFML Complete Game Tutorial
Post by: StormWingDelta on January 12, 2012, 12:41:19 am
Still can't find it.  I went through and compared your code to mine and I'm at a loss on this one.

http://
https://sites.google.com/site/sfmlworkscjr/sfmlfiles


The file labeled UnknownError has the code in it.  It should be easy to find errors like this one but I have no idea why I haven't spotted this one yet.
Title: SFML Complete Game Tutorial
Post by: Serapth on January 12, 2012, 01:05:26 am
Ahh, I think I've found your problem, I can't be certain because I am not running SFML2/CMake, so I can't test your project as posted.  That said, you have a definite no-no.


You have a #include "Game.h" in GameObjectManager.h, while having a #include "GameObjectManager.h" in Game.h, creating a circular dependency.

GameObjectManager.h should only include VisibleGameObject.h and nothing else.  Remove the #include "Game.h" from your GameObjectManager.h and the problem *might* go away.  


Generally what the error is saying is when it says "error C2146: syntax error : missing ';' before identifier '_something' " it generally means it doesn't know what somethings type is.
Title: SFML Complete Game Tutorial
Post by: StormWingDelta on January 12, 2012, 03:55:57 am
That's interesting and  :oops: .

I might have included it there for one reason or another because of something in one of the previous parts or there was something there that needed it at the time and I didn't move it to the other file.

It's where it should be now and not causing that loop anymore. :)

Funny how things can get forgotten with this much code and too bad the compiler isn't setup to mention these types of things rather then sending people on a wild goose chase for something that isn't the cause of the problem. :)



Thanks for the help.  The pong game on my end is up and running again.  I'm  going to go see if I can get Box2d into this to see what breaks this time. :)

The other things on that site were from other issues I was having that haven't been solved yet.  I'll start taking things off there that have been solved so people don't get confused. :)
Title: SFML Complete Game Tutorial
Post by: eot on January 12, 2012, 03:31:17 pm
Some short feedback:
There are a few instances where the names of the function arguments in the declarations don't match with the names in the function implementation. Specifically arguments of type sf::RenderWindow (off the top of my head you used 'rdw' 'window' 'renderWindow'). I know the compiler doesn't mind, but I think it's better to keep the names the same, especially in a tutorial.

Also, even though it gets long I think you should mention every change to every file you make in each part. Personally I re-write all the code instead of copy-pasting it and it gets harder to follow along when there are required changes that aren't mentioned. Take a look at how lazyfoo did his SDL tutorials.

Overall I think it's very good though  8) so thanks a lot.
Just needs a little bit of polish.
Title: SFML Complete Game Tutorial
Post by: Serapth on January 12, 2012, 03:50:15 pm
Quote from: "eot"
Some short feedback:
There are a few instances where the names of the function arguments in the declarations don't match with the names in the function implementation. Specifically arguments of type sf::RenderWindow (off the top of my head you used 'rdw' 'window' 'renderWindow'). I know the compiler doesn't mind, but I think it's better to keep the names the same, especially in a tutorial.


I wasn't aware I was even doing that, I did just look and found an example in VisibleGameObject.h, in the header I did:

virtual void Draw(sf::RenderWindow & window);

while in the implementation I did:

void VisibleGameObject::Draw(sf::RenderWindow & renderWindow)


Which I certainly shouldn't have done.  That said, parameter names in the definition are completely superfluous, they are ignored by the compiler and aren't required. This would have been equally valid:

virtual void Draw(sf::RenderWindow &);


I just personally find it easier to comprehend, especially when dealing with less obvious types, such as SomeFunc(int,int,char,int);


Anyways, you are right, that was a mistake on my behalf, but that's the explanation why the compiler doesn't complain, it really doesn't care about method names until implementation.

Quote

Also, even though it gets long I think you should mention every change to every file you make in each part. Personally I re-write all the code instead of copy-pasting it and it gets harder to follow along when there are required changes that aren't mentioned. Take a look at how lazyfoo did his SDL tutorials.


My thought when starting out was people would download the source each time or if not the "Click here to download Blah.cpp" links, an assumption that was very very wrong.  I figure from looking at stats, maybe 5 - 10% of people download the project files for each chapter.  So yeah, I really should have put more emphasis on the changes.

One of the big problems is, I take a long time between chapters and frankly forget what I've changed, especially when its a small one liner in Game.cpp or likewise.   Not saying you aren't right, I'm explaining why I kept doing it wrong! ;)   For future tutorials I am taking a much different route.  I need to find a good diff tool for VS.  One of the major downsides to Visual Studio Express ( which I've used for the tutorials ) is the lack of plugin support.

Quote

Overall I think it's very good though  8) so thanks a lot.
Just needs a little bit of polish.


You are welcome, hope it helped.
Title: SFML Complete Game Tutorial
Post by: krrice on January 14, 2012, 01:42:06 am
First I want to thank you for doing this tutorial there is no other like that I've been able to find.

I am using SFML 2 and everything has worked up until this point.I am on part 6 and I have had to do some minor changes to the code because you are using 1.6. The part i am stuck on is Game.cpp,you use sf::Input and 2.0 does not use it anymore now it is sf::Keyboard, sf::Mouse and I dont know how to change the code to make this work. If you or anyone else has any suggestions I would appreciate it.Here is the part of Game.cpp I am stuck on.

 
Code: [Select]


const sf::Input& Game::GetInput()
{
return _mainWindow.GetInput();
}


And this is PlayerPaddle.cpp / I know that in 2.0 its Keyboard and KeyPressed instead of key and IsKeyDown

Code: [Select]


void PlayerPaddle::Update(float elapsedTime)
{

if(Game::GetInput().IsKeyDown(sf::Key::Left))
{
this->_velocity-= 5.0f;
}
if(Game::GetInput().IsKeyDown(sf::Key::Right))
{
this->_velocity+= 5.0f;
}

if(Game::GetInput().IsKeyDown(sf::Key::Down))
{
this->_velocity= 0.0f;
}

if(_velocity > _maxVelocity)
this->_velocity = _maxVelocity;

if(_velocity < -_maxVelocity)
this->_velocity = -_maxVelocity;


sf::Vector2f pos = this->GetPosition();

if(pos.x  < GetSprite().GetSize().x/2
|| pos.x > (Game::SCREEN_WIDTH - GetSprite().GetSize().x/2))
{
_velocity = -_velocity; // Bounce by current velocity in opposite direction
}

GetSprite().Move(_velocity * elapsedTime, 0);
}
Title: SFML Complete Game Tutorial
Post by: krrice on January 14, 2012, 01:53:47 am
This is what I have changed but it still does not work.


Game.cpp
Code: [Select]


const sf::Keyboard& Game::GetInput()
{
return _mainWindow.GetInput();
}


PlayerPaddle.cpp
Code: [Select]

void PlayerPaddle::Update(float elapsedTime)
{
if(Game::GetInput().IsKeyPressed(sf::Keyboard::Right))
{
this->_velocity+= 5.0f;
}
if(Game::GetInput().IsKeyPressed (sf::Keyboard::Down))
{
this->_velocity= 0.0f;
}

if(_velocity > _maxVelocity)
this->_velocity = _maxVelocity;

if(_velocity < -_maxVelocity)
this->_velocity = -_maxVelocity;

sf::Vector2f pos =this->GetPosition();

if(pos.x <= GetSprite().GetSize().x/2
|| pos.x >= (Game::SCREEN_WIDTH - GetSprite().GetSize().x/2))
{
_velocity = -_velocity; // Bounce by current velocith in opposite direction
}

GetSprite().Move(_velocity * elapsedTime, 0);
}


I get a message in Game.cpp that sf::RenderWindow has no member GetInput[/code]
Title: SFML Complete Game Tutorial
Post by: Serapth on January 14, 2012, 04:15:49 am
I haven't ported to 2.0 yet but from my glances tonight, it looks like Keyboard has been added as a global static method, instead of accessed via GetInput() in the RenderWindow

So instead of using Game::GetInput() at all, now you do sf::Keyboard::IsKeyPressed().


So, you get rid of GetInput() completely from Game, and in the case of PlayerPaddle code like this:

 if(Game::GetInput().IsKeyPressed(sf::Keyboard::Right))


You do this:

 if(sf::KeyBoard::IsKeyPressed(sf::Keyboard::Right))
Title: SFML Complete Game Tutorial
Post by: krrice on January 14, 2012, 04:57:51 pm
Quote from: "Serapth"
I haven't ported to 2.0 yet but from my glances tonight, it looks like Keyboard has been added as a global static method, instead of accessed via GetInput() in the RenderWindow

So instead of using Game::GetInput() at all, now you do sf::Keyboard::IsKeyPressed().


So, you get rid of GetInput() completely from Game, and in the case of PlayerPaddle code like this:

 if(Game::GetInput().IsKeyPressed(sf::Keyboard::Right))


You do this:

 if(sf::KeyBoard::IsKeyPressed(sf::Keyboard::Right))


Thanks Serapth, I commented out the GetInput() from Game.cpp
and changed PlayerPaddle.cpp to if(sf::KeyBoard::IsKeyPressed(sf::Keyboard::Right)).It compiles fine now but now I have lost my paddle and ball maybe something simple.
Title: SFML Complete Game Tutorial
Post by: StormWingDelta on January 24, 2012, 04:45:10 pm
Just wondering when the next part is coming out since you mentioned soemthing to do with a nightmareish bug of some kind in the game loop.

Once that issue is worked out I'm planning on using the basic classes of this game for others when I figure out a few more things. :)

Aside from that it is good so far.  :D   :D
Title: SFML Complete Game Tutorial
Post by: Jove on January 25, 2012, 12:37:55 pm
Serapth, out of interest will you be providing a SFML2 compatible version to download at any point?

Regards.
Title: SFML Complete Game Tutorial
Post by: Serapth on January 25, 2012, 04:47:00 pm
@StormWingDelta, The bug isn't really all that dire, no worries, its a pretty simple fix, you can easily use this code as the basis for a future product.  It was actually something stupid that slipped in early and I just didn't review that code again.  ( It's the event loop ).

@Jove, I am going to actually do a post about porting to SFML, probably soon.  I won't do it for each chapter, but it should be clear enough to go from there.  What I will probably do is update the Part 2 solution, then part 9/10, so you can go with 2.0 from near the beginning or the end.  Updating all the middle ones though, just too much work.
Title: SFML Complete Game Tutorial
Post by: Jove on January 25, 2012, 05:48:07 pm
Thanks, I agree with what you say there.  I have converted it to the latest 2 snapshot, but it's acting a little crazy and I'm not sure why yet.
Title: SFML Complete Game Tutorial
Post by: Razzeeyy on January 26, 2012, 09:45:46 am
Serapth, Hi again.
I came back with couple of questions about collision (actually about response to collisions...) :D

So as far as you know I'm making the tank game...
The collision between tank and bullet was easy to made.
But the collision between tanks more complicated.

My Collision model is something like this:
1)Test Collisions in pairs through all objects
2) if collision happend, then execute Collide method of objects and pass references to the collided objects, one to another
3) objects decide on their own what to do on collision

This model is enough for bullets, but for collision between tanks.. em.. Should I pass the coordinates of obstacle or... something else?

I tried to make a 'simple' tank collision (just forcing the forward movement to act as backward on collision so we make step out of collision..) but I don't think this is an elegant solution.
Title: SFML Complete Game Tutorial
Post by: Serapth on January 26, 2012, 11:56:35 pm
Quote from: "Razzeeyy"
Serapth, Hi again.
I came back with couple of questions about collision (actually about response to collisions...) :D

So as far as you know I'm making the tank game...
The collision between tank and bullet was easy to made.
But the collision between tanks more complicated.

My Collision model is something like this:
1)Test Collisions in pairs through all objects
2) if collision happend, then execute Collide method of objects and pass references to the collided objects, one to another
3) objects decide on their own what to do on collision

This model is enough for bullets, but for collision between tanks.. em.. Should I pass the coordinates of obstacle or... something else?

I tried to make a 'simple' tank collision (just forcing the forward movement to act as backward on collision so we make step out of collision..) but I don't think this is an elegant solution.


Hi Razzeeyy,

Your solution seems reasonable.  You could implement this as another base class or interface ( ICollidable ) and do exactly what you discussed as another per frame action ( like Draw and Update now ), or within Update in GameObjectManager.

If you are passing in a reference to the object that collided with another object, why would you need to pass coordinates? You would already have access to them via the reference.
Title: SFML Complete Game Tutorial
Post by: Razzeeyy on January 27, 2012, 12:36:51 am
Serapth, oh yeah... that was stupid confuse about coordinates...
But I lack at math knowledge at this point :P so I can't model an elegant collision response model... Maybe you can advice me what to read on this topic?

BTW: If you want to take a look at current state of my project https://github.com/Razzeeyy/Re-tank-dev
The code organization (mostly) "inspired" by your great tutorial :)))
Title: SFML Complete Game Tutorial
Post by: Serapth on January 27, 2012, 03:36:05 pm
Quote from: "Razzeeyy"
Serapth, oh yeah... that was stupid confuse about coordinates...
But I lack at math knowledge at this point :P so I can't model an elegant collision response model... Maybe you can advice me what to read on this topic?

BTW: If you want to take a look at current state of my project https://github.com/Razzeeyy/Re-tank-dev
The code organization (mostly) "inspired" by your great tutorial :)))



Ill take a look through your code a bit later, I'm absolutely swamped right now.


But as for learning the required math, it's hard to be The Khan Academy ( http://www.khanacademy.org/ ).  They have video tutorials on EVERYTHING, and the few ive watched were extremely well done.  About 10x better than my OAC level math teachers, who I have a sneaking feeling didn't know shit.
Title: SFML Complete Game Tutorial
Post by: StormWingDelta on February 03, 2012, 02:24:04 am
Just wondering how to make an Array of sprites using the code for making sprites from the tutorial.  I'm setting up A* for path finding and need an array of sprites that can fill the map and not make more than I need.


Also do you happen to have a reusable Text Object making system yet?
I'm needing the same idea with the text objects.


I ran into an annoying problem when trying to use the static libs.  No matter what I did I kept getting errors any time I tried to use them and I had the SFML_STATIC in the right area. :(
Title: SFML Complete Game Tutorial
Post by: Razzeeyy on February 05, 2012, 02:18:07 pm
Quote from: "StormWingDelta"
Just wondering how to make an Array of sprites using the code for making sprites from the tutorial.  I'm setting up A* for path finding and need an array of sprites that can fill the map and not make more than I need.


Once I was making a sort of tile painter, and I used a map like that
std::map < sf::Vector2f, myObj* >

where is the sf::Vector2f was denoting the position of the object and the myObj* is a pointer to the object itself.

And then I just cycled trough the map and draw objects.

But I think it's messy solution... (but at least it works :P)
Maybe other people can offer a better way
Title: SFML Complete Game Tutorial
Post by: Nexus on February 06, 2012, 07:17:57 pm
Quote from: "Razzeeyy"
Maybe other people can offer a better way
If anyhow possible, I'd probably use a myObj instead of myObj*. This is problematic for polymorphic objects, but one approach is to use smart pointers like std::unique_ptr or specialized containers like boost::ptr_map...
Title: SFML Complete Game Tutorial
Post by: Serapth on February 06, 2012, 07:54:42 pm
Quote from: "Nexus"
Quote from: "Razzeeyy"
Maybe other people can offer a better way
If anyhow possible, I'd probably use a myObj instead of myObj*. This is problematic for polymorphic objects, but one approach is to use smart pointers like std::unique_ptr or specialized containers like boost::ptr_map...



I second this.  Actually unique_ptr is one of the areas I am going to address in the next chapter, I intend to replace the currently naked pointer used in the caching system.  Additionally, depending on your level setup, but if the size is known in advance, a good ole fashion 2D array might be your best bet.  Has minimally less overhead than using a map and is slightly less complicated.  Of course, your sizes are fixed in this situation.

@StormWingDelta, what are the errors you are receiving if you use static.
Title: SFML Complete Game Tutorial
Post by: StormWingDelta on February 22, 2012, 04:41:56 pm
Quote from: "Serapth"
Quote from: "Nexus"
Quote from: "Razzeeyy"
Maybe other people can offer a better way
If anyhow possible, I'd probably use a myObj instead of myObj*. This is problematic for polymorphic objects, but one approach is to use smart pointers like std::unique_ptr or specialized containers like boost::ptr_map...



I second this.  Actually unique_ptr is one of the areas I am going to address in the next chapter, I intend to replace the currently naked pointer used in the caching system.  Additionally, depending on your level setup, but if the size is known in advance, a good ole fashion 2D array might be your best bet.  Has minimally less overhead than using a map and is slightly less complicated.  Of course, your sizes are fixed in this situation.

@StormWingDelta, what are the errors you are receiving if you use static.


Don't remember the errors off hand so I'll have to look them up the next time I try to build my pong project with static libs.

In the meantime I've noticed a number of annoying things with the pong game that just seem off to me.

The first one is very noticeable in my version and that's when I go to the play state and than come out of it and go back into it.  The art and/or sprites don't load or they just aren't on the screen for some reason when I go back into the play state. It's like the game sprites are still in play state while the rest of the game isn't.

Next would be the AI tends to get stuck in walls when it gets too close and the reflection kicks in. The same thing happens to the player as well.

The other thing I've noticed is that any time I try to make changes to the game class I end up with more errors than I'd like. They all have something to do with it griping about incorrect declarations of some kind or another.

Aside from those things it is very good tutorial. :) Also when is part 10 coming out? :?:
Title: SFML Complete Game Tutorial
Post by: Serapth on February 22, 2012, 10:31:43 pm
Yeah, many of the annoyances should be addressed in the next chapter, whenever that is. :)

Quote
The other thing I've noticed is that any time I try to make changes to the game class I end up with more errors than I'd like.


There should be no real issues in changing the game code, so next time this happens, post the error that occurs and the code you added/changed.



As to disappearing sprites, they aren't actually disappearing, they are moving... very very very far.  The game no longer updates when showing the Menu, but SFML does, and this is where the "bug" is coming from.  Essentially each frame we are getting the elapsed time since the last frame which we then use to normalize movement the next frame.  The code assumes this number is always going to be a tiny fraction of a second, but this isn't true if we do something between drawing frames ( like hitting a break point or showing the menu ).


Any easy crude work around is to discard any deltas over a certain threshold.

So, in GameObjectManager, locate:
Code: [Select]

void GameObjectManager::UpdateAll()
{
std::map<std::string,VisibleGameObject*>::const_iterator itr = _gameObjects.begin();
float timeDelta = Game::GetWindow().GetFrameTime();
...


Add the line:
Code: [Select]

if(timeDelta > 0.1f) timeDelta = 0.0f;


Which basically says if more than 1/10th a second occurred between updates, 0 out the timeDelta, which will effectively cause no movement this update.  If there is a way to "reset" GetFrameTime() or to pause it in general, that would be a cleaner solution.

That will fix the disappearing sprite issues.
Title: SFML Complete Game Tutorial
Post by: Nexus on February 24, 2012, 05:55:07 pm
Quote from: "Serapth"
Yeah, many of the annoyances should be addressed in the next chapter, whenever that is. :)
I don't know whether it's a good idea to introduce bugs in chapters and fix them later. For some topics this can be meaningful because of the learning effect, but doing this too much gives the impression that your tutorial is incorrect. Maybe you had better fix them in the original code (given this doesn't complicate it as hell).

Quote from: "Serapth"
If there is a way to "reset" GetFrameTime() or to pause it in general, that would be a cleaner solution.
GetFrameTime() is a relict, it has been removed from SFML. You should use sf::Clock directly. By the way, even though this is out of scope for the tutorial, I have developped a StopWatch class which can be paused.

And StormWingDelta: If you only refer to the last sentence in a post, please only quote that last sentence. Full quotes are unnecessary and make the thread unreadable. Since the original post is just above, a quote is generally not required to understand the discussion.
Title: SFML Complete Game Tutorial
Post by: Serapth on February 25, 2012, 12:54:33 am
Quote from: "Nexus"
don't know whether it's a good idea to introduce bugs in chapters and fix them later. For some topics this can be meaningful because of the learning effect, but doing this too much gives the impression that your tutorial is incorrect. Maybe you had better fix them in the original code (given this doesn't complicate it as hell).



... yeah... intentional....  [[Wheres the whistle innocently gif???]]  Truth of the matter is, the way I did things, fixing a bug early on creates an absolute friggin nightmare for me, especially because I zip and share a compiled form of each chapters project, so if I change something in chapter 2, I need to propogate the change in chapters 2 thru 10, create and upload 9 8+ MB zips, then change all the source code examples where I expanded upon the code previously.

Quote
GetFrameTime() is a relict, it has been removed from SFML. You should use sf::Clock directly. By the way, even though this is out of scope for the tutorial, I have developped a StopWatch class which can be paused.


Tutorial is based on 1.6, where I though GetFrameTime was still the recommended way?  Trying to keep things the "out of the box" way as much as possible.  Got a link to your class, at the very least it would be useful to people reading this thread.

EDIT:  Nevermind, re the link, didnt see your sig while replying.
Title: SFML Complete Game Tutorial
Post by: Serapth on February 27, 2012, 06:26:38 pm
I just realized I made a small, but glaring omission wayyyyyyy back in part two! (http://www.gamefromscratch.com/page/Game-From-Scratch-CPP-Edition-Part-2.aspx).  Although I talked about pre-compiled headers and the use of stdafx, I forgot to include them in my write up!  This means you wouldn't have them if you weren't using the downloadable project.


This doesn't really sound like a big deal, until you realize that this is where all of the SFML includes are!   This explains some of the questions and problems people had early on and why downloading the full project fixed things.


Ooops.   :oops:


So, I've addressed this mistake so people following along in the future won't have this problem.  If you've run through the tutorial and ran into this problem...  this is why.  Considering #includes are one of the more confusing topics for beginner C++ programmers, this was a majorly stupid mistake on my behalf.  My apologies.
Title: SFML Complete Game Tutorial
Post by: Jove on March 05, 2012, 08:13:33 pm
Has anyone successfully converted the tutorial over to SFML2?

I have, but with a couple of strange issues.  In Debug I get an exception in SFML at:

Code: [Select]
void MutexImpl::Lock()
{
    EnterCriticalSection(&myMutex);
}


Similar error to some bad practices from me last year:
http://www.sfml-dev.org/forum/viewtopic.php?t=5654
(Nexus will be glad to hear I'm educating myself out of this!)


It seems to run in Release or from the .exe, but behaves very jittery indeed.

I also have another little project that uses some of the guts of Serapth's code along with the simple Image Manager tutorial on the Wiki. That too has these issues, better in Release than Pong, but still some odd things happen that don't make a lot of sense.
Title: SFML Complete Game Tutorial
Post by: Serapth on March 09, 2012, 08:53:28 pm
Quote from: "Jove"
Has anyone successfully converted the tutorial over to SFML2?

I have, but with a couple of strange issues.  In Debug I get an exception in SFML at:

Code: [Select]
void MutexImpl::Lock()
{
    EnterCriticalSection(&myMutex);
}


Similar error to some bad practices from me last year:
http://www.sfml-dev.org/forum/viewtopic.php?t=5654
(Nexus will be glad to hear I'm educating myself out of this!)


It seems to run in Release or from the .exe, but behaves very jittery indeed.

I also have another little project that uses some of the guts of Serapth's code along with the simple Image Manager tutorial on the Wiki. That too has these issues, better in Release than Pong, but still some odd things happen that don't make a lot of sense.



Hi Jove, read back earlier in the thread and there were a few people that successfully ported to 2.0, although I haven't really tried yet.

There is nothing in the project that should cause that error however.   If you are still searching for a needle in a haystack at this point, strip down your project  ( I do this so often I wrote a tool Project Cleaner (http://www.gamefromscratch.com/post/2011/08/25/Project-Cleaner.aspx) to do that job for me ), zip it up and send me a link and I will see if I can find your issue.
Title: SFML Complete Game Tutorial
Post by: Jove on March 10, 2012, 11:49:18 am
Thanks Serapth, PM sent.

If we solve this I'll post the solution, however shameful it may be ;)
Title: SFML Complete Game Tutorial
Post by: Serapth on March 10, 2012, 03:47:37 pm
Quote from: "Jove"
Thanks Serapth, PM sent.

If we solve this I'll post the solution, however shameful it may be ;)



I think I know your problem.  You need to use the same build settings on your SFML library compile as you do for your game project.  For example, if you compile the debug release to use multithread debug, you need to do the same when you build sfml.  Also, in your release version, you are linking to the static libraries. ( -s ), which is a no no with the settings you have.
Title: Re: SFML Complete Game Tutorial
Post by: BobDole on March 29, 2012, 03:46:16 pm
Nice, next part soon?
Title: Re: SFML Complete Game Tutorial
Post by: Serapth on March 30, 2012, 06:35:43 pm
Hopefully soon, been a bit hectic in these parts.
Title: Re: SFML Complete Game Tutorial
Post by: Serapth on April 26, 2012, 04:39:04 am
I've recently had some requests for a PDF version of this tutorial, which frankly will take some effort to create.  Just looking for a general consensus if it is worth my time to make such a thing, or is HTML good enough?
Title: Re: SFML Complete Game Tutorial
Post by: cotterall on April 30, 2012, 01:59:12 pm
I just want to thank you for writing these tutorials, they have helped me a great deal. I don't mind putting together the PDF version for you if you like.
Title: Re: SFML Complete Game Tutorial
Post by: Serapth on May 03, 2012, 12:21:32 am
That would be pretty awesome if you did!


On the topic of other people doing my work for me...  :)

Nathan is porting the source code from SFML 1.6 to 2.0, starting with chapter 6 ( before that it's pretty cut and paste ), so if you are interested in this tutorial in 2.0 form, check this out. (http://gamefromscratch.com/post/2012/05/02/Game-From-Scratch-CPP-Edition-(-Pang-)-being-ported-to-SFML-v2.aspx)

I will edit the originals to include 1.6 and 2.0 source downloads once he is completed.  For now, there is a starting point for 2.0 (RC).  Like the examples I provide, its download and go.
Title: Re: SFML Complete Game Tutorial
Post by: Jove on May 03, 2012, 11:51:58 am
Download linky is broken  :(
Title: Re: SFML Complete Game Tutorial
Post by: cotterall on May 03, 2012, 12:24:35 pm
The download link is case sensitive, it needs a capital P in the file name, this link should work:
http://www.gamefromscratch.com/downloads/pang/pang6/Pang6v2.zip

I'll start working on a PDF version of the tutorial.
Title: Re: SFML Complete Game Tutorial
Post by: Serapth on May 03, 2012, 02:41:53 pm
Thanks for the catch cotterall.

I've fixed the link... that was odd, I swore I tested it after posting.  Ill blame gremlins for that one.
Title: Re: SFML Complete Game Tutorial
Post by: Serapth on May 04, 2012, 10:27:35 pm
Part 7, 8 and 9 have now been ported to 2.0 as well. 

Detail link (http://www.gamefromscratch.com/post/2012/05/04/CPP-game-tutorial-(-Pang-)-chapters-7-8-and-9-updated-to-SFML-20.aspx)
Title: Re: SFML Complete Game Tutorial
Post by: Serapth on May 18, 2012, 05:54:52 pm
In response to a reader request, I just finished putting together one more part, this one covering compiling in release mode (http://www.gamefromscratch.com/page/Compiling-Pang-for-release-and-distribution.aspx).

It's part of the main tutorial series.  Essentially it covers building in release configuration, provides the required Visual Studio 2010 dlls and then covers what files need to be shipped with your game for someone else to play it.

If you are looking at distributing a 1.6 SFML game, even if you didn't run through my tutorial, this post should probably be of use to you.  Building the DLLs themselves is a bit problematic, thanks to the statically linked freetype library, which caused me one gigantic headache.  That is why I provided them in a zip.
Title: Re: SFML Complete Game Tutorial
Post by: dendroidking on April 18, 2017, 05:38:08 am
Amazing tutorial. Wish I found something like long time ago. Keep up the great work and good luck to everything you do.