コード例 #1
0
ファイル: myUtils.cpp プロジェクト: AlexanderSjoholm/CMS
Object* getSelectedObject(std::list<Object*>* allObjects, Player* player)
{
	if(!allObjects || allObjects->empty())
		return NULL;
	float a,b,c,d,e,f; 
	float minDistance = 999999999999;
	Object* closestObject;
	cv::Vec3f objectPosition;
	cv::Vec4f distanceVector;
	cv::Vec4f playerPosition(player->position[0], player->position[1], player->position[2], 1);
	cv::Vec4f lookAt(player->lookAtVector[0], player->lookAtVector[1], player->lookAtVector[2], 1);
	cv::Matx<float,4,4> plueckerCoords = playerPosition*lookAt.t() - lookAt*playerPosition.t();
	a = plueckerCoords(0,1);
	b = plueckerCoords(0,2);
	c = plueckerCoords(0,3);
	d = plueckerCoords(1,2);
	e = plueckerCoords(1,3);
	f = plueckerCoords(2,3);

	cv::Matx<float,4,4> dualPlueckerCoords(0, f, -e, d,
										   -f, 0, c, -b,
										   e, -c, 0, a,
										   -d, b, -a, 0);

	cv::Matx<float,3,3> A(0, f, -e,
						  -f, 0, c,
						  e, -c, 0);

	A = A.t()*A;

	dualPlueckerCoords = sqrt(2)/(A(0,0)*A(1,1)*A(2,2))*dualPlueckerCoords;
	
	
	for(std::list<Object*>::iterator it = allObjects->begin(); it != allObjects->end(); ++it)
	{
		objectPosition = (*it)->position;
		distanceVector = dualPlueckerCoords*cv::Vec4f(objectPosition(0), objectPosition(1), objectPosition(2), 1);
		std::cout << "vectorNorm" << cv::norm(cv::Vec3f(distanceVector(0),distanceVector(1),distanceVector(2))) << std::endl;
		if (minDistance > cv::norm(cv::Vec3f(distanceVector(0),distanceVector(1),distanceVector(2))))
		{
			minDistance = cv::norm(cv::Vec3f(distanceVector(0),distanceVector(1),distanceVector(2)));
			closestObject = (*it);
		}

	}
	std::cout << "plueckerCoords: " << plueckerCoords << std::endl;
	std::cout << "dualPlueckerCoords: " << dualPlueckerCoords << std::endl;
	std::cout << "plueckerCoords: " << a << "  " << b << "  " << c << "  " << d << "  " << e << "  " << f << std::endl;
	std::cout << "Minimum distance " << minDistance << std::endl;
	
	return closestObject;

	
	return NULL;
		
}
コード例 #2
0
ファイル: tippeligaen.cpp プロジェクト: jtd/tippeliga
void Tippeligaen::insertPlayerToTeamOfTheRound(){
    actionShowTeamOfTheRound_triggered();

    QSqlQuery insertTeamOfTheRound;
    insertTeamOfTheRound.prepare("INSERT INTO rundenslag (rundensLagNavn, navn, posisjon, lagNavn)"
                         "VALUES (:rundensLagNavn, :navn, :posisjon, :lagNavn)");
    insertTeamOfTheRound.bindValue(":rundensLagNavn", teamOfTheRoundIdLabel()->text());
    insertTeamOfTheRound.bindValue(":navn", playerName()->text());
    insertTeamOfTheRound.bindValue(":posisjon", playerPosition()->text());
    insertTeamOfTheRound.bindValue(":lagNavn", playerTeam()->text());
    insertTeamOfTheRound.exec();
}
コード例 #3
0
void ComponentCamera::update()
{
	shake();

	// ZOOM/ALTURA de la camara
/*	if(eventManager->isKeyPressed(KEY::KEY_HOME) || eventManager->isKeyPressed(KEY::KEY_KEY_P))
	{
		relativePosition.y = startYPosition;
	}
	if(eventManager->mouseState.wheelUp || eventManager->isKeyPressed(KEY::KEY_PRIOR) || eventManager->isKeyPressed(KEY::KEY_KEY_O))
	{
		speed += ACCELERATION;
	}
	else if(eventManager->mouseState.wheelDown || eventManager->isKeyPressed(KEY::KEY_NEXT) || eventManager->isKeyPressed(KEY::KEY_KEY_L))
	{
		speed -= ACCELERATION;
	}

	if (speed > MAX_SPEED)
	{
		speed = MAX_SPEED;
	}
	if (speed < -MAX_SPEED)
	{
		speed = -MAX_SPEED;
	}

	speed *= FRICTION;

	if (Math::abs(speed) < Math::abs(0.1))
	{
		speed = 0;
	}

	relativePosition.y += speed;

	if (relativePosition.y > MAX_ZOOM)
	{
		relativePosition.y = MAX_ZOOM;
	}
	else if (relativePosition.y < MIN_ZOOM)
	{
		relativePosition.y = MIN_ZOOM;
	}
	*/

	Vector3d playerPosition(parent->position.x, 0, parent->position.y);
	node->setPosition(playerPosition + relativePosition + offset);
	node->setTargetPosition(playerPosition + offset);
}
コード例 #4
0
  SimpleScene() : eyes({ { PerEyeArg(LEFT), PerEyeArg(RIGHT) } }) {
    eyeHeight = 1.0f;
    applyProjectionOffset = true;
    applyModelviewOffset = true;
    {
      OVR::Ptr<OVR::ProfileManager> profileManager = *OVR::ProfileManager::Create();
      OVR::Ptr<OVR::Profile> profile = *(profileManager->GetDeviceDefaultProfile(OVR::ProfileType::Profile_RiftDK1));
      ipd = profile->GetIPD();
      eyeHeight = profile->GetEyeHeight();
      glm::mat4 modelviewOffset = glm::translate(glm::mat4(),
        glm::vec3(ipd / 2.0f, 0, 0));
      eyes[LEFT].modelviewOffset = modelviewOffset;
      eyes[RIGHT].modelviewOffset = glm::inverse(modelviewOffset);
    }

    if (ovrManager) {
      ovrSensor =
        *ovrManager->EnumerateDevices<OVR::SensorDevice>().CreateDevice();
      if (ovrSensor) {
        sensorFusion.AttachToSensor(ovrSensor);
      }
    }
    if (sensorFusion.IsAttachedToSensor()) {
      SAY("Attached");
    } else {
      SAY("Attach failed");
    }

    {
      OVR::HMDInfo hmdInfo;
      Rift::getHmdInfo(ovrManager, hmdInfo);
      OVR::Util::Render::StereoConfig config;
      config.SetHMDInfo(hmdInfo);
      gl::Stacks::projection().top() = 
        glm::perspective(config.GetYFOVRadians(), eyeAspect, 0.01f, 1000.0f);
      glm::mat4 projectionOffset = glm::translate(glm::mat4(),
        glm::vec3(config.GetProjectionCenterOffset(), 0, 0));
      eyes[LEFT].projectionOffset = projectionOffset;
      eyes[RIGHT].projectionOffset = glm::inverse(projectionOffset);
    }

    glm::vec3 playerPosition(0, eyeHeight, ipd * 4.0f);
    player = glm::inverse(glm::lookAt(playerPosition, glm::vec3(0, eyeHeight, 0), GlUtils::Y_AXIS));
    CameraControl::instance().enableHydra(true);
  }
