View
219
Download
0
Embed Size (px)
Citation preview
More Game GUIand methods
This is where we left off
Input from the GUI
• We need to detect what the input is from the user:
• This is the Xbox controller code (it goes in the Update method of Game1.cs)
GamePadState gamePadState = GamePad.GetState(PlayerIndex.One);cannon.rotation += gamePadState.ThumbSticks.Left.X * 0.1f;
This is how it looks in the code
What is the thumbstick is sending the game program?
• Answer: Numbers– If you push the thumbstick left it will send a negative
number– If you push it right it will send a positive number
• We multiply it by 0.1f (a very small number that is a float) to make it a very small increment so that it looks like the cannon is moving smoothly.– Extra credit: do a one page report on floats– http://msdn.microsoft.com/en-us/library/b1e65aza
%28VS.71%29.aspx
And we need input from the keyboard (if not Xbox)
KeyboardState newState = Keyboard.GetState(); if(newState.IsKeyDown(Keys.Left)) { cannon.rotation -= 0.1f; } if(newState.IsKeyDown(Keys.Right)) { cannon.rotation += 0.1f; }
This is how it looks in the code
So now the cannon will spin
• And we really should lock down the rotationcannon.rotation = MathHelper.Clamp(cannon.rotation, -MathHelper.PiOver2, 0);
This is how it looks in the code.
Now run your game again and see what happens
• Does it spin?• Here is more info on the MathHelper class
– http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.mathhelper.aspx
– http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.mathhelper_members.aspx
– http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.mathhelper.clamp.aspx
– http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.mathhelper.piover2.aspx
Lets make the cannon shoot stuff
• We are going to use the GameObject.cs for the cannonballs– First we need to add 2 new fields for velocity and
whether or not the ball is alive or dead
Here it is in the code
And then initialize them in the constructor
velocity = Vector2.Zero;alive = false;
Here it is in the code
What does this do to the cannon?
• This question comes up because the cannon uses the same GameObject
• Answer: Nothing really– Since we are not using these new fields in the
cannon; it will not appear to be any different
A closer look at Attributes (also called fields)
Declaring Attributes(or fields) Reviewpublic class BankAccount {
private long accountID;private String name;private double balance;
Attributes are properties of objects, not local variables. (we will talk about types of variables later)
You should declare attributes near the top of the class. It is OK to declare attributes anywhere in the class (except inside a
method), but it makes them hard to find.
Attributes should normally be private or protected.
Declaring Attributes (2)public class BankAccount {
/** the account ID, a 10-digit number */private long accountID;/** the account name */private string name;/** the account balance, in Baht */private double balance;
Attributes are important! So, you should include some comments describing them.
Scope: Limiting AccessibilityThe attributes and methods of a class can be designated as:
public - can be used from any code. A public method can be called from any code that references an object. A public attribute can be assessed (or changed) from any code than references an object.
protected - can only be used from inside the class or inside a derived (child) class.
private - can only be used from inside the class.
Guidelines: Allow the outside program access only to the methods/data it needs to
perform its job. This is the "public interface" to the class. Methods that are part of the external interface are public;
everything else is private or protected. Attributes (state) should be private or protected. Although we did deviate
from this to keep our GameObject code lighter
A Closer look at Constructors
What the constructor does
• To set attributes when an object is created, you define a constructor.
• A constructor is called when an object is created, examples:
BankAccount ku = new BankAccount( );BankAccount ku = new BankAccount( "KU", 1234567890 );
Constructor• A constructor is a method that is called when a
new object is created.• A constructor has the same name as the class.• The constructor usually initializes the attributes
(state) of the object.public class BankAccount {
private long accountID;private String name;private double balance;/** constructor */public BankAccount( ) {
accountID = "unknown";balance = 0;
}
public double myMethod( ) {BankAccount acct;...acct = new BankAccount( );......
Constructor (2)• A class can have several constructors. The code will use the
one that matches the arguments in the "new" command.• If a matching constructor is not found, it is an error!
public class BankAccount {private long accountID;private String name;private double balance;/** constructor */public BankAccount( String aName, long id ) {
name = aName;accountID = id;balance = 0;
}
public double myMethod( ) {BankAccount acct;...acct = new BankAccount(
"T. Shinawat", 12345678);......
Writing Constructors (1)public class BankAccount {
private long accountID;private String name;private double balance;/* default constructor */public BankAccount( ) {
accountID = 0;name = "unknown";balance = 0;
}/* parameterized constructor */public BankAccount(String aname, long id) {
name = aname;accountID = id;balance = 0;
}
No return value -- not even "void" !
The default constructor doesn't have any parameters
Writing Constructors (2)public class BankAccount {
private long accountID;private String name;private double balance;/* default constructor */public BankAccount( ) {
accountID = 0;name = "unknown";balance = 0;
}/* a parameterized constructor */public BankAccount(String aname, long id) {
name = aname;accountID = id;balance = 0;
}
Initialize the attributes using parameter values
Parameterized Constructors:
A class can have many constructors, each with different parameters.
This is called overloading a constructor (over loading is good)
Writing Constructors (3)
/** default constructor */public BankAccount( ) {
this("unknown“, 0);}/* a parameterized constructor */public BankAccount(String aname, long id) {
name = aname;accountID = id;balance = 0;
}
Constructor can call another constructor.
A constructor can call another constructor using “this( … )”. “this(…)” must be the first statement in the constructor. This is useful for eliminating duplicate code.
What a class looks like
Structure of a Class// A Bank Account with deposit/withdrawpublic class BankAccount {
private long balance;private String accountNumber;private String accountName;private int homeBranch;
//create a new bank account objectpublic BankAccount( String
number, String name ) { }
/* deposit to account */public void deposit( long amount ) {
if(amount>=0) "Error: negative
deposit";balance += amount;
}
comment describes the class
Beginning of class definition, including accessibility
Attributes (fields) of the class
A constructor
A method with a parameter
Class Diagram for a BankAccount Class
BankAccount
nameaccountIDbalance
getBalance( )credit( double amount )debit( double amount )getName( )
A UML class diagram
The methods = what it DOES
The Class Name
The attributes or state = what it KNOWS
Specifying Visibility/Accessibility
BankAccount
- name- accountID- balance
+ getBalance( )+ credit(double amount)+ debit(double amount)+ getName( )
Public methods
The Class Name
Private attributes
Indicate accessibility in UML class diagrams using a prefix:+ public# protected- private
Generate the class diagram for the GameObject class
Right click on the class and go to View Class Diagram on the flyout menu
This is what it produces; this is what our GameObject class looks like
Ok so there seem to be objects and methods everywhere
• For example:– We used the Draw method of the SpriteBatch class– We used the Clamp method of the MathHelper
class
What is a Method?Programming view: a method is a function. It can return a value or not.
Design view: methods define the behavior of objects. Methods are the way by which objects communicate
// define a "deposit" behavior for a bank account.public class BankAccount {
private long balance; // acct balance attribute public void deposit( long amount ) {
balance = balance + amount;}
}
Invoking a MethodTo invoke the deposit method, you must use is as a behavior of a particular BankAccount object.Example:
// define a "deposit" behavior for a bank account.BankAccount myAcct = new BankAccount(“1111111");
// read some deposit datastring s = this.txtDepositAmount.Text;decimal money = Convert.ToDecimal(s);
// method: deposit the money in my accountmyAcct.deposit( money );
call "deposit" method of a BankAccount object
Writing a Method (1)A method consists of these parts.
// return the maximum of 2 double valuespublic double Max ( double a, double b ) {
if ( a > b ) return a;else return b;
}
Access Control:who can use this method?
Type of value returned by this method. "void" if nothing is returned.
Method Name
ParametersMethod
Body, with returned
value.
Scope of Methods• All methods (functions) must be
part of a class. • This avoids name conflicts.
Scope of Methods (2)• From inside of the class, you can refer to a method using just its
name.• From outside of the class, you must use a class name (static
methods) or object name (instance method) to call a method. – (We will go over the difference between static and instance methods later)
Visibility (Accessibility) of MethodsYou determine what objects or parts of the
program can access an object's methods.• private: method can only be invoked by objects of this class.• protected: method can be invoked by other code in the same package,
and by objects of this class and its subclasses.• public: method can be invoked by any program.
public void deposit( long amount ) {
/* body of the method */ }
visibility type of returned value. "void" if method doesn't return any value.
Returned Value of a Method
class BankAccount {
public void deposit(long amount) {balance += amount;}public long getBalance( ) { return balance; }
}
A method may return a value. The type of returned value must be declared in the method header.
A method which doesn't return any value should have a return type of "void".
In the method body, use "return <expression>".
void means this method does not return a value.
So lets make a method
• I think we would like to shoot cannonballs
First add the cannon balls; add these 2 fields
Load the cannon balls
Now we need a method to update the cannon balls; change the position etc so that it looks like the cannon is shooting
• Collapse the Update method so that you have more screen space• Here is the code: public void UpdateCannonBalls() { foreach (GameObject ball in cannonBalls) { if (ball.alive) { ball.position += ball.velocity; if (!viewportRect.Contains(new Point( (int)ball.position.X, (int)ball.position.Y))) { ball.alive = false; continue; } } }}
This is what it looks like in your code
Now we need to fire the cannonballsnote: this is the link to the reference of the Math class
http://msdn.microsoft.com/en-us/library/system.math_members%28VS.71%29.aspx
public void FireCannonBall() { foreach (GameObject ball in cannonBalls) { if (!ball.alive) { ball.alive = true; ball.position = cannon.position - ball.center; ball.velocity = new Vector2( (float)Math.Cos(cannon.rotation), (float)Math.Sin(cannon.rotation)) * 5.0f; return; } } }
Here it is in the code
It is time to use them
• We need to grab the current state of the game • We do that by comparing it with the previous
state
2 more fields at the top
Check the A button in the Update method
Check the space key(this also goes in the Update method)
Add the call to update the cannon balls; also in the Update method
Update the gamepad and keyboard states
Don’t forget to draw the cannon balls
Compile and see if you have errors
• You will probably have 2 (I did that on purpose)– Double click on the error and fix what is wrong.
Now run it and see if it works
Homework
• If you haven't already decided what your “enemies” are – then figure it out.– What are you going to shoot and why?
• Change out the cannon ball image