【cocos2dx】如何创建自己定义的精灵类Sprite

前端之家收集整理的这篇文章主要介绍了【cocos2dx】如何创建自己定义的精灵类Sprite前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


C++的知识的确不用都忘了。


写德州扑克想要写一个扑克类Card,继承自Spirite,并且额外添加些自己的属性,比如说牌面大小及花色。那么我在card.h中定义这个类。并且重载Sprite::create(filename)方法


//Card.h 

#pragma once

#include "cocos2d.h"
#include "define.h"

USING_NS_CC;
/*
we name the card such as "card_clubs_2.png"

Clubs =  1,1 ~ 13
Diamonds,2     14~ 26
Hearts,3     27~ 39
Spades,4     40~ 52

we get a random number from 0 ~ 47 as num,we rename the pic_name as a number;

*/
class Card :public Sprite
{
public:

	static Card* create(const char*);//重载

	void setCardID(int);
	void setCardName(char *);
	void setCardFace(int);
	void setCardSuit(int);

	int getCardID();
	int getCardFace();
	int getCardSuit();
	char * getCardName();
	
private:
	int cardID;     // 0~51
	char * cardName;
	int cardFace;   //2 ~ 14
	int cardSuit;   //0~3
};

是如何重载create(filename)方法的呢?
Card * Card::create(const char* picFileName){
	
	Card * sprite = new Card();

	if (sprite&& sprite->initWithFile(picFileName))

	{
		sprite->autorelease(); return sprite;
	}

	CC_SAFE_DELETE(sprite);
	return nullptr;

}


代码中使用Card类,创建对象。并在CCLOG中调试,得到log

	auto my_testCard = Card::create("roomgirl.png");  // auto == Card
	my_testCard->setPosition(screenSize.width / 2,screenSize.height - 200);
	my_testCard->setScale(0.6);
	my_testCard->setCardID(23);
	this->addChild(my_testCard);
	CCLOG("my_testCard->ID = %d .",my_testCard->getCardID());//会得到log:my_testCard->ID = 23 .


参考文章http://blog.csdn.net/fanzhang1990/article/details/40328297 文章提供了2种方法,并且对原理进行了详细的分析)

原文链接:https://www.f2er.com/cocos2dx/343079.html

猜你在找的Cocos2d-x相关文章