コード例 #5
0
ファイル: main.cpp プロジェクト: blueskies9041/Sam
int main( int argc, char* argv[] )
{	
	const int iScreenWidth = 1680;
	const int iScreenHeight = 1050;
	Initialise( iScreenWidth, iScreenHeight, false);

	uiBgImage = CreateSprite("./images/Blue Eye.png", iScreenWidth, iScreenHeight, false);

	Vector2D playerPosition(840, 625);
	Vector2D playerSpeed(0,0);
	Sprite Player(playerPosition, playerSpeed, 100, 100, -1); 

	do 
	{
		DrawSprite(uiBgImage);

	} while ( FrameworkUpdate() == false );
	
	Shutdown();

	return 0;
}
コード例 #6
0
ファイル: tippeligaen.cpp プロジェクト: jtd/tippeliga
void Tippeligaen::createTeamInfoGroupBox(){
    playerInfoGroupBox = new QGroupBox(tr("Spillerinfo"));
    _shirtLabel = new QLabel();
    _shirtLabel->setAlignment(Qt::AlignRight);
    _shirtLabel->setPixmap(QPixmap(":/bilder/0.png"));

    _playerNameLabel = new QLabel;
    _playerNameLabel->setText(tr("Spillernavn: "));
    _playerPositionLabel = new QLabel;
    _playerPositionLabel->setText(tr("Posisjon: "));
    _playerTeamLabel = new QLabel;
    _playerTeamLabel->setText(tr("Lag: "));

    deletePlayerButton = new QPushButton;
    deletePlayerButton->setText(tr("Slett"));
    addToTeamOfTheRoundButton = new QPushButton;
    addToTeamOfTheRoundButton->setText(tr("Legg til i rundens lag"));

    _playerName = new QLabel;
    _playerTeam = new QLabel;
    _playerPosition = new QLabel;

    QGridLayout *layout = new QGridLayout;
    layout->addWidget(playerNameLabel(), 0, 0);
    layout->addWidget(playerName(), 0, 1);
    layout->addWidget(playerPositionLabel(), 1, 0);
    layout->addWidget(playerPosition(), 1, 1);
    layout->addWidget(playerTeamLabel(), 2, 0);
    layout->addWidget(playerTeam(), 2, 1);
    layout->addWidget(deletePlayerButton, 3, 0);
    layout->addWidget(addToTeamOfTheRoundButton, 3, 1);
    layout->addWidget(shirtLabel(), 0, 2, 4, 1);
    playerInfoGroupBox->setLayout(layout);

    playerInfoGroupBox->setMinimumHeight(170);
}
コード例 #7
0
ファイル: MainGame.cpp プロジェクト: Awilg/Learning
void MainGame::processInput(){
	SDL_Event evnt;

	const float CAMERA_SPEED = 2.0f;
	const float SCALE_SPEED = 0.1f;

	while (SDL_PollEvent(&evnt)) {
		switch (evnt.type)
		{
		case SDL_QUIT:
			_gameState = GameState::EXIT;
			break;
		case SDL_MOUSEMOTION:
			_inputManager.setMouseCoords(evnt.motion.x, evnt.motion.y);
			break;
		case SDL_KEYUP:
			_inputManager.releaseKey(evnt.key.keysym.sym);
			break;
		case SDL_KEYDOWN:
			_inputManager.pressKey(evnt.key.keysym.sym);
			break;
		case SDL_MOUSEBUTTONDOWN:
			_inputManager.pressKey(evnt.button.button);
			break;
		case SDL_MOUSEBUTTONUP:
			_inputManager.releaseKey(evnt.button.button);
			break;
		default:
			break;	
		}
	}

	if (_inputManager.isKeyDown(SDLK_ESCAPE)) {
		_gameState = GameState::EXIT;
	}
	if (_inputManager.isKeyDown(SDLK_w)) {
		_camera.setPosition(_camera.getPosition() + glm::vec2(0.0f, CAMERA_SPEED));
	}
	if (_inputManager.isKeyDown(SDLK_s)) {
		_camera.setPosition(_camera.getPosition() + glm::vec2(0.0f, -CAMERA_SPEED));
	}
	if (_inputManager.isKeyDown(SDLK_a)) {
		_camera.setPosition(_camera.getPosition() + glm::vec2(-CAMERA_SPEED, 0.0f));
	}
	if (_inputManager.isKeyDown(SDLK_d)) {
		_camera.setPosition(_camera.getPosition() + glm::vec2(CAMERA_SPEED, 0.0f));
	}
	if (_inputManager.isKeyDown(SDLK_q)) {
		_camera.setScale(_camera.getScale() + SCALE_SPEED);
	}
	if (_inputManager.isKeyDown(SDLK_e)) {
		_camera.setScale(_camera.getScale() + -SCALE_SPEED);
	}
	if (_inputManager.isKeyDown(SDL_BUTTON_LEFT)) {
		glm::vec2 coords = _inputManager.getMouseCoords();
		coords = _camera.convertScreenToWorld(coords);
		std::cout << coords.x << " " << coords.y << std::endl;

		glm::vec2 playerPosition(0.0f);
		glm::vec2 direction = coords - playerPosition;
		direction = glm::normalize(direction);

		_bullets.emplace_back(playerPosition, direction, 5.0f, 1000);
	}

}
コード例 #8
0
ファイル: faceinvaders.cpp プロジェクト: m4dm4x/FaceInvaders
int main() {
	typedef std::deque<Invader> InvaderList;
	typedef std::deque<Shot> ShotList;

	cv::VideoCapture cap( DEFAULT_DEVICE );
	if(!cap.isOpened()) {
		std::cerr << "Error opening VideoCapture!" << std::endl;
		return -1;
	}
	
	cap.set(CV_CAP_PROP_FRAME_WIDTH, 1024);
	cap.set(CV_CAP_PROP_FRAME_HEIGHT, 768);
	
	cv::namedWindow("SpaceInvaders", CV_WINDOW_AUTOSIZE);
	
	cv::Mat cameraImage;
	cap >> cameraImage;
	
	const cv::Size CameraImageSize( cameraImage.size() );
	
	for (int key = -1; ' ' != key; key = cv::waitKey(WAIT_DELAY_MS)) {
		cap >> cameraImage;
		cv::flip(cameraImage, cameraImage, FLIPPING_AROUND_Y_AXIS);
		cv::putText(cameraImage, "Press space to play!", cv::Point(30,80), cv::FONT_HERSHEY_SIMPLEX, 2, cv::Scalar::all(255), 2, 8);
		cv::resize(cameraImage, cameraImage, CameraImageSize * 2);
		cv::imshow("SpaceInvaders", cameraImage);
	}
	
	const GameImage playerImage( PLAYER_PNG );
	const GameImage invaderImage( INVADER_PNG );
	
	const int YPlayerShot = CameraImageSize.height - playerImage.size().height;
	const int YGameOver = YPlayerShot - invaderImage.size().height;
	
	Player player(playerImage, CameraImageSize, SHOT_LINE_PIX);
	PlayerPosition playerPosition(player, HAARCASCADE_XML, CameraImageSize);
	Shot playerShot;
	bool gameOver = false;
	
	InvaderList invaders;
	std::generate_n(std::back_inserter(invaders), MAX_INVADERS, Invader::Factory(invaderImage, CameraImageSize, 5));
	
	ShotList shots;
	
	cv::RNG rng(uint64(std::time(0)));
	
	for (int key = -1; 'q' != key; key = cv::waitKey(WAIT_DELAY_MS)) {
		cap >> cameraImage;
		cv::flip(cameraImage, cameraImage, FLIPPING_AROUND_Y_AXIS);

		if (!gameOver) {
		
		playerPosition.update(cameraImage);
		playerShot.update();
		std::for_each(invaders.begin(), invaders.end(), GraphicUpdate);
		std::for_each(shots.begin(), shots.end(), GraphicUpdate);
		
		if (playerShot.isValid()) {
			const InvaderList::iterator iInvaderEnd = std::remove_if(invaders.begin(),invaders.end(), GraphicColision(playerShot.rect()));
			if (iInvaderEnd != invaders.end()) {
				invaders.erase(iInvaderEnd, invaders.end());
				playerShot = Shot();
			}
		}
		
		if (!shots.empty()) {
			const ShotList::iterator iShotsEnd = std::remove_if(shots.begin(), shots.end(), isInvalidShot);
			if (iShotsEnd != shots.end()) {
				shots.erase(iShotsEnd, shots.end());
			}
		}
		
		for (InvaderList::const_iterator iInvader = invaders.begin(); iInvader != invaders.end() && !gameOver; ++iInvader) {
			const cv::Rect irect( iInvader->rect() );
			if ((rng.uniform(0.0,1.0) < 0.05) && (shots.size() < MAX_INVADERS)) {
				cv::Point shotPos(irect.x + (irect.width / 2), irect.y + irect.height);
				shots.push_back( Shot(shotPos, SHOT_SPEED, cv::Scalar(100,50,100), CameraImageSize) );
			}
			if (irect.y >= YGameOver) {
				gameOver = true;
			}
		}
		
		if (!playerShot.isValid() && player.isShooting()) {
			cv::Point shotPoint( player.facePosition().x, YPlayerShot );
			playerShot = Shot(shotPoint, -SHOT_SPEED, cv::Scalar(100,170,10), CameraImageSize);
		}
		
		for (ShotList::iterator iShot(shots.begin()); iShot != shots.end() && !gameOver; ++iShot) {
			if (iShot->isValid() && checkColision(iShot->rect(),player.rect())) {
				gameOver = true;
			}
		}
		
		}
		
		std::for_each(invaders.begin(), invaders.end(), GraphicPaint(cameraImage));
		std::for_each(shots.begin(), shots.end(), GraphicPaint(cameraImage));
		player.paint(cameraImage);
		playerShot.paint(cameraImage);
		
		if (invaders.empty()) {
			cv::putText(cameraImage, "Winner!", cv::Point(30,80), cv::FONT_HERSHEY_SIMPLEX, 3, cv::Scalar::all(255), 2, 8);
		} else if (gameOver) {
			cv::putText(cameraImage, "Game Over!", cv::Point(30,80), cv::FONT_HERSHEY_SIMPLEX, 3, cv::Scalar::all(255), 2, 8);
		}
		
		cv::resize(cameraImage, cameraImage, CameraImageSize * 2);
		cv::imshow("SpaceInvaders", cameraImage);
	}
	
	return 0;
}
コード例 #9
0
/**
 ****************************************************************************************************
	\fn			void Update( GameEngine::Entity &i_entity )
	\brief		Update the position of Enemy
	\param		i_entity entity to be updated
	\return		NONE
 ****************************************************************************************************
*/
void EnemyController::Update( GameEngine::Entity &i_entity )
{
	FUNCTION_START;

	_bSprint = false;

	switch( _enemyState )
	{
	case E_ENEMY_IDLE:
		if( g_captureTheFlag::Get().m_playerTeam == Utilities::StringHash("BlueFlag") )
			g_world::Get().UpdateAIDestinationTo( i_entity.m_u8AIEntityIndex, GlobalConstant::BLUE_FLAG_NODE_ID );
		else
			g_world::Get().UpdateAIDestinationTo( i_entity.m_u8AIEntityIndex, GlobalConstant::RED_FLAG_NODE_ID );
		_prevState = _enemyState;
		_enemyState = E_ENEMY_SEARCH_FLAG;
		break;

	case E_ENEMY_SEARCH_FLAG:
		if( g_captureTheFlag::Get().m_bEnemyHasFlag == true )
		{
			g_world::Get().UpdateAIDestinationTo( i_entity.m_u8AIEntityIndex, GlobalConstant::GOAL_NODE_ID );
			_prevState = _enemyState;
			_enemyState = E_ENEMY_SEARCH_GOAL;
		}
		break;

	case E_ENEMY_SEARCH_GOAL:
		if( g_captureTheFlag::Get().m_bEnemyHasFlag == false )
		{
			_prevState = _enemyState;
			_enemyState = E_ENEMY_IDLE;
		}
		break;

	case E_ENEMY_TAG_PLAYER:
		//if( !_bAwareOfPlayer )
		{
			UINT32 u32NodeID;
			Utilities::Pointer::SmartPtr<GameEngine::Entity> player = g_world::Get().GetEntityByName( "Player" );

			D3DXVECTOR3 playerPosition( player->m_v3Position.X(), player->m_v3Position.Y(), player->m_v3Position.Z() );
			GameEngine::AI::FindClosestNodeIDFromPosition( playerPosition, u32NodeID );

			// If player moved to other area
			if( u32NodeID != _u32NewTargetNode )
				g_world::Get().UpdateAIDestinationTo( i_entity.m_u8AIEntityIndex, _u32NewTargetNode );
		}
		_bSprint = true;
		break;

	case E_ENEMY_ESCAPE:
		_bSprint = true;
		break;
	}

	if( !_bSprint && (_u32Power < GlobalConstant::MAX_POWER) )
		_u32Power += 1;

	GameEngine::Renderer::DrawSlider( D3DXVECTOR2(850, 64), _u32Power, 0, GlobalConstant::MAX_POWER );

	FUNCTION_FINISH;
}
コード例 #10
0
ファイル: Engine.cpp プロジェクト: RichardMarks/LWC
	void Engine::Execute()
	{
		// we don't have a state stack processor system yet
		// so lets just get a basic while loop running for testing
		
		
		Position playerPosition(0, 0, 0); 
		char hudActionMessage[0x100];
		char compassMessage[0x32];
		bool requestUpdateDisplay = true;
		bool requestClearActionMessage = false;
		int actionMessageClearDelay = 50;
		int actionMessageClearCounter = actionMessageClearDelay;
		
				
		sprintf(hudActionMessage, "%s", "Starting Out...");
		
		int actionMessageX = ((screen_->w / 2) - ((strlen(hudActionMessage) * 9) / 2));
		
		playerPosition.Copy(gameState_->GetPlayerPosition());
		
		int playerX = playerPosition.x_;
		int playerZ = playerPosition.y_;
		int compass = playerPosition.facing_;
		
		sprintf(compassMessage, "You are facing %s.",
			(0x0 == playerPosition.facing_) ? "North" :
			(0x1 == playerPosition.facing_) ? "East" :
			(0x2 == playerPosition.facing_) ? "South" :
			(0x3 == playerPosition.facing_) ? "West" : "<Invalid Direction>");

		int gameScreenX = 40;
		int gameScreenY = mainScreen_->h / 2 - screen_->h / 2;
		
		
		SDL_Surface* mainScreenOverlay = Engine::LoadImageResource("resources/overlays/mainscreen.png");
		
		if (!mainScreenOverlay)
		{
			this->Stop();
			return;
		}
		
		// small compass overlay images
		SDL_Surface** smallCompassOverlay = new SDL_Surface* [4];
		
		smallCompassOverlay[0] = Engine::LoadImageResource("resources/overlays/sm_compass_n.png");
		smallCompassOverlay[1] = Engine::LoadImageResource("resources/overlays/sm_compass_e.png");
		smallCompassOverlay[2] = Engine::LoadImageResource("resources/overlays/sm_compass_s.png");
		smallCompassOverlay[3] = Engine::LoadImageResource("resources/overlays/sm_compass_w.png");


		

		// better input handling
		const int MOTIONBUTTON_UP 			= 0x0;
		const int MOTIONBUTTON_DOWN 		= 0x1;
		const int MOTIONBUTTON_STRAFELEFT 	= 0x2;
		const int MOTIONBUTTON_STRAFERIGHT 	= 0x3;
		bool motionButtonDown[4] = { false, false, false, false };
		
		// slow the f*****g player down!
		int playerMotionDelay = 10;
		int playerMotionCounter = playerMotionDelay;
		
		
		// a minimap
		MiniMap miniMap(gameState_->GetCurrentMap(), 140, 140);

		// while the engine is running
		while(engineIsRunning_)
		{
			// process the events
			while(SDL_PollEvent(event_))
			{
				switch(event_->type)
				{
					// the window was closed
					case SDL_QUIT:
					{
						// stop the engine
						this->Stop();
					} break;

					// a key was pressed
					case SDL_KEYDOWN:
					{
						// what key is down
						switch(event_->key.keysym.sym)
						{
							case SDLK_ESCAPE:
							{
								// stop the engine
								this->Stop();
							} break;
							
							case 'w':
							case 'W':
							case SDLK_UP:
							{
								motionButtonDown[MOTIONBUTTON_UP] = true;
							} break;
							
							case 's':
							case 'S':
							case SDLK_DOWN:
							{
								motionButtonDown[MOTIONBUTTON_DOWN] = true;
							} break;
							
							case 'q':
							case 'Q':
							case SDLK_COMMA:
							case SDLK_LESS:
							{
								motionButtonDown[MOTIONBUTTON_STRAFELEFT] = true;
							} break;
							
							case 'e':
							case 'E':
							case SDLK_PERIOD:
							case SDLK_GREATER:
							{
								motionButtonDown[MOTIONBUTTON_STRAFERIGHT] = true;
							} break;
							
							default: break;
						} // end switch
					} break;
					
					// a key was released
					case SDL_KEYUP:
					{
						// what key is up
						switch(event_->key.keysym.sym)
						{
							case 'w':
							case 'W':
							case SDLK_UP:
							{
								motionButtonDown[MOTIONBUTTON_UP] = false;
							} break;
							
							case 's':
							case 'S':
							case SDLK_DOWN:
							{
								motionButtonDown[MOTIONBUTTON_DOWN] = false;
							} break;
							
							case 'q':
							case 'Q':
							case SDLK_COMMA:
							case SDLK_LESS:
							{
								motionButtonDown[MOTIONBUTTON_STRAFELEFT] = false;
							} break;
							
							case 'e':
							case 'E':
							case SDLK_PERIOD:
							case SDLK_GREATER:
							{
								motionButtonDown[MOTIONBUTTON_STRAFERIGHT] = false;
							} break;
							
							case 'a':
							case 'A':
							case SDLK_LEFT:
							{
								gameState_->TurnPlayerLeft();
								sprintf(hudActionMessage, "%s", "Turned Left...");
								requestUpdateDisplay = true;
							} break;
							
							case 'd':
							case 'D':
							case SDLK_RIGHT:
							{
								gameState_->TurnPlayerRight();
								sprintf(hudActionMessage, "%s", "Turned Right...");
								requestUpdateDisplay = true;
							} break;
							default: break;
						}
					} break;

					default: break;
				} // end switch
			} // end while
			
////////////////////////////////////////////////////////////////////////////////
// *************************** NEW PLAYER MOTION **************************** //
////////////////////////////////////////////////////////////////////////////////
			
			// are we moving forward?
			if (motionButtonDown[MOTIONBUTTON_UP])
			{
				if (--playerMotionCounter <= 0)
				{
					playerMotionCounter = playerMotionDelay;
					
					if (gameState_->MovePlayerForward())
					{
						sprintf(hudActionMessage, "%s", "Moved Forward...");
						requestUpdateDisplay = true;
					}
					else
					{
						sprintf(hudActionMessage, "%s", "That way is blocked!");
						requestUpdateDisplay = true;
					}
				}
			}
			
			// are we moving back?
			if (motionButtonDown[MOTIONBUTTON_DOWN])
			{
				if (--playerMotionCounter <= 0)
				{
					playerMotionCounter = playerMotionDelay;
					
					if (gameState_->MovePlayerBack())
					{
						sprintf(hudActionMessage, "%s", "Moved Back...");
						requestUpdateDisplay = true;
					}
					else
					{
						sprintf(hudActionMessage, "%s", "That way is blocked!");
						requestUpdateDisplay = true;
					}
				}
			}
			
			// are we strafing left?
			if (motionButtonDown[MOTIONBUTTON_STRAFELEFT])
			{
				if (--playerMotionCounter <= 0)
				{
					playerMotionCounter = playerMotionDelay;
					
					if (gameState_->MovePlayerLeft())
					{
						sprintf(hudActionMessage, "%s", "Stepped Left...");
						requestUpdateDisplay = true;
					}
					else
					{
						sprintf(hudActionMessage, "%s", "That way is blocked!");
						requestUpdateDisplay = true;
					}
				}
			}
			
			// are we strafing right?
			if (motionButtonDown[MOTIONBUTTON_STRAFERIGHT])
			{
				if (--playerMotionCounter <= 0)
				{
					playerMotionCounter = playerMotionDelay;
					
					if (gameState_->MovePlayerRight())
					{
						sprintf(hudActionMessage, "%s", "Stepped Right...");
						requestUpdateDisplay = true;
					}
					else
					{
						sprintf(hudActionMessage, "%s", "That way is blocked!");
						requestUpdateDisplay = true;
					}
				}
			}

			// is is time to request the action message be cleared?
			if (--actionMessageClearCounter <= 0)
			{
				actionMessageClearCounter = actionMessageClearDelay;
				requestClearActionMessage = true;
			}
			
			// should we clear the action message ?
			if (requestClearActionMessage)
			{
				sprintf(hudActionMessage, "%s", "Waiting...");
				requestClearActionMessage = false;
				requestUpdateDisplay = true;
			}
			
			// should we update the display?
			if (requestUpdateDisplay)
			{
				actionMessageX = ((screen_->w / 2) - ((strlen(hudActionMessage) * 9) / 2));
	
				playerPosition.Copy(gameState_->GetPlayerPosition());
	
				playerX = playerPosition.x_;
				playerZ = playerPosition.y_;
				compass = playerPosition.facing_;
	
				sprintf(compassMessage, "You are facing %s.",
					(0x0 == playerPosition.facing_) ? "North" :
					(0x1 == playerPosition.facing_) ? "East" :
					(0x2 == playerPosition.facing_) ? "South" :
					(0x3 == playerPosition.facing_) ? "West" : "<Invalid Direction>");
					
				
				mapView_->RenderMap(screen_, gameState_->GetCurrentMap(), gameState_->GetPlayerPosition());
				
				defaultFont_->Print(screen_, actionMessageX, 8, "%s", hudActionMessage);
				defaultFont_->Print(screen_, 8, screen_->h - 34, "Player X: %2d", playerX);
				defaultFont_->Print(screen_, 8, screen_->h - 25, "Player Z: %2d", playerZ);
				defaultFont_->Print(screen_, 8, screen_->h - 16, "%s", compassMessage);
			
				// blit the game screen onto the main screen
				Engine::BlitSprite(screen_, mainScreen_, gameScreenX, gameScreenY);
			
				// blit the overlays
				Engine::BlitSprite(mainScreenOverlay, mainScreen_, 0, 0);
				
				Engine::BlitSprite(smallCompassOverlay[compass], mainScreen_, 42, 42);
				
				// blit the minimap
				miniMap.Update();
				miniMap.Render(mainScreen_, 390, 290);
				
				requestUpdateDisplay = false;
			}
			
			
			
			// flip the screen
			this->FlipScreen();
			
			// reduce the cpu hoggingness of SDL ^-^
			SDL_Delay(20);
		} // end while
		
		Engine::UnloadImageResource(smallCompassOverlay[0]);
		Engine::UnloadImageResource(smallCompassOverlay[1]);
		Engine::UnloadImageResource(smallCompassOverlay[2]);
		Engine::UnloadImageResource(smallCompassOverlay[3]);
		delete [] smallCompassOverlay;
		
		Engine::UnloadImageResource(mainScreenOverlay);
		
		
	}
