tima620のゆらぎ

「のlog.txt」を畳み、「の」が崩御し、「のはざま」をはさんだ後に生まれた「のゆらぎ」

Cocos2d-x勉強_弾を撃つよ

弾を撃とうよ。

http://www.cocos2d-x.org/wiki/Chapter_4_-_How_to_Fire_some_Bullets


と、やってなかったので僕らのヒーローを追加。
http://www.cocos2d-x.org/wiki/Chapter_2_-_How_to_Add_a_sprite

リソース内にPlayer.pngとProjectile.pngを入れておこうね。

HelloWorldScene.cpp

bool HelloWorld::init()
{
...
----ここから追加----
	CCSize winSize = CCDirector::sharedDirector()->getWinSize();
	CCSprite *player = CCSprite::create("Player.png", CCRectMake(0,0,27,40));
	player->setPosition(ccp(player->getContentSize().width/2, winSize.height/2));
	this->addChild(player);

	this->setTouchEnabled(true);
----ここまで追加----
	return true
}

----ここから追加----
void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event)
{
	// Choose one of the touches to work with
	CCTouch* touch = (CCTouch*)(touches->anyObject());
	CCPoint location = touch->getLocationInView();
	location = CCDirector::sharedDirector()->convertToGL(location);

	// Set up initial location of projectile
	CCSize winSize = CCDirector::sharedDirector()->getWinSize();
	CCSprite *projectile = CCSprite::create("Projectile.png",CCRectMake(0,0,20,20));
	projectile->setPosition(ccp(20, winSize.height/2));

	// Determinie offset of location to projectile
	int offX = location.x - projectile->getPositionX();
	int offY = location.y - projectile->getPositionY();

	// Bail out if we are shooting down or backwards
	if(offX <= 0) return;

	// Ok to add now - we've double checked position
	this->addChild(projectile);

	// Determine where we wish to shoot the projectile to
	int realX = winSize.width + (projectile->getContentSize().width/2);
	float ratio = (float)offY / (float)offX;
	int realY = (realX * ratio) + projectile->getPositionY();
	CCPoint realDest = ccp(realX, realY);

	// Determine the length of how far we're shooting
	int offRealX = realX - projectile->getPositionX();
	int offRealY = realY - projectile->getPositionY();
	float length = sqrtf((offRealX * offRealX) + (offRealY * offRealY));
	float velocity = 480/1; // 480pixels/1sec
	float realMoveDuration = length/velocity;

	// Move projectile to actual endpoint
	projectile->runAction(CCSequence::create(CCMoveTo::create(realMoveDuration, realDest), 
				CCCallFuncN::create(this, callfuncN_selector(HelloWorld::spriteMoveFinished)), NULL));
}
----ここまで追加----

HelloWorldScene.h

class HelloWorld : public cocos2d::CCLayerColor
{
public:
----ここから追加----
	void ccTouchesEnded(cocos2d::CCSet* touches, cocos2d::CCEvent* event);
----ここまで追加----
};

こんな感じ。


次はあたり判定ですかねー