August 9, Sunny. "The River is like a picture, the mountain Xiao Wang clear sky." The rain is in the mirror and the Rainbow Falls. Inhabited by cold Orange pomelo, Autumn old Indus. "
The previous article has let airplanes loaded bullets and sound and background music, this article mainly add enemy aircraft .
Some of the functions to be used in this article are explained:
1, voidsettag (int nTag) sets the tag of the action.
2. The ccrandom_0_1 () function generates a random number between [0, 1] and a number ccrandom_0_1 * 100 between [0-100] to generate [ 1,5], which is ccrandom_0_1 * 4 + 1.
3, Sprite.getcontentsize get the rectangle area of the Elves wide, high. Gets the original size of the node, just the logical size, not the pixel.
Float initx = (winsize.width-sprite.getcontentsize (). width) * ccmacros.ccrandom_0_1 () + Sprite.getco Ntentsize (). Width/2;
indicates that the enemy aircraft is anywhere on the x-axis, Sprite.getcontentsize (). WIDTH/2 is to prevent the appearance of half enemy aircraft .
一、Mainactivity.java
Package Edu.eurasia.cocos2d_game04;import Org.cocos2d.layers.ccscene;import Org.cocos2d.nodes.ccdirector;import Org.cocos2d.opengl.ccglsurfaceview;import Org.cocos2d.sound.soundengine;import Android.os.Bundle;import Android.app.activity;import Android.view.window;import Android.view.windowmanager;public class MainActivity extends Activity {//Create a View object, the Cocos2d engine draws the graphic above the View object private Ccglsurfaceview view = null; @Overrideprotected void OnCreate ( Bundle savedinstancestate) {super.oncreate (savedinstancestate);//Do not display the title bar requestwindowfeature (window.feature_no_ TITLE);//Set Current program full-screen display GetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//settings do not allow the screen to automatically hibernate GetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_ KEEP_SCREEN_ON,WINDOWMANAGER.LAYOUTPARAMS.FLAG_KEEP_SCREEN_ON); view = new Ccglsurfaceview (this); SetContentView ( view);//Get Director Object Ccdirector Director = Ccdirector.shareddirector ();//Set the game engine screen output target viewdirector.attachinview (view);// Set whether the game shows FPS value//diRector.setdisplayfps (TRUE);//Set the game's refresh rate FPS = Frame per seconddirector.setanimationinterval (1/60.0f);//Generate Scene Object Ccscene Scene = Ccscene.node ();//Generate Layer object Planelayer layers = new Planelayer (this);//Add layer to scene scene.addchild (layer, 1);//Notify Director, Run scenario Director.runwithscene (scene);} @Overrideprotected void OnDestroy () {Super.ondestroy ();//Clear all sound effects soundengine.sharedengine (). Realesallsounds (); Soundengine.sharedengine (). realesalleffects ();//completely turn off the sound system soundengine.purgesharedengine ();}}Second, Planelayer.java
Package Edu.eurasia.cocos2d_game04;import Java.util.arraylist;import Java.util.list;import Org.cocos2d.actions.instant.cccallfuncn;import Org.cocos2d.actions.interval.ccmoveto;import Org.cocos2d.actions.interval.ccsequence;import Org.cocos2d.config.ccmacros;import Org.cocos2d.layers.CCLayer; Import Org.cocos2d.nodes.ccdirector;import Org.cocos2d.nodes.ccsprite;import Org.cocos2d.sound.soundengine;import Org.cocos2d.types.cgpoint;import Org.cocos2d.types.cgrect;import Org.cocos2d.types.cgsize;import Android.content.context;import Android.view.motionevent;public class Planelayer extends Cclayer {//Declare a Sprite object private Ccsprite plane;private ccdirector director;private cgsize winsize;private cgpoint offset;private boolean flag = false;// The speed of the righteous bullets is 500 pixels per second private float bulletspeed = 500;private Context context;private list<ccsprite> bullets = new Arraylis T<ccsprite> ();p rivate list<ccsprite> enemies = new arraylist<ccsprite> ();p rivate static final int E1_ TAG = 1;private STATic Final int e2_tag = 2;public Planelayer (context context) {super (); This.context = context;//Sets whether the current layer accepts touch events This.setisto Uchenabled (true);d Irector = Ccdirector.shareddirector (); winsize = Director.winsize ();//Initialize Sprite object plane = Ccsprite.sprite ("P.png");//Set the position of the Sprite object Plane.setposition (CGPOINT.CCP (WINSIZE.WIDTH/2,)); This.addchild (plane); /timer schedule, add bullets, call once every 0.5 seconds schedule ("Addbullet", 0.5f);//Add enemies, call once every second schedule ("Addenemy", 1f);// Background music Soundengine.sharedengine (). PlaySound (Context, r.raw.game_music, true);} When the user starts to touch the screen, execute the method @overridepublic Boolean Cctouchesbegan (Motionevent event) {Cgpoint point = DIRECTOR.CONVERTTOGL ( CGPOINT.CCP (Event.getx (), Event.gety ())); CGRect rect = Plane.getboundingbox (); flag = Cgrect.containspoint (rect, point); if (flag) {offset = Cgpoint.ccpsub ( Plane.getposition (), point);} Return Super.cctouchesbegan (event);} When the user finger leaves the screen, the method @overridepublic Boolean cctouchesended (Motionevent event) {flag = False;return super.cctouchesended (event);} This method is executed when the user's finger moves on the screen @overridepublic boolean cctouchesmoved (Motionevent event) {if (flag) {Cgpoint point = DIRECTOR.CONVERTTOGL (CGPOINT.CCP ( Event.getx (), Event.gety ()));p oint = Cgpoint.ccpadd (point, offset);p lane.setposition (point);} Return super.cctouchesmoved (event);} public void Addbullet (float delta) {//Generate a bullet Sprite object ccsprite bullet = Ccsprite.sprite ("Bullet.png");// Add the Bullet object to the layer This.addchild (bullet);//Place the newly added bullet object in the Bullets Collection Bullets.add (bullet);//Get the size of the sprite, Getcontentsize function to get the original size of the node cgsize planesize = Plane.getcontentsize (); Cgsize bulletsize = Bullet.getcontentsize (); Cgpoint Initpos = Plane.getposition ();//The initial position of the y-axis of the bullet Initpos.y = initpos.y + PLANESIZE.HEIGHT/2 + Bulletsize.height/2;bu Llet.setposition (Initpos);//Create an object that represents coordinates cgpoint Targetpos = CGPOINT.CCP (initpos.x, winsize.height);//calculates the distance between two coordinate points, Calculate the distance the bullet runs from float distance = cgpoint.ccpdistance (Initpos, Targetpos);//Calculate the time a bullet runs float t = distance/bulletspeed;//generate an animated pair Like, let the bullet move to the upper end of the screen ccmoveto moveTo = ccmoveto.action (t, targetpos);//Generates an Action object that, when executed, invokes the current object's OnbulletmoveTofinished method//cccallfuncn://It allows you to specify a callback function for an object that executes this action. The callback function We specify is: ONBULLETMOVETOFINISHEDCCCALLFUNCN func = cccallfuncn.action (This, "onbulletmovetofinished");// ccsequence://it allows us to make a series of actions into an action sequence, and the action can be executed sequentially. Execute all action at once. Ccsequence seq = ccsequence.actions (MoveTo, func);//notify Sprite to perform action bullet.runaction (SEQ);//Bullet Sound effect soundengine.sharedengine () . Playeffect (context, r.raw.bullet);} public void onbulletmovetofinished (Object sender) {if (sender instanceof Ccsprite) {ccsprite sprite = (ccsprite) sender;// Remove the bullet object from the collection Bullets.remove (sprite);//Remove the Bullet object from the screen This.removechild (Sprite, True);}} public void Addenemy (float delta) {String imgname = "e1a0.png"; int tag = e1_tag;//generates a random number between [0, 1] float ran = ccmacros.cc Random_0_1 (); if (ran > 0.8) {imgname = "e2a0.png"; tag = E2_tag;} Generates a Sprite object representing the enemy aircraft ccsprite sprite = Ccsprite.sprite (imgname);//Set the action's tag sprite.settag (tag);//Add enemy aircraft to the current layer This.addchild ( sprite);//Place the newly added enemy object in the Benemies collection Enemies.add (sprite);//calculate the initial position of the enemy plane float inity = winsize.height + Sprite. Getcontentsize (). Height/2;float Initx = (Winsize.width-sprite.getcontentsize (). width) * Ccmacros.ccrandom_0_1 () + Sprite.getcontentsize (). width/2;//creates an object that represents coordinates cgpoint Initpos = CGPOINT.CCP (INITX, inity);// Set the position of the enemy aircraft sprite.setposition (INITPOS);//Calculate the end position of the enemy aircraft run float Targetx = initx;float targety =-sprite.getcontentsize (). height/2;//creates an object that represents coordinates cgpoint Targetpos = CGPOINT.CCP (Targetx, targety);//Calculates the time that the enemy aircraft is running float t = 3 * CCMACROS.CCRANDOM_0_1 ( + 2;//generates MoveTo object for moving enemy aircraft ccmoveto moveTo = ccmoveto.action (t, Targetpos); CCCALLFUNCN func = cccallfuncn.action (This, "onenemymovetofinished"); Ccsequence seq = ccsequence.actions (MoveTo, func);//notify Sprite to perform action sprite.runaction (SEQ);} public void onenemymovetofinished (Object sender) {if (sender instanceof Ccsprite) {ccsprite sprite = (ccsprite) sender;// Remove the Enemies.remove (Sprite) from the collection of enemy aircraft flying out of the screen;//Remove the enemy object from the screen This.removechild (Sprite, True);}}} 三、Run Results
Source: