cocos2dの使い方【実践】① 〜スプライト(sprite)を表示(レイヤー(layer),シーン(scene)の上に)〜
では,今回は実際に文字や画像を表示してみます。
HelloWorldプロジェクトを開き,HelloWorldLayer.mを開いてコードを追加してみましょう。
HelloWorldLayer.m
-(id) init { // always call "super" init // Apple recommends to re-assign "self" with the "super's" return value if( (self=[super init])) { // create and initialize a Label CCLabelTTF *label = [CCLabelTTF labelWithString:@"Hello World" fontName:@"Marker Felt" fontSize:64]; // ask director the the window size CGSize size = [[CCDirector sharedDirector] winSize]; // position the label on the center of the screen label.position = ccp( size.width /2 , size.height/2 ); // add the label as a child to this Layer [self addChild: label]; //追加項目① ←ここから //Label //Labelをtestlabelという名前で"test"という文字を"Marker Felt"というフォントで32のサイズで生成 CCLabelTTF *testLabel = [CCLabelTTF labelWithString:@"test" fontName:@"Marker Felt" fontSize:32]; //位置を決める testLabel.position = ccp(50, 50); //HelloWorldLayerに貼る [self addChild:testLabel]; //Sprite //Spriteをgazoという名前で"sakura.png"という画像で生成する。使用メモリを自動解放するautoreleaseをつける。 CCSprite *gazo = [[CCSprite spriteWithFile:@"sakura.png"] autorelease]; //位置を決める gazo.position = ccp(250, 250); //HelloWorldLayerに貼る [self addChild:gazo]; //ここまで ←ここまで . . . } }
今回やっていることは,上のHelloWorldのLabelの英語のコメントアウトをみればその通りなのですが,
一応日本語でも書いておきました。
実際入力するとこの通りです。
そして先ほど指定した桜の画像の"sakura.png"はこちらの素材から利用いたしましたので,これを
~/HelloWorld/Resources/sakura.png
として保存します。
その後,sakura.png をxcode内のHelloWorldLayer.mのしたあたりにあるResourcesにドラッグ&ドロップをして上の画像の通りになっていれば,左上のRunボタンを押してシミュレーターを起動します。
そして
次回はタッチ機能について説明します。