void Creature::move(const Level& lvl, const std::vector<RObject*>& obstacles, const SDL_Rect* p_camera) { if (m_keep_action) return; m_box.x += m_delta_x; if (lvl.outOfBoardersX(m_box) || isCollision(obstacles)) { m_box.x -= m_delta_x; } else if (p_camera) { if (m_box.x < p_camera->x || m_box.x + m_box.w > p_camera->x + p_camera->w) { m_box.x -= m_delta_x; } } m_box.y += m_delta_y; if (lvl.outOfBoardersY(m_box) || isCollision(obstacles)) { m_box.y -= m_delta_y; } else if (p_camera) { if (m_box.y < p_camera->y || m_box.y + m_box.h > p_camera->y + p_camera->h) { m_box.y -= m_delta_y; } } }
/* * Moves the piece to rigth with collision detection * moving a piece is just a shift of the 4 chars of the piece */ void goRigth() { /* * try to move piece only if it still fits in the field after rotation * the trick is check if one of the less significant bits of each char is equal to 1 */ if (((actualPiece[0] | actualPiece[1] | actualPiece[2] | actualPiece[3]) & 0x01) == 0x00) { /* * first deletes the actual piece from the field and then * checks is there is no collision with the new position. if the * piece fits beetween the other pieces adds it to fild. else retores the original * piece if collides with other pieces */ deletePiece(); // deletes the actual piece from field updateTempPiece(); // updates temp piece shiftRigth(tempPiece); // shifts the temp piece if (isCollision() == 0x00) { // no collision? shifts the actual piece shiftRigth(actualPiece); // and adds it to the field addPiece(); updateTempPiece(); pieceShift++; } addPiece(); // no collision? replace the actual piece on field updateDisplayField(); // updates the display field } }
/* * Rotates the actual piece CCW with collision detection * the rotation is just a piece layout change with the actual piecePos, * rotates only if is possible. */ void rotate() { char i = 0; // try to rotate piece only if it still fits in the field after rotation if (pieceNum != 0x00 && getMaxLeftShift() <= pieceShift && pieceShift <= getMaxRigthShift()) { /* * first deletes the actual piece from the field and then * checks is there is no collision with the new position. if the * piece fits beetween the other pieces adds it to fild. else retores the original * piece if collides with other pieces */ deletePiece(); // deletes the actual piece from field piecePos++; // increments the piece y position if (piecePos == 0x04) { // controls the rotation position range piecePos = 0x00; } tempPiece[0] = pieces[pieceNum][piecePos][0]; // updates the temp piece tempPiece[1] = pieces[pieceNum][piecePos][1]; tempPiece[2] = pieces[pieceNum][piecePos][2]; tempPiece[3] = pieces[pieceNum][piecePos][3]; if (pieceShift < 0x00) { // shifts the temp piece to actal x position for (i = (-1) * pieceShift; i > 0; i--) { shiftLeft(tempPiece); } } else { for (i = pieceShift; i > 0; i--) { shiftRigth(tempPiece); } } if (isCollision() == 0x00) { // no collision? aplies the new rotation position actualPiece[0] = pieces[pieceNum][piecePos][0]; actualPiece[1] = pieces[pieceNum][piecePos][1]; actualPiece[2] = pieces[pieceNum][piecePos][2]; actualPiece[3] = pieces[pieceNum][piecePos][3]; // shifts the new piece to the last X position if (pieceShift < 0x00) { for (i = (-1) * pieceShift; i > 0; i--) { shiftLeft(actualPiece); } } else { for (i = pieceShift; i > 0; i--) { shiftRigth(actualPiece); } } } else { // collision? just go back and aplies the last piece if (piecePos == 0x00) { piecePos = 0x03; } else { piecePos--; } } addPiece(); updateDisplayField(); // updates the display field } }
void Enemy::update() { m_velocity.setY(5); m_currentFrame = (int)((SDL_GetTicks() / 100) % m_numsprites); if (isCollision()) { if (m_velocity.getX() <= 0) { if (flip == SDL_FLIP_NONE) { m_velocity.setX(-m_originalVelocity.getX()); flip = SDL_FLIP_HORIZONTAL; m_position.setX(m_position.getX() + 2); } else { m_velocity.setX(m_originalVelocity.getX()); flip = SDL_FLIP_NONE; m_position.setX(m_position.getX() - 2); } } collision = false; } CollisionObject::update(); }
void Enemy::checkCollision(visualObj *star) { bool interact = isCollision(star); int healthColor = (105 + health * 50); ///Enemy interection with star if (interact == true) { if (collisionTimer == 0) health--; if (health == 0 && respawnTimer == 0) ///If enemy has no health left respawnTimer = rand_int(5, 8) * 1000; //Generates a random time for the enemy to respawn setColor(255, 0, 0); //Enemy Collision [Damage taken, changes Red] collisionTimer = 400; //Enemy turns red for certain period of time based on this } ///Collision Timer counts down/makes enemy red if (collisionTimer > 0) collisionTimer--; //Collision Timer count down else if (collisionTimer == 0) setColor(255, healthColor, healthColor); //Changes enemy's color back after certain period of time ///Respawn Timer if (respawnTimer > 0) respawnTimer--; //Counts Down else if (respawnTimer == 0 && dead == true) respawn(); //Respawns after timer is up death(); //If Health = 0, Enemy is Dead }
bool Exporter::isMeshGroup(INode *maxNode, bool root) { if (root) { if (!maxNode->IsGroupHead()) return false; } else { if (!isCollision(maxNode)) { TimeValue t = 0; ObjectState os = maxNode->EvalWorldState(t); if (os.obj->SuperClassID() == GEOMOBJECT_CLASS_ID) return true; } } for (int i=0; i<maxNode->NumberOfChildren(); i++) { if (isMeshGroup(maxNode->GetChildNode(i), false)) return true; } return false; }
/*Larger operation to perform than the other collision tests *due to it being a little more complex. Therefore encapsulate *it into a separate function for readability.*/ int isSailCollision(struct vertex projPos, struct vertex sailCenter) { if(isCollision(projPos, sailCenter, RADIUS, SAIL_SIZE)) { int startfrom = 0; for(int j = 0; j < NUM_SHADOWS; j++) { /*Shadow breaks holds the integers where one shadow stops and another *should begin. That is why the startfrom variable is included to return *k to the value it was before the previous iteration completed.*/ for(int k = startfrom; k < globalGeometry.shadowBreaks[j]; k++, startfrom++) { struct vertex sail; sail.x = globalGeometry.shadow[k].x * (SAIL_SIZE + 0.001); sail.y = globalGeometry.shadow[k].y * (SAIL_SIZE + 0.001); sail.z = globalGeometry.shadow[k].z; float dist = distance(projPos, sail); /*Magic number which seems to work well.*/ if(dist <= SAIL_COLLISION_DIST) return TRUE; } } } return FALSE; }
/// // Recalculate and set the lowest valid Y position for the current piece. /// void updateHardDropY(FSEngine *f) { int y = f->y; while (!isCollision(f, f->x, y, f->theta)) { y += 1; } f->hardDropY = y - 1; }
void Player::actionIfCollision(Ball &ball) { Uint16 ballY = ball.getY(); if (isCollision(ball.getX(), ballY)) { Uint16 _y = y; double halfY = _y + HEIGHT/2; double influence = (30 * (ballY - halfY) / (HEIGHT/2)) * M_PI / 180; ball.changeAngle(influence, velocityY); } }
bool J2DPhysicalGameObject::checkSupportedByObject(J2DGameObject* target) { Uint32 dir = isCollision(*target->getInnerRect(), *this->getInnerRect()); if (dir == JLIB_COLLIDE_BOTTOM || dir == JLIB_COLLIDE_BOTTOMLEFT || dir == JLIB_COLLIDE_BOTTOMRIGHT || dir == JLIB_COLLIDE_RIGHT || dir == JLIB_COLLIDE_LEFT) { return true; } return false; }
void BattleScene::createNPCs() { BricksVec freeBricks; std::copy_if(_bricks.begin(), _bricks.end(), back_inserter(freeBricks), [this](Brick* brick) { bool canCreate = true; for (auto player : _players) { if (isCollision(brick, player, Size(240, 240))) { canCreate = false; break; } } return brick->getType() == EBACKGROUND && canCreate; }); std::random_shuffle(freeBricks.begin(), freeBricks.end()); auto vec = NPCManager::Instance()->createNPCs(accordion, 4); for (size_t i = 0; i < vec.size(); i++) { setDefaultParametrNpc(vec[i], freeBricks[i]->getPosition()); } BricksVec bricks; std::copy_if(_bricks.begin(), _bricks.end(), back_inserter(bricks), [this](Brick* brick) { bool canCreate = true; for (auto player : _players) { if (isCollision(brick, player, Size(240, 240))) { canCreate = false; break; } } return brick->getType() != EBRICK && canCreate; }); std::random_shuffle(bricks.begin(), bricks.end()); vec = NPCManager::Instance()->createNPCs(brush, 2); for (size_t i = 0; i < vec.size(); i++) { setDefaultParametrNpc(vec[i], bricks[i]->getPosition()); } }
void moveDown() { currentBlock.position.y++; if (isCollision() == 1) { currentBlock.position.y--; setBlockInCanvas(); resetBlock(); } }
/* Checks if direction is OK for moving (no collision, stc.) */ int dbDirSucceeded(t_Direction dir) { switch(dir) { case DIR_UP: return (isCollision( currentLevel.DrunkenBots[0].posX, currentLevel.DrunkenBots[0].posY-STEP) | isOutOfBounds(currentLevel.DrunkenBots[0].posX, currentLevel.DrunkenBots[0].posY-STEP)) ? 0 : 1; break; case DIR_RIGHT: return (isCollision( currentLevel.DrunkenBots[0].posX+STEP, currentLevel.DrunkenBots[0].posY) | isOutOfBounds(currentLevel.DrunkenBots[0].posX+STEP, currentLevel.DrunkenBots[0].posY)) ? 0 : 1; break; case DIR_DOWN: return (isCollision( currentLevel.DrunkenBots[0].posX, currentLevel.DrunkenBots[0].posY+STEP) | isOutOfBounds(currentLevel.DrunkenBots[0].posX, currentLevel.DrunkenBots[0].posY+STEP)) ? 0 : 1; break; case DIR_LEFT: return (isCollision( currentLevel.DrunkenBots[0].posX-STEP, currentLevel.DrunkenBots[0].posY) | isOutOfBounds(currentLevel.DrunkenBots[0].posX-STEP, currentLevel.DrunkenBots[0].posY)) ? 0 : 1; break; default: return 1; } return 1; }
void calcBallPosition(ball *aBall, paddle *p1, paddle *p2){ uint32_t collisionType = isCollision(aBall,p1,p2); uint32_t blue = 0x000099; //black = 0x0; if (collisionType == P1){ if( p1->direction == UP ) { aBall->vY = aBall->vY - 1; aBall->vX = -aBall->vX; } else if( p1->direction == DOWN ) { aBall->vY = aBall->vY + 1; aBall->vX = -aBall->vX; } else if( p1->direction == IDLE ) { aBall->vY = aBall->vY; aBall->vX = -aBall->vX; } } else if (collisionType == P2){ if( p2->direction == UP ) { aBall->vY = aBall->vY - 1; aBall->vX = -aBall->vX; } else if( p2->direction == DOWN ) { aBall->vY = aBall->vY + 1; aBall->vX = -aBall->vX; } else if( p2->direction == IDLE ) { aBall->vY = aBall->vY; aBall->vX = -aBall->vX; } } ballInBounds(aBall); // erase ball drawBall(blue,aBall); // calculate new positions aBall->x = aBall->x + aBall->vX; aBall->y = aBall->y + aBall->vY; updateFrame(p1->y, p2->y, aBall->x, aBall->y, aBall, p1, p2); if ( !isXInBounds( aBall->x ) ) { if ( aBall->vX == VEL_X ) { p1->score = p1->score + 1; } else p2->score = p2->score + 1; initializeGame(aBall, p1, p2); } }
void fetchUserInput() { Block orgBlock = currentBlock; if (gameState == 0) { switch (getch()) { case KEY_LEFT: moveLeft(); break; case KEY_RIGHT: moveRight(); break; case KEY_UP: rotateBlock(); break; case KEY_DOWN: moveDown(); break; case 'p': gameState = 1; break; } } else { switch (getch()) { case 'p': if (gameState == 1) { gameState = 0; } break; case 'r': resetGame(); break; case 'q': inGame = 0; break; } } if (isCollision()) { currentBlock = orgBlock; } }
/*Find the sum of the radii of a projectile *and given base.*/ int isBaseCollision(struct projectile proj, struct vertex base, char color) { /*Base = RADIUS * BASE_SIZE as it's been scaled.*/ float baseRadius = RADIUS * BASE_SIZE; /*Projectile has original radius size.*/ int collided = isCollision(proj.position, base, RADIUS, baseRadius); if(collided && proj.color != color) return TRUE; return FALSE; }
void GameMainLayer::update(float time) { if (hero->state == 0) this->isHeroDrop(); CCPoint pos1 = (map->getChildByTag(0))->getPosition(); CCPoint pos2 = (map->getChildByTag(1))->getPosition(); //检测主角是否吃到星星 for (int i = 0; i < 5; i++) { if (pos1.x <= 100 && (pos1.x + 480) >= 100) { GameObjStar *star = (GameObjStar *)(map->stars1)->objectAtIndex(i); if (star->get_visible() && isCollision(ccp(100,hero->getPosition().y + 62.5), ccp(pos1.x + 86 + 96*i, 280), 40, 35, 18.25, 17.75)) { star->set_visible(false); gameMark->addNumber(100); } } else { GameObjStar *star = (GameObjStar *)(map->stars2)->objectAtIndex(i); if (star->get_visible() && isCollision(ccp(100,hero->getPosition().y + 62.5), ccp(pos2.x + 86 + 96*i, 280), 40, 35, 18.25, 17.75)) { star->set_visible(false); gameMark->addNumber(100); } } } }
bool makeRoomSilentlyFail( Level & level, uint32_t & gen, OcclusionBuffer& occ ) { uint32_t x( nextRandomGenerator_( gen ) % TILE_DIM ); uint32_t y( nextRandomGenerator_( gen ) % TILE_DIM ); uint32_t w( (nextRandomGenerator_( gen ) % RESTWIDMAX) + WIDMIN ); uint32_t h( (nextRandomGenerator_( gen ) % RESTWIDMAX) + WIDMIN ); if( (x+w) < TILE_DIM-1 && (y+h) < TILE_DIM-1 && x != 0 && y != 0 && !isCollision( x, y, w, h, occ ) ) { occ.Occlude(x, y, x+w, y+h); level.rooms.emplace_back(x, y, w, h, (uint32_t)(level.rooms.size() + 1)); return true; } return false; }
void Tetromino::computeTargetNodePos(const int* bgInfo) { m_targetRow = m_row; int rowTest = m_targetRow-1; while(!isCollision(m_col,rowTest,m_rotate,bgInfo)) { m_targetRow = rowTest; rowTest--; } if(m_targetBlockNode) m_targetBlockNode->setPosition(Vec2(-m_blockSize*m_col,m_blockSize*m_targetRow)); }
void Timer(int) { if (ball.active) { ball.move(); //collision with a block for (int i = 0; i < 10; i++) { for (int j = 0; j < 15; j++) { Brick &b = brick[i][j]; if (isCollision(ball, b)) { //if a ball is above or below if (fabs(ball.x - b.col*b.w - b.w / 2) < fabs(ball.y - b.row*b.h - b.h / 2)) { ball.dy *= -1; } //if a ball is left or right else if (fabs(ball.x - b.col*b.w - b.w / 2) > fabs(ball.y - b.row*b.h - b.h / 2)) { ball.dx *= -1; } //a ball is on the diagonal side of the block else { if (ball.dx>0) { if (ball.x < b.col*b.w + 1) ball.dx *= -1; } else if (ball.x >(b.col + 1)*b.w - 1) ball.dx *= -1; if (ball.dy>0) { if (ball.y < b.row*b.h + 1) ball.dy *= -1; } else if (ball.y >(b.row + 1)*b.h - 1) ball.dy *= -1; } //If "life" block is equal to 0 if (--b.hit == 0) { b.active = false; } } } } } Draw(); glutTimerFunc(33, Timer, 0); }
/*Test whether this projectile has collided with any others. *Return the position of the other projectile it collided with. *This function will return NO_COLLISION if no collision occured.*/ int projectileCollided(struct vertex projPos, int posIndex) { for(int i = 0; i < globalProjectile.pIndex; i++) { /*If i and posIndex are the same then its the same *projectile and the loop should skip it.*/ if(i == posIndex) continue; if(isCollision(projPos, globalProjectile.projectiles[i].position, RADIUS, RADIUS)) return i; } return NO_COLLISION; }
/*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(); } } }
void Player::processInput(Display* display) { toBoat(display); if(keyboard->getState(SDLK_x) && !left_projectile->isActive() && shipState) { fireProjectile(); } if(keyboard->getState(SDLK_UP)) { direction = 0; if(!isCollision(display)) { y--; } } else if(keyboard->getState(SDLK_DOWN)) { direction = 2; if(!isCollision(display)) { y++; } } else if(keyboard->getState(SDLK_LEFT)) { direction = 3; if(!isCollision(display)) { x--; } } else if(keyboard->getState(SDLK_RIGHT)) { direction = 1; if(!isCollision(display)) { x++; } } }
bool Tetromino::drop(const int* bgInfo) { int rowTest = m_row-1; if(!isCollision(m_col,rowTest,m_rotate,bgInfo)) { m_row = rowTest; m_curBlockNode->setPosition(Vec2(-m_blockSize*m_col,m_blockSize*m_row)); return true; } return false; }
bool Tetromino::setRow(int r,const int* bgInfo) { if(!isCollision(m_col,r,m_rotate,bgInfo)) { m_row = r; m_curBlockNode->setPosition(Vec2(-m_blockSize*m_col,m_blockSize*m_row)); if(m_targetBlockNode) computeTargetNodePos(bgInfo); return true; } return false; }
/** * Method is used to detect collision. Use Bounding Box algorithm. */ void CollisionDetector::detectCollision() { vector< boost::shared_ptr<SceneEntity> >* scene = gameScene->getWorldScene(); unsigned int size = scene->size(); for(unsigned int i = 0; i < size; ++i) { BoundingBox firstBox; firstBox.max = scene->at(i).get()->getBoundingBox()->max; firstBox.min = scene->at(i).get()->getBoundingBox()->min; firstBox.max += scene->at(i).get()->position; firstBox.min += scene->at(i).get()->position; bool firstHaveCollided = scene->at(i).get()->haveCollided; for(unsigned int j = 3; j < size; ++j) { if(i == j) continue; BoundingBox secondBox; bool secondHaveCollided = scene->at(j).get()->haveCollided; secondBox.max = scene->at(j).get()->getBoundingBox()->max; secondBox.min = scene->at(j).get()->getBoundingBox()->min; secondBox.max += scene->at(j).get()->position; secondBox.min += scene->at(j).get()->position; Faction atypeID_1 = scene->at(i).get()->faction; Faction atypeID_2 = scene->at(j).get()->faction; if(isCollision(firstBox,secondBox)) { scene->at(i).get()->haveCollided = true; scene->at(j).get()->haveCollided = true; //handler->collisionCollection.push_back(Collision(scene->at(j).get()->position,i,j)); Faction typeID_1 = scene->at(i).get()->faction; Faction typeID_2 = scene->at(j).get()->faction; handler->collisionCollection.push_back( createCollisionObject(typeID_1, typeID_2, scene->at(j).get()->position, i, j, gameScene)); } } } }
void makeRoomSilentlyFail( Level & level ) { uint32_t r1 = nextRandomGenerator_(); uint32_t r2 = nextRandomGenerator_(); uint32_t x( r1 % TILE_DIM ); uint32_t y( r2 % TILE_DIM ); uint32_t w( (r1 % MAXWID) + MIW ); uint32_t h( (r2 % MAXWID) + MIW ); if( (x+w) >= TILE_DIM || (y+h) >= TILE_DIM || x == 0 || y == 0 ) return; if( !isCollision( level.rooms, x, y, w, h ) ) { Room r( x, y, w, h, level.rooms.size() + 1 ); level.rooms.push_back( r ); } }
void spawnNewBlock() { if (isGameMoving() == 0) { if (currentBlockInBatch >= 7) { createNewBlockBatch(); currentBlockInBatch = 0; } currentBlock = blockBatch[currentBlockInBatch]; currentBlockInBatch++; } if (isCollision()) { gameState = 2; } }
bool Tetromino::move(bool bLeft,const int* bgInfo) { int colTest = bLeft ? m_col+1 : m_col-1; if(!isCollision(colTest,m_row,m_rotate,bgInfo)) { m_col = colTest; m_curBlockNode->setPosition(Vec2(-m_blockSize*m_col,m_blockSize*m_row)); if(m_targetBlockNode) computeTargetNodePos(bgInfo); return true; } return false; }
vector findCollisionLineToBox(line l1, box b2){ vector l[] = { l1.pE1->position, l1.pE2->position, }; box b1; b1.position = { ((l[0].x + l[1].x) / 2), ((l[0].y + l[1].y) / 2) }; if ((l[0].x - l[1].x) == 0) b1.rotation = 0; else b1.rotation = atan2((l[0].x - l[1].x), (l[0].y - l[1].y)); b1.width = { sqrt(pow(l[0].x - l[1].x, 2) + pow(l[0].y - l[1].y, 2)), 2.0 }; if (isCollision(b1, b2)){ vector vertexs[4]; b2.getVertexs(vertexs); vector l[] = { l1.pE1->position, l1.pE2->position, vertexs[1], vertexs[2], vertexs[3], vertexs[0] }; double temp[] = { getDistanceBetweenPointAndLine(l[0].x, l[0].y, l[2].x, l[2].y, l[3].x, l[3].y), getDistanceBetweenPointAndLine(l[1].x, l[1].y, l[2].x, l[2].y, l[3].x, l[3].y), getDistanceBetweenPointAndLine(l[2].x, l[2].y, l[0].x, l[0].y, l[1].x, l[1].y), getDistanceBetweenPointAndLine(l[3].x, l[3].y, l[0].x, l[0].y, l[1].x, l[1].y) }; double shortDistance = temp[0]; int index = 0; for (int i = 1; i < 4; i++){ if (shortDistance>temp[i]){ shortDistance = temp[i]; index = i; } } return l[index]; } return vector(); }