Cocos2d-x Sprite 继承 class 错误
Cocos2d-x Sprite Inheritance class Error
我正在制作太空战争游戏。
我完成了添加敌人、发射子弹、检测碰撞。
下一步是为每个对象添加 HP。
我创建了 class 它继承了 Sprite
class Target : public cocos2d::Sprite
{
public:
int hp = -1;
};
我通过在下面添加 3 行代码来检查 HP 是否变化良好。
Target *target = new Target();
target->hp = 1;
CCLog("hp: %d", target->hp);
结果:
生命值:1
问题是,通过这行返回Sprite后,
target = (Target*)Sprite::createWithSpriteFrameName("enemy1.png");
CCLog("hp: %d", target->hp);
结果是
马力:-33686019
此外,我无法更改 HP 变量。当我更改它时,调试器停在 "target->hp = 1;".
试试这个,
target = Target::createWithSpriteFrameName("enemy1.png");
你做错了。首先 - 你不能在 .h 文件中初始化 int 。第二-不要直接使用new-如果处理不当很容易造成内存泄漏,而是使用cocos2d-x pattern.
我会这样做:
.h 文件:
#ifndef __Sample__Target__
#define __Sample__Target__
#include "cocos2d.h"
USING_NS_CC;
class Target : public Sprite
{
public:
static Target* create(const std::string& filename);
int hp;
};
#endif
.cpp 文件:
#include "Target.h"
Target* Target::create(const std::string& filename) {
auto ret = new (std::nothrow) Target;
if(ret && ret->initWithFile(filename)) {
ret->autorelease();
ret->hp = 1; //declare here or in init
return ret;
}
CC_SAFE_RELEASE(ret);
return nullptr;
}
我正在制作太空战争游戏。
我完成了添加敌人、发射子弹、检测碰撞。
下一步是为每个对象添加 HP。
我创建了 class 它继承了 Sprite
class Target : public cocos2d::Sprite
{
public:
int hp = -1;
};
我通过在下面添加 3 行代码来检查 HP 是否变化良好。
Target *target = new Target();
target->hp = 1;
CCLog("hp: %d", target->hp);
结果:
生命值:1
问题是,通过这行返回Sprite后,
target = (Target*)Sprite::createWithSpriteFrameName("enemy1.png");
CCLog("hp: %d", target->hp);
结果是
马力:-33686019
此外,我无法更改 HP 变量。当我更改它时,调试器停在 "target->hp = 1;".
试试这个,
target = Target::createWithSpriteFrameName("enemy1.png");
你做错了。首先 - 你不能在 .h 文件中初始化 int 。第二-不要直接使用new-如果处理不当很容易造成内存泄漏,而是使用cocos2d-x pattern.
我会这样做:
.h 文件:
#ifndef __Sample__Target__
#define __Sample__Target__
#include "cocos2d.h"
USING_NS_CC;
class Target : public Sprite
{
public:
static Target* create(const std::string& filename);
int hp;
};
#endif
.cpp 文件:
#include "Target.h"
Target* Target::create(const std::string& filename) {
auto ret = new (std::nothrow) Target;
if(ret && ret->initWithFile(filename)) {
ret->autorelease();
ret->hp = 1; //declare here or in init
return ret;
}
CC_SAFE_RELEASE(ret);
return nullptr;
}