Beispiel #1
0
void Quiddiards::animate(){
	if (pause){
		return;
	}
	handleCollision();
	clock_t gap = clock() - msec;
	msec += gap;
	float sec = gap / 1000.0f;
	ground->wave(sec);
	/* wave flags */
	for (int i = 0; i < FLAGNUM; i++){
		flags[i].wave(sec * wind.length());
	}
	/* move balls */
	for (unsigned i = 0; i < balls.size(); i++){
		balls[i]->move(sec);
		balls[i]->grav(sec);
		/* test touch with ground */
		float depth;
		if ((depth = ground->depth(balls[i]->getBottom())) > 0){
			balls[i]->floa(depth, sec);
		}
		//if (balls[i]->getType() == Ball::CUEBALL){
		//	operable = (balls[i]->getVelocity().length() < FLT_EPSILON);
		//	if (operable){
		//		cuebroom.setAim(balls[i]->getCenter());
		//	}
		//	else{
		//		/* change spotlight direction according to cueball movement */
		//		//glLoadIdentity();
		//		//spotDir = (cueball.getCenter() - spotPos.toVector3D()).normalized();
		//		//glLightfv(GL_LIGHT1, GL_SPOT_DIRECTION, (float*)&spotDir);
		//		//spotPos = { cueball.getX(), cueball.getY(), 15.0f ,1.0};
		//		//glLightfv(GL_LIGHT1, GL_POSITION, (float*)&spotPos);
		//	}
		//}
	}
	handleCollision();

	/* manage snitch states */
	static float cnt = 0;
	cnt += sec;
	if (cnt > snitch.getInterval()){
		cnt = 0;
		if (snitch.isSleep()){
			snitch.setVelocity({ 0, 0, snitch.getSpeed() / 5 });
			snitch.setSleep(false);
		}
		else{
			snitch.setVelocity({ 0, 0, -snitch.getSpeed() });
			snitch.setSleep(true);
		}
	}
	/* particle system */
	ps->simulate(sec);
	update();
}
Beispiel #2
0
/// Called when two fixtures begin to touch.
void CollisionHandler::BeginContact(b2Contact* contact)
{
    b2Body *bodyA = contact->GetFixtureA()->GetBody();
    b2Body *bodyB = contact->GetFixtureB()->GetBody();
    if (bodyA == NULL || bodyB == NULL)
        return;

    handleCollision(contact, bodyA, bodyB);
    handleCollision(contact, bodyB, bodyA);
}
Beispiel #3
0
void Animal::handleCollisions(Environment *environment) {
    Vector2D boundsCorrection;
    if (getBounds().getMinX() < environment->getBounds().getMinX()) {
        boundsCorrection.setX(environment->getBounds().getMinX() - getBounds().getMinX());
    }
    if (getBounds().getMinY() < environment->getBounds().getMinY()) {
        boundsCorrection.setY(environment->getBounds().getMinY() - getBounds().getMinY());
    }
    if (getBounds().getMaxX() > environment->getBounds().getMaxX()) {
        boundsCorrection.setX(environment->getBounds().getMaxX() - getBounds().getMaxX());
    }
    if (getBounds().getMaxY() > environment->getBounds().getMaxY()) {
        boundsCorrection.setY(environment->getBounds().getMaxY() - getBounds().getMaxY());
    }
    translate(boundsCorrection);
    
    std::vector<Object *> nearestObjects = environment->getNearestObjects(this);
    for (int k = 0; k < nearestObjects.size(); k++) {
        Object *nearestObject = nearestObjects[k];
        double distance = getPosition().distanceTo(nearestObject->getPosition());
        double radius = (OBJECT_WIDTH / 2);
        if (distance < 2.0 * radius) {
            Vector2D overlapVector = Vector2D(nearestObject->getPosition(), getPosition());        
            overlapVector = overlapVector.normalize();
            
            double overlapLength = 2.0 * radius - distance;
            overlapVector = overlapVector.mult(overlapLength);
            
            translate(overlapVector);
            
            handleCollision(environment, nearestObject);
        }
    }
}
void CTECHashTable<Type>::add(HashNode<Type> currentNode)
{
	if (!contains(currentNode))
	{
		//Update size if needed. Find where to put the value.
		if (this->size / this->capacity >= this->efficiencyPercentage)
		{
			updateSize();
		}

		int positionToInsert = findPosition(currentNode);

		if (internalStorage[positionToInsert] != nullptr)
		{
			//Loop over the internalStorage to find the next empty slot. Insert the value there.
			while(internalStorage[positionToInsert] != nullptr)
			{
				//positionToInsert = (positionToInsert + 1) % capacity;
				positionToInsert = handleCollision(currentNode);
			}
		}
		internalStorage[positionToInsert] = &currentNode;
		size++;
	}
}
Beispiel #5
0
void Boss::update(const double dt_){
	
	timePasssed += dt_;

	scoutPosition(dt_);

	this->animation->update(this->animationClip, dt_);
	this->powerAnimation->update(this->powerClip, dt_);
	this->shieldAnimation->update(this->shieldClip, dt_);

	updateBoundingBox();

	const std::array<bool, CollisionSide::SOLID_TOTAL> detections = detectCollision();
	handleCollision(detections);

	updatePosition(dt_);

	this->currentState->update(dt_);

    for(auto potion : this->potions){
        if(!potion->activated){
            // Delete potion.
        }
        potion->update(dt_);
    }
}
Beispiel #6
0
void
Snake::ReceiveMessage(Message* m)
{
    if(m_isStopped)
    {
        return;
    }
    
	if(m->GetMessageName() == "GridCollision")
    {
        handleCollision(m);
    }
    if(m->GetMessageName() == "FoodConsumed")
    {
        handleConsumedFood(m);
    }
    if(m->GetMessageName() == "MoveUp")
    {
        handleChangeDirection(DirectionUp);
    }
    if(m->GetMessageName() == "MoveDown")
    {
        handleChangeDirection(DirectionDown);
    }
    if(m->GetMessageName() == "MoveLeft")
    {
        handleChangeDirection(DirectionLeft);
    }
    if(m->GetMessageName() == "MoveRight")
    {
        handleChangeDirection(DirectionRight);
    }
}
Beispiel #7
0
int Ghost::eventHandler(Event *p_e) {
	if (p_e->getType() == HERO_MOVE_EVENT) {
		EventHeroMove *p_hm_e = static_cast<EventHeroMove *>(p_e);
		hero_pos = p_hm_e->getPos();
		return 1;
	}
	if (p_e->getType() == STEP_EVENT) {
		speed_cooldown--;
		if (speed_cooldown == 0) {
			speed_cooldown = max_speed_cooldown;
			move_to_hero();
		}
		return 1;
	}
	if (p_e->getType() == COLLISION_EVENT) {
		EventCollision *p_c_e = static_cast<EventCollision *>(p_e);
		handleCollision(p_c_e);
	}
	if (p_e->getType() == LEVEL_UP_EVENT) {
		EventLevelUp *le = static_cast<EventLevelUp *>(p_e);
		max_speed_cooldown -= le->getLevel();
		ghost_velocity += GHOST_VELOCITY * le->getLevel();
		if (max_speed_cooldown < 1){
			max_speed_cooldown = 1;
		}
	}
	return 0;
}
void BouncyBall::update(float deltaTime)
{
	// If we are jumping, velocity is affected by gravity */
	if(jumping)
		m_velY = m_velY + GRAVITY_CONSTANT * deltaTime * FUN_CONSTANT;

	// set new X and Y values and check boundaries
	m_y += m_velY * deltaTime * FUN_CONSTANT;
	m_x += m_velX * deltaTime * FUN_CONSTANT;

	CollisionType col;
	Platform * hitPlatform = NULL;
	if((col = platformCollision(hitPlatform)) != NONE)
	{
		handleCollision(col, hitPlatform);
	}

	if(sliding)
	{
		m_velX /= SLIDE_CONSTANT;

		if(abs(m_velX) <= SMALL_ENOUGH_NUMBER){
			m_velX = 0;
			sliding = false;
			canSlide = true;
		}
	}
}
Beispiel #9
0
void GameState::checkCollisions(std::shared_ptr<GraphicalEntity> graphical_sp) {

    for(auto it = mGraphicalEntities.begin(), end = mGraphicalEntities.end(); it != end; ++it) {
        auto other_sp = *it;

        //we can't collide with ourselves!
        if(graphical_sp == other_sp)
            continue;

        //check and handle collision
        handleCollision(graphical_sp.get(), other_sp.get());
    }

    for(auto it = mCollisionZones.begin(), end = mCollisionZones.end(); it != end; ++it) {
        auto other_sp = *it;

        //check and handle collision
        handleCollision(other_sp.get(), graphical_sp.get());
    }
}
Beispiel #10
0
int Tail::Game::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: handleCollision((*reinterpret_cast< const ContactPoint*(*)>(_a[1]))); break;
        default: ;
        }
        _id -= 1;
    }
    return _id;
}
Beispiel #11
0
/*Check whether any collisions occurred.*/
void checkForCollisions()
{
    struct vertex center = {0.0, 0.0, 0.0};
  
    for(int i = 0; i < globalProjectile.pIndex; i++)
    {
        struct vertex projPos = globalProjectile.projectiles[i].position;

        checkBaseCollisions(globalProjectile.projectiles[i], i);
       
        /*Test for outer ring collision. Negate the collision result 
         *to get when the sum of the radii is less than the distance.*/
        if(!isCollision(projPos, center, RADIUS, RING_SIZE))
            handleCollision(i);

        /*Test sun collision.*/
        if(isCollision(projPos, center, RADIUS, RADIUS))
            handleCollision(i);

        /*Test for sail collision.*/
        if(isSailCollision(projPos, center))
            handleCollision(i);

        /*Test if this projectile colllided with another projectile.*/
        int collided = projectileCollided(projPos, i);
        if(collided != NO_COLLISION)
        {
            printf("Got a collision! Proj:%d\n", i);
            deleteProjectile(i);
            /*Subtract 1 as the previously deleted projectile
             *will move the array one step to the left.*/
            deleteProjectile(collided - 1);
            playCrashSound();
        }
    }
}
Beispiel #12
0
void GameManager::start()
{
	while (!isExit() && m_alivePlayersCount > 1)
	{
		m_gameCounter++; // assume the game counter is lower than int max value.

		Sleep(SLEEP_TIME);

		if (isExit())
		{
			continue;
		}

		m_gameBoard.moveArrows();

		// move the game players
		if (m_gameCounter % 2 == 0)
		{
			for (int iPlayer = 0; iPlayer < m_alivePlayersCount; iPlayer++)
			{
				m_players[iPlayer]->move();
				if (m_gameCounter % 15 == 0)
				{
					//TODO - implement a shooting algorithm - probably should be in the player class on the shoot method. 
					m_players[iPlayer]->shoot();
				}
			}

			// TODO - handle more then 2 players
			if (m_alivePlayersCount > 1)
			{
				handleCollision(*(m_players[0]), *(m_players[1]));
			}
		}

		if (m_gameCounter % 4 == 0)
		{
			m_gameBoard.addSurprise();
		}
		
	}

	if (m_alivePlayersCount == 1)
	{
		printWinner();
	}
}
long HashTable<Type> :: findPosition(Type data)
{
    long insertedPosition;
    unsigned long address =(long)&data;
    insertedPosition = address % capacity;
    HashNode<Type>* indexPointer = front;
    for (long index = 0; index < insertedPosition; index++)
    {
        indexPointer = indexPointer->getNode();
    }
if (indexPointer->hasStuffed())
{
    insertedPosition = handleCollision(data, insertedPosition);
}
    
    return insertedPosition;
}
void CTECHashTable<Type>:: add(HashNode<Type> currentNode){
	if(!contains(currentNode)){
		//resize if needed
		if(size/capacity >= this->efficiencyPercentage){
			updateCapacity();
		}
		int insertionIndex = findPosition(currentNode);

		if(internalStorage[insertionIndex] != nullptr){
			insertionIndex = handleCollision(currentNode);

			while (internalStorage[insertionIndex] != nullptr){
				insertionIndex = (insertionIndex + 1)% capacity;
			}
		}

		internalStorage[insertionIndex] = currentNode;
		size ++;
	}
}
Beispiel #15
0
bool Car::move(vmml::Matrix4f rotationY){
    bool checkPointPassed = false;
    if(speed != 0){
        vmml::Vector3f planeChange=vmml::Vector3f(0.f, -1.f, speed/100.f);
    
        vmml::Matrix4f planeMotion=vmml::create_translation(planeChange);
        modelMatrix *= planeMotion;
    
        vmml::Matrix4f rotationMatrix = rotationY;
        modelMatrix *= rotationMatrix;
    
        for(int i = 0; i < collidables.size(); i++){
            if(handleCollision(collidables.at(i)) && collidables.at(i).getType() == ObjectType::CHECKPOINT){
                checkPointPassed = true;
            }
            
        }
    }
    
    return checkPointPassed;
}
Beispiel #16
0
/*Check for base collisions.*/
void checkBaseCollisions(struct projectile proj, int i)
{
    /*Positions of the bases.*/
    struct vertex midBlueBase = {MID_BASE_X, MID_BASE_Y, 0.0};
    struct vertex northBlueBase = {SIDE_BASE_X, SIDE_BASE_Y, 0.0};
    struct vertex southBlueBase = {SIDE_BASE_X, -SIDE_BASE_Y, 0.0};
    struct vertex midRedBase = {-MID_BASE_X, 0.0, 0.0};
    struct vertex northRedBase = {-SIDE_BASE_X, SIDE_BASE_Y, 0.0};
    struct vertex southRedBase = {-SIDE_BASE_X, -SIDE_BASE_Y, 0.0};

    /*Test the bases for collision only if they are alive(this is given
     *via the globalBase struct.)*/

    /*Test blue bases.*/
    if(isBaseCollision(proj, midBlueBase, BLUE_BASE) && globalBase.blueMid)
    {
        handleCollision(i);
        globalBase.blueMid = FALSE;
    }
    if(isBaseCollision(proj, northBlueBase, BLUE_BASE) && globalBase.blueNorth)
    {
        handleCollision(i);
        globalBase.blueNorth = FALSE;
    }
    if(isBaseCollision(proj, southBlueBase, BLUE_BASE) && globalBase.blueSouth)
    {
        handleCollision(i);
        globalBase.blueSouth = FALSE;
    }

    /*Test red bases.*/
    if(isBaseCollision(proj, midRedBase, RED_BASE) && globalBase.redMid)
    {
        handleCollision(i);
        globalBase.redMid = FALSE;
    }
    if(isBaseCollision(proj, northRedBase, RED_BASE) && globalBase.redNorth)
    {
        handleCollision(i);
        globalBase.redNorth = FALSE;
    }
    if(isBaseCollision(proj, southRedBase, RED_BASE) && globalBase.redSouth)
    {
        handleCollision(i);
        globalBase.redSouth = FALSE;
    }
}
Beispiel #17
0
void Potion::update(const double dt_){

	const int angle = 360 - 45;
	const double gravity = 35;

    updateBoundingBox();
    this->animation->update(this->animationClip, dt_);

	const std::array<bool, CollisionSide::SOLID_TOTAL> detections = detectCollision();
    handleCollision(detections);

	if(this->activated){

        this->getAnimation()->changeAnimation(0, 0, 1, false, 0);

		this->flightTime +=dt_;

		const double speedXIdk = (this->distance/300.0)*(this->vx + this->strength * cos(angle/57.29) * flightTime);
		const double speedYIdk = (this->vy + this->strength * sin(angle/57.29) * flightTime - 0.5*gravity*flightTime*flightTime);

		if(this->isRight){
			this->x += speedXIdk;
		}
		else{
			this->x -= speedXIdk;
		}

		this->y -= speedYIdk;
	}
    else{
        if(this->canExplode){
            this->getAnimation()->changeAnimation(1, 0, 12, false, 0.8);
            this->canExplode = false;
        }
        if(this->getAnimation()->getCurrentFrame() == 12){
            this->isExploding =false;
        }
    }
}
Beispiel #18
0
void HashTable<Type> :: add(HashNode<Type> currentNode)
{
    if (!contains(currentNode))
    {
        if(size/capacity >= this->efficiencyPercentage)
        {
            updateCapacity();
        }
        
        int positionToInsert = findPosition(currentNode);
        
        if(internalStorage[positionToInsert] != nullptr)
        {
            while(internalStorage[positionToInsert] != nullptr)
            {
                positionToInsert = handleCollision(currentNode);
            }
        }
        
        internalStorage[positionToInsert] = &currentNode;
        size++;
    }
}
Beispiel #19
0
void Butter::update(double delta_t) {
    
    Vector3* speedVec = new Vector3(0, 0, 0);
    
    if (hadCollision()) {
        handleCollision(delta_t);
    }
    
    speed -= atrito * delta_t;
    if(direction==0){
        if (speed > 0) {
            speed = 0;
        }
    }
    if(direction==1){
        if (speed < 0) {
            speed = 0;
        }
    }
    speedVec->setX(speed * cos(((Car*)_collider)->getRotate() * PI / 180));
    speedVec->setY(speed * sin(((Car*)_collider)->getRotate()  * PI / 180));
    speedVec->setZ(0);

	//Check limits
	/*
	if (getPosition()->getX()<-36.7 || getPosition()->getX()>37.5) {
		speedVec->setX(0);
	}

	if (getPosition()->getY()<-36.7 || getPosition()->getY()>37.5) {
		speedVec->setY(0);
	}
    */

    setVelocity(speedVec);
    setPosition(_position->add(getVelocity()));
}
Beispiel #20
0
void World::update(sf::Time dt)
{
    mWorldView.move(0.f, dt.asSeconds() * mScrollSpeed);
    mPlayerAircraft->setVelocity(0.f, 0.f);
    destoryEntitiesOutOfView();
    guideMissiles();
    
    updateScore();
    // onCommand
    while (!mCommandQueue.isEmpty())
        mSceneGraph.onCommand(mCommandQueue.pop(), dt);
    
    // handles the diagonal velocity
    sf::Vector2f velocity = mPlayerAircraft->getVelocity();
    if (velocity.x != 0.f && velocity.y != 0.f)
        mPlayerAircraft->setVelocity(velocity / std::sqrt(2.f));
    
    mPlayerAircraft->accelerate(0.f, mScrollSpeed);
    
    // handles the cases when aircraft reaches boundaries
    sf::FloatRect viewBounds(mWorldView.getCenter() - mWorldView.getSize() / 2.f,
                             mWorldView.getSize());
    const float borderDistance = 40.f;
    sf::Vector2f position = mPlayerAircraft->getPosition();
    position.x = std::max(position.x, viewBounds.left + borderDistance);
    position.x = std::min(position.x, viewBounds.left + viewBounds.width - borderDistance);
    position.y = std::min(position.y, viewBounds.top  + viewBounds.height - borderDistance -20.f);
    position.y = std::max(position.y, viewBounds.top +borderDistance);
    mPlayerAircraft->setPosition(position);
    
    ///////////////////
    handleCollision();
    mSceneGraph.removeWrecks();
    spawnEnemies();
    mSceneGraph.update(dt, mCommandQueue);
}
Beispiel #21
0
int main()
{
    bool done = false;
    bool redraw = true;
    bool is_game_over = false;
    ALLEGRO_DISPLAY *display = NULL;
    ALLEGRO_EVENT_QUEUE *events = NULL;
    ALLEGRO_TIMER *timer = NULL;
    ALLEGRO_FONT *font20 = NULL;
    ALLEGRO_FONT *font40 = NULL;

    if (!al_init())
        return 1;
    display = al_create_display(DISPLAY_WIDTH, DISPLAY_HEIGHT);
    if (!display)
        return 1;    

    // Initialize add-ons
    al_init_primitives_addon();
    al_install_keyboard();
    al_init_font_addon();
    al_init_ttf_addon();

    timer = al_create_timer(1.0 / FPS);
    events = al_create_event_queue();
    al_register_event_source(events, al_get_keyboard_event_source());
    al_register_event_source(events, al_get_timer_event_source(timer));

    font20 = al_load_font("arial.ttf", 20, 0);
    font40 = al_load_font("arial.ttf", 40, 0);

    al_start_timer(timer);
    while (!done)
    {        
        // Events handling
        ALLEGRO_EVENT ev;
        al_wait_for_event(events, &ev);

        if (ev.type == ALLEGRO_EVENT_KEY_UP)
        {
            switch (ev.keyboard.keycode)
            {
                case ALLEGRO_KEY_J:
                    keys[J] = false;
                    break;
                case ALLEGRO_KEY_K:
                    keys[K] = false;
                    break;
                case ALLEGRO_KEY_S:
                    keys[S] = false;
                    break;
                case ALLEGRO_KEY_D:
                    keys[D] = false;
                    break;
                case ALLEGRO_KEY_ESCAPE:
                    done = true;
                    break;
            }
        }
        else if (ev.type == ALLEGRO_EVENT_TIMER)
        {
            redraw = true;

            if (!is_game_over)
            {
                updateBall(*ball);
                updateLeftBar(*bar1);
                updateRightBar(*bar2);
                handleCollision(*bar1, *bar2, *ball);

                if (score1 == WINNING_SCORE || score2 == WINNING_SCORE)
                    is_game_over = true;
            }
        }
        else if (ev.type == ALLEGRO_EVENT_KEY_DOWN)
        {
            switch (ev.keyboard.keycode)
            {
                case ALLEGRO_KEY_J:
                    keys[J] = true;
                    break;
                case ALLEGRO_KEY_K:
                    keys[K] = true;
                    break;
                case ALLEGRO_KEY_S:
                    keys[S] = true;
                    break;
                case ALLEGRO_KEY_D:
                    keys[D] = true;
                    break;
            }
        }
        
        if (redraw && al_is_event_queue_empty(events))
        {
            redraw = false;
            if (!is_game_over)
            {
                // Rendering
                al_clear_to_color(al_map_rgb(0, 0, 0));
                ball->render();
                bar1->render();
                bar2->render();
                al_draw_textf(font20, al_map_rgb(255, 255, 255), DISPLAY_WIDTH/2, DISPLAY_HEIGHT - 40, ALLEGRO_ALIGN_CENTRE, "%d : %d", score1, score2);
                al_flip_display();
            }
            else
            {
                al_clear_to_color(al_map_rgb(0, 0, 0));
                if (score1 == WINNING_SCORE)
                    al_draw_text(font40, al_map_rgb(255, 255, 255), DISPLAY_WIDTH/2, DISPLAY_HEIGHT/2 - 20, ALLEGRO_ALIGN_CENTRE, "PLAYER 1 WON");
                else if (score2 == WINNING_SCORE)
                    al_draw_text(font40, al_map_rgb(255, 255, 255), DISPLAY_WIDTH/2, DISPLAY_HEIGHT/2 - 20, ALLEGRO_ALIGN_CENTRE, "PLAYER 2 WON");
                al_draw_text(font20, al_map_rgb(255, 255, 255), DISPLAY_WIDTH/2, DISPLAY_HEIGHT/2 + 40, ALLEGRO_ALIGN_CENTRE, "Press 'r' to start a new game");
                al_flip_display();
            }
            
        }
    }

    // House cleaning
    delete ball;
    delete bar1;
    delete bar2;
    al_destroy_font(font20);
    al_destroy_font(font40);
    al_destroy_display(display);
    al_destroy_event_queue(events);

    return 0;
}
Beispiel #22
0
void CharacterController::checkCollision(MeshCollider* collider)
{
  Vector3 pos = getGameObject()->getTransform()->getPosition();

  Mesh* mesh = collider->getMesh();
  std::vector<Vector3>* vertices = mesh->getVertices();

  // We basically want to set the mesh to the origin, including its rotation.
  // If we rotate the mesh, then we need to make sure we rotate the characters bounds too
  // so that the angle between the mesh and character remains the same.
  // If we set position to 0, 0, then we need to make the characters bounds box move the same way
  // (minus the mesh's position) so that it doesn't get closer.

  Matrix4x4 mat = Matrix4x4::getTrs(collider->getGameObject()->getTransform()->getPosition(),
                          collider->getGameObject()->getTransform()->getRotation(),
                          Vector3(1, 1, 1));
  mat = mat.inverse();

  Vector3 relPos = mat * pos;
  Vector3 extents = bounds.extents;
  extents.y = extents.y / 2.0f; // Set to 20.0f for a large step

  //**********************************************
  Collision collision;
  //collision.relativeVelocity = frameMoveSpeed;

  for(int v = 0; v < vertices->size(); v+=3)
  {
    Vector3 a = vertices->at(v);
    Vector3 b = vertices->at(v+1);
    Vector3 c = vertices->at(v+2);

    if(colliding(relPos, extents, a, b, c) == true)
    {
      ContactPoint contact;

      contact.normal = findNormal(a, b, c);
      contact.thisCollider = this;
      contact.otherCollider = collider;
      contact.a = a;
      contact.b = b;
      contact.c = c;

      collision.contacts.push_back(contact);
    }
  }

  Matrix4x4 rotMat = Matrix4x4::getIdentity();
  rotMat = rotMat.rotate(collider->getGameObject()->getTransform()->getRotation() * -1.0f);

  if(collision.contacts.size() > 0)
  {
    //relPos = handleCollision(collision, relPos, extents);
    //relPos = relPos + (rotMat * handleCollision(collision, relPos, extents));
    relPos = relPos + handleCollision(collision, relPos, extents);
  }
  //*******************************************

  ///////////////////////////////////
  Collision stepCollision;
  Vector3 stepExtents = bounds.extents;
  stepExtents.x = stepExtents.x / 2.0f;
  stepExtents.z = stepExtents.z / 2.0f;
  stepExtents.y = stepExtents.y + 0.01f;

  for(int v = 0; v < vertices->size(); v+=3)
  {
    Vector3 a = vertices->at(v);
    Vector3 b = vertices->at(v+1);
    Vector3 c = vertices->at(v+2);

    if(colliding(relPos, stepExtents, a, b, c) == true)
    {
      ContactPoint contact;

      contact.normal = findNormal(a, b, c);
      contact.thisCollider = this;
      contact.otherCollider = collider;
      contact.a = a;
      contact.b = b;
      contact.c = c;

      stepCollision.contacts.push_back(contact);
    }
  }

  stepExtents.y = stepExtents.y - 0.01f;

  if(stepCollision.contacts.size() > 0)
  {
    grounded = true;
    relPos = relPos + (rotMat * handleStep(stepCollision, relPos, stepExtents));
  }
  else
  {
    //grounded = false;
  }
  ///////////////////////////////////

  mat = mat.inverse();
  getGameObject()->getTransform()->setPosition(mat * relPos);
}
Beispiel #23
0
void Player::move(Map map, Enemy **enemylist, int numberOfEnemies)
{
	// If the player is dead, don't move.
	if (!isAlive) {
		return;
	}

	// If the player if moving left ...
	if (moveState == PLAYER_MOVE_LEFT) {
		for (int i = 0; i < velX; i++)
		{
			hc.calculateCollisionPoints(getHeight(), getWidth(),
				posX - 1, posY,
				collisionPoints);
			int collisionType = checkCollision(map, enemylist, numberOfEnemies);
			if (collisionType) {
				handleCollision(collisionType);
				break;
			}

			posX--;
		}
	}

	// If the player is moving right ...
	if (moveState == PLAYER_MOVE_RIGHT) {
		for (int i = 0; i < velX; i++)
		{
			hc.calculateCollisionPoints(getHeight(), getWidth(),
				posX + 1, posY,
				collisionPoints);
			int collisionType = checkCollision(map, enemylist, numberOfEnemies);
			if (collisionType) {
				handleCollision(collisionType);
				break;
			}

			posX++;
		}
	}

	// If the player is moving up ...
	if (velY > 0) {
		// ... check each position step-by-step instead of just moving
		// the player 7 pixels immediately.
		for (int i = 0; i < PLAYER_GRAVITY; i++)
		{
			hc.calculateCollisionPoints(getHeight(), getWidth(),
				posX, posY - 1,
				collisionPoints);
			int collisionType = checkCollision(map, enemylist, numberOfEnemies);
			if (collisionType) {
				handleCollision(collisionType);
				decelerateY();
				break;
			}

			posY--;
			velY--;
		}
	}
	// If the player is moving down ...
	else {
		for (int i = velY; i < 0; i++)
		{
			// If the player is falling, they cannot jump.
			canJump = false;

			// If the player collides with something below, they have
			// landed and can jump again.
			hc.calculateCollisionPoints(getHeight(), getWidth(),
				posX, posY + 1,
				collisionPoints);
			int collisionType = checkCollision(map, enemylist, numberOfEnemies);
			if (collisionType) {
				handleCollision(collisionType);
				canJump = true;
				isJumping = false;
				break;
			}

			posY++;
		}
	}
}
Beispiel #24
0
void motor::Game::handlePlayer()
{
	float multiplierMove = 0;
	float multiplierRotate = 0;

	if(input->isPressed(Key::LSHIFT))
	{
		multiplierMove = 1.5f;
		multiplierRotate = 1.5f;
	}
	else if(input->isPressed(Key::RCTRL))
	{
		multiplierMove = 0.1f;
	}
	else
	{
		multiplierMove = 5.4f;
		multiplierRotate = 5.0f;
	}

	multiplierMove *= time->getFrameTime();
	multiplierRotate *= time->getFrameTime() * 20;

	glm::vec3 deltaMove(0, 0, 0);

	if(input->isPressed(Key::COMMA) && !input->isPressed(Key::O))//w
	{
		glm::vec3 delta = glm::vec3(0, 0, -1); //forward vector
		glm::vec2 deltaXZ = rotate(glm::vec2(delta.x, delta.z), camera->rotation.y);
		delta = glm::vec3(deltaXZ.x, delta.y, deltaXZ.y);
		deltaMove += delta;
		deltaMove = glm::normalize(deltaMove);
	}
	if(input->isPressed(Key::O) && !input->isPressed(Key::COMMA))//S
	{
		glm::vec3 delta = glm::vec3(0, 0, 1); //backward vector
		glm::vec2 deltaXZ = rotate(glm::vec2(delta.x, delta.z), camera->rotation.y);
		delta = glm::vec3(deltaXZ.x, delta.y, deltaXZ.y);
		deltaMove += delta;
		deltaMove = glm::normalize(deltaMove);
	}
	if(input->isPressed(Key::A) && !input->isPressed(Key::E))//a
	{
		glm::vec3 delta = glm::vec3(-1, 0, 0); //left vector
		glm::vec2 deltaXZ = rotate(glm::vec2(delta.x, delta.z), camera->rotation.y);
		delta = glm::vec3(deltaXZ.x, delta.y, deltaXZ.y);
		deltaMove += delta;
		deltaMove = glm::normalize(deltaMove);
	}
	if(input->isPressed(Key::E) && !input->isPressed(Key::A))//d
	{
		glm::vec3 delta = glm::vec3(1, 0, 0); //right vector
		glm::vec2 deltaXZ = rotate(glm::vec2(delta.x, delta.z), camera->rotation.y);
		delta = glm::vec3(deltaXZ.x, delta.y, deltaXZ.y);
		deltaMove += delta;
		deltaMove = glm::normalize(deltaMove);
	}

	if(input->isPressed(Key::LEFT))
	{
		camera->moveRotation(glm::vec3(0, -multiplierRotate, 0));
	}
	if(input->isPressed(Key::RIGHT))
	{
		camera->moveRotation(glm::vec3(0, multiplierRotate, 0));
	}
	if(input->isPressed(Key::UP))
	{
		camera->moveRotation(glm::vec3(-multiplierRotate, 0, 0));
	}
	if(input->isPressed(Key::DOWN))
	{
		camera->moveRotation(glm::vec3(multiplierRotate, 0, 0));
	}
	//----------------------------------
	//
	handleCollision(deltaMove, multiplierMove);

	if(input->isPressed(Key::SEMICOLON))
	{
		//newPos.y += 1.f * multiplierMove;
		//newPos.y += .1f;
		//camera->setPosition(newPos);
		vel.y = +15.f;
		pos.y += 1.f * multiplierMove;
	}
	if(input->isPressed(Key::DOT))
	{
		//newPos.y -= 1.f * multiplierMove;
		//newPos.y -= .1f;
		//camera->setPosition(newPos);
		vel.y = -15.f;
		pos.y -= 1.f * multiplierMove;
	}
	if(input->isPressed(Key::TAB))
	{
		pos.y = floor(pos.y) + .6;
	}
	//camera->setPosition(newPos);

	if(input->isPressed(Key::W) && input->getKeyDelay(Key::W) > .2f)
	{
		input->resetKeyDelay(Key::W);
		settings.printPosition = !settings.printPosition;
	}
	if(settings.printPosition)
	{
		cout << pos << " velY: " << vel.y << "\n";
	}

	if(input->isPressed(Key::BACKSPACE))
	{
		world.setBlock(int(pos.x) + 1, int(pos.y), int(pos.z), BLOCK_AIR);
		world.setBlock(int(pos.x) - 1, int(pos.y), int(pos.z), BLOCK_AIR);
		world.setBlock(int(pos.x) + 1, int(pos.y) - 1, int(pos.z), BLOCK_AIR);
		world.setBlock(int(pos.x) - 1, int(pos.y) - 1, int(pos.z), BLOCK_AIR);

		world.setBlock(int(pos.x), int(pos.y), int(pos.z) + 1, BLOCK_AIR);
		world.setBlock(int(pos.x), int(pos.y), int(pos.z) - 1, BLOCK_AIR);
		world.setBlock(int(pos.x), int(pos.y) - 1, int(pos.z) + 1, BLOCK_AIR);
		world.setBlock(int(pos.x), int(pos.y) - 1, int(pos.z) - 1, BLOCK_AIR);

		//world.setBlock(int(pos.x), int(pos.y - 1.6) - 1, int(pos.z), BLOCK_AIR);

		world.recalculateChunck(int(fabs(pos.x)), int(fabs(pos.y)), int(fabs(pos.z)));
		world.recalculateChunck(int(fabs(pos.x)) - 16, int(fabs(pos.y)), int(fabs(pos.z)));
		world.recalculateChunck(int(fabs(pos.x)) + 16, int(fabs(pos.y)), int(fabs(pos.z)));
		world.recalculateChunck(int(fabs(pos.x)), int(fabs(pos.y)), int(fabs(pos.z)) + 16);
		world.recalculateChunck(int(fabs(pos.x)), int(fabs(pos.y)), int(fabs(pos.z)) - 16);

		world.recalculateChunck(int(fabs(pos.x)) - 16, int(fabs(pos.y)), int(fabs(pos.z)) + 16);
		world.recalculateChunck(int(fabs(pos.x)) - 16, int(fabs(pos.y)), int(fabs(pos.z)) - 16);
		world.recalculateChunck(int(fabs(pos.x)) + 16, int(fabs(pos.y)), int(fabs(pos.z)) + 16);
		world.recalculateChunck(int(fabs(pos.x)) + 16, int(fabs(pos.y)), int(fabs(pos.z)) - 16);
	}

}
// ---------------------------------------------------------------
// strategie exploration en passant par la rangee en y = 1350
// ---------------------------------------------------------------
bool StrategyLargeAttackCL::preDefinedSkittleExploration2()
{
    LOG_COMMAND("preDefinedLargeSkittleExploration2\n");
    MvtMgr->setRobotDirection(MOVE_DIRECTION_FORWARD);
    bool noRotation = true;
    Point lineStart(2500, 1500);
    Point lineEnd(3200, 1500);
    Move->go2Target(lineStart,
		    MOVE_USE_DEFAULT_GAIN,
		    MOVE_USE_DEFAULT_SPEED,
		    noRotation);
    Events->wait(evtEndMove);
    if (!Events->isInWaitResult(EVENTS_MOVE_END)) {
        // on n'a pas reussi
        if (checkEndEvents()) return false; // c'est la fin du match?
	CollisionEnum collision = checkCollisionEvents();
	if (collision != COLLISION_NONE) {
	    if (!handleCollision(collision, lineStart, lineEnd))
		return false;
	} else {
	    LOG_WARNING("don't know what caused abort of movement. -> abort predefined exploration\n");
	    return false;
	}
    } else {
	// go2Target succeeded its movement.
	Move->rotate(0); // face right border
	Events->wait(evtEndMove);
	if (!Events->isInWaitResult(EVENTS_MOVE_END)) {
	    if (checkEndEvents()) return false; // end of match
	    // ok. normally the collision can only be on the left side...
	    CollisionEnum collision = checkCollisionEvents();
	    if (collision == COLLISION_LEFT) {
		if (!handleCollision(collision, lineStart, lineEnd))
		    return false;
	    } else if (collision == COLLISION_NONE) {
		LOG_WARNING("unhandled event. leaving function\n");
		return false;
	    } else {
		LOG_WARNING("collision, but most likely not a support\n");
		return false;
	    }
	}
    }

    bool endOfLine = false;
    while (!endOfLine) {
	Move->go2Target(lineEnd);
	Events->wait(evtEndMove);
	if (!Events->isInWaitResult(EVENTS_MOVE_END)) {
	    // let's hope it's a support.
	    if (checkEndEvents()) return false; // c'est la fin du match?
	    CollisionEnum collision = checkCollisionEvents();
	    if (collision != COLLISION_NONE) {
		if (!handleCollision(collision, lineStart, lineEnd))
		    return false;
	    } else {
		LOG_WARNING("don't know what caused abort of movement. -> abort predefined exploration\n");
		return false;
	    }
	    if (!RobotPos->isTargetForward(lineEnd))
		endOfLine = true;
	} else {
	    // ok. no more supports detected
	    endOfLine = true;
	}
    }

    LOG_INFO("predefined-large finished.\n");

    //alignBorder();
    
    // on recule un petit peu car on ne sais pas ce qu'on va se prendre en
    // approchant du robot adverse!, mieux vaut tenir que courir
    MvtMgr->setRobotDirection(MOVE_DIRECTION_BACKWARD);
    Trajectory t;
    t.clear();
    t.push_back(Point(3144, 1350)); 
    t.push_back(Point(3190, 1700)); 
    Move->followTrajectory(t, TRAJECTORY_BASIC);
    Events->wait(evtEndMove);
    if (!Events->isInWaitResult(EVENTS_MOVE_END)) {
        // on n'a pas reussi
        // c'est la fin du match?
        if (checkEndEvents()) return false;
        // TODO manage collisions
        return false;
    }

    //alignBorder();

    // on va droit sur l'adversaire
    MvtMgr->setRobotDirection(MOVE_DIRECTION_FORWARD);
    Move->go2Target(Point(3190, 650));
    Events->wait(evtEndMove);
    if (!Events->isInWaitResult(EVENTS_MOVE_END)) {
        // on n'a pas reussi
        // c'est la fin du match?
        if (checkEndEvents()) return false;
        // TODO manage collisions
        return false;
    }

    // on recule un peu
    MvtMgr->setRobotDirection(MOVE_DIRECTION_BACKWARD);
    Move->go2Target(Point(3190, 1050));
    Events->wait(evtEndMove);
    if (!Events->isInWaitResult(EVENTS_MOVE_END)) {
        // on n'a pas reussi
        // c'est la fin du match?
        if (checkEndEvents()) return false;
        // TODO manage collisions
        return false;
    }
    
    t.clear();
    t.push_back(Point(2550, 1050)); 
    t.push_back(Point(2594, 1650)); 
    t.push_back(Point(3340, 1650)); 
    MvtMgr->setRobotDirection(MOVE_DIRECTION_FORWARD);
    Move->followTrajectory(t, TRAJECTORY_BASIC);
    Events->wait(evtEndMove);
    if (!Events->isInWaitResult(EVENTS_MOVE_END)) {
        // on n'a pas reussi
        // c'est la fin du match?
        if (checkEndEvents()) return false;
        // TODO manage collisions
        return false;
    }

    MvtMgr->setRobotDirection(MOVE_DIRECTION_BACKWARD);
    Move->go2Target(Point(3190, 1650));
    Events->wait(evtEndMove);
    if (!Events->isInWaitResult(EVENTS_MOVE_END)) {
        // on n'a pas reussi
        // c'est la fin du match?
        if (checkEndEvents()) return false;
        // TODO manage collisions
        return false;
    }

    return true;
}
Beispiel #26
0
bool OEMFGame :: checkPosition(OEMFGObject * causedObj, int newX, int newY, bool handleCollisions)
{
	int dx, dy;
	dx = newX - causedObj->posX();
	dy = newY - causedObj->posY();
	// probe position
	deque<OEMFGObject *> objects = m_level->probePosition(newX, newY);
	OEMFGObject * obj;
	bool canPass = false;
	for (deque<OEMFGObject *>::iterator it = objects.begin(); it != objects.end(); it++)
	{
		obj = *it;
		if (obj != causedObj)
		{
			switch (obj->type())
			{
				case TYPE_START:
					if (causedObj != m_player)
					{
						if (handleCollisions) handleCollision(causedObj, obj, dx, dy, true);
						return false;
					}
					break;
				case TYPE_WALL:
					if (handleCollisions) handleCollision(causedObj, obj, dx, dy, true);
					return false;
					break;
				case TYPE_MOVABLE:
					if (dx != 0)
					{
						if (checkPosition(obj, obj->posX() + dx, obj->posY()))
						{
							m_level->moveObject(obj, obj->posX() + dx, obj->posY());
#ifndef WINCE
							if (!Mix_Playing(15))
								Mix_PlayChannel(15, sounds[SND_DRAG], 0);
#endif
							canPass = true;
						}
						else
						{
#ifndef WINCE
							Mix_HaltChannel(15);
#endif
							canPass = false;
						}
					}
					else
						canPass = false;
						
					// canPass = false;
					if (handleCollisions) handleCollision(causedObj, obj, dx, dy, !canPass);
					if (!canPass) return false;
					break;
				case TYPE_COIN100:
					if (handleCollisions) handleCollision(causedObj, obj, dx, dy, false);
					break;
				case TYPE_UNSTABLE:
					if (handleCollisions) handleCollision(causedObj, obj, dx, dy, (obj->flag() != 1));
					if (obj->flag() != 1) return false; // if flag is set, unstable object is not there and the space is open
					break;
				case TYPE_PLATFORM:
					if (handleCollisions) 
						handleCollision(causedObj, obj, dx, dy, dy > 0 && causedObj->posY() <= obj->posY() - 32);
					if (dy > 0 && causedObj->posY() <= obj->posY() - 32) return false;
					break;
				case TYPE_END:
					if (handleCollisions) handleCollision(causedObj, obj, dx, dy, true);
					return false;
					break;
				case TYPE_DEADLY:
					if (handleCollisions) handleCollision(causedObj, obj, dx, dy, true);
					return false;
					break;
				case TYPE_LEFTCONV:
				case TYPE_RIGHTCONV:
					if (handleCollisions) handleCollision(causedObj, obj, dx, dy, true);
					return false;
					break;
				case TYPE_LEFTFORCE:
				case TYPE_RIGHTFORCE:
					if (handleCollisions) handleCollision(causedObj, obj, dx, dy, false);
					break;
			}
		}
	}
	return true;
}
//used to handle all user input
void handleInput(int deltatime)
{
	
	float deltaseconds = deltatime / 1000.0f;

	if (State == "Play"){

		Time += deltaseconds;
		glutSetCursor(GLUT_CURSOR_NONE);
		glutPassiveMotionFunc(setMouse);
		glutWarpPointer(win1.width / 2, win1.height / 2);
		float mouseSpeed = 5;
		float xAngle = mouseSpeed * deltaseconds * float(win1.width / 2 - mPosX);
		float yAngle = mouseSpeed * deltaseconds * float(win1.height / 2 - mPosY);

		camera1->mouseLook(xAngle, yAngle);
		cylinder1.yaw(-xAngle);

		if (keys['w']) {
			if (!jumping)
				PlaySound(TEXT("step.wav"), NULL, SND_FILENAME | SND_ASYNC| SND_NOSTOP);
			camera1->move(deltaseconds * (15 + boost));
			distanceFromMaze = checkCollision(toClosestEdge);
			if (distanceFromMaze > 4.0){
				handleCollision();
			}
			moveTime++;
			if (moveTime > 30){
				legAngle *= -1;
				moveTime = 0;
			}
			thighLeft.pitch(legAngle);
			thighRight.pitch(-legAngle);

		}
		else{
			moveTime = 15;
			thighLeft.resetOrientation();
			thighRight.resetOrientation();


		}
		if (keys['f']){
			savePlayer = cylinder1;
			savePoint = camera1->getPosition();
			saveUP = camera1->getCameraUp();
			saveFOR = camera1->getForward();
			savePoint.y = 2;
			hasSavePoint = true;
			keys['f'] = false;
		}
		if (keys['g'] && hasSavePoint){
			cylinder1 = savePlayer;
			camera1->setPosition(savePoint);
			camera1->setCameraUp(saveUP);
			camera1->setForward(saveFOR);
			keys['g'] = false;
		}
		if (keys['s']){
			if (!jumping)
				PlaySound(TEXT("step.wav"), NULL, SND_FILENAME | SND_ASYNC | SND_NOSTOP);
			camera1->move(-deltaseconds * (15 + boost));
			distanceFromMaze = checkCollision(toClosestEdge);
			if (distanceFromMaze > 4.0){
				handleCollision();
			}

		}
		if (keys['a']) {
			if (!jumping)
				PlaySound(TEXT("step.wav"), NULL, SND_FILENAME | SND_ASYNC | SND_NOSTOP);
			camera1->strafe(-deltaseconds * (15 + boost));
			distanceFromMaze = checkCollision(toClosestEdge);
			if (distanceFromMaze > 4.0){
				handleCollision();
			}
		}
		if (keys['d']) {
			if (!jumping)
				PlaySound(TEXT("step.wav"), NULL, SND_FILENAME | SND_ASYNC | SND_NOSTOP);
			camera1->strafe(deltaseconds * (15 + boost));
			distanceFromMaze = checkCollision(toClosestEdge);
			if (distanceFromMaze > 4.0){
				handleCollision();
			}
		}
		if (keys['p']) {
			State = "Menu";
			isPaused = true;
		}
		if (keys[' '] && Stamina > 5 && !jumping) {
			PlaySound(TEXT("jump.wav"), NULL, SND_FILENAME | SND_ASYNC );
			jumping = true;
			Stamina -= 5;
			keys[' '] = false;
		}
		if (jumping) camera1->jump(deltaseconds * 10);
	
		
		if (camera1->getPosition().y <= 2){
			camera1->setPosition(Vector3(camera1->getPosition().x, 2, camera1->getPosition().z));
			jumping = false;
			camera1->gravity = 0.25;
		}

		if (special[GLUT_KEY_SHIFT_L] && Stamina > 0){
			Stamina -= (0.001 / deltaseconds);
			if (Stamina < 0){
				Stamina = 0;
				boost = 0;
			}
			else{
				boost = 10;
			}
		}
		else{
			boost = 0;
			Stamina += (0.001 / deltaseconds);
			if (Stamina >= 100){
				Stamina = 100;
			}
		}
	
	}
	if (State == "Menu"){
		if (!isPaused){
			if (special[GLUT_KEY_UP]){
				MenOption--;
				PlaySound(TEXT("switch.wav"), NULL, SND_FILENAME | SND_ASYNC);
				special[GLUT_KEY_UP] = false;
				if (MenOption < 0){
					MenOption = 3;
				}
			}

			if (special[GLUT_KEY_DOWN]){
				MenOption++;
				PlaySound(TEXT("switch.wav"), NULL, SND_FILENAME | SND_ASYNC);
				special[GLUT_KEY_DOWN] = false;
				if (MenOption > 3){
					MenOption = 0;
				}
			}
		}
		else{
			if (special[GLUT_KEY_UP]){
				PlaySound(TEXT("switch.wav"), NULL, SND_FILENAME | SND_ASYNC);
				MenOption--;
				special[GLUT_KEY_UP] = false;
				if (MenOption < 0){
					MenOption = 4;
				}
			}

			if (special[GLUT_KEY_DOWN]){
				PlaySound(TEXT("switch.wav"), NULL, SND_FILENAME | SND_ASYNC);
				MenOption++;
				special[GLUT_KEY_DOWN] = false;
				if (MenOption > 4){
					MenOption = 0;
				}
			}
		}

		if (keys[' '] && MenOption == 0){
			PlaySound(TEXT("play.wav"), NULL, SND_FILENAME | SND_ASYNC);
			if (!isPaused)
				State = "Loading";
			else
				State = "Play";
			keys[' '] = false;
			isPaused = false;
		}
		if (keys[' '] && MenOption == 1){
			PlaySound(TEXT("switch.wav"), NULL, SND_FILENAME | SND_ASYNC);
			State = "Controls";
			keys[' '] = false;
		}
		if (keys[' '] && MenOption == 2){
			PlaySound(TEXT("switch.wav"), NULL, SND_FILENAME | SND_ASYNC);
			State = "Credits";
			keys[' '] = false;
		}
		if (keys[' '] && MenOption == 3){
			PlaySound(TEXT("switch.wav"), NULL, SND_FILENAME | SND_ASYNC);
			glutExit();
		}
		if (keys[' '] && MenOption == 4){
			PlaySound(TEXT("switch.wav"), NULL, SND_FILENAME | SND_ASYNC);
			Stamina = 100;
			camera1 = new Camera(Vector3(levels[currLevel]->startPoint->x, 2, levels[currLevel]->startPoint->y), findPosition(levels[currLevel]), Vector3(0, 1, 0));
			State = "Loading";
			keys[' '] = false;
			isPaused = false;
		}
	}

	if (State == "Credits"){
		if (keys[' ']){
			PlaySound(TEXT("switch.wav"), NULL, SND_FILENAME | SND_ASYNC);
			State = "Menu";
			keys[' '] = false;
		}
	}
	if (State == "Controls"){
		if (keys[' ']){
			PlaySound(TEXT("switch.wav"), NULL, SND_FILENAME | SND_ASYNC);
			State = "Menu";
			keys[' '] = false;
		}
	}
	if (State == "Loading"){
		if (keys[' ']){
			PlaySound(TEXT("switch.wav"), NULL, SND_FILENAME | SND_ASYNC);
			State = "Play";
			keys[' '] = false;
		}
	}
}
Beispiel #28
0
int main()
{
    WORKING_DIR=SDL_GetBasePath();
    WORKING_DIR=WORKING_DIR.substr(0,WORKING_DIR.find_last_of("/\\"));
    WORKING_DIR=WORKING_DIR.substr(0,WORKING_DIR.find_last_of("/\\"));
    WORKING_DIR=WORKING_DIR.substr(0,WORKING_DIR.find_last_of("/\\"));
#ifdef __gnu_linux__
    WORKING_DIR+="/";
#elif __WIN32
    WORKING_DIR+="\\";
#endif
    std::cout<< WORKING_DIR<<std::endl;

    SDL_Window *mainwindow; /* Our window handle */
    SDL_GLContext maincontext; /* Our opengl context handle */
    Mix_Chunk *pong = NULL;
    Mix_Chunk *pong2 = NULL;
    Mix_Chunk *pong3 = NULL;
    if( SDL_Init( SDL_INIT_VIDEO| SDL_INIT_AUDIO ) < 0 )
    {
        sdldie("SDL could not initialize! SDL Error: %s\n");
    }
    else
    {
        //Use OpenGL 3.3 core
        SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
        SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 3 );
        SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );

        //Create window
        mainwindow = SDL_CreateWindow( "pong", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screenWidth, screenHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN |SDL_WINDOW_RESIZABLE );
        if( mainwindow == NULL )
        {
            sdldie("Unable to create window");
        }
        else
        {
            //Create context
            maincontext = SDL_GL_CreateContext( mainwindow );
            if( maincontext == NULL ){
                sdldie("OpenGL context could not be created! SDL Error: %s\n");
            }
            else
            {
                //Initialize GLEW
                glewExperimental = GL_TRUE;
                GLenum glewError = glewInit();
                if( glewError != GLEW_OK )
                {
                    std::cout<<"Error initializing GLEW! %s\n"<<glewGetErrorString( glewError );
                }

                //Use Vsync
                if( SDL_GL_SetSwapInterval( 1 ) < 0 )
                {
                    std::cout<<"Warning: Unable to set VSync! SDL Error: %s\n"<<SDL_GetError();
                }
                SDL_DisplayMode current;
                int should_be_zero = SDL_GetCurrentDisplayMode(0, &current); //@HACK:should check for multiple monitors
                if(should_be_zero != 0)
                  sdldie("Could not get display mode for video display");
                screenWidth=(3.0f/4.0f)*current.w;
                screenHeight=(3.0f/4.0f)*current.h;
                (*(int*)(&originalScreenHeight))=screenHeight;
                (*(int*)(&originalScreenWidth))=screenWidth;
            }
        }
    }
    //Initialize SDL_mixer
    if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 ) {
        std::cout<<"SDL_mixer could not initialize! SDL_mixer Error: "<<Mix_GetError();
        return 1;
    }
     //Load sound effects
    pong = Mix_LoadWAV(WORKING_DIR_FILE("assets/sounds/pong.wav"));
    if( pong == NULL ) {
        std::cout<< "Failed to load scratch sound effect! SDL_mixer Error: "<<Mix_GetError();
        return 1;
    }
    pong2 = Mix_LoadWAV(WORKING_DIR_FILE("assets/sounds/pong2.wav"));
    if( pong2 == NULL ) {
        std::cout<< "Failed to load scratch sound effect! SDL_mixer Error: "<<Mix_GetError();
        return 1;
    }
    pong3 = Mix_LoadWAV(WORKING_DIR_FILE("assets/sounds/pong3.wav"));
    if( pong3 == NULL ) {
        std::cout<< "Failed to load scratch sound effect! SDL_mixer Error: "<<Mix_GetError();
        return 1;
    }

    glEnable(GL_DEPTH_TEST);
    glViewport(0, 0, screenWidth, screenHeight);

    /* Clear our buffer with a red background */
    glClearColor ( 1.0, 0.0, 0.0, 1.0 );
    glClear ( GL_COLOR_BUFFER_BIT );
    /* Swap our back buffer to the front */
    SDL_GL_SwapWindow(mainwindow);
    /* Wait 2 seconds */
    SDL_Delay(100);

    /* Same as above, but green */
    glClearColor ( 0.0, 1.0, 0.0, 1.0 );
    glClear ( GL_COLOR_BUFFER_BIT );
    SDL_GL_SwapWindow(mainwindow);
    SDL_Delay(100);

    /* Same as above, but blue */
    glClearColor ( 0.0, 0.0, 1.0, 1.0 );
    glClear ( GL_COLOR_BUFFER_BIT );
    SDL_GL_SwapWindow(mainwindow);
    SDL_Delay(100);


    GLfloat vertices[] = {
         0.5f,  0.5f, 0.0f,  // Top Right
         0.5f, -0.5f, 0.0f,  // Bottom Right
        -0.5f, -0.5f, 0.0f,  // Bottom Left
        -0.5f,  0.5f, 0.0f,   // Top Left
    };
    GLuint indices[] = {  // Note that we start from 0!
        0, 1, 3,  // First Triangle
        1, 2, 3   // Second Triangle
    };

    std::vector<Vertex> vertices2;
    std::vector<GLuint> indices2;
    {
        for(unsigned int i=0;i<(sizeof(vertices)/sizeof(vertices[0]));i+=3){
            Vertex aux;
            aux.position={vertices[i+0],vertices[i+1],vertices[i+2]};
            vertices2.push_back(aux);
        }
        for(unsigned int i=0;i<(sizeof(indices)/sizeof(indices[0]));i++){
            indices2.push_back(indices[i]);
        }

    }
    Sprite sprite(vertices2,indices2);

    GLfloat quadVertices[] = {   // Vertex attributes for a quad that fills the entire screen in Normalized Device Coordinates.
        // Positions   // TexCoords
        -1.0f,  1.0f,  0.0f, 1.0f,
        -1.0f, -1.0f,  0.0f, 0.0f,
         1.0f, -1.0f,  1.0f, 0.0f,

        -1.0f,  1.0f,  0.0f, 1.0f,
         1.0f, -1.0f,  1.0f, 0.0f,
         1.0f,  1.0f,  1.0f, 1.0f
    };

    // Setup cube VAO
    GLuint quadVAO, quadVBO;
    glGenVertexArrays(1, &quadVAO);
    glGenBuffers(1, &quadVBO);
    glBindVertexArray(quadVAO);
        glBindBuffer(GL_ARRAY_BUFFER, quadVBO);
            glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), quadVertices, GL_STATIC_DRAW);
            glEnableVertexAttribArray(0);
            glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0);
            glEnableVertexAttribArray(1);
            glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)(2 * sizeof(GLfloat)));
    glBindVertexArray(0);


    unsigned int points_p1=0,points_p2=0;
    bool first_point_p1=true,first_point_p2=true;

    GameObject player1(&sprite,{0.0f,2.0f});
    GameObject player2(&sprite,{0.0f,2.0f});
    GameObject ball(&sprite,{0.0f,0.0f});
    Entity roof(&sprite);
    Entity floor(&sprite);
    GameObject leftwall(&sprite,{0.0f,0.0f});
    GameObject rightwall(&sprite,{0.0f,0.0f});
    {
        player1.entity.setPos({-0.95f,0.0f});
        player2.entity.setPos({0.95f,0.0f});
        ball.entity.setPos({0.0f,8.0f});

        roof.setPos({-1.0f,1.10f});
        floor.setPos({-1.0f,-1.10f});
        roof.scale({4.0f,1.0f});
        floor.scale({4.0f,1.0f});

        leftwall.entity.setPos({-1.0f,0.0f});
        rightwall.entity.setPos({1.0f,0.0f});
        leftwall.entity.scale({0.025f,2.0f});
        rightwall.entity.scale({0.025f,2.0f});

        player1.entity.scale({0.025f, 0.49f});
        player2.entity.scale({0.025f, 0.49f});
        ball.entity.scale({0.0625f,0.0625f});
        ball.entity.order(SCALE,ROTATE,TRANSLATE);


    }

    std::vector<CollisionChecker> collisions;
    {
        collisions.push_back(CollisionChecker(&player1.entity,&roof));
        collisions.push_back(CollisionChecker(&player1.entity,&floor));
        collisions.push_back(CollisionChecker(&player2.entity,&roof));
        collisions.push_back(CollisionChecker(&player2.entity,&floor));
    }


    CollisionChecker ball_floor(&ball.entity,&floor);
    CollisionChecker ball_roof(&ball.entity,&roof);
    CollisionChecker ball_p1(&ball.entity,&player1.entity);
    CollisionChecker ball_p2(&ball.entity,&player2.entity);
    CollisionChecker ball_leftwall(&ball.entity,&leftwall.entity);
    CollisionChecker ball_rightwall(&ball.entity,&rightwall.entity);

    SDL_StartTextInput();
    bool quit = false;
    bool started=false;
    glm::vec2 p1_speed_gain(0.0f,0.0f);
    glm::vec2 p2_speed_gain(0.0f,0.0f);
    unsigned int i=0;
    Uint32 lastFrame=0;
    Uint32 deltaTime=0;
    float framerate=0.0f;
    float dt;


    framebuffer fb(originalScreenWidth,originalScreenHeight);
    Shader shader(WORKING_DIR_FILE("assets/shaders/shader.vert"),WORKING_DIR_FILE("assets/shaders/shader.frag"));
    Shader fb_shader(WORKING_DIR_FILE("assets/shaders/framebuffer_shader.vert"),WORKING_DIR_FILE("assets/shaders/framebuffer_shader.frag"));
    while(!quit)
    {
        SDL_PumpEvents();
        Uint32 currentFrame =            SDL_GetTicks();//miliseconds
        deltaTime           =  currentFrame - lastFrame;
        lastFrame           =              currentFrame;
        dt                  =         deltaTime/1000.0f;
        framerate          +=         1000.0f/deltaTime;

        p1_speed_gain={0.0f,0.0f};
        p2_speed_gain={0.0f,0.0f};
        {
            const Uint8 *keystates =                                     SDL_GetKeyboardState( NULL );
            quit                   = keystates[SDL_GetScancodeFromKey(SDLK_q)] || SDL_QuitRequested();
            started                =         started || keystates[SDL_GetScancodeFromKey(SDLK_SPACE)];
            if(started){
                if(keystates[SDL_GetScancodeFromKey(SDLK_w   )])
                {
                    player1.move( dt );
                    p1_speed_gain={ 0.0f , 1.0f };
                }
                if(keystates[SDL_GetScancodeFromKey(SDLK_s   )])
                {
                    player1.move(-dt );
                    p1_speed_gain={ 0.0f ,-1.0f };
                }
                if(keystates[SDL_GetScancodeFromKey(SDLK_UP  )])
                {
                    player2.move( dt );
                    p2_speed_gain={ 0.0f , 1.0f };
                }
                if(keystates[SDL_GetScancodeFromKey(SDLK_DOWN)])
                {
                    player2.move(-dt );
                    p2_speed_gain={ 0.0f ,-1.0f };
                }
                if(keystates[SDL_GetScancodeFromKey(SDLK_j)])
                {
                    player1.entity.rotate(15.0f );
                }

                do_ball_movement(ball,dt);
            }

        }
        {
            unsigned int size=collisions.size();
            for(unsigned int i=0;i<size;i++)
            {
                if(collisions[i].checkCollision())
                    handleCollision(collisions[i]);
            }
        }
        {
            glm::vec3 pos=ball.entity.position;
            glm::vec3 oldpos=ball.entity.oldPosition;
            if(ball_floor.checkCollision()){
                handleCollision(ball_floor);
                ball.speed=glm::normalize(glm::reflect(glm::vec2(pos.x-oldpos.x,pos.y-oldpos.y),glm::vec2(0.0f,1.0f)))*glm::length(ball.speed);
                Mix_PlayChannel( -1, pong2, 0 );
            }
            if(ball_roof.checkCollision()){
                handleCollision(ball_roof);
                ball.speed=glm::normalize(glm::reflect(glm::vec2(pos.x-oldpos.x,pos.y-oldpos.y),glm::vec2(0.0f,-1.0f)))*glm::length(ball.speed);
                Mix_PlayChannel( -1, pong2, 0 );
            }
            if(ball_p1.checkCollision()){
                handleCollision(ball_p1);
                ball.speed=glm::normalize(glm::reflect(glm::vec2(pos.x-oldpos.x,pos.y-oldpos.y),glm::vec2(1.0f,0.0f)) + p1_speed_gain)
                        *
                        (glm::length(ball.speed)+glm::length(p1_speed_gain));
                Mix_PlayChannel( -1, pong, 0 );
            }
            if(ball_p2.checkCollision()){
                handleCollision(ball_p2);
                ball.speed=glm::normalize(glm::reflect(glm::vec2(pos.x-oldpos.x,pos.y-oldpos.y),glm::vec2(-1.0f,0.0f)) + p2_speed_gain)
                        *
                        (glm::length(ball.speed)+glm::length(p2_speed_gain));
                Mix_PlayChannel( -1, pong, 0 );
            }

            if(ball_leftwall.checkCollision()){
                points_p2++;
                ball.entity.setPos({0.0f,8.0f});//scale adjusted due the order it uses...
                ball.speed={0.0f,0.0f};
                Mix_PlayChannel( -1, pong3, 0 );
            }
            if(ball_rightwall.checkCollision()){
                points_p1++;
                ball.entity.setPos({0.0f,8.0f});
                ball.speed={0.0f,0.0f};
                Mix_PlayChannel( -1, pong3, 0 );
            }
            if(((ball.speed.y/ball.speed.x)>3.0f) || ((ball.speed.y/ball.speed.x)<-3.0f)){
                ball.speed.y/=2.0f;
                ball.speed.x*=4.0f;
            }
        }
        if(i==100){
            i=0;
            framerate/=100.0f;
            std::cout<<framerate<<std::endl;
            std::cout<<points_p1<<'-'<<points_p2<<std::endl;
            framerate=0.0f;
        }
        i+=1;
        shader.Use();
            fb.bind();
                glViewport(0,0,originalScreenWidth,originalScreenHeight);
                glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
                glEnable(GL_DEPTH_TEST);
                glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

                glm::mat4 projection;//= glm::ortho(-1.0f,1.0f,-1.0f,1.0f,0.0f,1.0f);
                GLint projection_uniform=glGetUniformLocation(shader.Program, "projection");
                glUniformMatrix4fv(projection_uniform, 1, GL_FALSE, glm::value_ptr(projection));


                glm::vec2 position;
                position=glm::vec2(-3.0f*1.06255f*0.125f,0.0f);
                if(points_p1>=5 || points_p2>=5){
                    drawdigit(-1,&shader,position,{0.125f,0.125f},DIGIT_TOP|DIGIT_MIDDLE|DIGIT_TOPLEFT|DIGIT_TOPRIGHT|DIGIT_BOTTOMLEFT);
                    position+=glm::vec2(1.0625f*0.125f,0.0f);
                    drawdigit((points_p1>=5)?1:2,&shader,position,{0.125f,0.125f});
                    position+=glm::vec2(1.0625f*0.125f,0.0f);
                    position+=glm::vec2(1.0625f*0.125f,0.0f);
                    drawdigit(-1,&shader,position,{0.125f,0.125f},DIGIT_TOPLEFT |DIGIT_BOTTOMLEFT |DIGIT_BOTTOMLEFT_MIDDLE|
                                                                  DIGIT_TOPRIGHT|DIGIT_BOTTOMRIGHT|DIGIT_BOTTOMRIGHT_MIDDLE);
                    position+=glm::vec2(1.0625f*0.125f,0.0f);
                    drawdigit(-1,&shader,position,{0.125f,0.125f},DIGIT_TOPMIDDLE|DIGIT_BOTTOMMIDDLE);
                    position+=glm::vec2(1.0625f*0.125f,0.0f);
                    drawdigit(-1,&shader,position,{0.125f,0.125f},DIGIT_BOTTOMLEFT |DIGIT_TOPLEFT|DIGIT_TOPLEFT_BOTTOMRIGHT|
                                                                  DIGIT_BOTTOMRIGHT|DIGIT_TOPRIGHT);
                    position+=glm::vec2(1.0625f*0.125f,0.0f);
                    drawdigit(5,&shader,position,{0.125f,0.125f});
                    started=false;
                }

                player1.entity.draw(&shader);
                player2.entity.draw(&shader);
                if(started) ball.entity.draw(&shader);
                roof.draw(&shader);
                floor.draw(&shader);
                leftwall.entity.draw(&shader);
                rightwall.entity.draw(&shader);




                unsigned int aux=points_p2;
                position=glm::vec2(0.25f,0.5f);
                //NOTE: when one of the points hits 20 I should put a you win screen
                first_point_p2=points_p2? false:true;
                while((aux/10) || (aux%10) || first_point_p2){
                    drawdigit(aux%10,&shader,position,{0.125f,0.125f});
                    position.x-=1.5f*0.125f;
                    aux=aux/10;
                    first_point_p2=false;//endless loop if I dont
                }

                aux=points_p1;
                position={-0.25f,0.5f};
                first_point_p1=points_p1? false:true;
                while((aux/10) || (aux%10) || first_point_p1){
                    drawdigit(aux%10,&shader,position,{0.125f,0.125f});
                    position.x-=1.5f*0.125f;
                    aux=aux/10;
                    first_point_p1=false;
                }


            fb.unbind();
        SDL_GetWindowSize(mainwindow,&screenWidth,&screenHeight);
        glViewport(0,0,screenWidth,screenHeight);
        glClearColor(0.0f, 0.0f, 0.1f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        glDisable(GL_DEPTH_TEST);
        fb_shader.Use();
            glm::mat4 screenscaler;
            float aspectRatio=(float)screenWidth/(float)screenHeight;
            float inverseAspectRatio=(float)screenHeight/(float)screenWidth;
            if(aspectRatio>1.0f)
            screenscaler = glm::perspective(radians(59.2f),aspectRatio,0.1f,1.0f);
            else
            screenscaler = glm::perspective(radians(59.2f),inverseAspectRatio,0.1f,1.0f);
            GLint model_uniform=glGetUniformLocation(fb_shader.Program, "model");
            glUniformMatrix4fv(model_uniform, 1, GL_FALSE, glm::value_ptr(screenscaler));

            glBindVertexArray(quadVAO);//should scale the scale to the % of resolution
            glActiveTexture(GL_TEXTURE0);
            glBindTexture(GL_TEXTURE_2D, fb.texture);
                glDrawArrays(GL_TRIANGLES, 0, 6);
            glBindTexture(GL_TEXTURE_2D,0);
            glBindVertexArray(0);


        SDL_Delay(1);
        SDL_GL_SwapWindow(mainwindow);
        if(points_p1>=5 || points_p2>=5){
            points_p1=0;
            points_p2=0;
            ball.speed={0.0f,0.0f};
            SDL_Delay(3000);
        }
    }
    DESTRUCTOR(fb);
    DESTRUCTOR(shader);
    DESTRUCTOR(fb_shader);
    Mix_FreeChunk(pong);
    Mix_FreeChunk(pong2);
    Mix_FreeChunk(pong3);
    SDL_GL_DeleteContext(maincontext);
    SDL_DestroyWindow(mainwindow);
    SDL_Quit();

    return 0;
}