iPhone Game Programming Tutorial Part 2- User Interaction, Simple AI, Game Logic

    February 18th, 2009 Posted by: - posted under:Tutorials

    Ok folks, here it is. The next tutorial in our iPhone game programming tutorial (sorry for the delay). Today, I will be discussing the basics of player interaction, simple game AI, and game logic. We will also be exploring how to do simple collision detection so we know when the ball hits a paddle. Per popular request, I will be adding “Challenges” to the bottom of the tutorials from now on to give some more advanced ideas for improvement. Let’s begin. Start by opening your code from part 1…

    User Interaction

    The first thing we will implement is user interaction. All we really want to do is move the paddle’s X location to the X location of the touch from the user. This will be a very simple implementation and could be much better (I will add this as a challenge at the bottom of the tutorial). Open iTennisViewController.m and add the following code.

    screenshot_01

    Just as we did in a previous tutorial, we are overriding the touchesMoved method. This will detect when the user “drags” their finger on the screen. First, I added the “else if” statement inside of touchesBegan that simply forwards all events to touchesMoved if the game is in a running state.

    The first 2 lines inside of touchesMoved simply detect the location of the user’s touch. Next, we need to create a new CGPoint from the X location of the touch and the Y location of the yellow racquet (player racquet). Objective-C won’t simply let us say racquet_yellow.center.x = location.x. This is probably because CGPoint is immutable (not editable).

    Finally, the center of the player’s racquet is set to our new location.

    Collision Detection

    *Update, the user Naren has pointed out a much simpler collision detection. The code has been updated to reflect it. Inside the gameLoop method of iTennisViewController.m add the following code

    screenshot_011

    So, Apple has provided us with a very handy methods to check if to object frames collide. Its called CGRectIntersectsRect. We simply hand this method the frame of our ball and racquet. When the ball collides with the racquet, we want to reverse its Y velocity. The next if statement is required because sometimes we get in a state where the ball gets “trapped” on a paddle bouncing back and for and not going anywhere. So, we want to ensure the ball’s velocity only gets reversed if it is front of each racquet. (Note, the NSlog is not needed, it was just for debugging)

    Simple Game AI

    Next, we are going to discuss how simple AI can be added to allow a computer player to play iTennis with you. Many of you might not know just how much is involved in a decent Artificial intelligence. I could go on and on with nerdy math, philosophy, heuristics and the like, but I’m not. I will show you some super NOOB, very easy to understand game AI. Basically, the computer will “watch” the ball and move in the direction of it in hopes of hitting it. Let’s get started…

    We first need to define a constant that will define how fast the computer player can move. Add the following define to the top of iTennisViewController.m

    picture-2

    As you start testing, you can adjust this number. This is basically defining how fast the computer player can move in order to get to the ball. The higher you make this number, the “better” the computer player will be. You could actually make your computer unbeatable if this number were high enough. Now, add the following code right under your collision detection code:

    picture-3

    The first “if” statement is to add some difficulty for the computer. It basically checks to see if the ball is on “his” side of the court. The computer will not move or respond to the ball unless it’s on his side. It could be omitted, but makes for a more interesting game. The next if statements check to see if the X coordinates of the center of the ball are different than the X coordinates of the center of the racquet. If the ball is to the right of the computer’s racquet, the X coordinate of the computer’s racquet is increased by kCompMoveSpeed. If the ball is to the left of the computer’s racquet, the X coordinate of the computer’s racquet is decreased by kCompMoveSpeed.

    It should now be clear how adjusting the kCompMoveSpeed variable, will affect the computer’s performance…

    Now, you can actually hit Build and Go to see the game in action. As you can see the computer responds to the ball and hits it most of the time. There is still one last piece to make the game fun. Scoring!

    Game Mechanics: Scoring

    Now, we need a way to keep score. This is actually some more simple collision detection. We are basically checking to see if the ball collides with the back walls. First, let’s define a few variables and a method. Open up iTennisViewController.h. Add the following highlighted code:

    picture-4

    We need integer representations of the score so we can add points when the player and the computer score. Also, we will need a function called reset that will be called to reset the ball to the center of the screen. Now we need to define one more variable. Add the following line to your defines at the top of iTennisViewController.m

    picture-5

    This variable is pretty self explanatory, but in case you didn’t catch on, it defines the amount of points needed to win. I just made it 5 for a quick game. Now, let’s check to see if a player or computer scored. Right after your AI code, add the following code:

    picture-6

    Ok, first we see 2 if statements. The are basically checking to see if the ball has hit/passed the top or bottom of the screen. If it passes the top, the player score gets incremented. If it passes the bottom, the computer score gets incremented. The next line contains a little bit of fanciness if you are new to programming. We are calling the reset function, but what is that expression we are passing to it?

    Well, if you look at the definition of reset, it takes a BOOL value that determines if the game is over. So this can either be true or false. We are simply passing true or false when the expression is evaluated. So, (player_score_value >= kScoreToWin) will evaluate to false when the player_score_value variable is less than 5. Once this variable reaches 5, it will return true and pass it into the reset function.

    Why do this? Well it saves us lines of code and complexity. So now you don’t have to do if(player_score_value >= kScoreToWin) ) [self reset:YES]; }else{[self reset:NO];} . make sense?

    Now, let’s define the reset function. Add the following method to iTennisViewController.m

    picture-7

    The first thing we do is pause the game. Remember pausing the game causes the “Tap to Begin” Message to Display. Next, we center the ball on the screen. If YES/true was passed in for the newGame variable, we need to do a few things. First, we check who won by comparing the computer and player scores. Next, we update the “tapToBegin” message to notify the player who won. You could add another label for this, but I am just recycling this one… Finally, we reset the player and computer scores to 0 because a new game is starting.

    If it is not a new game, we need to reset the tapToBegin message to display “tapToBegin”. This has to be done in case the message was altered to say “Player/Computer wins!”. Finally, we update the labels on the screen to reflect the new scores. Now you should be good to go…

    Click Build and Go and battle the computer in an epic game of iTennis! If you have any comments or questions, leave them here or . You can also download the source for this tutorial here

    As Promised, Here are some challenges

    • Improve on user interaction – Make it so when the user taps, the racquet moves towards the tap rather than moves directly to the tap location
    • Improve collision detection – When the ball hits the paddle, use some simple physics to make the speed of the paddle affect the speed (and direction) of the ball
    • Improve on the AI – add some randomness to your AI, make it attempt to “predict” where the ball is going to be
    • Improve Scoring – Make it used tennis scores 15, 30 , etc…
    • Improve scoring – Make it so you must win by 2 points

    Stay tuned for the next tutorial when I will be going over game audio, splash screen, about, and some other polishing… Happy iCoding!