Example #1
0
//check if player collided with an object, and if so, flag it
void Player::collisionDetection(QuadtreeNode *node)
{
	//reject all child nodes if player is not in this node
	if (!playerInQuadtreeNode(node))
	{
		return;
	}

	//if there are child nodes, recurse
	if (node->nw)
	{
		collisionDetection(node->nw);
		collisionDetection(node->ne);
		collisionDetection(node->sw);
		collisionDetection(node->se);
	}

	for (unsigned int i = 0; i < node->nodeObjectVector.size(); ++i)
	{
		Object *obj = (node->nodeObjectVector)[i];

		//check if object touches player
		if (((minX >= obj->minX && minX <= obj->maxX) || (maxX >= obj->minX && maxX <= obj->maxX)) &&
			((minY >= obj->minY && minY <= obj->maxY) || (maxY >= obj->minY && maxY <= obj->maxY)))
		{
			//collision detected
			collision = true;
		}
	}
}
void CSliderMultiPos::mouseMoveEvent(QMouseEvent* event){
    QStyleOptionSlider opt;

    previousMousePos = event->globalPos();
    if( lastPressedIndex==INVALID_INDEX ){
        event->ignore();
        return;
    }

    initStyleOption( &opt );
    const int m = style()->pixelMetric( QStyle::PM_MaximumDragDistance,&opt,this );
    int newPosition = pixelPosToRangeValue( pick( event->pos() ) - offset );
    if( m >= 0 ){
        const QRect r = rect().adjusted( -m,-m,m,m );
        if( !r.contains( event->pos() ) ){
            newPosition = tempPosition;
        }
    }

    newPosition = collisionDetection( newPosition );
    setCurPosition( lastPressedIndex, newPosition);

    event->accept();
    update();
}
Example #3
0
point getEmptyRandomCoordinateInField() {
    point p;
    do {
        p = getRandomCoordinateInField();
    } while (collisionDetection(p) != EMPTY);
    return p;
}
void BattleField::myDefine(Node* who)
{
	Bullet* bulletdestroy = (Bullet*)who;
	collisionDetection();
	bullets.eraseObject(bulletdestroy);
	who->removeFromParentAndCleanup(true);
	
}
void PropertyMove::updateCurrentTime( int currentTime )
{
#ifdef COLLISIONS
    collisionDetection();
#endif

    QPropertyAnimation::updateCurrentTime( currentTime );
}
Example #6
0
void ControlPlayer(GameState *game){
    const Uint8 *state = SDL_GetKeyboardState(NULL); //Flyttar på spelaren om det inte finns hinder(Collision detection)

    if(state[SDL_SCANCODE_LEFT] || state[SDL_SCANCODE_A]){ // Spelaren går till vänster
        spriteFacing.x = 32;
        spriteFacing.y = 32;
        game->Entity.rect.x -= PLAYER_SPEED;
        if(collisionDetection(&game->Entity)) {
           game->Entity.rect.x += PLAYER_SPEED;
        }
    }

    if(state[SDL_SCANCODE_RIGHT] || state[SDL_SCANCODE_D]){ // Spelaren går till höger
        spriteFacing.x = 0;
        spriteFacing.y = 32;
        game->Entity.rect.x += PLAYER_SPEED;
        if(collisionDetection(&game->Entity)){
           game->Entity.rect.x -= PLAYER_SPEED;
        }
    }

    if(state[SDL_SCANCODE_UP] || state[SDL_SCANCODE_W]){ // Spelaren går upp
        spriteFacing.x = 0;
        spriteFacing.y = 0;
        game->Entity.rect.y -= PLAYER_SPEED;
        if(collisionDetection(&game->Entity)){
           game->Entity.rect.y += PLAYER_SPEED;
        }
    }

    if(state[SDL_SCANCODE_DOWN] || state[SDL_SCANCODE_S]){ // Spelaren går ner
        spriteFacing.x = 32;
        spriteFacing.y = 0;
        game->Entity.rect.y += PLAYER_SPEED;
        if(collisionDetection(&game->Entity)){
           game->Entity.rect.y -= PLAYER_SPEED;
        }
    }

    if(state[SDL_SCANCODE_SPACE]){ // Spelaren går Attackerar
        spawnAttack(&game->Entity);
        if(collisionDetection(&game->Entity)){
           game->Entity.rect.y -= PLAYER_SPEED;
        }
    }
}
Example #7
0
int moveInhabitants() {
    for(int iinhabitant = 0; iinhabitant < g_inhabitantCount; iinhabitant++) {
        inhabitant* cSnake = &g_inhabitants[iinhabitant];
        //if the snakes direction is null too, use a random one
        if(cSnake->direction == 0 && iinhabitant != 0 && (iinhabitant != 1 || !g_confTwoPlayer)) {
            cSnake->direction = getRandomDirection();
        }

        int nextCollision;
        int actCollision;
        point nextPosition = getNextField(cSnake->direction, cSnake->body[cSnake->length-1]);

        actCollision = collisionDetection(cSnake->body[cSnake->length-1]);
        nextCollision = collisionDetection(nextPosition);

        if ((nextCollision == EMPTY || nextCollision == FRUIT)) { // && cSnake->length < MAX_INHABITANT_LENGTH){
            cSnake->body[cSnake->length] = nextPosition;
        } else {
            // snake dead !
            cSnake->alive = false;
        }

        if (actCollision != FRUIT) {
            int count;
            for(count = 0; count < cSnake->length; count++) {
                cSnake->body[count] = cSnake->body[count + 1];
            }
            if(cSnake->alive && rand() % POINTS_LEN_ROUNDS == 0) {
                //for every 10 length -> get one point per round
                cSnake->points = cSnake->points + (cSnake->length/POINTS_LEN);
            }
        } else {
            reInitFruit(cSnake->body[cSnake->length-1]);
            if(cSnake->length < MAX_INHABITANT_LENGTH) {
                cSnake->length++;
            }
            //get points for eating fruit!
            cSnake->points =  cSnake->points + POINTS_FRUIT;
        }
        if(cSnake->points > g_confWin) {
            return 0;
        }
    }
    return 1;
}
bool boxesCollisionUp(Boxes &box) {

	unsigned int leftUp = g_worldGrid[box.boxLocationX - 1][box.boxLocationY - 3];
	unsigned int centerUp = g_worldGrid[box.boxLocationX][box.boxLocationY - 3];
	unsigned int rightUp = g_worldGrid[box.boxLocationX + 1][box.boxLocationY - 3];

	return collisionDetection(leftUp, centerUp, rightUp);

}
bool playerCollisionDetectionRight() {

	int upRight = g_worldGrid[charLocation.X + 2][charLocation.Y - 2];
	int centerRight = g_worldGrid[charLocation.X + 2][charLocation.Y - 1];
	int bottomRight = g_worldGrid[charLocation.X + 2][charLocation.Y];
	
	return collisionDetection(upRight, centerRight, bottomRight);

}
bool playerCollisionDetectionLeft() {

	int upLeft = g_worldGrid[charLocation.X - 2][charLocation.Y - 2];
	int centerLeft = g_worldGrid[charLocation.X - 2][charLocation.Y - 1];
	int bottomLeft = g_worldGrid[charLocation.X - 2][charLocation.Y];

	return collisionDetection(upLeft, centerLeft, bottomLeft);

}
bool playerCollisionDetectionDown() {

	int leftBottom = g_worldGrid[charLocation.X - 1][charLocation.Y + 1];
	int centerBottom = g_worldGrid[charLocation.X][charLocation.Y + 1];
	int rightBottom = g_worldGrid[charLocation.X + 1][charLocation.Y + 1];
	
	return collisionDetection(leftBottom, rightBottom, centerBottom);

}
bool playerCollisionDetectionUp() {
	
	int centerUp = g_worldGrid[charLocation.X][charLocation.Y - 3];
	int leftUp = g_worldGrid[charLocation.X - 1][charLocation.Y - 3];
	int rightUp = g_worldGrid[charLocation.X + 1][charLocation.Y - 3];

	return collisionDetection(centerUp, leftUp, rightUp);

}
bool boxesCollisionRight(Boxes &box) {

	unsigned int topRight = g_worldGrid[box.boxLocationX + 2][box.boxLocationY - 2];
	unsigned int centerRight = g_worldGrid[box.boxLocationX + 2][box.boxLocationY - 1];
	unsigned int bottomRight = g_worldGrid[box.boxLocationX + 2][box.boxLocationY];

	return collisionDetection(topRight, centerRight, bottomRight);

}
bool boxesCollisionLeft(Boxes &box) {

	unsigned int topLeft = g_worldGrid[box.boxLocationX - 2][box.boxLocationY - 2];
	unsigned int centerLeft = g_worldGrid[box.boxLocationX - 2][box.boxLocationY - 1];
	unsigned int bottomLeft = g_worldGrid[box.boxLocationX - 2][box.boxLocationY];

	return collisionDetection(topLeft, centerLeft, bottomLeft);

}
bool boxesCollisionDown(Boxes &box) {

	unsigned int leftDown = g_worldGrid[box.boxLocationX - 1][box.boxLocationY + 1];
	unsigned int centerDown = g_worldGrid[box.boxLocationX][box.boxLocationY + 1];
	unsigned int rightDown = g_worldGrid[box.boxLocationX + 1][box.boxLocationY + 1];

	return collisionDetection(leftDown, centerDown, rightDown);

}
Example #16
0
void AI::path(Unit& unit){ 
	float rad = unit.getR();
	float theta = unit.getTheta();
	float speed = unit.getSpeed();
	float range = unit.getRange();
	 
	if(unit.attacking())
        attack(unit);
    
	if(unit.pursuing()){ 
		Unit *pursuing = unit.getPursuing();
		CIwFVec2 pursuingPos = pursuing->getPosition();
		CIwFVec2 pursuitVector = pursuingPos - unit.getPosition();
		CIwSVec2 tempPos; 
		if (pursuitVector.GetLength()<range)
            attack(unit);

		tempPos = (pursuitVector/speed)+unit.getPosition();
        unit.setVelocity(tempPos-unit.getPosition());
		
        std::list<Unit*> *tempArray = collisionDetection(unit, unit.getGame()->getUnits());
        
        if (tempArray == NULL || !tempArray->empty())
            unit.setVelocity(CIwFVec2::g_Zero);
        
        delete tempArray;
	}
	else {
		Unit *Enemy = detectEnemy(unit, unit.getGame()->getUnits());
		float thetaChange = speed/rad;
		float tempTheta = thetaChange + theta;
        unit.setRTheta(rad, tempTheta);
        CIwFVec2 tempPos = unit.getPosition();
        unit.setRTheta(rad, theta);
        unit.setVelocity(tempPos-unit.getPosition());
        
        std::list<Unit*> *tempArray = collisionDetection(unit, unit.getGame()->getUnits());
        if (tempArray == NULL || !tempArray->empty()) {
            unit.setVelocity(CIwFVec2::g_Zero);
        }
        delete tempArray;
	}
		
}
Example #17
0
////////////////////////////
/// @brief Update function
////////////////////////////
void Physicsworld::update()
{
  for(auto& i:Objectslist)
  {
    i.update();
  }
  for(auto i:MapList)
  {
    i.update();
  }
  collisionDetection();
  }
