cocos2d-android——触摸事件

1、MainActivity

package com.njupt.touch01;

import org.cocos2d.layers.CCScene;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.opengl.CCGLSurfaceView;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

	//cocos2d引擎会把图形会知道在该view对象上
	private CCGLSurfaceView view = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		view = new CCGLSurfaceView(this);
		setContentView(view);
		
		
		CCDirector director = CCDirector.sharedDirector();//得到CCDirector对象
		/**
		 * 设置游戏程序的相关属性
		 */
		director.attachInView(view);//设置当前游戏程序中所使用的view对象
		director.setDisplayFPS(true);//设置游戏程序是否显示FPS值
		director.setAnimationInterval(1.0f/60);//设置游戏渲染一帧所需要的时间
		
		//生成一个游戏场景对象
		CCScene scene = CCScene.node();
	
		//生成布景层对象
		GameLayer gameLayer = new GameLayer();
		
		//将布景层对象添加至游戏场景中
		scene.addChild(gameLayer);
		
		//运行游戏场景
		director.runWithScene(scene);
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}



2、GameLayer

package com.njupt.touch01;

import org.cocos2d.actions.interval.CCJumpTo;
import org.cocos2d.layers.CCLayer;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.types.CGPoint;

import android.view.MotionEvent;

public class GameLayer extends CCLayer{

	//接受用户的触摸事件,首先必须对当前图层进行设置
	public GameLayer() {
		//黄色纸当前图层是否接受触摸事件
		this.setIsTouchEnabled(true);
	}

	//当用户开始触摸屏幕是,执行该方法
	@Override
	public boolean ccTouchesBegan(MotionEvent event) {
		
		float x = event.getX();
		float y = event.getY();
		
		
		//convertToGL(p1):将以左上角为原点的坐标转换成一左下角为原点的坐标
		CGPoint p1 = CGPoint.ccp(x, y);
		CGPoint p2 = CCDirector.sharedDirector().convertToGL(p1);
		
		System.out.println("p1.x: " + p1.x +",p1.y: " + p1.y);
		System.out.println("p2.x: "+ p2.x +",p2.y: " + p2.y);
		System.out.println("-------->began");
		return super.ccTouchesBegan(event);
	}

	//当用户手指离开屏幕时,执行该方法
	@Override
	public boolean ccTouchesEnded(MotionEvent event) {
		
		System.out.println("-------->end");
		return super.ccTouchesEnded(event);
	}

	//当用户手指在屏幕移动时,执行该方法
	@Override
	public boolean ccTouchesMoved(MotionEvent event) {
		
		System.out.println("-------->move");
		return super.ccTouchesMoved(event);
	}
	
	
}


你可能感兴趣的:(cocos2d-android——触摸事件)