LoginSignup
5
5

More than 5 years have passed since last update.

スプライトを使うサンプルコード(Cocos Code IDE, Lua言語)

Last updated at Posted at 2014-09-13

Cocos Code IDEを使ってLua言語でスプライトを使う方法をまとめました。

実行環境、IDE Cocos2d-xバージョン 言語
Cocos Code IDE Mac OS X 1.0.0-RC2 Cocos2d-x V3.2 Lua言語

サンプルコード

プロジェクトの新規作成で作成されるGameScene.luaのGameScene.create()を書き換えます。

画像ファイルからスプライトを作成して位置を指定、シーンに追加して表示します。

function GameScene.create()
    local scene = GameScene.new()

    local sprite = cc.Sprite:create("image.png")
    sprite:setPosition(100, 100)
    scene:addChild(sprite)

    return scene
end

画像ファイル名をimage.pngとしています。resディレクトリにimage.pngを置いておきます。

テクスチャから作成

local texture = cc.Director:getInstance():getTextureCache():addImage("texture.png")
local sprite = cc.Sprite:createWithTexture(texture, cc.rect(0, 0, 64, 64))

スプライトフレームから作成

local texture = cc.Director:getInstance():getTextureCache():addImage("texture.png")
local spriteFrame = cc.SpriteFrame:createWithTexture(texture, cc.rect(0, 0, 64, 64))
local sprite = cc.Sprite:createWithSpriteFrame(spriteFrame)    

スプライトを画面の中央に表示したい

local visibleSize = cc.Director:getInstance():getVisibleSize()
sprite:setPosition(visibleSize.width / 2, visibleSize.height / 2)

スプライトのサイズを取得

local size = sprite:getContentSize()
-- size.widthで幅、size.heightで高さがわかる

スプライトの位置を取得

local x = sprite:getPositionX()
local y = sprite:getPositionY()
-- または、
local pos = cc.p(sprite:getPosition()) -- pos.xとpos.yでX座標、Y座標がわかります。
-- または、
local x, y = sprite:getPosition()

拡大・縮小・回転・反転

-- 2倍に拡大
sprite:setScale(2.0)
-- X方向に半分に縮小
sprite:setScaleX(0.5)
-- 時計回りに45度回転
sprite:setRotation(45)
-- X方向に反転
sprite:setFlippedX(true)

シーンへ追加、削除

-- Zオーダーを指定してレイヤへ追加
scene:addChild(sprite, 10)
-- レイヤから削除
sprite:removeFromParent()

実際はレイヤーを作成してその上に配置することが多いでしょうが、レイヤーの場合でも同じです。

名前をつける

-- 名前をつける
sprite:setName("name1")
-- 名前をつけたスプライトを取得する
local name1Sprite = scene:getChildByName("name1")

タグをつける

-- タグをつける
sprite:setTag(10)
-- タグを指定してスプライトを取得する
local name1Sprite = scene:getChildByTag(10)

Z座標を指定する

sprite:setPositionZ(1)

表示・非表示

sprite:setVisible(true)

falseで非表示

透明度

-- 半透明
sprite:setOpacity(255/2)
-- 透明
sprite:setOpacity(0)

アンカーポイントの変更

-- 中央(デフォルト)
sprite:setAnchorPoint(0.5, 0.5)
-- 左上
sprite:setAnchorPoint(0, 1)

スプライト同士の交差を調べる

local result = cc.rectIntersectsRect(sprite1:getBoundingBox(), sprite2:getBoundingBox())

交差しているとtrueが返ります。

点がスプライトに含まれるかを調べる

local position = cc.p(100, 100)
local result = cc.rectContainsPoint(sprite:getBoundingBox(), position)

点がスプライトのバウンディングボックス内にあるとtrueが返ります。

スプライトに独自のデータを設定する

サンプルのソースを見ると、sprite.isPaused = falseなどとしていたので、適当にピリオドのあとにユーザー変数を作れるのだと思います。

パラパラ漫画のアニメーション

長くなるので別記事で 投稿予定 です。
投稿しました。パラパラアニメーション基本(Cocos Code IDE, Lua言語)を参照してください。

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5