Cocos2d development and learning 6: A simple demo of the hamster game

Source: Internet
Author: User
Tags addchild

First, declare

1. The original game demo and resources are from the sub-Dragon Mountain of the blog home http://www.cnblogs.com/zilongshanren /. I strongly recommend this blog. If you are interested, you can view it on your own. There are a lot of materials.

2. I will upload a demo that works with the previous example and adds some home page menus, transition scenarios, and simple use of transition animations.

First of all, I have not been playing games, whether it is a j2-active or android.

That is, express and design the prototype of the next simplest game based on your own ideas,

The following content is based on the ground rat as an example.

In fact, when we develop an application or game, it is difficult to start with the lack of materials and resources, which leads to delay in our own operations, this also leads to the impulse to learn PS and AI.

The blog of Zilong mountain mentioned above provides both resources and source code. Of course, this is very helpful for you to start a game on your own at the early stage of your learning, and for you to complete a simple game on your own,

It is also of great significance and sense of accomplishment for beginners.

Okay. Let's talk about the subject.

Let's take a look at the number of hamster games.

1. Enter the game menu

Of course, the four tabs are just a simulation. Only the "Start new game" has a click listener. This interface and a simple menu are provided.

2. Click to enter the new game to enter the transition scenario

We know that there is a transitional scenario when we enter the game scenario after the menu is selected. First, it can help us solve the problem of high memory during scenario switching,

The second is to help me load the data required for the next scenario, and then jump to the game scenario after loading is complete, so as to avoid the visual latency and lag caused by data loading.

3. transition effect of a boring scenario

Game scenarios pushed from top to bottom

4. Formal game scenarios

Game scenarios are the most important part of the entire demo.

This part of the code logic may be a little different from those of Shan Ren.

Because I search for texturepacker on the Internet, that is, the texture set creation tool. At first I saw the tutorial of this tool, that is, the first article of the hamster.

(The next day I browsed his other blog posts and found that there is still another article about the hamster ~~~).

Then mountain people provided the basic resources for the entire game, so I decided to follow the game.

Now let's take a look at the distribution of elements on this interface.

1. The green grass in the background is actually divided into two parts by the circle half of the hole. At first I got the resource and looked puzzled. I divided the grass into two parts for Mao.

Later I learned that when your hamster came out, the whole hamster felt like it was in front of the lawn (the green area behind the hamster was covered), but when the mouse fell down,

How can this problem be solved? Of course we can use hidden attributes, but we all know that, whether it is set attributes or instant animation, moles are instantly lost,

