【Cocos2d-x】画像のタッチ判定
【Cocos2d-x】画像のタッチ判定
今回は、配置した画像をタッチしたかどうかの判定について説明します。
前回の記事を参考に、シングルタップを有効にしてください。
その後は下記のように記述していってください。
//Spriteインスタンス作成 Sprite *_sprite;
_sprite = Sprite::create("buildman_logo.png"); //画像を左下に配置 _sprite->setPosition(Vec2(_sprite->getContentSize().width/2, _sprite->getContentSize().height/2)); this->addChild(_sprite);
タッチイベント内で画像をタッチしたか判定します。
//タッチ終了時の処理 void HelloWorld::onTouchEnded(cocos2d::Touch *pTouch, cocos2d::Event *pEvent) { //タッチ座標を取得 Vec2 location = pTouch->getLocation(); //画像のRect Rect spriteRect = Rect(_sprite->getPosition().x - _sprite->getContentSize().width/2, _sprite->getPosition().y - _sprite->getContentSize().width/2, _sprite->getContentSize().width, _sprite->getContentSize().height); if (spriteRect.containsPoint(location)) { log("画像をタッチしました。"); } }
これで、画像をタッチすると、”画像をタッチしました。”と、表示されます。
流れは、タッチ処理を有効にする→タッチ座標を取得→画像のRectを取得→ifで条件分岐、という感じです。
画像のタッチ判定は以上です。
この記事へのコメントはこちら