cocos2dx | 创建一个可以跟随角色位置滚动的背景类

Background.h

#ifndef _BACKGROUND_H_
#define _BACKGROUND_H_

#include <iostream>
#include "cocos2d.h"

USING_NS_CC;

class Background : public Sprite
{
private:
	Size visibleSize = Director::getInstance()->getVisibleSize();
	enum Message { up = 1001, left, right, down, stay, sleep, over };
	int _front;

public:
	Background();
	~Background();
	virtual bool init();
	virtual void update(float dt);

public:
	//only front "up"or"down",then dealWithMoveCommand
	void moveCommand(int front);
	//is next of moveCommand
	void dealWithMoveCommand();
	
	static Background* create();
};
#endif

Background.cpp

#include "Background.h"



Background::Background()
{
}


Background::~Background()
{
	this->unscheduleUpdate();//析构时停止该类的update更新。
}


bool Background::init()
{
	Sprite::init();

	//add updating background map
	Size backSize = Size(480, 2400);
	auto background = Sprite::create("UpdateMap.png");
	background->setPosition(background->getContentSize().width / 2, background->getContentSize().height / 2);//锚点, 在类内部的精灵设置坐标是相对于类对象的。
	this->addChild(background);//把sprite添加到Background中,外部把Background添加到Layer中。
	this->setContentSize(backSize);
	this->setPosition(visibleSize.width / 2, visibleSize.height / 2);

	scheduleUpdate();//在初始化时,加入每一帧进行update更新的操作。

	return true;
}

void Background::update(float dt)
{	
	//dealWithFrontMessage();
}

void Background::dealWithMoveCommand()
{
	switch (_front)
	{
	case up:
	{
		if (this->getPositionY() > (visibleSize.height / 2 + this->getContentSize().height / 3))
		{
			this->setPosition(visibleSize.width / 2, visibleSize.height / 2);
		}
		else
		{
			this->setPositionY(this->getPositionY() + 20);//背景上升速度
			log("back is up, hero is down");
		}
	}; break;

	case down:
	{
		if (this->getPositionY() < (visibleSize.height / 2 - this->getContentSize().height / 3))
		{
			this->setPosition(visibleSize.width / 2, visibleSize.height / 2);
		}
		else
		{
			this->setPositionY(this->getPositionY() - 10);//背景下降移动速度
			log("back is down, hero is up");
		}
	}; break;

	default:
		break;
	}
}

void Background::moveCommand(int front)
{
	_front = front;
}

Background* Background::create()
{
	auto background = new Background();
	background->init();
	background->autorelease();
	return background;
}

猜你喜欢

转载自blog.csdn.net/u011607490/article/details/81143708