Exemplo n.º 1
0
void Senario::update(float time)
{
    if(animatedStringList != NULL)
    {
        for (int i = 0; i < animatedStringList->count(); i++)
        {
            AnimatedString* as = (AnimatedString*) animatedStringList->objectAtIndex(i);
            as->update(time);
        }
    }
    
    if(animatedSpriteList != NULL)
    {
        for (int i = 0; i < animatedSpriteList->count(); i++)
        {
            AnimatedSprite* as = (AnimatedSprite*) animatedSpriteList->objectAtIndex(i);
            as->update(time);
        }
    }
    
    if(animatedDialogueList != NULL)
    {
        for (int i = 0; i < animatedDialogueList->count(); i++)
        {
            AnimatedDialogue* ad = (AnimatedDialogue*) animatedDialogueList->objectAtIndex(i);
            ad->update(time);
        }
    }
}
Exemplo n.º 2
0
pacman::pacman(sf::Texture spr)
{
    //ctor
    xpos = 250;
    ypos = 500;
    xvel = 0;
    yvel = 0;
    text = spr;
    upan.setSpriteSheet(text);
    upan.addFrame(sf::IntRect(0, 0, 25, 25));
    upan.addFrame(sf::IntRect(75, 0, 25, 25));
    downan.setSpriteSheet(text);
    downan.addFrame(sf::IntRect(0, 0, 25, 25));
    downan.addFrame(sf::IntRect(25, 0, 25, 25));
    leftan.setSpriteSheet(text);
    leftan.addFrame(sf::IntRect(0, 0, 25, 25));
    leftan.addFrame(sf::IntRect(100, 0, 25, 25));
    rightan.setSpriteSheet(text);
    rightan.addFrame(sf::IntRect(0, 0, 25, 25));
    rightan.addFrame(sf::IntRect(50, 0, 25, 25));
    currentanim = &leftan;

    anspr = AnimatedSprite(sf::seconds(.2f), false, true);
    anspr.setPosition(sf::Vector2f(xpos, ypos));
    //std::cout << "1 pacman" << std::endl;
    anspr.play(*currentanim);


    //sprite.setPosition(xpos, ypos);
    collision_box = sprite.getGlobalBounds();
    dir = 3;
}
Exemplo n.º 3
0
AnimatedSprite* AnimatedSprite::create(std::string filepath, int columns, int rows)
{
    AnimatedSprite* animatedsprite = new AnimatedSprite();
    animatedsprite->init(filepath, columns, rows);
    animatedsprite->autorelease();
    return animatedsprite;
}
Exemplo n.º 4
0
static void _find_anim_sprites(Node *p_node, List<Node *> *r_nodes, Ref<SpriteFrames> p_sfames) {

	Node *edited = EditorNode::get_singleton()->get_edited_scene();
	if (!edited)
		return;
	if (p_node != edited && p_node->get_owner() != edited)
		return;

	{
		AnimatedSprite *as = p_node->cast_to<AnimatedSprite>();
		if (as && as->get_sprite_frames() == p_sfames) {
			r_nodes->push_back(p_node);
		}
	}

	{
		AnimatedSprite3D *as = p_node->cast_to<AnimatedSprite3D>();
		if (as && as->get_sprite_frames() == p_sfames) {
			r_nodes->push_back(p_node);
		}
	}

	for (int i = 0; i < p_node->get_child_count(); i++) {
		_find_anim_sprites(p_node->get_child(i), r_nodes, p_sfames);
	}
}
Exemplo n.º 5
0
/*
	update - This method should be called once per frame. It updates
	both the sprites and the game world. Note that even though the game
	world is for static data, should the user wish to put anything dynamic
	there (like a non-collidable moving layer), the updateWorld method
	is called.
*/
void GameStateManager::update(Game *game)
{
	game->getGameRules()->spawnEnemies(game);
	spriteManager->update(game);
	world.update(game);
	physics.update(game);

	AnimatedSprite *p = spriteManager->getPlayer();
	PhysicalProperties *pp = p->getPhysicalProperties();
	float pVelX = pp->getVelocityX();
	float pVelY = pp->getVelocityY();

	//VIEWPORT SCOPING
	/*Viewport *vp = game->getGUI()->getViewport();
	
	if(pVelX < 0 
		&& (pp->round(pp->getX() - vp->getViewportX())) < vp->getViewportWidth()/3)
	{
		vp->setScrollSpeedX(pVelX);
		if(vp->getViewportX() == 0)
			vp->setScrollSpeedX(0);
	}
	else if(pVelX > 0 
		&& (pp->round(pp->getX() - vp->getViewportX())) > (vp->getViewportWidth()/3*2))
	{
		vp->setScrollSpeedX(pVelX);
		if(vp->getViewportX()+vp->getViewportWidth() == world.getWorldWidth())
			vp->setScrollSpeedX(0);
		
	}
	else
	{
		vp->setScrollSpeedX(0);
	}

	if(pVelY < 0 
		&& (pp->round(pp->getY() - vp->getViewportY())) < vp->getViewportHeight()/3)
	{
		vp->setScrollSpeedY(pVelY);
		if(vp->getViewportY() == 0)
			vp->setScrollSpeedY(0);
	}
	else if(pVelY > 0 
		&& (pp->round(pp->getY() - vp->getViewportY())) > (vp->getViewportHeight()/3*2))
	{
		vp->setScrollSpeedY(pVelY);
		if(vp->getViewportY()+vp->getViewportHeight() == world.getWorldHeight())
			vp->setScrollSpeedY(0);
	}
	else
	{
		vp->setScrollSpeedY(0);
	}

	vp->moveViewport(	vp->getScrollSpeedX(),
						vp->getScrollSpeedY(),
						world.getWorldWidth(),
						world.getWorldHeight());*/
}
Exemplo n.º 6
0
void pacman::update(){
    xpos += xvel;
    ypos += yvel;
    sprite.setPosition(sf::Vector2f(xpos, ypos));
    anspr.setPosition(sf::Vector2f(xpos, ypos));
    collision_box = anspr.getGlobalBounds();
    anspr.update(frame_time.restart());
}
Exemplo n.º 7
0
//static 
AnimatedSprite* AnimatedSprite::create( AnimationLogic* animLogic, JsonValueRef spriteFrames  )
{
	AnimatedSprite* sprite = new AnimatedSprite();
	sprite->init(animLogic, spriteFrames);
	sprite->autorelease();
	return sprite;

}
Exemplo n.º 8
0
AnimatedSprite* ResourceManager::get_sprite(string request, string animation, int sprite_width, int sprite_height){
	AnimatedSprite* sprite = new AnimatedSprite();

	Animation* sprite_animation = get_animation(request, animation, sprite_width, sprite_height);

	sprite->set_animation(sprite_animation);
	return sprite;
}
Exemplo n.º 9
0
void ScienceMouseEventHandler::handleMousePressEvent(Game *game, int mouseX, int mouseY)
{
	if (game->getGSM()->isGameInProgress())
	{
		Viewport *viewport = game->getGUI()->getViewport();
		
		// DETERMINE WHERE ON THE MAP WE HAVE CLICKED
		int worldCoordinateX = mouseX + viewport->getViewportX();
		int worldCoordinateY = mouseY + viewport->getViewportY();

		// NOW LET'S SEE IF THERE IS A SPRITE THERE
		GameStateManager *gsm = game->getGSM();
		SpriteManager *spriteManager = gsm->getSpriteManager();

		
		// IF THERE IS NO SELECTED SPRITE LOOK FOR ONE
		if (!(spriteManager->getIsSpriteSelected()))
		{
			// IF THIS DOES NOT RETURN NULL THEN YOU FOUND A SPRITE AT THAT LOCATION
			if((spriteManager->getSpriteAt(worldCoordinateX, worldCoordinateY) != NULL))
			{
				AnimatedSprite *selected = spriteManager->getSpriteAt(worldCoordinateX, worldCoordinateY);
				spriteManager->setIsSpriteSelected(true);
			}
		}
		else if (spriteManager->getSelectedSprite() != NULL)
		{
			// MOVE A SPRITE IN A DESIRED DIRECTION 
			AnimatedSprite *selected = spriteManager->getSelectedSprite();
			PhysicalProperties *pp = selected->getPhysicalProperties();
			float spriteX = pp->getX();
			float spriteY = pp->getY();

			//IF A SPRITE IS WHERE YOU WANT IT THEN STOP IT
			if (((spriteX > worldCoordinateX - 64) && (spriteX < worldCoordinateX + 64)) && (spriteY > worldCoordinateY - 64) && (spriteY < worldCoordinateY + 64))
			{
				pp->setVelocity(0, 0);
			}
			else
			{
				float deltaX = worldCoordinateX - spriteX;
				float deltaY = worldCoordinateY - spriteY;
				float hyp = sqrtf((deltaX * deltaX) + (deltaY * deltaY));

				pp->setVelocity((deltaX / hyp) * 3, (deltaY / hyp) * 3);
			}
			spriteManager->setIsSpriteSelected(false);

		//	GridPathfinder *pathfinder = spriteManager->getPathfinder();
		//	pathfinder->mapPath(selected, (float)worldCoordinateX, (float)worldCoordinateY);
		//	gsm->setSpriteSelected(false, selected);
		}
		else
		{
			spriteManager->setIsSpriteSelected(false);
		}
	}
}
Exemplo n.º 10
0
AnimatedSprite *StatusEffect::getIcon()
{
    if (mIcon.empty())
        return NULL;
    else {
        AnimatedSprite *sprite = AnimatedSprite::load(
                "graphics/sprites/" + mIcon);
        if (false && sprite) {
            sprite->play(ACTION_DEFAULT);
            sprite->reset();
        }
        return sprite;
    }
}
Exemplo n.º 11
0
void
Game::SpawnExplosion(int x, int y)
{
	Explosion* explosion = new Explosion();
	explosion->SetPositionX(x - 10);
	explosion->SetPositionY(y - 10);



	AnimatedSprite* exploding = m_pBackBuffer->CreateAnimatedSprite("assets\\explosion.png");
	exploding->SetLooping(false);
	exploding->SetFrameWidth(64);
	exploding->SetFrameSpeed(0.05);
	exploding->AddFrame(0);
	exploding->AddFrame(64);
	exploding->AddFrame(128);
	exploding->AddFrame(192);
	exploding->AddFrame(256);




	explosion->Initialise(exploding);

	Explosions.push_back(explosion);
}
Exemplo n.º 12
0
AnimatedSprite*
BackBuffer::CreateAnimatedSprite(const char* pcFilename)
{
	assert(m_pTextureManager);

	Texture* pTexture = m_pTextureManager->GetTexture(pcFilename);

	AnimatedSprite* pSprite = new AnimatedSprite();
	if (!pSprite->Initialise(*pTexture))
	{
		LogManager::GetInstance().Log("Sprite Failed to Create!");
	}

	return (pSprite);
}
Exemplo n.º 13
0
Arquivo: being.cpp Projeto: Ablu/mana
void Being::setSprite(unsigned int slot, int id, const std::string &color,
                      bool isWeapon)
{
    if (slot >= size())
        ensureSize(slot + 1);

    if (slot >= mSpriteIDs.size())
        mSpriteIDs.resize(slot + 1);

    if (slot >= mSpriteColors.size())
        mSpriteColors.resize(slot + 1);

    // id = 0 means unequip
    if (id == 0)
    {
        removeSprite(slot);

        if (isWeapon)
            mEquippedWeapon = 0;
    }
    else
    {
        std::string filename = itemDb->get(id).getSprite(mGender);
        AnimatedSprite *equipmentSprite = 0;

        if (!filename.empty())
        {
            if (!color.empty())
                filename += "|" + color;

            equipmentSprite = AnimatedSprite::load(
                                    paths.getStringValue("sprites") + filename);
        }

        if (equipmentSprite)
            equipmentSprite->setDirection(getSpriteDirection());

        CompoundSprite::setSprite(slot, equipmentSprite);

        if (isWeapon)
            mEquippedWeapon = &itemDb->get(id);

        setAction(mAction);
    }

    mSpriteIDs[slot] = id;
    mSpriteColors[slot] = color;
}
Exemplo n.º 14
0
bool handleDownstreamDamageZoneCreationEvent(
		const DamageZoneCreationEvent& e,
		const TeamMembership* actorTeamMembership,
		const irr::core::aabbox3df& actorHitBox,
		AnimatedSprite& actorSprite)
{
	// damage only happens if you're on different teams
	if (actorTeamMembership->getTeam() != e.getInflictorMembership()->getTeam())
	{
		if (actorHitBox.intersectsWithBox(e.getDamageZoneBounds()))
		{

			GameApp::getSingleton().getSoundEngine()->play2D("../../../art/punch.wav");
			actorSprite.toggleFlipHorizontal();
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
}
Exemplo n.º 15
0
void Player::setSprite(unsigned int slot, int id, const std::string &color)
{
    assert(slot >= BASE_SPRITE && slot < VECTOREND_SPRITE);

    // id = 0 means unequip
    if (id == 0)
    {
        delete mSprites[slot];
        mSprites[slot] = NULL;

#ifdef EATHENA_SUPPORT
        if (slot == WEAPON_SPRITE)
            mEquippedWeapon = NULL;
//        if (slot == )
#endif
    }
    else
    {
        std::string filename = ItemDB::get(id).getSprite(mGender);
        AnimatedSprite *equipmentSprite = NULL;

        if (!filename.empty())
        {
            if (!color.empty())
                filename += "|" + color;

            equipmentSprite = AnimatedSprite::load("graphics/sprites/" +
                                                   filename);
        }

        if (equipmentSprite)
            equipmentSprite->setDirection(getSpriteDirection());

        delete mSprites[slot];

        mSprites[slot] = equipmentSprite;

        if (slot == WEAPON_SPRITE)
            mEquippedWeapon = &ItemDB::get(id);

        setAction(mAction);
    }

    mSpriteIDs[slot] = id;
    mSpriteColors[slot] = color;
}
Exemplo n.º 16
0
void BackBuffer::DrawAnimatedSprite(AnimatedSprite& sprite, int x, int width) 
{
	SDL_Rect dest;

	dest.x = sprite.GetX();
	dest.y = sprite.GetY();
	dest.w = width;
	dest.h = sprite.GetHeight();

	SDL_Rect* f = new SDL_Rect;
	//location of animation frame
	f->x = x;
	f->y = 0;
	f->w = width;
	f->h = sprite.GetHeight();
	
	SDL_RenderCopy(m_pRenderer, sprite.GetTexture()->GetTexture(), f, &dest);
}
Exemplo n.º 17
0
void VisibilityEnabler2D::_change_node_state(Node *p_node, bool p_enabled) {

	ERR_FAIL_COND(!nodes.has(p_node));

	{
		RigidBody2D *rb = Object::cast_to<RigidBody2D>(p_node);
		if (rb) {

			rb->set_sleeping(!p_enabled);
		}
	}

	{
		AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(p_node);

		if (ap) {

			ap->set_active(p_enabled);
		}
	}
	{
		AnimatedSprite *as = Object::cast_to<AnimatedSprite>(p_node);

		if (as) {

			if (p_enabled)
				as->play();
			else
				as->stop();
		}
	}

	{
		Particles2D *ps = Object::cast_to<Particles2D>(p_node);

		if (ps) {

			ps->set_emitting(p_enabled);
		}
	}
}
Exemplo n.º 18
0
AnimatedSprite* AnimatedSprite::create(std::string filename)
{
    AnimatedSprite *pSprite = new (std::nothrow) AnimatedSprite();
    if (pSprite && pSprite->init())
    {

        cocos2d::SpriteFrameCache * cache = cocos2d::SpriteFrameCache::getInstance();
        cache->addSpriteFramesWithFile(cocos2d::String::createWithFormat("anims/%s.plist", filename.c_str())->getCString());

        if (pSprite->initWithSpriteFrameName(cocos2d::String::createWithFormat("anims/%s_01.png", filename.c_str())->getCString()))
        {
            auto cache = cocos2d::AnimationCache::getInstance();
            cache->addAnimationsWithFile(cocos2d::String::createWithFormat("anims/%s.plist", filename.c_str())->getCString());
            pSprite->runAction(AnimationUtils::getAnimationRunningForever((filename + "_idle").c_str()));

            pSprite->autorelease();
            return pSprite;
        }
    }
    CC_SAFE_DELETE(pSprite);
    return NULL;
}
Exemplo n.º 19
0
void pacman::set_curr_anim(int d){
    if (d == 0){
        currentanim = &upan;
    } else if (d == 1){
        currentanim = &downan;
    } else if (d == 2){
        currentanim = &rightan;
    } else {
        currentanim = &leftan;
    }

    anspr.play(*currentanim);
}
Exemplo n.º 20
0
scene::ISceneNode* AnimatedSprite::clone(scene::ISceneNode* newParent, scene::ISceneManager* newManager)
{
	if (!newParent)
		newParent = Parent;
	if (!newManager)
		newManager = SceneManager;

	AnimatedSprite* ns = new AnimatedSprite(spriteData, newParent,
		newManager, ID);
	ns->setSize(size);
	ns->playing = playing;
	ns->startTime = startTime;
	ns->startFrame = startFrame;
	ns->currentSequence = currentSequence;

	ns->cloneMembers(this, newManager);
	ns->material = material;

	if ( newParent )
		ns->drop();

	return ns;
}
Exemplo n.º 21
0
void Invaders::populateInvaders(AnimatedSprite& invader)
{
    vector<AnimatedSprite> invaderCol;

    for(int col = 0; col < 10; col++)
    {
        for(int row = 0; row < 5; row++)
        {
            invader.setPosition(m_posX, m_posY);
            invaderCol.push_back(invader);
            m_posY += 40;
        }

        m_invaderPop->push_back(invaderCol);
        invaderCol.clear();
        m_posY -= 200;
        m_posX += 40;
    }

    m_posX = 100;
    m_posY = 70;
}
Exemplo n.º 22
0
/*
handleKeyEvent - this method handles all keyboard interactions. Note that every frame this method
gets called and it can respond to key interactions in any custom way. Ask the GameInput class for
key states since the last frame, which can allow us to respond to key presses, including when keys
are held down for multiple frames.
*/
void BugsKeyEventHandler::handleKeyEvents(Game *game)
{
	// WE CAN QUERY INPUT TO SEE WHAT WAS PRESSED
	GameInput *input = game->getInput();

	// LET'S GET THE PLAYER'S PHYSICAL PROPERTIES, IN CASE WE WANT TO CHANGE THEM
	GameStateManager *gsm = game->getGSM();
	AnimatedSprite *player = gsm->getSpriteManager()->getPlayer();
	PhysicalProperties *pp = player->getPhysicalProperties();
	Viewport *viewport = game->getGUI()->getViewport();

	// IF THE GAME IS IN PROGRESS
	if (gsm->isGameInProgress())
	{
		if (input->isKeyDownForFirstTime(D_KEY))
		{
			viewport->toggleDebugView();
			game->getGraphics()->toggleDebugTextShouldBeRendered();
		}
		if (input->isKeyDownForFirstTime(L_KEY))
		{
			game->getGraphics()->togglePathfindingGridShouldBeRendered();
		}
		if (input->isKeyDownForFirstTime(F_KEY))
		{
			game->getGraphics()->togglePathfindingPathShouldBeRendered();
		}
		if (input->isKeyDownForFirstTime(R_KEY))
		{
			if (wcscmp(player->getCurrentState().c_str(), L"RUNNING") == 0)
				player->setCurrentState(L"WALKING");
			else if ((wcscmp(player->getCurrentState().c_str(), L"IDLE") != 0) && (wcscmp(player->getCurrentState().c_str(), L"DANCING") != 0))
				player->setCurrentState(L"RUNNING");
		}
		if (input->isKeyDownForFirstTime(Y_KEY)){
			player->setCurrentState(DYING);
		}
		if (input->isKeyDownForFirstTime(I_KEY)){
			player->setCurrentState(IDLE);
		}
		bool viewportMoved = false;
		float viewportVx = 0.0f;
		float viewportVy = 0.0f;
		float vX = pp->getVelocityX();
		float vY = pp->getVelocityY();
		if (input->isKeyDown(UP_KEY))
		{
			if (pp->getY() < (viewport->getViewportY() + 0.5f * viewport->getViewportHeight()))
				viewportVy -= MAX_PLAYER_VELOCITY;
			vY = -1 * MAX_PLAYER_VELOCITY;
			vX = 0;
			viewportMoved = true;
		}
		else if (input->isKeyDown(DOWN_KEY))
		{
			if (pp->getY() > (viewport->getViewportY() + 0.5f * viewport->getViewportHeight()))
				viewportVy += MAX_PLAYER_VELOCITY;
			vY = MAX_PLAYER_VELOCITY;
			vX = 0;
			viewportMoved = true;
		}
		else if (input->isKeyDown(LEFT_KEY))
		{
			if (pp->getX() < (viewport->getViewportX() + 0.5f * viewport->getViewportWidth()))
				viewportVx -= MAX_PLAYER_VELOCITY;
			vX = -1 * MAX_PLAYER_VELOCITY;
			vY = 0;
			viewportMoved = true;
		}
		else if (input->isKeyDown(RIGHT_KEY))
		{
			if (pp->getX() > (viewport->getViewportX() + 0.5f * viewport->getViewportWidth()))
			viewportVx += MAX_PLAYER_VELOCITY;
			vX = MAX_PLAYER_VELOCITY;
			vY = 0;
			viewportMoved = true;
		}
		else {
			vX = 0.0f;
			vY = 0.0f;
		}
		if (viewportMoved)
			viewport->moveViewport((int)floor(viewportVx+0.5f), (int)floor(viewportVy+0.5f), game->getGSM()->getWorld()->getWorldWidth(), game->getGSM()->getWorld()->getWorldHeight());
		pp->setVelocity(vX, vY);
	}

	// 0X43 is HEX FOR THE 'C' VIRTUAL KEY
	// THIS CHANGES THE CURSOR IMAGE
	if ((input->isKeyDownForFirstTime(C_KEY))
		&& input->isKeyDown(VK_SHIFT))
	{
		Cursor *cursor = game->getGUI()->getCursor();
		unsigned int id = cursor->getActiveCursorID();
		id++;
		if (id == cursor->getNumCursorIDs())
			id = 0;		
		cursor->setActiveCursorID(id);
	}

	// LET'S MESS WITH THE TARGET FRAME RATE IF THE USER PRESSES THE HOME OR END KEYS
	WindowsTimer *timer = (WindowsTimer*)game->getTimer();
	int fps = timer->getTargetFPS();

	// THIS SPEEDS UP OUR GAME LOOP AND THUS THE GAME, NOTE THAT WE COULD ALTERNATIVELY SCALE
	// DOWN THE GAME LOGIC (LIKE ALL VELOCITIES) AS WE SPEED UP THE GAME. THAT COULD PROVIDE
	// A BETTER PLAYER EXPERIENCE
	if (input->isKeyDown(VK_HOME) && (fps < MAX_FPS))
		timer->setTargetFPS(fps + FPS_INC);

	// THIS SLOWS DOWN OUR GAME LOOP, BUT WILL NOT GO BELOW 5 FRAMES PER SECOND
	else if (input->isKeyDown(VK_END) && (fps > MIN_FPS))
		timer->setTargetFPS(fps - FPS_INC);
}
Exemplo n.º 23
0
bool GameState::Update() {
	//Updates the timers
	m_timerGuards += Settings::ms_deltatime;
	m_timerPlayer += Settings::ms_deltatime;
	m_bumpTimer += Settings::ms_deltatime;

	//Updates keypresses. returns true if the game is exiting
	if(UpdateEvents()) {
		return false;
	}

	//Updates the player
	int noise = mp_player->Update(cl, fm, mp_fov);
	if(noise != -1 && m_bumpTimer > 0.91f) {
		sf::Sound* bump = nullptr;
		if(!SoundEntity::IsMuted()) {
			bump = Settings::ms_soundManager.GetSound("../data/sound/FURNITURE.ogg")->CreateSound(mp_player->GetPosition());
			if(bump != nullptr) {
				bump->play();
			}
		}
		m_soundRippleManager.CreateSoundRipple(mp_player->GetPosition(), noise, true, m_spriteManager.Load("Ripple.txt"), bump);
		m_bumpTimer = 0.0f;
	}

	//Update the listener
	Settings::ms_soundManager.Update(mp_player->GetPosition());
	if(mp_player->IsRunning() && m_timerPlayer > 0.5f) {
		m_timerPlayer = 0.0f;
		sf::Sound* footstep = nullptr;
		if(mp_player->IsRightFoot()) {
			if(!SoundEntity::IsMuted()) {
				footstep = Settings::ms_soundManager.GetSound("../data/sound/RUN_1.ogg")->CreateSound(mp_player->GetPosition());
			}
		}
		else {
			if(!SoundEntity::IsMuted()) {
				footstep = Settings::ms_soundManager.GetSound("../data/sound/RUN_2.ogg")->CreateSound(mp_player->GetPosition());
			}
		}
		m_soundRippleManager.CreateSoundRipple(mp_player->GetPosition(), 4, true, m_spriteManager.Load("Ripple.txt"), footstep);
	}

	for(unsigned int i = 0; i < m_guards.size(); i++) {
		//checks to see if a guard is within hearing range of a playercreated sound
		sf::Vector2f pos(m_soundRippleManager.GuardNotice(m_guards.at(i)->GetPosition()));
		if(pos.x > 1.0f && pos.y > 1.0f) {
			m_guards.at(i)->AddWaypointToFront(pos);
		}

		//updates the guard
		m_guards.at(i)->Update(mp_player->GetPosition(), cl, fm);

		//checks to see if a foot step is to be created. Move or change so it is in sync with the walk animation
		if(m_guards.at(i)->IsWalking() && m_timerGuards > 0.5f) {
			AnimatedSprite* footPrint = m_spriteManager.Load("GuardFootStep.txt");
			sf::Sound* sound = nullptr;
			if(m_guards.at(i)->GetFoot() == 0) {
				footPrint->ChangeAnimation("Footstep_left.png");
				if(!SoundEntity::IsMuted())
				{
					sound = Settings::ms_soundManager.GetSound("../data/sound/STEP_1.ogg")->CreateSound((m_guards.at(i)->GetPosition()));
				}
			}
			else {
				footPrint->ChangeAnimation("Footstep_right.png");
				if(!SoundEntity::IsMuted())
				{
					sound = Settings::ms_soundManager.GetSound("../data/sound/STEP_2.ogg")->CreateSound((m_guards.at(i)->GetPosition()));
				}
			}
			mp_guardFootSteps->AddRipple(m_guards.at(i)->GetPosition(), m_guards.at(i)->GetSprite()->getSprite()->getRotation(), footPrint, sound);
		}

		//updates the guards flashlight position and direction
		Vec2f vecG(m_guards.at(i)->GetPosition().x, -m_guards.at(i)->GetPosition().y + mp_view->getSize().y);
		float angle = (static_cast<int>(m_guards.at(i)->GetSprite()->getSprite()->getRotation() - 90) % 360)  * (3.141592 / 180);
		lm->GetLight(m_guards.at(i))->m_directionAngle = -angle;
		lm->GetLight(m_guards.at(i))->SetCenter(vecG);
		lm->GetLight(m_guards.at(i))->CalculateAABB();
	}

	//resets the timer
	if(m_timerGuards > 0.5f) {
		m_timerGuards = 0.0f;
	}

	//Check if door is open
	if(Settings::ms_inputManager.IsDownOnceKeyboard(sf::Keyboard::E) || Settings::ms_inputManager.IsDownOnceKeyboard(sf::Keyboard::Space)) {
		sf::CircleShape* door = cl->Circle_DoorUse(*mp_player->GetSprite());
		if(door != nullptr) {
			if(!dm->OpenDoor(door)) {
				for(int i = 0; i < mp_gui->GetItemCount(); i++) {
					sf::Color color = mp_gui->GetItem(i)->getColor();
					if(dm->OpenDoor(door, color)) {
						mp_gui->RemoveItem(i);
						if(!SoundEntity::IsMuted())
						{
							mp_unlock->play();
							mp_unlock->setPosition(door->getPosition().x, 0, door->getPosition().y);
						}
						break;
					}
				}
			}
			else
			{
				if(dm->GetDoor(door)->IsOpen())
				{
					if(!SoundEntity::IsMuted())
					{
						sf::Sound* mp_closeDoor = Settings::ms_soundManager.GetSound("../data/sound/DOOR_CLOSE.ogg")->CreateSound(door->getPosition());
						m_soundRippleManager.CreateSoundRipple(mp_player->GetPosition(), 1, true, m_spriteManager.Load("Ripple.txt"), mp_closeDoor);
					}
				}
				else
				{
					if(!SoundEntity::IsMuted())
					{
						sf::Sound* mp_openDoor = Settings::ms_soundManager.GetSound("../data/sound/DOOR_OPEN.ogg")->CreateSound(door->getPosition());
						m_soundRippleManager.CreateSoundRipple(mp_player->GetPosition(), 1, true, m_spriteManager.Load("Ripple.txt"), mp_openDoor);
					}
				}
			}
		}
	}

	//check if key is close enough to pick up
	sf::CircleShape* circle_key = cl->Circle_KeyPickup(*mp_player->GetSprite());
	if(circle_key != nullptr) {
		Key* key = km->PickUpKey(circle_key);
		sf::Color color = key->GetPickUpRadius()->getFillColor();
		color.a = 255;
		key->setColor(color);
		mp_gui->AddItem(key);
		if (!SoundEntity::IsMuted())
		{
			mp_keySound->play();
			mp_keySound->setPosition(key->getPosition().x, 0, key->getPosition().y);
		}
	}

	//updates the footsteps and the soundripples
	mp_guardFootSteps->Update();
	m_soundRippleManager.UpdateSounds();

	//updates the light around the player
	Vec2f vec(mp_player->GetPosition().x, -mp_view->getCenter().y + mp_view->getSize().y);
	lm->GetLight(mp_player)->SetCenter(vec);

	//checks if the player has won or lost.
	if(Settings::ms_gameOver && m_gameOverTimer > 3.2f) {
		m_nextState = "GameOverState";
		Settings::ms_gameOver = false;
		return false;
	}
	else if(mp_player->GetPosition().x > Settings::ms_exit.x - 100 && mp_player->GetPosition().x < Settings::ms_exit.x + 100 && mp_player->GetPosition().y > Settings::ms_exit.y - 100 && mp_player->GetPosition().y < Settings::ms_exit.y + 100) {
		m_levelToLoad++;
		m_levelToLoad = m_levelToLoad % 5;
		if(m_levelToLoad == 0) {
			m_nextState = "VictoryState";
			return false;
		}
		else {
			Exit();
			Enter();
		}
	}
	else if(Settings::ms_gameOver) {
		if(m_gameOverTimer > 0.5f && !m_deathSoundPlayed)
		{
			int random = rand()%10;
			if(random == 0)
			{
				mp_jokeDeath->play();
			}
			else
			{
				mp_death->play();
			}
			m_deathSoundPlayed = true;
		}
		m_gameOverTimer += Settings::ms_deltatime;
	}

	if(Settings::ms_inputManager.IsDownOnceKeyboard(sf::Keyboard::F1) && Settings::ms_inputManager.IsDownKeyboard(sf::Keyboard::LControl) && Settings::ms_inputManager.IsDownKeyboard(sf::Keyboard::LShift)) {
		m_levelToLoad = 1;
		Exit();
		Enter();
	}
	else if(Settings::ms_inputManager.IsDownOnceKeyboard(sf::Keyboard::F2) && Settings::ms_inputManager.IsDownKeyboard(sf::Keyboard::LControl) && Settings::ms_inputManager.IsDownKeyboard(sf::Keyboard::LShift)) {
		m_levelToLoad = 2;
		Exit();
		Enter();
	}
	else if(Settings::ms_inputManager.IsDownOnceKeyboard(sf::Keyboard::F3) && Settings::ms_inputManager.IsDownKeyboard(sf::Keyboard::LControl) && Settings::ms_inputManager.IsDownKeyboard(sf::Keyboard::LShift)) {
		m_levelToLoad = 3;
		Exit();
		Enter();
	}
	else if(Settings::ms_inputManager.IsDownOnceKeyboard(sf::Keyboard::F4) && Settings::ms_inputManager.IsDownKeyboard(sf::Keyboard::LControl) && Settings::ms_inputManager.IsDownKeyboard(sf::Keyboard::LShift)) {
		m_levelToLoad = 4;
		Exit();
		Enter();
	}
	else if(Settings::ms_inputManager.IsDownOnceKeyboard(sf::Keyboard::F5) && Settings::ms_inputManager.IsDownKeyboard(sf::Keyboard::LControl) && Settings::ms_inputManager.IsDownKeyboard(sf::Keyboard::LShift)) {
		m_levelToLoad = 0;
		Exit();
		Enter();
	}
	else if(Settings::ms_inputManager.IsDownOnceKeyboard(sf::Keyboard::F11)) {
		Settings::SetFullscreen();
	}
	else if(Settings::ms_inputManager.IsDownOnceKeyboard(sf::Keyboard::F12)) {
		Settings::SetWindowed();
	}
	else if(Settings::ms_inputManager.IsDownOnceKeyboard(sf::Keyboard::Escape)) {
		m_nextState = "StartMenuState";
		return false;
	}

	return true;
}
Exemplo n.º 24
0
/*
This is where all game physics starts each frame. It is called each frame 
by the game statem manager after player input and AI have been processed. It
updates the physical state of all dynamic objects in the game and
moves all objects to their end of frame positions, updates all necessary
object velocities, and calls all collision event handlers.
*/
void Physics::update(Game *game)
{
	// WE'LL USE A CONTINUOUS COLLISION SYSTEM TO ENSURE TEMPORAL 
	// COHERENCE, WHICH MEANS WE'LL MAKE SURE COLLISIONS ARE RESOLVED
	// IN THE ORDER WITH WHICH THEY HAPPEN. WE DON'T WANT GAME EVENTS
	// TO APPEAR TO HAPPEN IN THE WRONG ORDER. WE'LL TRY TO MAKE IT
	// A LITTLE MORE EFFICIENT BY EMPLOYING A VARIATION ON THE
	// SWEEP AND PRUNE ALGORITHM FOR DYNAMIC-DYNAMIC OBJECT COLLISIONS

	// IN CASE WE'RE DOING THE ONE UPDATE STEP AT A TIME
	// THIS MAKES SURE THE UPDATE DOESN'T GET CALLED AGAIN
	// NEXT FRAME WITHOUT THE USER EXPLICITY REQUESTING IT
	// BY PRESSING THE 'T' KEY (for Time sTep)
	activatedForSingleUpdate = false;

	// WE'LL NEED THE WORLD TO ACCESS THE SPRITES AND WORLD LAYERS
	GameStateManager *gsm = game->getGSM();
	World *world = gsm->getWorld();

	// NOTE THAT WE MAKE SURE THE activeCollisions VECTOR IS
	// EMPTIED BEFORE THIS METHOD EXITS, SO WE CAN ASSUME
	// IT'S EMPTY NOW. activeCollisions CONTAINS ALL THE COLLISIONS
	// EMPTIED BEFORE THIS METHOD EXITS, SO WE CAN ASSUME
	// IT'S EMPTY NOW. activeCollisions CONTAINS ALL THE COLLISIONS
	// DETECTED SO FAR THIS FRAME. THESE ARE THE THINGS WE MUST
	// RESOLVE.

	// START THE CLOCK AT 0, THAT MEANS 0% OF THE WAY THROUGH THE FRAME.
	// NOTE THAT TIME 0 IS THE MOST DANGEROUS TIME FOR DETECTING COLLISIONS
	// BECAUSE THEY CAN BE EASILY OVERLOOKED. THE SAME FOR SIMULTANEOUS 
	// COLLISIONS. TO MINIMIZE RIGID BODY PENETRATION, SUCH CIRCUMSTANCES
	// ARE TYPICALLY HANDLED AS SPECIAL CASES
	currentCollisionTime = 0.0f;

	// FIRST WE NEED TO DO COLLISION TESTING PREP WORK FOR SPRITES
	// APPLY ACCELERATION AND GRAVITY TO VELOCITY
	// INIT TILE COLLISION INFO
	// SET ON TILE LAST FRAME USING ON TILE THIS FRAME
	// SET ON TILE THIS FRAME TO FALSE	
	// GET COLLISIONS WITH ALL TILES TO HAPPEN DURING THIS FRAME
	// PUT THESE COLLISIONS INTO A SORTABLE DATA STRUCTURE
	// INIT SPRITE'S SWEPT SHAPE INFO

	// FOR ALL SPRITES, INCLUDING THE BOTS AND PLAYER
	vector<CollidableObject*>::iterator spritesIt = sortedSweptShapes[LEFT_EDGE]->begin();
	while (spritesIt != sortedSweptShapes[LEFT_EDGE]->end())
	{
		CollidableObject *sprite = (*spritesIt);
		prepSpriteForCollisionTesting(world, sprite);
		getAllTileCollisionsForAGivenSprite(world, sprite, 1.0f);
		spritesIt++;
	}

	// PREPARE FOR SPRITE-SPRITE COLLISION TESTING

	// SWEEP AND PRUNE DATA STRUCTURES PREP WORK
	// SORT S_AND_P VECTOR SORTED BY START X OF SWEPT SHAPE
	// SORT S_AND_P VECTOR SORTED BY END X OF SWEPT SHAPE
	// WE DON'T NEED THE Y-AXIS SORTED, BUT WOULD IF THIS
	// WERE A 3D SYSTEM TO SAVE ON COMPARISONS.

	// WE'RE USING C++'s STL sort METHOD AND ARE PROVIDING
	// A CUSTOM MEANS FOR COMPARISON
	sort(sortedSweptShapes[LEFT_EDGE]->begin(),		sortedSweptShapes[LEFT_EDGE]->end(),	SweptShapesComparitorByLeft());
	sort(sortedSweptShapes[RIGHT_EDGE]->begin(),	sortedSweptShapes[RIGHT_EDGE]->end(),	SweptShapesComparitorByRight());

	// RECORD SORTED POSITIONS WITH EACH SPRITE. THEY NEED TO KNOW WHERE
	// THEY ARE IN THOSE DATA STRUCTURES SUCH THAT WE CAN JUMP INTO
	// THOSE DATA STRUCTURES TO TEST COLLISIONS WITH NEIGHBORS
	updateSweptShapeIndices();

	// YOU'LL NEED TO TEST FOR SPRITE-TO-SPRITE COLLISIONS HERE

	// *** LOOP STARTS HERE. WE'LL DO THIS UNTIL THERE ARE NO
	// MORE COLLISIONS TO RESOLVE FOR THIS FRAME
	while (activeCollisions.size() > 0)
	{
		// SORT COLLISION OBJECTS BY TIME OF COLLISION
		// NOTE THAT I'M JUST EMPLOYING THE STL'S List
		// CLASS' SORT METHOD BY PROVIDING MY OWN
		// MEANS FOR COMPARING Collision OBJECTS
		activeCollisions.sort(CollisionComparitor());

		// GET FIRST COLLISION - NOTE THAT WE HAVE THE COLLISIONS SORTED
		// IN DESCENDING ORDER, SO TO TAKE THE EARLIEST ONE, WE REMOVE IT
		// FOM THE BACK OF THE SORTED LIST
		Collision *earliestCollision = activeCollisions.back();
		activeCollisions.pop_back();
		float collisionTime = earliestCollision->getTimeOfCollision();

		// MOVE ALL SPRITES UP TO TIME OF FIRST COLLISION USING
		// APPROPRIATELY SCALED VELOCITIES
		moveAllSpritesUpToBufferedTimeOfCollision(earliestCollision);

		// AND ADVANCE COLLISION TIME
		currentCollisionTime = collisionTime;

		// AND UPDATE THE VELOCITIES OF THE SPRITE(S) INVOLVED IN THE COLLISION
		performCollisionResponse(earliestCollision);

		// EXECUTE COLLISION EVENT CODE
		// TEST TO SEE TYPES OF OBJECTS AND APPROPRIATE RESPONSE
		// ACCORDING TO CUSTOMIZED COLLISION EVENT HANDLER
		collisionListener->respondToCollision(game, earliestCollision);

		// FOR THE TWO OBJECTS INVOLVED IN THE COLLISION
		// REMOVE ALL OTHER COLLISIONS INVOLVING THEM
		// SINCE THEY ARE NOW OBSOLETE. THE REASON BEING
		// THE OBJECT COLLISION NOW LIKELY HAS A 
		// DIFFERENT VECTOR
		// UPDATE THEIR SWEPT SHAPES
		// TEST THEM AGAINST TILES AGAIN
		CollidableObject *co1 = earliestCollision->getCO1();
		CollidableObject *co2 = earliestCollision->getCO2();
		removeActiveCOCollisions(co1);
		co1->updateSweptShape(1.0f - currentCollisionTime);
		getAllTileCollisionsForAGivenSprite(world, co1, 1.0f - currentCollisionTime);

		// ONLY DO IT FOR THE SECOND ONE IF IT'S NOT A TILE
		if (!earliestCollision->isCollisionWithTile())
		{
			removeActiveCOCollisions(co2);
			co2->updateSweptShape(1.0f - currentCollisionTime);
			getAllTileCollisionsForAGivenSprite(world, co2, 1.0f - currentCollisionTime);
		}
		else
		{
			spriteToTileCollisionsThisFrame[co1].insert(earliestCollision->getTile());
			recycledCollidableObjectsList.push_back(co2);
		}

		// NOW WE NEED TO SEE IF THE SPRITES INVOLVED IN THE JUST
		// RESOLVED COLLISION ARE GOING TO BE INVOLVED IN ANY MORE
		// WITH OTHER SPRITES BUT WE DON'T WANT TO CHECK ALL OF THEM,
		// WE ONLY WANT TO CHECK NEIGHBORS, BUT FIRST WE HAVE TO
		// MAKE SURE THE SPRITE(S) THAT WE JUST RESOLVED ARE IN THEIR
		// PROPER SWEPT SHAPE LOCATIONS WITHOUT HAVING TO RESORT EVERTYHING

		// IF IT WAS ONLY ONE SPRITE WITH A TILE THIS IS EASY TO DO
		if (earliestCollision->isCollisionWithTile())
		{
			reorderCollidableObject(co1);
		}
		// YOU'LL HAVE TO WORRY ABOUT REORDERING STUFF FOR COLLISIONS
		// BETWEEN TWO SPRITES

		// NOW TEST NEIGHBORS OF SPRITES INVOLVED IN RESOLVED COLLISION
		// AGAINST NEIGHBORS IN SWEPT SHAPE DATA STRUCTURES. YOU'LL HAVE
		// TO FIGURE OUT HOW TO DO THIS AND HOW TO RESOLVE SUCH COLLISIONS

		// RECYCLE THE COLLISION SINCE WE'RE NOW DONE WITH IT
		recycledCollisions.push_back(earliestCollision);
	}

	// APPLY THE REMAINING TIME TO MOVE THE SPRITES. NOTE THAT
	// THIS IS ACTUALLY A VERY RISKY, TRICKY STEP BECAUSE IT COULD
	// MOVE OBJECTS ALMOST TO THE POINT OF COLLISION, WHICH MAY THEN
	// BE DETECTED ALMOST AT TIME 0 NEXT FRAME. THERE ARE OTHER TRICKY
	// ISSUES RELATED TO OUR BUFFER AS WELL, SO WE CHEAT A LITTLE HERE
	// AND SCALE THE TIME REMAINING DOWN A LITTE
	if (currentCollisionTime < 1.0f)
		moveAllSpritesToEndOfFrame();

	// INIT TILE COLLISION INFO
	// SET ON TILE LAST FRAME USING ON TILE THIS FRAME
	// SET ON TILE THIS FRAME TO FALSE
	spritesIt = sortedSweptShapes[LEFT_EDGE]->begin();
	while (spritesIt != sortedSweptShapes[LEFT_EDGE]->end())
	{
		CollidableObject *sprite = (*spritesIt);
		sprite->advanceOnTileStatus();
		spritesIt++;
	}
//	while(!colliding){
	for (b2Contact* contact = game->getbworld()->GetContactList(); contact; contact = contact->GetNext()) {
		b2Body* a = contact->GetFixtureA()->GetBody(); 
		b2Body* b = contact->GetFixtureB()->GetBody();

		AnimatedSprite* c = (AnimatedSprite*) a->GetUserData(); 
		AnimatedSprite* d = (AnimatedSprite*) b->GetUserData();

		unsigned int x = c->getSpriteType()->getSpriteTypeID(); 
		unsigned int y = d->getSpriteType()->getSpriteTypeID();
		
		switch(x){
		case 0: // player 
			break;
		case 1: // 
			break;
		case 2:
			GarbageMon *e; 
			e= (GarbageMon*)c;
			//co.remove(e);
			//game->getbworld()->DestroyBody(e->getBody());
			//e->collisionResponse(game);
			break;
		case 4:
			//Trash *f = (Trash*)c;
			//f->collisionResponse(game);
			break;
		}
		
		switch(y){
		//	if (x == 0) {
				case 0: // player 
					break;
				case 1: // 
					break;
				case 2:
		//			colliding = true;
					GarbageMon *g;
					g= (GarbageMon*)d;
					co.push_back(g);
					co.remove(g);
					//g->setCurrentState(L"DYING");
					g->getPhysicalProperties()->setPosition(9999.9f, 9999.9f);
					game->playExplosion();
					//wstring s = c->getCurrentState();
					g->getBody()->ApplyLinearImpulse(b2Vec2(99999.9f, 0.0f), g->getBody()->GetPosition(), true);
					//game->getbworld()->DestroyBody(g->getBody());
					//g->getBody()->DestroyFixture(g->getBody()->GetFixtureList());
					//g->getBody()->GetWorld()->DestroyBody(g->getBody());
					g->collisionResponse(game);
					//colliding = false;
					break;
				case 5:
					Trash *h = (Trash*)d;
					co.remove(h);
					//h->collisionResponse(game);
					break;
			}
		}
	//}
	//}
	//update sprites according to box2d thingies
	list<CollidableObject*>::iterator i = co.begin();

	while (i != co.end()) {
		CollidableObject* c = *i;

		PhysicalProperties* p = c->getPhysicalProperties();
		p->setX(c->getBody()->GetPosition().x * pikachu);
		p->setY(c->getBody()->GetPosition().y * pikachu);

		i++;
	}

	float32 time = 1.0f/1.25f;
	int32 vel = 8;
	int32 pos = 3;
	game->getbworld()->Step (time, vel, pos);

	for (b2Contact* contact = game->getbworld()->GetContactList(); contact; contact = contact->GetNext()) {
		b2Fixture* a = contact->GetFixtureA();
		b2Fixture* b = contact->GetFixtureB();
		AnimatedSprite* a2 = (AnimatedSprite*) a->GetBody()->GetUserData();
		AnimatedSprite* b2 = (AnimatedSprite*) b->GetBody()->GetUserData();
		if(a2->getSpriteType()->getSpriteTypeID() == 0 && b2->getSpriteType()->getSpriteTypeID() == 2){
			b->GetBody()->ApplyLinearImpulse(a->GetBody()->GetWorldVector(b2Vec2(0,-2)), b->GetBody()->GetPosition(), true);
			b->GetBody()->SetLinearVelocity(b2Vec2 (0,0));
			SpriteManager *sm = game->getGSM()->getSpriteManager();
			int health = (int) _wtoi(sm->getHealthBar()->getCurrentState().c_str());
			if (health <= 10){
				// WHEN PLAYER RUNS OUT OF HEALTH, SKIP TO NEXT DAY
				// PENALTY LIES IN THE PLAYER NOT ACHIEVING THE DAY'S GOALS
				// AND HAVE TO SUFFER INCREASE IN POLLUTION BAR
				sm->getHealthBar()->setCurrentState(to_wstring(100));
			}
			else{
				//OutputDebugStringW(L"HI");
				sm->getHealthBar()->setCurrentState(to_wstring(health - 10));
			}
		}

		//contact->GetFixtureB()->GetBody()->DestroyFixture(a);
	}

	// WE'RE NOT GOING TO ALLOW MULTIPLE COLLISIONS TO HAPPEN IN A FRAME
	// BETWEEN THE SAME TWO OBJECTS
	spriteToTileCollisionsThisFrame.clear();
}
Exemplo n.º 25
0
	MainMenu() : system(TextureManager::instance().getTexture("assets/rticle.png"))
	{
		pointer.setTexture(TextureManager::instance().getTexture("assets/two_pointer.png"));
		//pointer.setPosition(1183, 427);

		//system = new thor::ParticleSystem();

		emitter.setEmissionRate(0.5f);
		emitter.setParticleLifetime( sf::seconds(40) );

		emitter.setParticleRotation( thor::Distributions::uniform(0.f, 360.f) );
		emitter.setParticlePosition( sf::Vector2f(1260,740) );
		emitter.setParticleScale(sf::Vector2f(0.1,0.1));

		system.addEmitter(thor::refEmitter(emitter));

		thor::ColorGradient gradient;
		gradient[0.0f] = sf::Color::Magenta;
		gradient[0.1f] = sf::Color::Red;
		gradient[0.2f] = sf::Color::Blue;
		gradient[0.3f] = sf::Color::Cyan;
		gradient[0.4f] = sf::Color::Green;
		gradient[0.5f] = sf::Color::Red;
		gradient[0.6f] = sf::Color::Magenta;
		gradient[0.7f] = sf::Color::Cyan;
		gradient[0.8f] = sf::Color::Red;
		gradient[0.9f] = sf::Color::Blue;
		gradient[1.0f] = sf::Color::Red;

		thor::ColorAnimation colorizer(gradient);
		thor::FadeAnimation fader(0.1f, 0.1f);

		system.addAffector( thor::ScaleAffector(sf::Vector2f(0.1f,0.1)));	
		system.addAffector( thor::AnimationAffector(fader) );
		system.addAffector( thor::AnimationAffector(colorizer) );

		sprite = AnimatedSprite(sf::seconds(0.3));

		v.setTexture(TextureManager::instance().getTexture("assets/one_upper.png"));
		back2.setTexture(TextureManager::instance().getTexture("assets/two_menu.png"));
		logo.setTexture(TextureManager::instance().getTexture("assets/one_logo.png"));
		press.setTexture(TextureManager::instance().getTexture("assets/one_anybutton.png"));
		anim.setSpriteSheet(TextureManager::instance().getTexture("assets/one_animooted.jpg"));

		for (int i = 0; i < 5; i++)
		{
			anim.addFrame(sf::IntRect(0, 800 * i, WIDTH, HEIGHT));
		}

		sprite.setAnimation(anim);
		sprite.setLooped(true);
		sprite.play();

		logo.setColor(sf::Color(255,255,255,0));
		press.setColor(sf::Color(255,255,255,0));
		pointer.setColor(sf::Color(255,255,255,0));
		press.setPosition(WIDTH/2 - press.getTextureRect().width/2, HEIGHT/2 - press.getTextureRect().height/2 + 100);
		pressFading = true;

		newLogoY = 800;
		oTweener.addTween(&CDBTweener::TWEQ_BACK, CDBTweener::TWEA_INOUT, 2.f, &newLogoY, 0.0f);

		first = true;

		pressFactor = 0.2;
		transition = false;
		check = false;
		
		sm.init(sf::Vector2f(WIDTH, HEIGHT));
		rt.create(WIDTH, HEIGHT);

		MusicManager::instance().playMusicFast("low");

		selection = 1;
	};
Exemplo n.º 26
0
/*
	This is where all game physics starts each frame. It is called each frame 
	by the game statem manager after player input and AI have been processed. It
	updates the physical state of all dynamic objects in the game and
	moves all objects to their end of frame positions, updates all necessary
	object velocities, and calls all collision event handlers.
*/
void Physics::update(Game *game)
{

	GameStateManager *gsm = game->getGSM();
	SpriteManager *spm = gsm->getSpriteManager();
	AnimatedSprite *player = spm->getPlayer();

	if (once == 0) {

	
	/*	b2PolygonShape groundBox;
		groundBox.SetAsBox(50.0f, 10.0f);

		groundBody->CreateFixture(&groundBox, 0.0f);
*/
		b2BodyDef bodyDef;
		bodyDef.type = b2_dynamicBody;
		bodyDef.position.Set(600, 9280);
		body = world->CreateBody(&bodyDef);

		b2PolygonShape dynamicBox;
		dynamicBox.SetAsBox(32.0f, 32.0f);

		b2FixtureDef fixtureDef;
		fixtureDef.shape = &dynamicBox;


		// Set the box density to be non-zero, so it will be dynamic.
		fixtureDef.density = 1.0f;

		// Override the default friction.
		fixtureDef.friction = 0.3f;

		// Add the shape to the body.
		body->CreateFixture(&fixtureDef);
		//body->SetLinearVelocity(b2Vec2(0,-1000));

		//body->SetUserData(player);
		player->setBody(body);
		// This is our little game loop.

		


		once += 1;
	}

	body->ApplyForce( world->GetGravity(), body->GetWorldCenter(), true );

			float32 timeStep = 1.0f / 60.0f;
			int32 velocityIterations = 6;
			int32 positionIterations = 2;

			world->Step(timeStep, velocityIterations, positionIterations);

			// Now print the position and angle of the body.
			b2Vec2 position = body->GetPosition();
			//b2Vec2 position2 = body2->GetPosition();

			float32 angle = body->GetAngle();

			printf("%4.2f %4.2f %4.2f\n", position.x, position.y, angle);
		
			if (f == 0) {
				World *woorld = gsm->getWorld();
				vector<WorldLayer*> *layers = woorld->getLayers();
				CollidableObject *sprite = NULL;
				for (int i = 0; i < woorld->getNumLayers(); i++)
				{
					WorldLayer *layer = layers->at(i);
					if (layer->hasCollidableTiles())
					{
						layer->findTileCollisionsForSprite(this,sprite);
					}
				}
				f++;
			}
			
			if (player->getinvincible() == true) {
				if (invincibletimer == 0) {
					invincibletimer = 100;
				}
				invincibletimer -= 1;
				if (invincibletimer == 0) {
					player->setinvincible(false);
				}
			}
			
				 
			if (z!=0)z--;
			if (z==0)
			if (player->getinvincible() == false)
			for (b2ContactEdge* edge = body->GetContactList(); edge; edge = edge->next)
				if (edge->contact->IsTouching()) {
					z=50;

					if(game->getPlayerLife() > 0)
						{game->decreasePlayerLife();
					PlaySound(L"data/sounds/explosion.wav", NULL, SND_FILENAME|SND_SYNC);}
					else 
					{
					if(game->getLives() > 1) {
						game->decreaseLives();
					}						
					else if(game->getLives() == 1 && game->getPlayerLife() == 0)
					{
						GameStateManager *gsm = game->getGSM();
						once = 0;
						//body->SetTransform(b2Vec2((600-position.x),(9280-position.y)),body->GetAngle());
						Viewport *viewport = game->getGUI()->getViewport();
						viewport->setViewportX(0);
						viewport->setViewportY(8880);

						gsm->gameOver();
						PlaySound(L"data/sounds/end.wav", NULL, SND_FILENAME|SND_SYNC);
					}
	
					game->setPlayerLife();
				}

			}

			/*if (f > 0)
			{
				if(game->getPlayerLife() > 0)
				game->decreasePlayerLife();
		
				else 
				{
					if(game->getLives() > 1)
						game->decreaseLives();
					else if(game->getLives() == 1 && game->getPlayerLife() == 0)
					{
						GameStateManager *gsm = game->getGSM();
						gsm->setCurrentGameState(GS_GAME_OVER);
					}
	
					game->setPlayerLife();
				}	
			}*/
			//OutputDebug(L"My output string.");


	//		activatedForSingleUpdate = false;

	//// WE'LL NEED THE WORLD TO ACCESS THE SPRITES AND WORLD LAYERS
	//World *woorld = gsm->getWorld();

	//currentCollisionTime = 0.0f;


	//// FOR ALL SPRITES, INCLUDING THE BOTS AND PLAYER
	//vector<CollidableObject*>::iterator spritesIt = sortedSweptShapes[LEFT_EDGE]->begin();
	//while (spritesIt != sortedSweptShapes[LEFT_EDGE]->end())
	//{
	//	CollidableObject *sprite = (*spritesIt);
	//	prepSpriteForCollisionTesting(woorld, sprite);
	//	getAllTileCollisionsForAGivenSprite(woorld, sprite, 1.0f);
	//	spritesIt++;
	//}

	//// PREPARE FOR SPRITE-SPRITE COLLISION TESTING

	//	// SWEEP AND PRUNE DATA STRUCTURES PREP WORK
	//		// SORT S_AND_P VECTOR SORTED BY START X OF SWEPT SHAPE
	//		// SORT S_AND_P VECTOR SORTED BY END X OF SWEPT SHAPE
	//		// WE DON'T NEED THE Y-AXIS SORTED, BUT WOULD IF THIS
	//		// WERE A 3D SYSTEM TO SAVE ON COMPARISONS.

	//// WE'RE USING C++'s STL sort METHOD AND ARE PROVIDING
	//// A CUSTOM MEANS FOR COMPARISON
	//sort(sortedSweptShapes[LEFT_EDGE]->begin(),		sortedSweptShapes[LEFT_EDGE]->end(),	SweptShapesComparitorByLeft());
	//sort(sortedSweptShapes[RIGHT_EDGE]->begin(),	sortedSweptShapes[RIGHT_EDGE]->end(),	SweptShapesComparitorByRight());
	//	
	//// RECORD SORTED POSITIONS WITH EACH SPRITE. THEY NEED TO KNOW WHERE
	//// THEY ARE IN THOSE DATA STRUCTURES SUCH THAT WE CAN JUMP INTO
	//// THOSE DATA STRUCTURES TO TEST COLLISIONS WITH NEIGHBORS
	//updateSweptShapeIndices();

	//// YOU'LL NEED TO TEST FOR SPRITE-TO-SPRITE COLLISIONS HERE

	//// *** LOOP STARTS HERE. WE'LL DO THIS UNTIL THERE ARE NO
	//// MORE COLLISIONS TO RESOLVE FOR THIS FRAME
	//while (activeCollisions.size() > 0)
	//{
	//	// SORT COLLISION OBJECTS BY TIME OF COLLISION
	//	// NOTE THAT I'M JUST EMPLOYING THE STL'S List
	//	// CLASS' SORT METHOD BY PROVIDING MY OWN
	//	// MEANS FOR COMPARING Collision OBJECTS
	//	activeCollisions.sort(CollisionComparitor());

	//	// GET FIRST COLLISION - NOTE THAT WE HAVE THE COLLISIONS SORTED
	//	// IN DESCENDING ORDER, SO TO TAKE THE EARLIEST ONE, WE REMOVE IT
	//	// FOM THE BACK OF THE SORTED LIST
	//	Collision *earliestCollision = activeCollisions.back();
	//	activeCollisions.pop_back();
	//	float collisionTime = earliestCollision->getTimeOfCollision();

	//	// MOVE ALL SPRITES UP TO TIME OF FIRST COLLISION USING
	//	// APPROPRIATELY SCALED VELOCITIES
	//	moveAllSpritesUpToBufferedTimeOfCollision(earliestCollision);

	//	// AND ADVANCE COLLISION TIME
	//	currentCollisionTime = collisionTime;

	//	// AND UPDATE THE VELOCITIES OF THE SPRITE(S) INVOLVED IN THE COLLISION
	//	performCollisionResponse(earliestCollision);

	//	// EXECUTE COLLISION EVENT CODE
	//	// TEST TO SEE TYPES OF OBJECTS AND APPROPRIATE RESPONSE
	//	// ACCORDING TO CUSTOMIZED COLLISION EVENT HANDLER
	//	collisionListener->respondToCollision(game, earliestCollision);

	//	CollidableObject *co1 = earliestCollision->getCO1();
	//	CollidableObject *co2 = earliestCollision->getCO2();
	//	removeActiveCOCollisions(co1);
 //		co1->updateSweptShape(1.0f - currentCollisionTime);
	//	getAllTileCollisionsForAGivenSprite(woorld, co1, 1.0f - currentCollisionTime);

	//	// ONLY DO IT FOR THE SECOND ONE IF IT'S NOT A TILE
	//	if (!earliestCollision->isCollisionWithTile())
	//	{
	//		removeActiveCOCollisions(co2);
	//		co2->updateSweptShape(1.0f - currentCollisionTime);
	//		getAllTileCollisionsForAGivenSprite(woorld, co2, 1.0f - currentCollisionTime);
	//	}
	//	else
	//	{
	//		spriteToTileCollisionsThisFrame[co1].insert(earliestCollision->getTile());
	//		recycledCollidableObjectsList.push_back(co2);
	//	}
	//	
	//	// IF IT WAS ONLY ONE SPRITE WITH A TILE THIS IS EASY TO DO
	//	if (earliestCollision->isCollisionWithTile())
	//	{
	//		reorderCollidableObject(co1);
	//	}
	//	// YOU'LL HAVE TO WORRY ABOUT REORDERING STUFF FOR COLLISIONS
	//	// BETWEEN TWO SPRITES
	//	
	//	// NOW TEST NEIGHBORS OF SPRITES INVOLVED IN RESOLVED COLLISION
	//	// AGAINST NEIGHBORS IN SWEPT SHAPE DATA STRUCTURES. YOU'LL HAVE
	//	// TO FIGURE OUT HOW TO DO THIS AND HOW TO RESOLVE SUCH COLLISIONS
	//		
	//	// RECYCLE THE COLLISION SINCE WE'RE NOW DONE WITH IT
	//	recycledCollisions.push_back(earliestCollision);
	//}

	//// APPLY THE REMAINING TIME TO MOVE THE SPRITES. NOTE THAT
	//// THIS IS ACTUALLY A VERY RISKY, TRICKY STEP BECAUSE IT COULD
	//// MOVE OBJECTS ALMOST TO THE POINT OF COLLISION, WHICH MAY THEN
	//// BE DETECTED ALMOST AT TIME 0 NEXT FRAME. THERE ARE OTHER TRICKY
	//// ISSUES RELATED TO OUR BUFFER AS WELL, SO WE CHEAT A LITTLE HERE
	//// AND SCALE THE TIME REMAINING DOWN A LITTE
	//if (currentCollisionTime < 1.0f)
	//	moveAllSpritesToEndOfFrame();

	//// INIT TILE COLLISION INFO
	//// SET ON TILE LAST FRAME USING ON TILE THIS FRAME
	//// SET ON TILE THIS FRAME TO FALSE
	//spritesIt = sortedSweptShapes[LEFT_EDGE]->begin();
	//while (spritesIt != sortedSweptShapes[LEFT_EDGE]->end())
	//{
	//	CollidableObject *sprite = (*spritesIt);
	//	sprite->advanceOnTileStatus();
	//	spritesIt++;
	//}

	//// WE'RE NOT GOING TO ALLOW MULTIPLE COLLISIONS TO HAPPEN IN A FRAME
	//// BETWEEN THE SAME TWO OBJECTS
	//spriteToTileCollisionsThisFrame.clear();
	//


}
Exemplo n.º 27
0
//FOR NOW, TESTS SPRITES AGAINST ALL OTHER SPRITES. IF I HAVE TIME, I WILL IMPLEMENT SWEEP AND PRUNE
void Physics::collideTestWithSprites(Game* game, CollidableObject* c, list<Collision*> *collisions)
{
	SpriteManager *sm = game->getGSM()->getSpriteManager();
	AnimatedSprite* player = sm->getPlayer();

	if(c != player)
	{
		if(player->isCurrentlyCollidable() == true)
		{
			if(willObjectsCollide(player, c) == true)
			{
				Collision* currentCollision = collisionStack[collisionStackCounter];
				collisionStackCounter --;
				currentCollision->setCO1(player);
				currentCollision->setCO2(c);
				currentCollision->calculateTimes();

				if(currentCollision->getTOC() > 0 && currentCollision->getTOC() <= 1)
				{
					collisions->push_back(currentCollision);
				}
				else
				{
					collisionStackCounter ++;
					collisionStack[collisionStackCounter] = currentCollision;
				}
			}//end if
		}//end if
	}//end if
	else
	{
		list<Bot*>::iterator botIterator = sm->getBotsIterator();
		while (botIterator != sm->getEndOfBotsIterator())
		{			
			Bot *bot = (*botIterator);
			if(c != bot && bot->isCurrentlyCollidable() == true)
			{
				if(willObjectsCollide(c, bot) == true)
				{
					Collision* currentCollision = collisionStack[collisionStackCounter];
					collisionStackCounter --;
					currentCollision->setCO1(c);
					currentCollision->setCO2(bot);
					currentCollision->calculateTimes();

					if(currentCollision->getTOC() > 0 && currentCollision->getTOC() <= 1)
					{
						collisions->push_back(currentCollision);
					}
					else
					{
						collisionStackCounter ++;
						collisionStack[collisionStackCounter] = currentCollision;
					}
				}//end if
			}//end if
			botIterator++;
		}//end while
		
	}
	/*Collision* currentCollision = collisionStack[collisionStackCounter];
	collisionStackCounter --;


	currentCollision->setCO1(c);
	currentCollision->setCO2(tileCO);
	currentCollision->calculateTimes();

	collisions->push_back(currentCollision);*/

}
void BalloonEscapeCollisionListener::respondToCollision(Game *game, Collision *collision)
{
	// NOTE FROM THE COLLIDABLE OBJECTS, WHICH ARE IN THE COLLISION,
	// WE CAN CHECK AND SEE ON WHICH SIDE THE COLLISION HAPPENED AND
	// CHANGE SOME APPROPRIATE STATE ACCORDINGLY
	GameStateManager *gsm = game->getGSM();
	AnimatedSprite *player = gsm->getSpriteManager()->getPlayer();
	PhysicalProperties *pp = player->getPhysicalProperties();
	//AnimatedSprite *bot = collision
	CollidableObject *sprite2 = collision->getCO2();
	PhysicalProperties *pp2 = sprite2->getPhysicalProperties();
	AnimatedSprite *bot = (AnimatedSprite*)sprite2;
	if (!collision->isCollisionWithTile() && player->getCurrentState() != L"DYING")
	{
		CollidableObject *sprite = collision->getCO1();

		if (sprite2->getPhysicalProperties()->getZ() == 1.0f) {
			
			bot = (AnimatedSprite*)sprite;
				 pp = sprite2->getPhysicalProperties();
					pp2 = sprite->getPhysicalProperties();

			sprite = collision->getCO2();
			sprite2 = collision->getCO1();
			if (sprite->getCollisionEdge() == BOTTOM_EDGE)
			{	
				bot->setCurrentState(L"DYING");
				pp2->setVelocity(0.0f, 0.0f);
				pp2->setAccelerationX(0);
				pp2->setAccelerationY(0);
				// ENEMY IS DEAD - WE SHOULD PLAY A DEATH ANIMATION
				// AND MARK IT FOR REMOVAL
			}
			else if (bot->getCurrentState() != L"DYING")
			{
				if (pp->getDelay() == 0) {
					if (pp->getHP() == 10 ) {
						//lives->setCurrentState(L"TWO");
						if(deadonce == true)
						//lives->setCurrentState(L"ONE");
						player->setCurrentState(L"DYING");
						pp->setDelay(90);
						pp->setVelocity(0.0f, 0.0f);
						pp->setAccelerationX(0);
						pp->setAccelerationY(0);
						deadonce=true;
					}
					else {
						pp->setDelay(90);
						pp->setHP(pp->getHP()-10);
						SpriteManager *spriteManager = gsm->getSpriteManager();
						AnimatedSpriteType *yellowman = spriteManager->getSpriteType(3);
						player->setSpriteType(yellowman);
					}
				}

				// PLAYER IS DEAD - WE SHOULD PLAY A DEATH ANIMATION
				// AND MARK IT FOR REMOVAL/RESPAWN/RESTART GAME, WHATEVER
				// THE DEMANDS OF THE GAME ARE
			}
		}
		else if(sprite->getPhysicalProperties()->getZ() == 1.0f) {
			PhysicalProperties *pp = sprite->getPhysicalProperties();
			if (sprite->getCollisionEdge() == BOTTOM_EDGE)
			{
				
				bot->setCurrentState(L"DYING");
				pp2->setVelocity(0.0f, 0.0f);
				pp2->setAccelerationX(0);
				pp2->setAccelerationY(0);
				// ENEMY IS DEAD - WE SHOULD PLAY A DEATH ANIMATION
				// AND MARK IT FOR REMOVAL

			}
			else if (bot->getCurrentState() != L"DYING")
			{
				if (pp->getDelay() == 0) {
					if (pp->getHP() == 10 ) {


						//lives->setCurrentState(L"TWO");
						if(deadonce == true)
						//lives->setCurrentState(L"ONE");
						player->setCurrentState(L"DYING");
						pp->setDelay(90);
						pp->setVelocity(0.0f, 0.0f);
						pp->setAccelerationX(0);
						pp->setAccelerationY(0);
						deadonce=true;

					}
					else {
						pp->setDelay(90);
						pp->setHP(pp->getHP()-10);
						SpriteManager *spriteManager = gsm->getSpriteManager();
						AnimatedSpriteType *yellowman = spriteManager->getSpriteType(3);
						player->setSpriteType(yellowman);
					}
				}

				// PLAYER IS DEAD - WE SHOULD PLAY A DEATH ANIMATION
				// AND MARK IT FOR REMOVAL/RESPAWN/RESTART GAME, WHATEVER
				// THE DEMANDS OF THE GAME ARE
			}
		}
	}

	if (pp->getDelay() == 0) {
			SpriteManager *spriteManager = gsm->getSpriteManager();
			AnimatedSpriteType *redman = spriteManager->getSpriteType(2);
			player->setSpriteType(redman);
	}
}
Exemplo n.º 29
0
/*
	handleKeyEvent - this method handles all keyboard interactions. Note that every frame this method
	gets called and it can respond to key interactions in any custom way. Ask the GameInput class for
	key states since the last frame, which can allow us to respond to key presses, including when keys
	are held down for multiple frames.
*/
void SoSKeyEventHandler::handleKeyEvents(Game *game)
{
	// WE CAN QUERY INPUT TO SEE WHAT WAS PRESSED
	GameInput *input = game->getInput();

	// LET'S GET THE PLAYER'S PHYSICAL PROPERTIES, IN CASE WE WANT TO CHANGE THEM
	GameStateManager *gsm = game->getGSM();
	AnimatedSprite *player = gsm->getSpriteManager()->getPlayer();
	PhysicalProperties *pp = player->getPhysicalProperties();
	
	if(gsm->isAtSplashScreen())
	{
		if(input->isKeyDown(ENTER_KEY))
		{
			gsm->goToMainMenu();
		}
	}

	

	// IF THE GAME IS IN PROGRESS
	if (gsm->isGameInProgress())
	{
		// CHECK FOR WASD KEYS FOR MOVEMENT
		int incX = 0;
		int incY = 0;
		bool movingLR = false;
		bool attacking = false;

		if(!pp->isStunned())
		{
			if(input->isKeyDown(SPACE_KEY))
			{
				attacking = true;
				if(input->isKeyDownForFirstTime(SPACE_KEY))
				{
			
					player->setCurrentState(L"ATTACK_STATE");
					if(!pp->isOrientedRight())
						player->setCurrentState(L"ATTACKL_STATE");
				}
			
			}

			// WASD AND DIRECTION KEY PRESSES WILL CONTROL THE PLAYER,
			// SO WE'LL UPDATE THE PLAYER VELOCITY WHEN THESE KEYS ARE
			// PRESSED, THAT WAY PHYSICS CAN CORRECT AS NEEDED
			float vX = pp->getVelocityX();
			float vY = pp->getVelocityY();

		
			if (input->isKeyDown(A_KEY) || input->isKeyDown(LEFT_KEY))
			{
				movingLR = true;
				pp->setOrientedLeft();
				vX = -PLAYER_SPEED;
				if (vY == 0 && player->getCurrentState().compare(L"LEFT_STATE") != 0)
					player->setCurrentState(L"LEFT_STATE");
				else if(vY != 0 && player->getCurrentState().compare(L"JUMPL_STATE") != 0)
					player->setCurrentState(L"JUMPL_STATE");
			}
			if (input->isKeyDown(D_KEY) || input->isKeyDown(RIGHT_KEY))
			{
				movingLR = true;
				pp->setOrientedRight();
				vX = PLAYER_SPEED;
				if (vY == 0 && player->getCurrentState().compare(L"RIGHT_STATE") != 0)
					player->setCurrentState(L"RIGHT_STATE");
				else if(vY != 0 && player->getCurrentState().compare(L"JUMP_STATE") != 0)
					player->setCurrentState(L"JUMP_STATE");
			}
			/*if (input->isKeyDown(S_KEY) || input->isKeyDown(DOWN_KEY))
			{
				vY = PLAYER_SPEED;
			}*/
			if (input->isKeyDown(W_KEY) || input->isKeyDown(UP_KEY))
			{
			

				if ((input->isKeyDownForFirstTime(W_KEY) || input->isKeyDownForFirstTime(UP_KEY))
					&& pp->hasDoubleJumped() == false)
				{
					if(pp->hasJumped() == true)
						pp->setDoubleJumped(true);
					pp->setJumped(true);

					vY = -PLAYER_SPEED;
					player->setCurrentState(L"JUMP_STATE");
					if(vX < 0)
						player->setCurrentState(L"JUMPL_STATE");
				}
			}	

			if(!movingLR)
			{
				vX = 0;
			}

			if(vY == 0 && vX == 0 && !attacking && 
				player->getCurrentState().compare(L"IDLE_STATE") != 0 && player->getCurrentState().compare(L"IDLEL_STATE") != 0 )
			{
				player->setCurrentState(L"IDLE_STATE");
				if(!pp->isOrientedRight())
					player->setCurrentState(L"IDLEL_STATE");
			}
		
			// NOW SET THE ACTUAL VELOCITY
			Physics *physics = gsm->getPhysics();
			pp->setVelocitySafely(physics, vX, vY);

		}
		// NOTE THAT THE VIEWPORT SHOULD FOLLOW THE PLAYER, AND SO SHOULD BE CORRECTED AFTER PHYSICS
		// ARE APPLIED. I HAVE PROVIDED A SIMPLE WAY OF DOING SO, WHICH SHOULD BE IMPROVED, DEPENDING
		// ON THE GAME'S NEED



		if(input->isKeyDownForFirstTime(TAB_KEY))
		{
			gsm->goToPaused();
		}

	}

	else if(gsm->isGamePaused() && input->isKeyDownForFirstTime(TAB_KEY))
	{
		gsm->goToGame();
	}

	// 0X43 is HEX FOR THE 'C' VIRTUAL KEY
	// THIS CHANGES THE CURSOR IMAGE
	if ((input->isKeyDownForFirstTime(C_KEY))
		&& input->isKeyDown(VK_SHIFT))
	{
		Cursor *cursor = game->getGUI()->getCursor();
		unsigned int id = cursor->getActiveCursorID();
		id++;
		if (id == cursor->getNumCursorIDs())
			id = 0;		
		cursor->setActiveCursorID(id);
	}

	// LET'S MESS WITH THE TARGET FRAME RATE IF THE USER PRESSES THE HOME OR END KEYS
	WindowsTimer *timer = (WindowsTimer*)game->getTimer();
	int fps = timer->getTargetFPS();

	// THIS SPEEDS UP OUR GAME LOOP AND THUS THE GAME, NOTE THAT WE COULD ALTERNATIVELY SCALE
	// DOWN THE GAME LOGIC (LIKE ALL VELOCITIES) AS WE SPEED UP THE GAME. THAT COULD PROVIDE
	// A BETTER PLAYER EXPERIENCE
	if (input->isKeyDown(VK_HOME) && (fps < MAX_FPS))
		timer->setTargetFPS(fps + FPS_INC);

	// THIS SLOWS DOWN OUR GAME LOOP, BUT WILL NOT GO BELOW 5 FRAMES PER SECOND
	else if (input->isKeyDown(VK_END) && (fps > MIN_FPS))
		timer->setTargetFPS(fps - FPS_INC);
}
Exemplo n.º 30
0
void Physics::update(Game *game)
{
	// REMEMBER, AT THIS POINT, ALL PLAYER INPUT AND AI
	// HAVE ALREADY BEEN PROCESSED AND BOT AND PLAYER
	// STATES, VELOCITIES, AND ACCELERATIONS HAVE ALREADY
	// BEEN UPDATED. NOW WE HAVE TO PROCESS THE PHYSICS
	// OF ALL THESE OBJECTS INTERACTING WITH EACH OTHER
	// AND THE STATIC GAME WORLD. THIS MEANS WE NEED TO
	// DETECT AND RESOLVE COLLISIONS IN THE ORDER THAT
	// THEY WILL HAPPEN, AND WITH EACH COLLISION, EXECUTE
	// ANY GAMEPLAY RESPONSE CODE, UPDATE VELOCITIES, AND
	// IN THE END, UPDATE POSITIONS

	// FIRST, YOU SHOULD START BY ADDING ACCELERATION TO ALL 
	// VELOCITIES, WHICH INCLUDES GRAVITY, NOTE THE EXAMPLE
	// BELOW DOES NOT DO THAT


	// FOR NOW, WE'LL JUST ADD THE VELOCITIES TO THE
	// POSITIONS, WHICH MEANS WE'RE NOT APPLYING GRAVITY OR
	// ACCELERATION AND WE ARE NOT DOING ANY COLLISION 
	// DETECTION OR RESPONSE
	float timer = 0;

	GameStateManager *gsm = game->getGSM();
	SpriteManager *sm = gsm->getSpriteManager();
	World *w = gsm->getWorld();
	GameRules* gR = game->getGameRules();
	vector<WorldLayer*> *layers = w->getLayers();

	AnimatedSprite *player;
	PhysicalProperties *pp;
	TiledLayer *tL;
	list<Collision*> collisions;
	
	//finding TileLayer
	for(unsigned int i = 0; i < layers->size(); i++)
	{
		WorldLayer *currentLayer = (*layers)[i];
		if(currentLayer->hasCollidableTiles() == true)
		{
			tL = dynamic_cast<TiledLayer*>(currentLayer);
			if(tL != 0)
			{
				i = layers->size();
			}//end if
		}//end if
	}


	player = sm->getPlayer();
	pp = player->getPhysicalProperties();

	//UPDATING ALL VELOCITIES AND DOING TILE COLLISION
	pp->incVelocity(this,pp->getAccelerationX(), pp->getAccelerationY() + gravity); 
	collideTestWithTiles(player, tL, &collisions);

	list<Bot*>::iterator botIterator = sm->getBotsIterator();
	while (botIterator != sm->getEndOfBotsIterator())
	{			
		Bot *bot = (*botIterator);
		pp = bot->getPhysicalProperties();
		pp->incVelocity(this, pp->getAccelerationX(), pp->getAccelerationY());
		if(pp->isGravAffected() == true)
			pp->incVelocity(this, 0, gravity);
		collideTestWithTiles(bot, tL, &collisions);
		botIterator++;
	}

	//HERE, COLLIDE SPRITES WITH OTHER SPRITES
	collideTestWithSprites(game, player, &collisions);
	botIterator = sm->getBotsIterator();
	while (botIterator != sm->getEndOfBotsIterator())
	{			
		Bot *bot = (*botIterator);
		if(bot->isCurrentlyCollidable() == true);
			collideTestWithSprites(game, bot, &collisions);
		botIterator++;
	}

	//SORT COLLISIONS
	collisions.sort(compare_collisionTime);

	//RESOLVING ALL THE COLLISIONS
	while(collisions.empty() == false)
	{
		Collision* currentCollision = collisions.front();
		collisions.pop_front();
		float colTime = currentCollision->getTOC();
		CollidableObject* co1 = currentCollision->getCO1();
		CollidableObject* co2 = currentCollision->getCO2();

		if(colTime >= 0 && colTime <= 1)
		{
			
			pp = co1->getPhysicalProperties();
			//pp->setVelocity(pp->getVelocityX()*9.99f,pp->getVelocityY()*9.99f);
			pp = co2->getPhysicalProperties();
			//pp->setVelocity(pp->getVelocityX()*9.99f,pp->getVelocityY()*9.99f);

			pp = player->getPhysicalProperties();
			pp->setPosition(pp->getX() + (pp->getVelocityX()*(colTime-timer)),pp->getY() + (pp->getVelocityY()*(colTime-timer)));
			botIterator = sm->getBotsIterator();
			while (botIterator != sm->getEndOfBotsIterator())
			{			
				Bot *bot = (*botIterator);
				pp = bot->getPhysicalProperties();
				pp->setPosition(pp->getX() + (pp->getVelocityX()*(colTime-timer)), pp->getY() + (pp->getVelocityY()*(colTime-timer)));
				botIterator++;
			}

			gsm->updateViewport(game, colTime-timer);

			resolveCollision(game, currentCollision);
			gR->gameSpecificResolve(game, currentCollision);
			
			boolean deleteLast = false;
			list<Collision*>::iterator cIterator = collisions.begin();
			list<Collision*>::iterator lastIterator;
			while(cIterator != collisions.end())
			{
				if(deleteLast == true)
				{
					collisions.erase(lastIterator);
				}
				deleteLast = false;
				Collision* check = (*cIterator);
				if(check->contains(co1) || check->contains(co2))
				{
					CollidableObject* checkStatic = check->getCO2();
					if(checkStatic->isStaticObject())
					{
						coStackCounter ++;
						coStack[coStackCounter] = checkStatic;
					}

					collisionStackCounter ++;
					collisionStack[collisionStackCounter] = check;

					lastIterator = cIterator;
					deleteLast = true;
				}
				else
				{
					//check->calculateTimes();
				}

				cIterator++;
			}

			if(deleteLast == true)
			{
				collisions.erase(lastIterator);
			}

			collideTestWithTiles(co1, tL, &collisions);
			collideTestWithSprites(game, co1, &collisions);

			if(co2->isStaticObject() == false)
			{
				collideTestWithTiles(co2, tL, &collisions);
				collideTestWithSprites(game, co2, &collisions);
			}

			collisions.sort(compare_collisionTime);

			timer += (colTime-timer);
		}//end if


		if(co2->isStaticObject() == true)
		{
			coStackCounter ++;
			coStack[coStackCounter] = co2;
		}

		collisionStackCounter ++;
		collisionStack[collisionStackCounter] = currentCollision;
	
	}
	
	if(timer < 1)
	{
		gsm->updateViewport(game, 1-timer);
		pp = player->getPhysicalProperties();
		pp->setPosition(pp->getX() + (pp->getVelocityX()*(1-timer)),pp->getY() + (pp->getVelocityY()*(1-timer)));
		//pp->setVelocity(0.0f, pp->getVelocityY());
		botIterator = sm->getBotsIterator();
		while (botIterator != sm->getEndOfBotsIterator())
		{			
			Bot *bot = (*botIterator);
			pp = bot->getPhysicalProperties();
			pp->setPosition(pp->getX() + (pp->getVelocityX()*(1-timer)), pp->getY() + (pp->getVelocityY()*(1-timer)));
			botIterator++;
		}
		gsm->updateViewport(game, 1-timer);
	}
	
	pp = player->getPhysicalProperties();
	if(pp->getX() < 0)
	{
		pp->setX(0);
	}
	if(pp->getY() < 0)
	{
		pp->setY(0);
	}
	//pp->setVelocity(0.0f, pp->getVelocityY());
	/*pp->setPosition(pp->getX() + pp->getVelocityX(), pp->getY() + pp->getVelocityY());

	// FOR NOW THE PLAYER IS DIRECTLY CONTROLLED BY THE KEYBOARD,
	// SO WE'LL NEED TO TURN OFF ANY VELOCITY APPLIED BY INPUT
	// SO THE NEXT FRAME IT DOESN'T GET ADDED
	pp->setVelocity(0.0f, pp->getVelocityY());

	// AND NOW MOVE ALL THE BOTS
	list<Bot*>::iterator botIterator = sm->getBotsIterator();
	while (botIterator != sm->getEndOfBotsIterator())
	{			
		Bot *bot = (*botIterator);
		pp = bot->getPhysicalProperties();
		pp->setPosition(pp->getX() + pp->getVelocityX(), pp->getY() + pp->getVelocityY());
		botIterator++;
	}*/

	
}