Example #18
0
int main(int argc, char *argv[])
{
	Init();

	Character *snake = new Snake("snake2.bmp", 20, 20);
	Character *dot = new Dot("dot.bmp", 20, 20);

	bool quit = false;

	while (!quit)
	{
		while (SDL_PollEvent(&event) != 0)
		{
			if (event.type == SDL_QUIT) {
				quit = true;
			}
		}
		SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);		// select colour for drawing
		SDL_RenderClear(renderer);									// clear entire screen to our selected colour

		snake->m_Move();  // (*snake).Move();
		dot->Render();
		OutOfScreen(*snake);
		collisionDetection(*snake, *dot);

		if (collisionDetection(*snake, *dot)) {						// checks IF TRUE
			dot->NewDot();
			dot->Render();
		}
		

		SDL_RenderPresent(renderer);								/* everything before this was drawn behind the scenes this actually
																	puts the colour on screen for us */
		SDL_Delay(70);												// gives us time to see the screen
	}

	Close();

	return 0;
}
void CSliderMultiPos::triggerAction(QAbstractSlider::SliderAction action){
    bool noAction = false;
    int newPos = 0;
    int minPos;
    int maxPos;

    if( lastPressedIndex==0 ){
        minPos = minimum();
    }
    else{
        minPos = handles.at(lastPressedIndex-1).getPosition();
    }
    if( lastPressedIndex==(nbValues()-1) ){
        maxPos = maximum();
    }
    else{
        minPos = handles.at(lastPressedIndex-1).getPosition();
    }

    blockTracking = true;
    switch( action ){
        case QAbstractSlider::SliderSingleStepAdd :
            newPos = qBound( minPos,minPos + singleStep(),maxPos );
            break;
        case QAbstractSlider::SliderSingleStepSub :
            newPos = qBound( minPos,maxPos - singleStep(),maxPos );
            break;
        case QAbstractSlider::SliderToMinimum :
            newPos = minPos;
            break;
        case QAbstractSlider::SliderToMaximum :
            newPos = maxPos;
            break;
        case QAbstractSlider::SliderMove :
        case QAbstractSlider::SliderNoAction :
            noAction = true;
            break;
        default :
            qWarning( "QxtSpanSliderPrivate::triggerAction: Unknown action" );
            break;
    }

    if( noAction ){
        // Nothing to do for this action
    }
    else{
        newPos = collisionDetection(newPos);
        setCurPosition( lastPressedIndex,newPos );
    }
    blockTracking = false;
}
/*
 * This is applying the physics for this particle for this time delta
 * the current particle should not be in the array of particles given
 */
