Chào các anh chị, mình đang làm 1 Game SpaceShip bằng cocos2dx và đang gặp phải 1 vấn đề khó hiểu ở phần Sprite và SpriteBatchNote.
Mình có 1 class MissionScene, trên này mình sẽ tạo 1 phi thuyền (Ship) bằng hàm CCSprite và kết hợp CCSpriteBatchNode, chạy ngon lành. Nhưng sau đó mình tạo 1 class Ship base từ class CCSprite, sau đó trở lại class MissionScene, thay vì tạo Ship từ CCSprite mình tạo Ship từ class Ship, và xảy ra lỗi khi chạy "CCSprite is not using the same texture id"
Đây là đoạn code đầu tiên mình tạo Ship trên MissionScene bằng class CCSprite
void MissionScene::createPlayerShip(){
auto shipBatch = SpriteBatchNode::create("PlayerShip.png", 40);
SpriteFrameCache::getInstance()->addSpriteFramesWithFile("PlayerShip.plist");
auto ship = Sprite::createWithSpriteFrameName("PlayerShip0.png");
this->addChild(shipBatch);
shipBatch->addChild(ship);
}
Và đây là sau khi mình tách ra 1 class Ship base từ class CCSprite
#include "Ship.h"
using namespace cocos2d::ui;
static bool shipToFrameCache = false;
Ship* Ship::createShip(float startX, float startY){
if (!shipToFrameCache){
SpriteFrameCache::getInstance()->addSpriteFramesWithFile("PlayerShip.plist");
shipToFrameCache = true;
}
auto ship = Ship::create();
ship->setPosition(startX, startY);
return ship;
}
bool Ship::init(){
if (!Sprite::init()){
return false;
}
this->createWithSpriteFrameName("PlayerShip0.png");
return true;
}
Và đây là code mình tạo ship từ class Ship trên:
void MissionScene::createPlayerShip(){
auto shipBatch = SpriteBatchNode::create("PlayerShip.png", 40);
auto ship = Ship::createShip(320,-50);
this->addChild(shipBatch);
shipBatch->addChild(ship);
}
Sau đó chạy thì xảy ra lỗi "CCSprite is not using the same texture id". Cách tạo không có gì khác chỉ là mình tách ra 1 class Ship riêng thôi, mà chạy không được. Còn nếu tạo ngay trên class MissionScene thì chạy được…Tại sao nhỉ ?
[SOLVED]
Thêm 1 dòng code trước khi add đối tượng thuộc class Ship vào SpriteBatchNode nhằm buộc nó dùng chung texture với thằng SpriteBatchNode
ship ->setTexture(shipBatch->getTexture());

83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?