//使用了单例模式(没打算做双人模式)。。。
//只做了4个方向
#include "cocos2d.h"
#include "Def.h"
USING_NS_CC;
using namespace std;
class Player :public Sprite
{
public:
static Player* getInstance();
void runLeft();//左跑
void runRight();
void stand();//站立
void jump();//跳
void down();//趴下
void up();//向上举枪
void setPlayerState(int state);//设置人物状态
int getPlayerState();
void setHight(int speed = SPEED_Y);//人物跳跃高度的设置
int getHight();
void fire();//发射子弹
int m_direction;//人物方向。。。用来判断子弹发射方向(不好使用状态判断,因为跳跃时还是要判断方向的)
private:
Player(){}
~Player();
static Player* sharePlayer;
void initAnimation();
void initPlayer();
AnimationCache *Cache_animation;
int playerState;
int m_High;//人物已经跳起来的高度
int m_bulltType;
};
#include "Player.h"
Player* Player::sharePlayer = NULL;
Player *Player::getInstance()
{
if (sharePlayer == NULL)
{
sharePlayer = new Player;
sharePlayer->initPlayer();
}
return sharePlayer;
}
void Player::initPlayer()//初始化主角
{
Sprite::initWithFile(STRING_PLAYER_STAND);
this->setScaleX(-1);//朝向右
playerState = STATE_PLAYER_STAND;//初始状态为站立
m_direction = DIRECTION_RIGHT;
m_High = 0;//初始跳起来的高度为0
m_bulltType = 0;//子弹类型
Cache_animation = AnimationCache::getInstance();
initAnimation();//载入动画
}
void Player::initAnimation()
{
auto m_runLeftAction = Animation::create();
for (int i = 1; i < 6; i++)
{
string s;
s = "run" + to_string(i) + ".png";
m_runLeftAction->addSpriteFrameWithFileName(s);
}
m_runLeftAction->setDelayPerUnit(0.1);
m_runLeftAction->setLoops(-1);
Cache_animation->addAnimation(m_runLeftAction, "runleft");
}
//设计定时器来判断是否长按。。。(待完成)
void Player::runLeft()
{
stopAllActions();
//if (getPlayerState() != STATE_PLAYER_JUMP)
{
Animate *ai = Animate::create(Cache_animation->getAnimation("runleft"));
runAction(ai);
setPlayerState(STATE_PLAYER_RUNLEFT);
}
this->setScaleX(1);//归正。。。即向左
}
void Player::runRight()
{
stopAllActions();
//if (getPlayerState() != STATE_PLAYER_JUMP)//在GameLayer层进行状态判断
{
Animate *ai = Animate::create(Cache_animation->getAnimation("runleft"));
runAction(ai);
setPlayerState(STATE_PLAYER_RUNRIGHT);
}
this->setScaleX(-1);//由左翻转得到右
}
void Player::jump()//跳
{
stopAllActions();
setSpriteFrame(SpriteFrame::create("jump.png", Rect(0, 0, 32, 32)));
//Sleep(1000);
}
void Player::down()
{
stopAllActions();
setSpriteFrame(SpriteFrame::create(STRING_PLAYER_DOWN,Rect(0,0,85,32)));
}
void Player::up()
{
stopAllActions();
setSpriteFrame(SpriteFrame::create(STRING_PLAYER_UP, Rect(0, 0, 32, 77)));
}
void Player::stand()
{
if (getPlayerState() != STATE_PLAYER_JUMP)
{
setPlayerState(STATE_PLAYER_STAND);
this->stopAllActions();
this->setSpriteFrame(SpriteFrame::create(STRING_PLAYER_STAND, Rect(0, 0, 42, 48)));
}
}
Player::~Player()
{
if (Cache_animation)
{
delete Cache_animation;
}
if (sharePlayer)
{
delete sharePlayer;
}
}
void Player::setPlayerState(int state)
{
playerState = state;
}
int Player::getPlayerState()
{
return playerState;
}
void Player::setHight(int speed)
{
m_High += speed;
if (speed == 0)m_High = 0;
}
int Player::getHight()
{
return m_High;
}