Game Development Reference
In-Depth Information
much more. So, in order to make everything clearer, we use methods to separate
instructions into chunks that belong together.
In C#, you can add an arbitrary number of methods to your class. Of course, it
is a good idea to think beforehand about how you want to structure your instruc-
tions into methods. Some of these methods are required by the framework and their
header cannot be changed, such as the Main method in your application class. Other
methods can be fully designed by yourself. When you add a method to a class, think
about why you do it. For example, it would probably not be very useful to add a
method that loads the background sprite, because that method would only contain
one instruction and we can just as well write that instruction directly. Furthermore,
this method would solve only one very specific problem (loading the background
sprite) and it would be called only once.
It is a good idea to group instructions together that have some logical connection,
such as the instructions that handle all the input, or instructions for drawing sprites
on the screen. Finally, when you have created your own method, give it a logical
name. The name HandleInput gives an idea of what this method is doing. If you name
your method ILikeMashedPotatoes then, although we would have some insight into
your food preferences, it would be very difficult later on to deduce what the method
is actually doing.
7.2.3 Different Kinds of Methods: With or Without Parameters,
with or Without a Result
We have seen and used already quite a few different kinds of methods. For example,
there is a clear difference between the Update method in our class, and the HandleInput
method: the latter one does not have any parameters, whereas the first one does (the
game time). Additionally, some methods can have a result object that can be used
in the instruction that does the method call, for example, by storing the result in a
variable:
currentKeyboardState = Keyboard.GetState();
Here, we call the GetState method from the Keyboard class, and we store its result
in the member variable currentKeyboardState .The HandleInput method does not pro-
vide a result that we can store in a variable. Of course, the method does have an
effect of some sort, since it interprets the input from the player and changes the
member variables accordingly. However, when we talk about the result of a method ,
we do not mean that the method has some effect on an object. We mean that the
method call returns a value that can be stored in a variable. This is also called
the return value of a method. In mathematics, it is quite common that a method
(or: 'function' in mathematics) has a result. A mathematical function f(x)
x 2
takes as parameter an x -value and it returns its square as a result. We could ac-
tually write this mathematical function in C# as a part of our class if we wanted
to:
=
 
Search WWH ::




Custom Search