void CAIAwarenessToPlayerHelper::RecalculateAwareness()
{
	int highestAlertnessInGameRightNow = 0;

	float distanceToTheClosestHostileAgentSq = FLT_MAX;
	Vec3 playerPosition(ZERO);

	const IFactionMap& factionMap = gEnv->pAISystem->GetFactionMap();
	uint8 playerFactionID = factionMap.GetFactionID("Players");

	IAIObject* playerAiObject = NULL;
	CActor* playerActor = static_cast<CActor*>(gEnv->pGame->GetIGameFramework()->GetClientActor());

	if (playerActor)
	{
		if (IEntity* playerEntity = playerActor->GetEntity())
		{
			playerPosition = playerEntity->GetWorldPos();
			playerAiObject = playerEntity->GetAI();
		}
	}

	IF_UNLIKELY ((playerActor == NULL) || (playerAiObject == NULL))
		return;

	const bool playerIsCloaked = playerActor ? playerActor->IsCloaked() : true;

	const bool applyProximityToHostileAgentIncrement = m_actualAwareness < kAIAwarenessToPlayerAware && !playerPosition.IsZero();

	// Go through actors
	IActorIteratorPtr actorIt = gEnv->pGame->GetIGameFramework()->GetIActorSystem()->CreateActorIterator();
	if (actorIt)
	{
		while (IActor* actor = actorIt->Next())
		{
			const IAIObject* ai = actor->GetEntity()->GetAI();
			const IAIActor* aiActor = ai ? ai->CastToIAIActor() : NULL;
			if (aiActor && aiActor->IsActive())
			{
				const int alertness = GetAlertnessAffectedByVisibility(*aiActor, *playerAiObject, playerIsCloaked);

				highestAlertnessInGameRightNow = std::max(alertness, highestAlertnessInGameRightNow);

				if (applyProximityToHostileAgentIncrement && 
					factionMap.GetReaction(playerFactionID, ai->GetFactionID()) == IFactionMap::Hostile)
				{
					float distanceSq = playerPosition.GetSquaredDistance(ai->GetPos());
					if (distanceToTheClosestHostileAgentSq > distanceSq)
					{
						distanceToTheClosestHostileAgentSq = distanceSq;
					}
				}
			}
		}
	}

	// Go through non Actors
	{
		SAwarenessEntitiesVector::iterator it = m_awarenessEntities.begin();
		SAwarenessEntitiesVector::iterator end = m_awarenessEntities.end();

		for (; it != end; ++it)
		{
			const IAwarenessEntity* pAwarenessEntity = *it;
			const int awareness = pAwarenessEntity->GetAwarenessToActor( playerAiObject, playerActor );
			highestAlertnessInGameRightNow = std::max(awareness, highestAlertnessInGameRightNow);
		}
	}


	///
	assert(highestAlertnessInGameRightNow >= 0 && highestAlertnessInGameRightNow <= 2);

	switch (highestAlertnessInGameRightNow)
	{
	default: 
		{
			const float thresholdDistanceSq = square(g_pGameCVars->ai_ProximityToHostileAlertnessIncrementThresholdDistance);
			if (applyProximityToHostileAgentIncrement && distanceToTheClosestHostileAgentSq < thresholdDistanceSq)
			{
				m_actualAwareness = kAIAwarenessToPlayerAware * (1 - (distanceToTheClosestHostileAgentSq / thresholdDistanceSq));
			}
			else
			{
				m_actualAwareness = 0.0f;
			}
		}
		break;
	case 1:  m_actualAwareness = kAIAwarenessToPlayerAware;  break;
	case 2:  m_actualAwareness = kAIAwarenessToPlayerAlerted; break;
	}
}
コード例 #12
0
ファイル: MainGame.cpp プロジェクト: Chefkoch85/MGamesWBen
//Processes input with SDL
void MainGame::processInput() 
{
    SDL_Event evnt;

    const float CAMERA_SPEED = 2.0f;
    const float SCALE_SPEED = 0.1f;

    //Will keep looping until there are no more events to process
    while (SDL_PollEvent(&evnt)) 
	{
		mGuiMgr.Update(evnt);

        switch (evnt.type) 
		{
            case SDL_QUIT:
                _gameState = GameState::EXIT;
                break;

            case SDL_MOUSEMOTION:
                _inputManager.setMouseCoords((float)evnt.motion.x, (float)evnt.motion.y);
                break;

            case SDL_KEYDOWN:
                _inputManager.pressKey(evnt.key.keysym.sym);
                break;

            case SDL_KEYUP:
                _inputManager.releaseKey(evnt.key.keysym.sym);
                break;

            case SDL_MOUSEBUTTONDOWN:
                _inputManager.pressKey(evnt.button.button);
                break;

            case SDL_MOUSEBUTTONUP:
                _inputManager.releaseKey(evnt.button.button);
                break;
        }
    }

	static bool enter = false;
	if (_inputManager.isKeyPressed(SDLK_1) && !enter)
	{
		enter = true;
		mGuiMgr.SetActiveScene(0);
	}
	else if (_inputManager.isKeyPressed(SDLK_2) && !enter)
	{
		enter = true;
		mGuiMgr.SetActiveScene(1);
	}

	if (!_inputManager.isKeyPressed(SDLK_1) &&
		!_inputManager.isKeyPressed(SDLK_2))
	{
		enter = false;
	}

    if (_inputManager.isKeyPressed(SDLK_w)) 
	{
        _camera.setPosition(_camera.getPosition() + glm::vec2(0.0f, CAMERA_SPEED));
    }
    if (_inputManager.isKeyPressed(SDLK_s))
	{
        _camera.setPosition(_camera.getPosition() + glm::vec2(0.0f, -CAMERA_SPEED));
    }
    if (_inputManager.isKeyPressed(SDLK_a)) 
	{
        _camera.setPosition(_camera.getPosition() + glm::vec2(-CAMERA_SPEED, 0.0f));
    }
    if (_inputManager.isKeyPressed(SDLK_d)) 
	{
        _camera.setPosition(_camera.getPosition() + glm::vec2(CAMERA_SPEED, 0.0f));
    }
    if (_inputManager.isKeyPressed(SDLK_q))
	{
        _camera.setScale(_camera.getScale() + SCALE_SPEED);
    }
    if (_inputManager.isKeyPressed(SDLK_e))
	{
        _camera.setScale(_camera.getScale() - SCALE_SPEED);
    }

    if (_inputManager.isKeyPressed(SDL_BUTTON_LEFT)) 
	{
        glm::vec2 mouseCoords = _inputManager.getMouseCoords();
        mouseCoords = _camera.convertScreenToWorld(mouseCoords);
        
        glm::vec2 playerPosition(0.0f);
        glm::vec2 direction = mouseCoords - playerPosition;
        direction = glm::normalize(direction);

        _bullets.emplace_back(playerPosition, direction, 5.00f, 50);
    }
}
コード例 #13
0
void NetworkManager::BeginUpdate( void )
{
	RakNet::Packet *packet = GameEngine::Network::ReceivePacket();

	while( packet )
	{
		switch( packet->data[0] )
		{
			case ID_CONNECTION_REQUEST_ACCEPTED:
				GameEngine::Network::SetOtherAddress( packet->systemAddress );
				break;

			case ID_NEW_INCOMING_CONNECTION:
				GameEngine::Network::SetOtherAddress( packet->systemAddress );
				if( GameEngine::Network::IsServer() )
				{
					enemy->SetController( NULL );
					GameEngine::AI::RemoveAIEntity( enemy->m_u8AIEntityIndex );

					S_START_UP_PACKET startUpPacket;
					startUpPacket.serverPositionX = player->m_v3Position.X();
					startUpPacket.serverPositionY = player->m_v3Position.Y();
					startUpPacket.serverPositionZ = player->m_v3Position.Z();
					startUpPacket.clientPositionX = enemy->m_v3Position.X();
					startUpPacket.clientPositionY = enemy->m_v3Position.Y();
					startUpPacket.clientPositionZ = enemy->m_v3Position.Z();
					startUpPacket.serverTeam = g_captureTheFlag::Get().m_playerTeam;
					startUpPacket.clientTeam = g_captureTheFlag::Get().m_enemyTeam;
					startUpPacket.u32ServerScore = g_captureTheFlag::Get().m_u32PlayerScore;
					startUpPacket.u32ClientScore = g_captureTheFlag::Get().m_u32EnemyScore;
					startUpPacket.u8ServerAreaID = g_captureTheFlag::Get().m_u8PlayerAreaID;
					startUpPacket.u8ClientAreaID = g_captureTheFlag::Get().m_u8EnemyAreaID;
					startUpPacket.bServerHasFlag = g_captureTheFlag::Get().m_bPlayerHasFlag;
					startUpPacket.bClientHasFlag = g_captureTheFlag::Get().m_bEnemyHasFlag;

					GameEngine::Network::SendHighPriorityPackage( E_ID_START_UP, (char*)&startUpPacket, sizeof(startUpPacket) );
				}
				break;

			case ID_CONNECTION_ATTEMPT_FAILED:
				g_captureTheFlag::Get().m_bNetworkReady = false;
				exit( 0 );
				break;

			case ID_CONNECTION_LOST:
			case ID_DISCONNECTION_NOTIFICATION:
				g_captureTheFlag::Get().m_bNetworkReady = false;
				GameEngine::Network::IsConnected( false );
				break;

			case E_ID_START_UP:
				if( !GameEngine::Network::IsServer() )
				{
					S_START_UP_PACKET startUpPacket;
					RakNet::BitStream bs( packet->data, packet->length, false );

					bs.IgnoreBytes( sizeof(RakNet::MessageID) );
					bs.Read( (char*)&startUpPacket, sizeof(startUpPacket) );

					g_captureTheFlag::Get().m_playerTeam = startUpPacket.clientTeam;
					g_captureTheFlag::Get().m_enemyTeam = startUpPacket.serverTeam;
					g_captureTheFlag::Get().m_u32PlayerScore = startUpPacket.u32ClientScore;
					g_captureTheFlag::Get().m_u32EnemyScore = startUpPacket.u32ServerScore;
					g_captureTheFlag::Get().m_u8PlayerAreaID = startUpPacket.u8ClientAreaID;
					g_captureTheFlag::Get().m_u8EnemyAreaID = startUpPacket.u8ServerAreaID;
					g_captureTheFlag::Get().m_bPlayerHasFlag = startUpPacket.bClientHasFlag;
					g_captureTheFlag::Get().m_bEnemyHasFlag = startUpPacket.bServerHasFlag;

					D3DXVECTOR3 playerPosition( startUpPacket.clientPositionX, startUpPacket.clientPositionY, startUpPacket.clientPositionZ );
					D3DXVECTOR3 enemyPosition( startUpPacket.serverPositionX, startUpPacket.serverPositionY, startUpPacket.serverPositionZ );

					if( !g_captureTheFlag::Get().Initialize(playerPosition,enemyPosition) )
					{
						GameEngine::ShutDown();
						return;
					}

					g_captureTheFlag::Get().m_bNetworkReady = true;
				}
				break;

			case E_ID_UPDATE:
			{
				RakNet::BitStream bs( packet->data, packet->length, false );
				D3DXVECTOR3 position;

				bs.IgnoreBytes( sizeof(RakNet::MessageID) );
				bs.Read( (char*)&position, sizeof(position) );

				enemy->m_v3Position = position;
				enemy->m_v3ProjectedPosition = position;
				break;

			}

			case E_ID_WORLD_EVENT:
				if( GameEngine::Network::IsServer() )
					return;

				S_EVENT_PACKET eventPacket;
				RakNet::BitStream bs( packet->data, packet->length, false );

				bs.IgnoreBytes( sizeof(RakNet::MessageID) );
				bs.Read( (char*)&eventPacket, sizeof(eventPacket) );

				switch( eventPacket.u8Type )
				{
					case E_WORLD_EVENT_SCORE:
					{
						UINT32 prevEnemyScore = g_captureTheFlag::Get().m_u32PlayerScore;
						UINT32 prevPlayerScore = g_captureTheFlag::Get().m_u32EnemyScore;

						g_captureTheFlag::Get().m_u32PlayerScore = eventPacket.data[1];
						g_captureTheFlag::Get().m_u32EnemyScore = eventPacket.data[0];

						if( prevEnemyScore < g_captureTheFlag::Get().m_u32EnemyScore )
							GameEngine::Audio::Play2DSoundEffect( g_captureTheFlag::Get().m_u32EnemyScore, "enemyScore.wav" );
						else if( prevPlayerScore < g_captureTheFlag::Get().m_u32PlayerScore )
							GameEngine::Audio::Play2DSoundEffect( g_captureTheFlag::Get().m_u32PlayerScore, "playerScore.wav" );
						break;
					}

					case E_WORLD_EVENT_FLAG_PICK_UP:
						if( eventPacket.data[0] )
						{
							g_captureTheFlag::Get().m_bEnemyHasFlag = true;
							GameEngine::Audio::Play2DSoundEffect( g_captureTheFlag::Get().m_u32EnemyPickUpSfxID, "enemyPickFlag.wav" );
						}
						else
						{
							g_captureTheFlag::Get().m_bPlayerHasFlag = true;
							GameEngine::Audio::Play2DSoundEffect( g_captureTheFlag::Get().m_u32PlayerPickUpSfxID, "playerPickFlag.wav" );
						}
						break;

					case E_WORLD_EVENT_FLAG_RESET:
						if( eventPacket.data[0] )
							g_captureTheFlag::Get().m_bEnemyHasFlag = false;
						else
							g_captureTheFlag::Get().m_bPlayerHasFlag = false;
						GameEngine::Audio::Play2DSoundEffect( g_captureTheFlag::Get().m_u32FlagResetSfxID, "flagReset.wav" );
						break;
				}
				break;
		}

		packet = GameEngine::Network::ReceivePacket( packet );
	}
}