1.屏幕触摸事件:
bool HelloWorld::init(){
//省略上一次的一些代码
this->schedule(schedule_selector(HelloWorld::usecreatesprite),2);//定时器this->setTouchEnabled(true);/CCLayer是可以相应点击对象的,默认情况是没开启的,我们通过this->setTouchEnabled(true)来设置是否接受触摸事件。
return true;
}
void HelloWorld::ccTouchesEnded(CCSet*pTouches,CCEvent*pEvent){ //点击事件所响应的函数
CCSize visiblesize=CCDirector::sharedDirector()->getVisibleSize();
CCTouch*touch=(CCTouch*)pTouches->anyObject(); //由于响应函数传过来时一个集合,我们要从中先取出一个点
CCPoint locatpoint=touch->getLocationInView(); //获取单机坐标基于2D,是以左上角为原点。
CCPoint loc=CCDirector::sharedDirector()->convertToGL(locatpoint); //获取单机坐标,基础Cocos2d
//计算发射目标的最终坐标算法(利用精灵坐标(20,visiblesize.height/2),点击坐标(loc.x,loc.y),和发射精灵可经过的最大路程也就是窗口的对角线长度D,然后用相似三角形原理求出发射精灵的最终坐标(endx,endy))
double x=loc.x-20;
double y=loc.y-visiblesize.height/2;
double d=sqrt(x*x+y*y);
double D=sqrt(visiblesize.width*visiblesize.width+visiblesize.height*visiblesize.height);
double ratio=d/D;
double endx=x/ratio+20;
double endy=y/ratio+visiblesize.height/2;
//创建发射精灵
CCSprite* fire=CCSprite::create("1.png");
fire->setPosition(ccp(20,visiblesize.height/2));
this->addChild(fire);
//创建发射精灵动作
CCMoveTo*move=CCMoveTo::create(1.0f,ccp(endx,endy));
CCCallFuncN*disappear=CCCallFuncN::create(this,callfuncN_selector(HelloWorld::selfdefine));
CCSequence*action=CCSequence::create(move,disappear,NULL);
fire->runAction(action)
}
效果图: