加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 21:17:31 所属栏目:百科 来源:网络整理
导读:C++的知识的确不用都忘了。 写德州扑克想要写一个扑克类Card,继承自Spirite,并且额外添加些自己的属性,比如说牌面大小及花色。那么我在card.h中定义这个类。并且重载Sprite::create(filename)方法。 //Card.h #pragma once#include "cocos2d.h"#include


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种方法,并且对原理进行了详细的分析)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读