void FluidParticle::updateParticle(float timeStep, FluidParticle *fluidParticles, int numParticles) {
    glm::vec3 gravity = glm::vec3(0.0, -9.8, 0.0);
    
    // solve for the change in velocity at this time according to Navier-Stokes
    glm::vec3 dvdt = gravity - this->pressureTerm + this->viscosityTerm;
    
    // printf("Acceleration: %.2f, %.2f, %.2f\n", dvdt.x, dvdt.y, dvdt.z);
    // Update with Semi-implicit Euler integration
    this->velocity += dvdt * timeStep;
    // printf("TimeStep: %.2f\n", timeStep);
    // printf("Velocity: %.2f, %.2f, %.2f\n", this->velocity.x, this->velocity.y, this->velocity.z);
    this->pos += this->velocity * timeStep;
    // printf("Position: %.2f, %.2f, %.2f\n", this->pos.x, this->pos.y, this->pos.z);
    // doing fluid fluid collision detection here
    collisionDetection(fluidParticles, numParticles, timeStep);
}
Example #21
0
void doGameplay()
{
	playing = 1;
	playerX = 10;
	playerY = 10;
	badGuyX = 230;
	badGuyY = 230;

	while( playing == 1 ) {
		updateJoypad();
		updateBadGuy();
		collisionDetection();
		delay(10);
		wait_vbl_done();
	}
}
Example #22
0
/**
 * Animation function, only put animation code here!
 * That is to say, code that updates positioning of drawables.
 */
