第三十九天 一乐在其中—Android的小游戏打飞机(三)让子弹飞

             8月7日,小雨。“乳鸦啼散玉屏空,一枕新凉一扇风。睡起秋色无觅处,满阶梧桐月明中。”

        上篇已经让飞机随手指自由移动,本篇加载子弹和音效及背景音乐。

        本篇要用到的几个函数讲解:

       一、cocos2d的音效、背景音乐函数如下:

        1、SoundEngine.sharedEngine().playSound(Context ctxt, int resId, boolean loop)    

           用于播放背景音乐。

         2、SoundEngine.sharedEngine().playEffect(Context app,int resId)

                    用于播放音效,如子弹射击、碰撞、爆炸等音乐效果

            3、SoundEngine.sharedEngine().realesAllSounds();

       SoundEngine.sharedEngine().realesAllEffects();
                    清理所有的音效-Clean everything up

                    SoundEngine.purgeSharedEngine();

         完全关闭音响系统-Completely shut down the sound system

        二、单线程的定时器schedule

       schedule(String selector,float interval)

       第二个参数的意思是,每隔多少秒执行一次函数,记住,单位是秒。

    为了使游戏变得更加有趣,我们会随着时间连续不断地发射一些精灵出来。可以使用cocos2d的定时scheduler,并指定一个回调函数来完成此功能。一秒钟或半秒调用一次回调函数就可以了。

     三、action

      cocos2d里面提供了许多非常方便的内置的action,你可以使用这样action来让你的精灵动起来。比如move action,jump action,fade action,animation action(就是播放图片序列)等。这里,我们对目标对象子弹使用了3种类型的action:     

  • CCMoveTo: 我们使用CCMoveTo.action让子弹移动到屏幕的上端,直到移出屏幕。注意,这里我们可以指定这个过程要花费多长时间。这里使用了变化的时间间隔2-4秒。
  • CCCallFuncN: 它可以让你为某个执行此action的对象指定一个回调函数。我们指定的回调函数是:onBulletMoveToFinished。
  • CCSequence: 它允许我们把一系列的action组成一个action序列,并且这些acton可以按顺序执行。一次执行完所有的action。 

        四、MainActivity.java

package edu.eurasia.cocos2d_game03;

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 {

	// 创建一个view对象,cocos2d引擎会把图形绘制在该view对象上面
	private CCGLSurfaceView view = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// 不显示标题栏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// 设置当前程序全屏显示
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		// 设置不允许屏幕自动休眠
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		view = new CCGLSurfaceView(this);
		setContentView(view);

		// 获取导演对象
		CCDirector director = CCDirector.sharedDirector();
		// 设置游戏引擎画面的输出目标View
		director.attachInView(view);
		// 设置游戏是否显示FPS值
		// director.setDisplayFPS(true);
		// 设置游戏的刷新率 FPS = frame per second
		director.setAnimationInterval(1 / 60.0f);
		// 生成场景对象
		CCScene scene = CCScene.node();
		// 生成图层对象
		PlaneLayer layer = new PlaneLayer(this);
		// 将图层添加至场景当中
		scene.addChild(layer, 1);
		// 通知导演,运行场景
		director.runWithScene(scene);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		//清理所有的音效
		SoundEngine.sharedEngine().realesAllSounds();
		SoundEngine.sharedEngine().realesAllEffects();
		// 完全关闭音响系统
		SoundEngine.purgeSharedEngine();
	}

}
       五、 PlaneLayer.java
package edu.eurasia.cocos2d_game03;

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.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 {
	// 声明一个精灵对象
	private CCSprite plane;
	private CCDirector director;
	private CGSize winSize;
	private CGPoint offset;
	private boolean flag = false;
	// 定义子弹的速度为每秒500像素
	private float bulletSpeed = 500;
	private Context context;

	private List<CCSprite> bullets = new ArrayList<CCSprite>();

	public PlaneLayer(Context context) {
		super();
		this.context = context;
		// 设置当前图层是否接受触摸事件
		this.setIsTouchEnabled(true);
		director = CCDirector.sharedDirector();
		winSize = director.winSize();
		// 初始化精灵对象
		plane = CCSprite.sprite("p.png");
		// 设置精灵对象的位置
		plane.setPosition(CGPoint.ccp(winSize.width / 2, 200));
		this.addChild(plane);
		// 定时器schedule
		schedule("addBullet", 0.5f);
		// 背景音乐
		SoundEngine.sharedEngine().playSound(context, R.raw.game_music, true);
	}

	// 当用户开始触摸屏幕,执行该方法
	@Override
	public 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);
	}

	// 当用户手指离开屏幕时,执行该方法
	@Override
	public boolean ccTouchesEnded(MotionEvent event) {
		flag = false;
		return super.ccTouchesEnded(event);
	}

	// 当用户手指在屏幕移动时,执行该方法
	@Override
	public boolean ccTouchesMoved(MotionEvent event) {
		if (flag) {
			CGPoint point = director.convertToGL(CGPoint.ccp(event.getX(),
					event.getY()));
			point = CGPoint.ccpAdd(point, offset);
			plane.setPosition(point);
		}
		return super.ccTouchesMoved(event);
	}

	public void addBullet(float delta) {
		// 生成一个子弹精灵对象
		CCSprite bullet = CCSprite.sprite("bullet.png");
		// 将子弹对象添加至图层当中
		this.addChild(bullet);
		// 将新添加的子弹对象放置在bullets集合当中
		bullets.add(bullet);

		// 获得精灵的大小,getContentSize函数来获得节点原始的大小
		CGSize planeSize = plane.getContentSize();
		CGSize bulletSize = bullet.getContentSize();

		CGPoint initPos = plane.getPosition();
		// 子弹的y轴的初始位置
		initPos.y = initPos.y + planeSize.height / 2 + bulletSize.height / 2;
		bullet.setPosition(initPos);
		// 创建一个代表坐标的对象
		CGPoint targetPos = CGPoint.ccp(initPos.x, winSize.height);
		// 计算两个坐标点之间的距离,计算子弹运行的距离
		float distance = CGPoint.ccpDistance(initPos, targetPos);
		// 计算子弹运行的时间
		float t = distance / bulletSpeed;
		// 生成一个动画对象,让子弹移动到屏幕的上端
		CCMoveTo moveTo = CCMoveTo.action(t, targetPos);
		// 生成一个动作对象,该动作执行时,将会调用当前对象的onBulletMoveToFinished方法
		// CCCallFuncN:
		// 它可以让你为某个执行此action的对象指定一个回调函数。我们指定的回调函数是:onBulletMoveToFinished
		CCCallFuncN func = CCCallFuncN.action(this, "onBulletMoveToFinished");
		// CCSequence:
		// 它允许我们把一系列的action组成一个action序列,并且这些acton可以按顺序执行。一次执行完所有的action。
		CCSequence seq = CCSequence.actions(moveTo, func);
		// 通知精灵执行动作
		bullet.runAction(seq);
		// 子弹声效
		SoundEngine.sharedEngine().playEffect(context, R.raw.bullet);
	}

	public void onBulletMoveToFinished(Object sender) {
		if (sender instanceof CCSprite) {
			CCSprite sprite = (CCSprite) sender;
			// 将子弹对象从集合中移除
			bullets.remove(sprite);
			// 将子弹对象从屏幕中移除
			this.removeChild(sprite, true);

		}
	}

}
       六、 运行结果


                  源代码下载地址:http://download.csdn.net/detail/zwszws/7731459


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值