What we want to do is to slowly move the mole down to the ground and use a delayed animation to go down to the ground. Then we can't say computing and tailoring the mouse. Let's take care of that part of the ground (I won't do it anyway ).

Therefore, the depth can be used to solve the masking problem.

// Add the lawn. Note that the depth parameter is mainly used when adding the lawn, because when there will be moles coming out, the depth of the genie should be, the front of a lawn, moles, cgsize winsize = [[ccdirector shareddire] winsize]; ccsprite * grassup = [ccsprite spritewithspriteframename: @ "grass_upper.png"]; grassup. position = cgpointmake (winsize. width/2, winsize. height/2); grassup. anchorpoint = cgpointmake (0.5, 0); [self addchild: grassup Z:-1]; ccsprite * grasslow = [ccsprite spritewithspriteframename: @ "grass_lower.png"]; grasslow. position = cgpointmake (winsize. width/2, winsize. height/2); grasslow. anchorpoint = cgpointmake (0.5, 1); [self addchild: grasslow Z: 1];

The z_order depth of moles is set to 0, which is the default state, so the masking scenario meets our needs.

2. Mole.

This is the most complex element. Here I design moles as an independent genie class.

Potential properties and behaviors of moles under analysis

1. whether the mouse is in the active state. This attribute is prepared for the mole to run out at intervals, that is, when we traverse all the hamsters, we can check whether the mouse is in the active state,

And decide whether to let him run on the ground.

2. Whether you are on the ground or not. This is an attribute that was added later. Because moles are only active and on the ground, and ridicule your 0. x seconds, you can beat it.

3. moles, a single spam, mocking your activity: You need to analyze the changes involved in this dispatch.

First, logic 1 is executed to let the mole go, so his activity attribute is activated-"drill down from bottom to ground-" ridicule attribute activation-"laugh at the animation

-"When ridicule ends, ridicule attributes cool-" lower ground action-"activity attributes cool-down. (Of course, you may not think of so many logic processing at the beginning. Try to solve it several times ).

-(void)popMole{    [self unschedule:@selector(popMole)];    [self stopAllActions];        CCAnimation* anim = [CCAnimation animationWithFrame:@"mole_laugh" frameCount:3 delay:0.2f];    CCAnimate* laughAn = [CCAnimate actionWithAnimation:anim];       CCCallFunc *setLaugh = [CCCallFunc actionWithTarget:self selector:@selector(setLaguhingU:)];    CCCallFunc *quitLaugh = [CCCallFunc actionWithTarget:self selector:@selector(quitLaguhingU:)];    CCMoveBy *up = [CCMoveBy actionWithDuration:0.5 position:ccp(0, self.contentSize.height)];    CCEaseInOut *es = [CCEaseInOut actionWithAction:up rate:5.0];    id moveDown = [es reverse];           CCCallFunc *endCall = [CCCallFunc actionWithTarget:self selector:@selector(keepQuiet)];    [self runAction:[CCSequence actions:es, setLaugh,laughAn, quitLaugh,moveDown, endCall, nil]];     }

4. When a dispatch is triggered, the attack will be triggered.

With the above, this is easy to understand. What can happen now is that the hamster laughed at you on it,

Beat it, okay, it's very simple. At this moment, stop his entire action sequence-> laugh at attribute cooling (for simplicity, I also cool down its activity attribute, but I want a good effect, it is best to cool down next to the ground)

-> After being beaten, the animation of an emoticons is pushed down slowly.

// Hit the mole-(void) thumpmole {[self stopallactions]; [self keepquiet]; ccanimation * anim = [ccanimation animationwithframe: @ "mole_thump" framecount: 3 delay: 0.2f]; ccanimate * thumps = [ccanimate actionwithanimation: anim]; Id thumac = [ccrepeatforever actionwithaction: thumps]; [self runaction: thumac]; [self schedule: @ selector (molehide :) interval: 0.2];}

3. There is nothing to say about the splitter in the game scenario, that is, refresh it when hitting the hamster. The specific refresh location will be mentioned below, as we all know.

4. Logic Control for game scenarios. The main logic scenario is to control the location of the hamster. The logic algorithm for this location is in the demo.

# Pragma mark mole start-(void) molestartpop :( cctime) dt {for (mole * mole in moles) {If (arc4random () % 3 = 0) {If (! Mole. Active) {mole. Active = yes; [mole popmole] ;}}}

Execute this method every DT second. The method traverses the mouse array that is always referenced in the current scenario.

Arc4random () % 3 returns 0 to 2 to determine whether it is equal to 0, that is, each hamster is selected as a 1/3 opportunity. After the selection, it determines whether it is underground, and then let him out of the ground.

Of course, we will soon find that this algorithm will cause problems (without hitting it). Sometimes many hamster holes are made, and most of the time there is not a hamster on the ground ~

According to our ideas or level design, it may be said that we want to keep at least N hamsters active in the entire scenario. In this case, we need to add a new array to save the underground hamster in the current scenario,

The traversal is taken out from this (n-number of active hamsters), and so on. Of course, it is a great system overhead to update the data in the fast array.

Here, we can use the demo to provide us with this method. After all, our purpose is to run the process.

I am confused about the exception. When I wrote this demo, I only wrote about adding play grass, and the FPS suddenly only had 30. I don't know what the situation is.

5. Hit listening for hamster in scenarios

In itself, I think this listener should be designed and placed in the rat's place by function, but then I will encounter a problem where the listener occurs in the hamster object, however, the reference of the score counter is in the scenario class.

It will be very troublesome to refresh the mouse after hitting it. Of course, there may be many solutions we can think of, One callback, one notification, and if you have read

In the previous chapters of "Learn iPhone and iPad cocos2d game development", we will mention a way to design the game scenario into a pseudo singleton. Then we get the object in the rat's place and operate on it.

The score generator refreshes.

Later, considering the simplicity of the game, we put the click event directly in the game scenario class.

- (void)registerWithTouchDispatcher{    [[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:NO];}

Register this listener first

Then

-(Bool) cctouchbegan :( uitouch *) touch withevent :( uievent *) event {// uitouch * Touch = [touches anyobject]; // cgpoint toucgpoint = [Touch locationinview: [Touch view]; cgpoint toucgpoint = [self converttouchtonodespace: Touch]; for (mole * mole in moles) {If (mole. islaguh) {// cgrect molerect = cgrectmake (mole. position. x-(mole. contentsize. width/2), // mole. position. y-(mole. contentsize. height/2), // mole. contentsize. width, // mole. contentsize. height); If (cgrectcontainspoint (mole. boundingbox, toucgpoint) {[mole thumpmole]; score ++; scorelabel. string = [nsstring stringwithformat: @ "% d mole hit", score] ;}} return yes ;}

The above code is very simple. It mainly refers to the conversion of coordinate points, cgpoint toucgpoint = [self converttouchtonodespace: Touch];

I didn't use this sentence at first, and found that when I clicked the mouse's head, the detected click point was not in the mouse's circle. The next day, I saw this article by the Mountain.

The second point is to judge whether there is a vertex in a rectangle. Of course, this is a direct method ~ '

Finally, remember to handle the Click Event and return YES, so that the distribution touch event will not be passed to the next layer.

Now, the entire simple game is complete.

Of course, I still can make a lot of improvements, because I have only been involved for a few days. To be honest, I don't know how to design the logic of a game framework,

After all, I had to take money to work for the company. I spent an afternoon Learning and coding this demo.

Last

1. When entering the game screen, you can add one more start, pause, and so on to control the button tag of the scenario logic method (I am the logic automatically executed several seconds after the scene enters)

2. If you are interested, you can narrow down the lawn, and then 3*4 = 12 hamster. Haha, this should be fun. However, in this way, you can package your resources for Western medicine,

In the free version of the TP tool, some images are watermark text ~~~~

3. The animation help class introduced in "Learn iPhone and iPad cocos2d game development" is very useful ~

4. You can set a group for loading and releasing game resources.

Nsstring * bgplist = @ "background. plist "; nsstring * fgplist = @" foreground. plist "; nsstring * spplist = @" sprites. plist "; nsstring * ssheet = @" sprites. PVR. CCZ "; // load the image resources required for the current scenario to the sprite frame cache [[ccspriteframecache cached] cached: bgplist]; [[ccspriteframecache sharedspriteframecache] cached: fgplist]; [[ccspriteframecache sharedspriteframecache] addspriteframeswithfile: spplist];

For example, I only need to pass in a tag parameter for the scenario I want to enter. The Group class Automatically releases the cache resources for the previous scenario and requires texture resources to load the next scenario.

5. Do it by yourself. I think it is more dynamic to do it with materials.

This is the demo resource address above.

Http://download.csdn.net/detail/nono_love_lilith/4443857

If you need to read the original version, you can go to the Zilong Mountain Blog

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.