void animate( )
{
	int currentTime = glutGet(GLUT_ELAPSED_TIME);
	int deltaTime = currentTime - glutElapsedTime;
	glutElapsedTime = currentTime;


    LightPos[0] += 0.002;
    
	for (int i = 0; i < numberOfRidges; i++)
	{
		mountains[i].move(deltaTime);
	}
	background->move(deltaTime);
	groundfloor->move(deltaTime);


	for (auto &enemy : enemies) {
		enemy.animate(deltaTime);
	}
	for (auto &projectile : projectiles) {
		projectile.animate(deltaTime);
	}

	character.animate(deltaTime);
	character.position[0] = std::fmax(character.position[0], topLeft[0] + (character.width / 2.0f) * character.scale);
	character.position[0] = std::fmin(character.position[0], bottomRight[0] - (character.width / 2.0f) * character.scale);

	character.position[1] = std::fmin(character.position[1], topLeft[1] - (character.height / 2.0f) * character.scale);
	character.position[1] = std::fmax(character.position[1], bottomRight[1] + (character.height / 2.0f) * character.scale + 1.0);

	if (toggleBoss)
		boss.animate(deltaTime);

	collisionDetection();

    // After everything has moved, lighting should be recalculated
    computeLighting();
}
void MainContentComponent::timerCallback() {
    
    if (isjBMode) {
        noteLabel.setText(std::to_string(processingAudio->getMidiIn()), dontSendNotification);
    }
    else {
//        myObstacle->setBounds(0, 0, myObstacle->getObstacleLength(), getHeight());
        myObstacle->setBounds(obsX-=10.5, 0, myObstacle->getObstacleLength(), getHeight());
        myObstacle->setCurTime( 10.5 );

        copterPlacement();
        
        collisionDetection();

        //if ( keyRelease == true ) {
        //    ypos += 5;
        //    Copter.setBounds((int)xpos,(int)ypos,80,60);
        //}
        gamePlayEvents();
    }
    
}
Example #24
0
int main( void )
{
	character hero = { 1000, 1000, 200, 200, 50, 40, "小呆", false, false }, 
			monster = { 200, 200, 100, 100, 20, 20, "哥布林", false, false }, 
			woman =  { 400, 400, 500, 100, 100, 200, "医生MM", false, false };

	srand( ( unsigned )time( NULL ) );
	//physicalAttack( monster, hero );
	//physicalAttack( hero, monster );

	//defense( hero );
	//physicalAttack( hero, monster );

	//heal( hero, woman );

	//lookupInfo( monster, hero );

	GameInfo gi;
	initGame( gi );
	draw( gi );

	while ( !gi.hero.isDead )
	{
		Sleep( 200 );
		system( "cls" );

		if( kbhit() )
		{
			char dir = getch();
			move( gi.heroPos, dir );
			collisionDetection( gi );
		}
		
		draw( gi );
	}

	gotoxy( 0, MAP_SIZE + 2 );
	return 0;
}
Example #25
0
void GameScene::play(float t)
{
    if(!gameOverFlag){
        //移动蛇
        for(int i=snake.size()-1;i>=0;i--){
            SnakeNode *node=snake.at(i);
            int x=node->x;
            int y=node->y;
            int d=controlDir;
            int step=snakeNodeWidth/snakeStep;
            if(i==0) d=controlDir;
            else {
                DirNode *dirNode =dirChain.at((i-1)*snakeStep+snakeStep-1);
                d=dirNode->dir;
                //CCLOG("end %d %d",dirChain.,y);
            }
            switch (d)
            {
                case DIR_DEF::UP:
                    y +=step;
                    break;
                case DIR_DEF::DOWN:
                    y -=step;
                    break;
                case DIR_DEF::LEFT:
                    x -=step;
                    break;
                case DIR_DEF::RIGHT:
                    x +=step;
                    break;
            }
            
            node->x=x;
            node->y=y;
            //node->sprite->setPosition(Point(node->x, node->y));
            
            float duration =speed*0.8f;//+(CCRANDOM_0_1()-0.5f)*speed*0.2 ;
            auto actionMove = MoveTo::create(duration,
                                             Point(node->x, node->y));
            
            node->sprite->runAction(Sequence::create(actionMove, NULL, NULL));
            
            
        }
        //调整移动方向链
        for(int i=dirChain.size()-1;i>=0;i--){
            DirNode *dirNode=dirChain.at(i);
            int d=dirNode->dir;
            if(i==0) d=controlDir;
            else {
                DirNode *lastDirNode =dirChain.at(i-1);
                d=lastDirNode->dir;
            }
            dirNode->dir=d;
        }
        
        //碰撞判断
        SnakeNode *head=snake.at(0);
        //检测是否吃到蛋
        if(collisionDetection(head,egg)){
            //处理并显示分数
            score+=1;//增加分数
            if(score>highScore) highScore=score;
            this->removeChild(labelScore);
            char buff[20] = {0};
            sprintf(buff,"Score: %d",score);
            labelScore = Label::createWithSystemFont(buff, "Arial", 22);
            
            labelScore->setPosition(Point(winWidth-labelScore->getContentSize().width,
                                          winHeight-labelScore->getContentSize().height));
            this->addChild(labelScore);
            
            CocosDenshion::SimpleAudioEngine::getInstance()->playEffect(EAT_SOUND);

            //增长蛇身的处理
            auto tail=snake.at(snake.size()-1);
            auto sprite = Sprite::create("snake.png");
            auto node = new SnakeNode();
            Point pt=tail->sprite->getPosition();
            node->x=tail->x;
            node->y=tail->y;
            node->sprite=sprite;
            node->sprite->setPosition(Point(node->x, node->y));
            node->sprite->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT);
            this->addChild(node->sprite);
            snake.pushBack(node);
            snakeLength++;
            
            for(int j=0;j<snakeStep;j++){
                auto dirNode = new DirNode();
                dirNode->dir=0;
                dirChain.pushBack(dirNode);
            }
            
            
            //生成新的鸡蛋
            this->removeChild(egg->sprite);
            egg =genEgg();
            this->addChild(egg->sprite);
            
        }
        else {
            //检测是否撞到边界
            if(borderDetection(head->sprite)) {
                gameOverFlag=true;
            }
            //检测是否撞到蛇身
            for(int i=2;i<snake.size();i++){
                SnakeNode *node=snake.at(i);
                if(collisionDetection(head,node)) {
                    gameOverFlag=true;
                    break;
                }
            }
        }
        snakeAllStep++;
        if(gameOverFlag){
            CocosDenshion::SimpleAudioEngine::getInstance()->stopBackgroundMusic();
            CocosDenshion::SimpleAudioEngine::getInstance()->playEffect(GAMEOVER_SOUND);
            double PI=3.14159f;
            
            for(int i=0;i<snake.size();i++){
                SnakeNode *node=snake.at(i);
                int dir;
                if(i==0) dir=controlDir;
                else {
                    DirNode *dirNode=dirChain.at((i-1)*snakeStep+snakeStep-1);
                    dir=dirNode->dir;
                }
                double angle=(rand()%150+15)*PI/180;
                if(dir==DIR_DEF::UP) angle=-angle;
                else if(dir==DIR_DEF::LEFT) angle=angle-PI/2;
                else if(dir==DIR_DEF::RIGHT) angle=angle+PI/2;

                int x=node->x+cos(angle)*snakeNodeWidth*100.0f;
                int y=node->y+sin(angle)*snakeNodeWidth*100.0f;
                //log("%d %d angle: %d %d,%d",node->x,node->y,(int)(angle/PI*180),x,y);
                float duration =speed*20.0f;//+(CCRANDOM_0_1()-0.5f)*speed*0.2 ;
                auto actionMove = MoveTo::create(duration,
                                                 Point(x, y));
                
                node->sprite->runAction(Sequence::create(actionMove, NULL, NULL));
            }

        }
    }
    else {
        gameOverDelay--;
        if(gameOverDelay<0) gameOver();
    }
}
Example #26
0
int main(int argc, char* args[])
{
    SDL_Event event;
    int start;
    int x, y;
    int row, col;
    ALIEN_TYPE type;
    bool dirChanged;

    // Start SDL
    SDL_Init(SDL_INIT_EVERYTHING);

    // Set up screen
    screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_SWSURFACE);

    // Title-bar caption
    SDL_WM_SetCaption(WINDOW_TITLE, NULL);

    // Set the keyboard repeat rate
    SDL_EnableKeyRepeat(KEY_REPEAT, KEY_REPEAT);

    // Initialise the fonts
    TTF_Init();

    // Load the freeSans font
    font = TTF_OpenFont("/usr/share/fonts/truetype/freefont/FreeSans.ttf", 18);
    if (font == NULL)
    {
      printf("TTF_OpenFont() Failed: %s\n", TTF_GetError());
      TTF_Quit();
      SDL_Quit();
      exit(1);
    }

    // Create our ship
    ship = new Ship();

    // Create the shields
    shield[0] = new Shield(102, 380);
    shield[1] = new Shield(240, 380);
    shield[2] = new Shield(378, 380);
    shield[3] = new Shield(516, 380);

    // Create the aliens
    for (row = 0; row < 5; row++) {

        if (row == 0) {
            type = ALIEN_TYPE_TOP;
        }
        if ((row == 1) || (row == 2)) {
            type = ALIEN_TYPE_MIDDLE;
        }
        if ((row == 3) || (row == 4)) {
            type = ALIEN_TYPE_BOTTOM;
        }


        for (col = 0; col < 5; col++) {
            aliens[row][col] = new Alien((SCREEN_WIDTH/2-16)+((32+ALIEN_GAP_X)*col), 10+20+((20+ALIEN_GAP_Y)*row), 50, type);
        }
    }

    initialiseGame();

    while (!quit) {

        start = SDL_GetTicks();

        // Poll the keyboard
        while (SDL_PollEvent(&event)) {

            switch(event.type) {
                case SDL_QUIT: 	quit = true;
				break;
                case SDL_KEYDOWN:
				if (event.key.keysym.sym == SDLK_LEFT) {
					ship->moveLeft(true);
				}
				if (event.key.keysym.sym == SDLK_RIGHT) {
					ship->moveRight(true);
				}
				if (event.key.keysym.sym == SDLK_SPACE) {
                                    ship->fire();
				}
				if (event.key.keysym.sym == SDLK_ESCAPE) {
				    quit = true;
				}
				if (event.key.keysym.sym == SDLK_n) {
                                    if (gameOver) initialiseGame();
				}
                                paused = false;
				break;
		case SDL_KEYUP:
				if (event.key.keysym.sym == SDLK_LEFT) {
					ship->moveLeft(false);
				}
				if (event.key.keysym.sym == SDLK_RIGHT) {
					ship->moveRight(false);
				}
            }

        }  

        if ((!gameOver) && !(lockout)) {

            // Update our ship and missile
            ship->missile->move();
            ship->move();

	    if ((!paused) && (speed++ == alienSpeed)) {
                updateAliens(&alienSpeed, &alienDirection);
	        speed = 0;
            }

            for (col=0; col < 5; col++) {
                for (row=0; row < 5; row++) {
                    aliens[row][col]->missile->move();
                }
            }

            collisionDetection();

            for (y = 0; y < 5; y++) {
                for (x = 0; x < 5; x++) {
		    aliens[x][y]->update();
                }
            }
            ship->update();

            if ((ship->isHit()) && (ship->visible == 0)) {
                ship->reset();
            }

            // Check if game over
            if ((hits == 25) || (ship->getLives() == 0)) {
                gameOver = true;
            }

            // Clear the screen
            SDL_FillRect(screen, NULL,0);

            // Render the screen
            drawScreen();

            // Update the screen
            SDL_Flip(screen);
        }

        if (lockout) {
            lockout--;
        }

        printf("------------------\n");
        for (x = 0; x < 5; x++) {
            for (y = 0; y < 5; y++) {
                if (aliens[x][y]->isBomber()) {
                    printf("Bomber: row %d col %d\n", x, y);
                }
            }
        }
        printf("------------------\n");

        // Delay for the appropriate amount of time
        if (1000/FPS > (SDL_GetTicks() - start)) {
	    SDL_Delay(1000/FPS - (SDL_GetTicks() - start));
        }

    }

    printf("Exiting...\n");

    // Free the loaded image
    SDL_FreeSurface(screen);

    // Quit SDL
    SDL_Quit();

    return 0;
}
Example #27
0
void game_update(void){
	snakePosUpdate();
	collisionDetection();
	snakeElongation();
}
Example #28
0
void Player::update(sf::Time dt)
{


	if(mIsMovingLeft || mIsMovingRight || mIsJumping)
		mMovement.x*=mFrictionStart;
	else
		mMovement.x*=mFrictionStop;

	if(mIsJumping)
		mMovement.y+=mFrictionVertical;

 
	
	sf::FloatRect playerRect = getTransform().transformRect(mAnimation.getGlobalBounds());
	playerRect.left+=mMovement.x*dt.asSeconds();
	playerRect.top+=mMovement.y*dt.asSeconds();

	// Update player's collision points
	mCollPoints.up[0]=sf::Vector2f(playerRect.left+mCollMarg,playerRect.top);
	mCollPoints.up[1]=sf::Vector2f(playerRect.left+playerRect.width-mCollMarg,playerRect.top);
	mCollPoints.down[0]=sf::Vector2f(playerRect.left+mCollMarg,playerRect.top+playerRect.height);
	mCollPoints.down[1]=sf::Vector2f(playerRect.left+playerRect.width-mCollMarg,playerRect.top+playerRect.height);
	mCollPoints.left[0]=sf::Vector2f(playerRect.left,playerRect.top+mCollMarg);
	mCollPoints.left[1]=sf::Vector2f(playerRect.left,playerRect.top+playerRect.height-mCollMarg);
	mCollPoints.left[2]=sf::Vector2f(playerRect.left,playerRect.top+playerRect.height/2);
	mCollPoints.right[0]=sf::Vector2f(playerRect.left+playerRect.width,playerRect.top+mCollMarg);
	mCollPoints.right[1]=sf::Vector2f(playerRect.left+playerRect.width,playerRect.top+playerRect.height-mCollMarg);
	mCollPoints.right[2]=sf::Vector2f(playerRect.left+playerRect.width,playerRect.top+playerRect.height/2);

	//Collision detection
	collisionDetection(playerRect);
	pickupCollisionDetection(playerRect);



	if(mCollisionRight)
		if(mMovement.x>0)
			mMovement.x*=-0.1f;
			
	if(mCollisionLeft)
		if(mMovement.x<0)
			mMovement.x*=-0.1f;

	if(mCollisionUp)
		if(mMovement.y<0)
			mMovement.y*=-0.1f;

	if(mCollisionDown)
	{
		if(!(mIsMovingLeft || mIsMovingRight || mPlayerDead))
			mAnimation.playAnimation("stay");
		if(mMovement.y>0)
		//	mMovement.y*=-0.1f;
			mMovement.y=0;

		mIsJumping=false;
	}
	else
	{
		/*if(mAnimation.getCurrentAnimation()!="jump")
			mAnimation.playAnimation("fall");*/
		mIsJumping=true;
		mMovement.y+=getGravity();
	}


	
	mAnimation.update(dt);

	move(mMovement*dt.asSeconds());

	if(mEnemyManager->intersection(getAABB()))
	{
			mPlayerDead=true;
			mAnimation.playAnimation("dead");
	}

	if(mStar->getGlobalBounds().intersects(getAABB()))
		mLevelCompleted=true;

	//ss.str("");
	//ss << "Left: "<<(int)mCollisionLeft<< "\nRight: "<<(int)mCollisionRight<<"\nUp: "<<(int)mCollisionUp<<"\nDown: "<<(int)mCollisionDown;// put float into string buffer
	
	//Reset variables

	mIsMovingLeft=false;
	mIsMovingRight=false;

	mCollisionDown=false;
	mCollisionLeft=false;
	mCollisionRight=false;
	mCollisionUp=false; 
	
}