【Summary】(Cocos2d-x)Cocos2d-x初学,包括Director/Scene/Layer等的基本用法,触摸检测和碰撞检测

1.Cocos2d-x的几个核心类可以参照这个:https://blog.csdn.net/blackzhangwei/article/details/82555495

一般在AppDelegate::applicationDidFinishLaunching()中会对Director进行配置,包括分辨率设置,帧数等。

2.触摸检测
我写过的代码,可以参照一下

	auto contactListener = EventListenerPhysicsContact::create();
	contactListener->onContactBegin = CC_CALLBACK_1(GameScene::onContactBegin, this);
	_eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this);

	bool GameScene::onContactBegin(const PhysicsContact & contact)
{
	auto target = contact.getShapeA()->getBody()->getNode();
	if (target->getTag() == STAR)
	{
		gameMap->moveNode(target);
	}
	else if (target->getTag() == NPC && target->getPositionY() + 
		target->getContentSize().height / 2 < player->getPositionY())
	{
		gameMap->moveNode(target);
		addScore(150);
	}
	else if (target->getTag() == NPC && target->getPositionY() + 
		target->getContentSize().height / 2 >= player->getPositionY())
		gameOver();
	else if (target->getTag() == TOOL)
	{
		jumpTotal = 3;
		auto toolIcon = Sprite::create("accelerate_state.png");
		toolIcon->setPosition(Point(visibleOrigin.x + 180, 
			visibleOrigin.y + 50));
		this->addChild(toolIcon, 2);
		target->removeFromParent();
		addScore(300);
	}
	else {
		jumpTimes = 0;
	}

	//Turn back to running
	if (player->playerState == JUMP) {
		player->run();
	}

	return true;
}

3.触摸检测,也就是点击的功能,例子如下:

	auto touchListener = EventListenerTouchOneByOne::create();
	touchListener->onTouchBegan = CC_CALLBACK_2(GameScene::onTouchBegan, this);
	touchListener->onTouchEnded = CC_CALLBACK_2(GameScene::onTouchEnded, this);
	_eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);

	bool GameScene::onTouchBegan(Touch * touch, Event * event)
{
	auto touchPoint = touch->getLocation();
	if (slideBtn->getBoundingBox().containsPoint(touchPoint))
	{
		slideBtn->setTexture(slideBtnTextures.at(1));
		player->slide();
	}

	if (jumpTimes < jumpTotal && 
		jumpBtn->getBoundingBox().containsPoint(touchPoint))
	{
		if (isSound)
			SimpleAudioEngine::getInstance()->playEffect("jump.wav");
		jumpBtn->setTexture(jumpBtnTextures.at(1));
		player->jump();
		jumpTimes++;
	}

	return true;
}

void GameScene::onTouchEnded(Touch * touch, Event * event)
{
	auto touchPoint = touch->getLocation();
	if (slideBtn->getBoundingBox().containsPoint(touchPoint))
	{
		slideBtn->setTexture(slideBtnTextures.at(0));
		player->run();
	}

	if (jumpBtn->getBoundingBox().containsPoint(touchPoint))
	{
		jumpBtn->setTexture(jumpBtnTextures.at(0));
	}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值