Exemplo n.º 1
0
void Octree::doCollisions()
{
	std::set<std::pair<OctreeObject*, OctreeObject*>, OctreeObjectPairLess> l;
	getUnitUnitColl(l);
	for(auto it = l.begin(); it != l.end(); ++it)
	{
		auto o = it->first;
		auto o2 = it->second;
		
		Location bot1 = o->bb_bot();
		Location top1 = o->bb_top();
		
		Location bot2 = o2->bb_bot();
		Location top2 = o2->bb_top();
		
		if (Collision::boxBox(bot1, top1, bot2, top2))
		{
			if(top1.y < top2.y)
			{
				o->collides(*o2);
				o2->collides(*o);
			}
			else
			{
				o2->collides(*o);
				o->collides(*o2);
			}
		}
	}
}
Exemplo n.º 2
0
void Physics::step( real_t dt )
{
    // step the world forward by dt. Need to detect collisions, apply
    // forces, and integrate positions and orientations.
    for(size_t i=0; i<num_spheres(); i++){
        //Update Spheres boundbox
        Vector3 upper = spheres[i]->position + Vector3(spheres[i]->radius, spheres[i]->radius, spheres[i]->radius);
        Vector3 lower = spheres[i]->position - Vector3(spheres[i]->radius, spheres[i]->radius, spheres[i]->radius);
        spheres[i]->bound = BoundBox(lower, upper);
        
        for(size_t j=0; j<num_spheres(); j++){
            if(i!=j){
                collides(*spheres[i], *spheres[j], collision_damping);
            }
        }
        for(size_t j=0; j<num_planes(); j++){
            collides(*spheres[i], *planes[j], collision_damping);
        }
        for(size_t j=0; j<num_triangles(); j++){
            collides(*spheres[i], *triangles[j], collision_damping);
        }
        for(size_t j=0; j<num_models(); j++){
            collides(*spheres[i], *models[j], collision_damping);
        }
        
        //RK4 Position & Orientation
        rk4_update(*spheres[i], dt);
        
        spheres[i]->clear_force();
    }
    
    
}
Exemplo n.º 3
0
// LOOK OUT FOR A CREATURE THAT IS WILLING TO REPLICATE
void Creature::searchPartner(std::vector<Creature*>& creatures)
{
	for(int i = 0; i < creatures.size(); ++i)
	{
    // I DON'T HAVE A PARTNER YET :(
		if(partner == NULL || !partner->isReadyToReplicate() || !collides(partner))
		{
      // FOUND ONE THAT IS LEGIT?
			if( creatures[i] != this && collides(creatures[i]) 
				&& creatures[i]->isReadyToReplicate() && !creatures[i]->isReplicating()
				&& (creatures[i]->getPartner() == NULL || creatures[i]->getPartner() == this))
			{
        // YAY I FOUND A PARTNER -> MOVE TOWARDS PARTNER
				moveAction.setTargetPosition((creatures[i]->getPosition() + position) / 2.f);
				sight.setFillColor(sf::Color(255, 255, 0, 100));
				partner = creatures[i];
				movingToPartner = true;
			}
		} 
    // I ALREADY HAVE A PARTNER :)
    else 
    {
      // MOVE TOWARD CREATURE
			moveAction.setTargetPosition((partner->getPosition() + position) / 2.f);
			sight.setFillColor(sf::Color(255, 255, 0, 100));
			movingToPartner = true;
		}
	}
  
  // UNHIGHLIGHT
	if(!movingToPartner)
	{
		sight.setFillColor(sf::Color(200, 200, 200, 50));
	}
}
Exemplo n.º 4
0
void Follower::detectCollision()
{
	//bounding sphere for follower
	BoundingSphere followerSphere = BoundingSphere(mPosition, mRadius);
	D3DXVECTOR3 movement;
	bool wall = false;
	//collision with walls or obstacles in level
	for (Mesh* M : gCurrentLevel->getWorldGeometry())
	{
		for (AxisAlignedBoundingBox AABB : M->getBoundsBoxList())
		{
			if (collides(AABB, followerSphere, movement))
			{
				mPosition += movement;
				wall = true;
			}
		}
	}
	//collide with player unless there is a wall in the way
	if (!wall)
	{
		BoundingSphere playerSphere = BoundingSphere(gPlayer->getPosition(), gPlayer->getRadius());
		if (collides(followerSphere, playerSphere, movement))
		{
			mPosition += movement;
		}
	}
}
Exemplo n.º 5
0
void Simulation::checkCollisions() {
    const QPolygonF& objectPolygon = object_.polygon();
    const QPolygonF fingertip1 = gripper_.fingertip1Polygon();
    const QPolygonF fingertip2 = gripper_.fingertip2Polygon();

    bool collided = false;

    if(objectPolygon.boundingRect().intersects(fingertip1.boundingRect())) {
        // Detailed collision check between object and fingertip 1
        collided = collides(objectPolygon, fingertip1) ? true : collided;
    }
    if(objectPolygon.boundingRect().intersects(fingertip2.boundingRect())) {
        // Detailed collision check between object and fingertip 2
        collided = collides(objectPolygon, fingertip2) ? true : collided;
    }

    if(collided) {
		// Do nothing
    }
    else {
        // Mark the areas around the fingertips as clear
        info_.markClear(gripper_.fingertip1Polygon());
        info_.markClear(gripper_.fingertip2Polygon());
    }
}
Exemplo n.º 6
0
void Enemy::detectCollision()
{
	//bounding sphere for follower
	BoundingSphere mySphere = BoundingSphere(mPosition, mRadius);
	D3DXVECTOR3 movement;
	bool wall = false;
	//collision with walls or obstacles in level
	for (Mesh* M : gCurrentLevel->getWorldGeometry())
	{
		for (AxisAlignedBoundingBox AABB : M->getBoundsBoxList())
		{
			if (collides(AABB, mySphere, movement))
			{
				mPosition += movement;
				wall = true;
			}
		}
	}
	//collide with other enemies unless there is was wall in the way
	if (!wall)
	{
		for (Enemy* E : gCurrentLevel->getSpawner()->getEnemies())
		{
			BoundingSphere otherSphere = BoundingSphere(E->getPosition(), E->getRadius());
			if (collides(mySphere, otherSphere, movement))
			{
				mPosition += (movement / 2);
				E->move(-(movement / 2));
			}
		}
	}
}
    bool AABBCollider::collides(Collider* pCollider) const {
        AABBCollider* aabb(static_cast<AABBCollider*>(pCollider));
        if (aabb)
            return collides(*aabb);

        PointCollider* point(static_cast<PointCollider*>(pCollider));
        if (point)
            return collides(*point);

        return Collider::collides(pCollider);
    }
Exemplo n.º 8
0
void GameState::update()
{
	//spawn enemies
	spawnDelay += sfw::getDeltaTime();

	if (spawnDelay > spawnRate)
	{
		spawnDelay = 0;
		spawnRate *= .98f;
		spawnEnemy(randRange(BOUNDS_LEFT, BOUNDS_RIGHT), BOUNDS_TOP);
	}

	//updating
	player.update();
	for (int i = 0; i < bullets.size(); ++i)
		bullets[i].update();
	for (int i = 0; i < enemies.size(); ++i)
		enemies[i].update();

	//Collision
	//player v bullets/enemies
	for (int i = 0; i < bullets.size(); ++i)
		collides(player, bullets[i]);
	for (int i = 0; i < enemies.size(); ++i)
		collides(player, enemies[i]);

	//bullet v enemies
	for (int i = 0; i < enemies.size(); ++i)
		for (int j = 0; j < bullets.size(); ++j)
			collides(enemies[i], bullets[j]);

	for (int i = 0; i < bullets.size(); ++i)
		for (int j = 0; j < bullets.size(); ++j)
			collides(bullets[i], bullets[j]);

	if (appState == GAME)
	{
		if (!player.active)
		{
			std::fstream fout("scores.dat",std::ios_base::out | std::ios_base::app);
			fout << score << std::endl;
			fout.close();
			
			appState = VICTORY;
		}
		if (sfw::getKey('P'))
			appState = PAUSE;
	}
}
Exemplo n.º 9
0
void _checkCollisions(Entity *entity, CellList* list) {
    if(list) {
        float posX = entity->pos.x;
        float posY = entity->pos.y;
        int sizeX = entity->size.x;
        int sizeY = entity->size.y;

        EntityPtr *ents = list->_list;

        for(int i=0; i<list->index; i++) {
            if(ents[i] != entity) {
                Vec2d *pos2 = &ents[i]->pos;
                Vec2di *size2 = &ents[i]->size;

                if(collides(posX, posY,
                            posX + sizeX, posY + sizeY,
                            pos2->x, pos2->y,
                            pos2->x + size2->x, pos2->y + size2->y)) {
                    if(entity == playerEntity) {
                        removeObject(ents[i]);
                    }
                }
            }
        }
    }
}
Exemplo n.º 10
0
/* Perform a Monte Carlo sweep */
static TaskSignal monteCarloTaskTick(void *state)
{
	assert(state != NULL);
	MonteCarloState *mcs = (MonteCarloState*) state;
	MonteCarloConfig *mcc = &mcs->conf;

	assert(mcc->delta > 0);

	for (int i = 0; i < world.numParticles; i++) {
		Particle *p = &world.particles[randIndex(world.numParticles)];
		Vec3 oldPos = p->pos;

		p->pos.x += mcc->delta * (rand01() - 1/2.0);
		p->pos.y += mcc->delta * (rand01() - 1/2.0);
		if (!world.twoDimensional)
			p->pos.z += mcc->delta * (rand01() - 1/2.0);

		reboxParticle(p);

		if (collides(p)) {
			/* Back to old position! */
			p->pos = oldPos;
			reboxParticle(p);
		} else {
			mcs->accepted++;
		}
	}

	mcs->attempted += world.numParticles;

	return TASK_OK;
}
Exemplo n.º 11
0
void Projectile::midstep(Gamestate *state, double frametime)
{
    if (isrectangular())
    {
        if (state->currentmap->collides(getrect(), std::atan2(vspeed, hspeed)))
        {
            oncollision(state);
        }
        for (auto p : state->playerlist)
        {
            // DEBUGTOOL: Replace this check with checking whether p is on enemy team
            if (p != owner)
            {
                Character *c = state->get<Player>(p)->getcharacter(state);
                if (c != 0)
                {
                    if (collides(state, state->get<Player>(p)->character, std::atan2(vspeed, hspeed)))
                    {
                        oncollision(state, c);
                    }
                }
            }
        }
    }
}
Exemplo n.º 12
0
void SurfaceObject::blit(Active * obj)
{
    use_fbo_blit = true;
    if (!collides(0, 0, selected_image->width, selected_image->height,
                  dest_x, dest_y, dest_x+dest_width, dest_y+dest_height))
        return;

    Image * img = obj->image;
    int scale_x = SURFACE_FBO_WIDTH / selected_image->width;
    int scale_y = SURFACE_FBO_HEIGHT / selected_image->height;
    int index = blit_images.size();
    blit_images.resize(index+1);
    blit_images[index].x = dest_x * scale_x;
    blit_images[index].y = dest_y * scale_y;
    dest_width *= scale_x;
    dest_height *= scale_y;
    int img_w = src_width;
    if (img_w == -1)
        img_w = img->width;
    int img_h = src_height;
    if (img_h == -1)
        img_h = img->height;
    blit_images[index].scale_x = dest_width / double(img_w);
    blit_images[index].scale_y = dest_height / double(img_h);
    blit_images[index].scroll_x = 0;
    blit_images[index].scroll_y = 0;

    if (blit_effect != 1 && blit_effect != 11) {
        std::cout << "Unsupported blit effect: " << blit_effect << std::endl;
        blit_images[index].effect = 1;
    } else
        blit_images[index].effect = blit_effect;

    blit_images[index].image = img;
}
Exemplo n.º 13
0
void Physics::detect_collisions()
{   
    for (size_t i = 0; i < num_spheres(); i++) {
        for (size_t j = 0; j < num_spheres(); j++) {
            if (i != j) {
                collides(*(spheres[i]), *(spheres[j]), collision_damping);
            }
        }

        for (size_t j = 0; j < num_planes(); j++) {
            collides(*(spheres[i]), *(planes[j]), collision_damping);
        }
        
        for (size_t j = 0; j < num_triangles(); j++) {
            collides(*(spheres[i]), *(triangles[j]), collision_damping);
        }
    }
}
Exemplo n.º 14
0
//takes the corner of the -x/-z corner and int size
//since the map for this is always flat and square
//works best when map size is divisible by GRID_SIZE
//This only works effectively if done after all the addWorldGeometry
void AStar::initPathfinding()
{
	D3DXVECTOR3 corner = gCurrentLevel->getNegCorner();
	//set up path nodes for enemy path finding
	//place path nodes every GRID_SIZE units except
	//in places where it would collide
	UINT iterationsX = (UINT)gCurrentLevel->getSize().x / GRID_SIZE;
	UINT iterationsZ = (UINT)gCurrentLevel->getSize().z / GRID_SIZE;
	for (UINT x = 0; x < iterationsX; ++x)
	{
		for (UINT z = 0; z < iterationsZ; ++z)
		{
			bool canPlace = true;
			//for each mesh in the current map
			for (Mesh* M : gCurrentLevel->getWorldGeometry())
			{
				//for each AABB in that mesh
				for (AxisAlignedBoundingBox AABB : M->getBoundsBoxList())
				{
					//find the center of the node to compare with
					D3DXVECTOR3 nodeCenter = D3DXVECTOR3(corner.x + (float)(x * GRID_SIZE),
						0.0f, corner.z + (float)(z * GRID_SIZE));
					//make a bounding sphere with it
					BoundingSphere PS = BoundingSphere(nodeCenter, CLOSE_RADIUS);
					//if the AABB collides with that sphere, we can't place one here
					if (collides(AABB, PS))
					{
						canPlace = false;
						break;
					}
					if (!canPlace)
						break;
				}
				if (!canPlace)
					break;
			}
			//if no obstruction was found, place the node
			if (canPlace)
			{
				D3DXVECTOR3 position = D3DXVECTOR3(corner.x, 0.0f/*SAM:50.0f*/, corner.z)
					+ D3DXVECTOR3((float)(x * GRID_SIZE), 0.0f, (float)(z * GRID_SIZE));

#ifdef DEBUG_PATHS
				//set up the mesh if in debug
				PathNode* pn = new PathNode(L"Content/Models/ball.x", position, D3DXVECTOR3(2.0f, 2.0f, 2.0f));
#else
				//use no mesh if not in debug, this saves a lot of time loading
				PathNode* pn = new PathNode(position);
#endif
				//add new node
				mPathNodes.push_back(pn);
			}
		}
	}
	//connect the nodes to their closest neighbors
	connectPathfinding();
}
Exemplo n.º 15
0
bool Enemy::noticeFollower()
{
	bool returnBool = false;
	D3DXVECTOR3 followerPos = gFollower->getPosition();
	float distanceSq = D3DXVec3LengthSq(&(mPosition - followerPos));
	if (distanceSq > mSightRangeSq)//if not within range, they can't see follower
	{
		bAttackFollower = false;
		return false;
	}
	// they are close enough to hear the follower through a wall or behind them
	if (distanceSq < mHearRangeSq)
		returnBool = true;
	//if the follower would be behind the enemy, they don't get a chance to see them
	//current enemy rotation is mRotation.y
	//find rotation towards follower
	D3DXVECTOR3 toFollower = gFollower->getPosition() - mPosition;
	float followerDirection = atan2(toFollower.x, toFollower.z);
	//if not within VISION_RANGE degrees/PI radians of each other
	//this only applies if the player has not injured them. If player has, they are more 
	//watchful
	if (mHealth == mHealthMax && returnBool == false)
	{
		//1.57 ~ 1/2 * PI      6.28 ~ 2 * PI
		if ((fabs(followerDirection - mRotation.y) > 1.57) &&
			((fabs(followerDirection - 6.28)) + mRotation.y > 1.57) &&
			((fabs(mRotation.y - 6.28)) + followerDirection > 1.57))
		{
			bAttackFollower = false;
			return false;
		}
	}
	//if they are between max hearing and max sight range, see if they are line of sight to player
	//make a line segment between enemy and player location
	//only take into account x and z here since map is flat, will save time
	LineSegment line3D(mPosition, followerPos);
	for (Mesh* M : gCurrentLevel->getWorldGeometry())
	{
		for (AxisAlignedBoundingBox AABB : M->getBoundsBoxList())
		{
			//if further out than sight range, no point in checking it
			if (D3DXVec3LengthSq(&(AABB.mMin - mPosition)) > mSightRangeSq)
				continue;
			//see if it collides with the line
			if (collides(AABB, line3D))
			{
				bAttackPlayer = false;
				return returnBool;
			}
		}
	}
	//if it gets through the above checks, then it can see the player
	mLoseSightFollower = 0.0f;
	bAttackFollower = true;
	bSeenPlayer = true;
	return true;
}
Exemplo n.º 16
0
static void 
recursefindpack(Rectangle *    const current,
                Coord          const currentsz,
                Coord *        const best,
                unsigned int   const minarea,
                unsigned int * const maxareaP, 
                unsigned int   const depth,
                unsigned int   const n,
                unsigned int   const xinc,
                unsigned int   const yinc,
                unsigned int   const quality,
                unsigned int   const qfactor) {

    if (depth == n) {
        if (currentsz.x * currentsz.y < *maxareaP) {
            unsigned int i;
            for (i = 0; i < n; ++i)
                best[i] = current[i].ul;
            *maxareaP = currentsz.x * currentsz.y;
        }
    } else {
        unsigned int i;

        Rectangle * const newP = &current[depth];

        for (i = 0; ; ++i) {
            for (newP->ul.x = 0, newP->ul.y = i * yinc;
                 newP->ul.y <= i * yinc;) {

                Coord c;

                c.x = MAX(lr(*newP).x, currentsz.x);
                c.y = MAX(lr(*newP).y, currentsz.y);
                pm_message("current = (%u.%u, %u.%u) new = (%u.%u, %u.%u)",
                           current[0].ul.x, current[0].size.x,
                           current[0].ul.y, current[0].size.y,
                           newP->ul.x,   newP->size.x,
                           newP->ul.y,   newP->size.y);
                if (!collides(*newP, current, depth)) {
                    pm_message("Depth %u: Doesn't collide at i=%u", depth,i);
                    recursefindpack(current, c, best, minarea, maxareaP,
                                    depth + 1, n, xinc, yinc,
                                    quality, qfactor);
                    if (*maxareaP <= minarea)
                        return;
                }
                if (newP->ul.x == (i - 1) * xinc)
                    newP->ul.y = 0;
                if (newP->ul.x < i * xinc)
                    newP->ul.x += xinc;
                else
                    newP->ul.y += yinc;
            }
        }
    }
}
Exemplo n.º 17
0
//This game starts the game the setting of speed is done by using the clock() function
void startgame(int snakeXY[][MAX_SIZE], int foodXY[], int consolewidth, int consoleheight, int snakelength, int dir, int score, int speed) {
	int isgameover = 0;
	clock_t endwait;
	int waittime = CLOCKS_PER_SEC-(speed)*(CLOCKS_PER_SEC/10);
	waittime = waittime / 2.5;	
	int tempscore = 10 * speed;
	int olddir;
	int newdir = 1;
	endwait = clock() + waittime;
	do {
		if(newdir) {
			olddir = dir;
			dir = checkkey(dir);
		}
		if(olddir != dir) 
			newdir = 0;
		if(clock() >= endwait) {
			displaymovement(snakeXY,snakelength,dir);
			newdir = 1;
			if(checkeatfood(snakeXY, foodXY)) {
				foodcreate(foodXY, consolewidth, consoleheight, snakeXY, snakelength);
				snakelength++;
				score = score + speed; // I have incremented the score with the speed ( 9 gets the most score)
				 if( score >= 10*speed+tempscore) {
                    			speed = speed * 2;
                    			tempscore = score;
 					if(speed <= 9)
                        			waittime = waittime - (CLOCKS_PER_SEC);
                    			else if(waittime >= 40)
                            			waittime = waittime - (CLOCKS_PER_SEC);
                         			
                   		}
				scoreboard(score, speed);			
			}
			endwait = clock() + waittime;	
		}
		isgameover = collides(snakeXY, consolewidth, consoleheight, snakelength);
		 
		if(snakelength >= MAX_SIZE-5) {
            		isgameover = 2;
            		score+=1500; 
        	}	

	
	} while(!isgameover);
	
	switch(isgameover) {
		case 1: 
			gameoverscreen();
			break;
		default: ;
			break;
	}		
	
	
}
Exemplo n.º 18
0
int move(int move, int* board) {
    int slid = slides(move, board, 1);
    int collided = collides(move, board, 1);

    if (collided) {
        slides(move, board, 1);
    }

    return slid || collided;
}
Exemplo n.º 19
0
bool collides(Collision& col1, Collision& col2)
{
  if (collides(col1.bounding_boxes, col1.x, col1.y,
               col2.bounding_boxes, col2.x, col2.y))
    return true;

  // As we implement more collisions, check each combination with the appropriate function
  // here

  return false;
}
void Particle::update(float delta)
{
	std::uniform_real_distribution<> dist(-0.5f, -0.15f);

	velocity.x -= glm::sign(velocity.x) * 10.0f * delta;
	velocity.y += gravity * delta;

	position += velocity * delta;
	//position.x += velocity.x * delta;
	//position.y = glm::min(position.y + velocity.y * delta, 1000.0f - size*2);

	for (auto it = game->blocks.begin(); it != game->blocks.end(); ++it)
	{
		if (!it->alive)
			continue;

		glm::vec2 pos = it->getPosition();

		if (collides(position.x, position.y, size*2, size*2, pos.x, pos.y, 50.0f, 50.0f))
		{
			if (pos.y - position.y < size)
			{
				position.y = pos.y - size;
				velocity.y *= (float)dist(game->random);
			}
			else
			{
				position.x = pos.x + (position.x < pos.x ? -50 : 50);
				velocity.x *= (float)dist(game->random);
			}
		}
	}

	if (position.x < 0)
	{
		position.x = 0.0f;
		velocity.x *= (float)dist(game->random);
		game->bound[0] = 1.0f;
	}
	else if (position.x > 3200.0f - size * 2)
	{
		position.x = 3200.0f - size * 2;
		velocity.x *= (float)dist(game->random);
		game->bound[1] = 1.0f;
	}

	if (position.y > 1000.0f - size * 2)
	{
		position.y = 1000.0f - size * 2;
		velocity.y *= (float)dist(game->random);
	}

	duration -= delta;
}
Exemplo n.º 21
0
// 'Versuchen' Alien zu töten (wenn schon tot, false zurückgeben)
int killEnemy(Game *g, int x, int y)
{
    if (!g->enemyContainer.enemys[x][y].dead) {
        SDL_Rect p_rect = {g->player.shot->posx, g->player.shot->posy, PLAYER_SHOT_WIDTH, PLAYER_SHOT_HEIGHT};
        SDL_Rect e_rect;
        
        e_rect.x = g->enemyContainer.posx + (x * FIELD_WIDTH) + (x * FIELD_MARGIN * 2) - FIELD_MARGIN;
        e_rect.y = g->enemyContainer.posy + (y * FIELD_HEIGHT) + (y * FIELD_MARGIN * 2) - FIELD_MARGIN;
        e_rect.w = FIELD_WIDTH;
        e_rect.h = FIELD_HEIGHT;
        
        // Überscheiden die Umrisse sich?
        if (!collides(p_rect, e_rect)) {
            return false;
        }
        
        // Schuss überschreiben
        SDL_FillRect(g->screen, &p_rect, SDL_MapRGB(g->screen->format, 0, 0, 0));
        
        // Speicher freimachen
        free(g->player.shot);
        // Pointer auf NULL setzen
        g->player.shot = NULL;
        // Alien tot
        g->enemyContainer.enemys[x][y].dead = true;
        
        // Alien löschen
        SDL_FillRect(g->screen, &e_rect, SDL_MapRGB(g->screen->format, 0, 0, 0));
        
        // Zähler dekrementieren
        g->enemyContainer.aliveCount--;
        
        // Punkte gutschreiben
        if (g->enemyContainer.enemys[x][y].type == 3) {
            g->score += ALIEN_3_POINTS;
        } else if (g->enemyContainer.enemys[x][y].type == 2) {
            g->score += ALIEN_2_POINTS;
        } else if (g->enemyContainer.enemys[x][y].type == 1) {
            g->score += ALIEN_1_POINTS;
        }
        // Anzeigen
        updateScore(g);
        
        // Alle tot -> neues Level
        if (g->enemyContainer.aliveCount == 0) {
            startNewLevel(g);
        }
        
        return true;
    } else {
        return false;
    }
}
Exemplo n.º 22
0
bool Bearpaw::
collides(R3Scene *scene, R3Node *node)
{
    if (bbox.intersects(node->bbox)) {
        return true;
    }
    for (unsigned int i = 0; i < node->children.size(); i++) {
        if (collides(scene, node->children[i])) {
            return true;
        }
    }
    return false;
}
Exemplo n.º 23
0
void Physics::step( real_t dt )
{
	// Check collision between every sphere and other objects.
	for (size_t i = 0; i < num_spheres(); i++) {
		for (size_t j = 0; j < num_planes(); j++)
			collides(*spheres[i], *planes[j], collision_damping);
		for (size_t j = 0; j < num_triangles(); j++)
			collides(*spheres[i], *triangles[j], collision_damping);
		for (size_t j = i + 1; j < num_spheres(); j++) {
			collides(*spheres[i], *spheres[j], collision_damping);
		}

	}

	std::vector<State> states(num_spheres());
	for (size_t i = 0; i < num_spheres(); i++) {
		states[i].position = spheres[i]->position;
		states[i].velocity = spheres[i]->velocity;
		states[i].angular_velocity = spheres[i]->angular_velocity;

		// Step dt using rk4 integral.
		rk4_integrate(states[i], spheres[i], dt);
	}

	// Update every sphere's state after rk4 integral.
	for (size_t i = 0; i < num_spheres(); i++) {
		spheres[i]->position = states[i].position;
		spheres[i]->velocity = states[i].velocity;
		spheres[i]->angular_velocity = states[i].angular_velocity;
		spheres[i]->update_orientation(states[i].angular_position);
		spheres[i]->sphere->orientation = spheres[i]->orientation;
		spheres[i]->sphere->position = states[i].position;

		// Update the offset vector of this sphere in every spring it is attached to.
		for (size_t j = 0; j < spheres[i]->spring_ptrs.size(); j++) {
			spheres[i]->spring_ptrs[j]->update_offset(spheres[i], states[i].angular_position);
		}
	}
}
Exemplo n.º 24
0
void Enemy::process(std::shared_ptr<Entity> e) {
	if(collides(e)) {
		std::shared_ptr<Explosion> exp = std::dynamic_pointer_cast<Explosion>(e);
		if(exp) {
			remove();
		} else {
			std::shared_ptr<Mine> mine = std::dynamic_pointer_cast<Mine>(e);
			if(mine && mine->anti_enemy) {
				mine->trip();
			}
		}
	}
}
Exemplo n.º 25
0
int is_impossible(int* board) {
    int impossible = TRUE;

    for (int m=0; m<4; m++) {
        if (slides(m, board, 0)) {
            impossible = FALSE;
            break;
        }
        if (collides(m, board, 0)) {
            impossible = FALSE;
            break;
        }
    }

    return impossible;
}
Exemplo n.º 26
0
bool collides(std::vector<BoundingBox>& boxes1, int x1, int y1,
              std::vector<BoundingBox>& boxes2, int x2, int y2)
{
  std::vector<BoundingBox>::iterator it1;
  std::vector<BoundingBox>::iterator it2;
  for (it1 = boxes1.begin(); it1 != boxes1.end(); it1++)
  {
    for (it2 = boxes2.begin(); it2 != boxes2.end(); it2++)
    {
      if ( collides(*it1, x1, y1, *it2, x2, y2) )
        return true;
    }
  }

  return false;
}
Exemplo n.º 27
0
static void fillWorld(void)
{
	double ws = world.worldSize;

	for (int i = 0; i < world.numParticles; i++) {
		Particle *p = &world.particles[i];
		p->pos = (Vec3) {0, 0, 0};
		addToGrid(p);
		do {
			p->pos.x = ws * (rand01() - 1/2.0);
			p->pos.y = ws * (rand01() - 1/2.0);
			if (!world.twoDimensional)
				p->pos.z = ws * (rand01() - 1/2.0);

			reboxParticle(p);
		} while (collides(p));
	}
}
Exemplo n.º 28
0
bl particle::iterate( vector& _vector, const map2d::layer* _layer, f32 _f32_gravity, bl _bl_fixed,
f32 _f32_rate )
{
	translation translation_iteration;

	if( collides( translation_iteration, _layer, _bl_fixed, _f32_rate ) )
	{
		_vector = translation_iteration.vector_collision;

		if( translation_iteration.get_collision_distance() - ENG2D_PRECISION > 0.f )
			position() = get_moved( direction, translation_iteration.get_collision_distance() - ENG2D_PRECISION );

		f32 d = direction;
		f32 c = translation_iteration.line_collision.get_normal_direction();
		f32 b = c - d;

		direction = c + b - math<f32>::radians_05();

		vector vector_offset = get_offset(true);

		const map2d::tile* tile_map = &_layer->get( _vector );

		vector_offset.x *= ( 1.f - roughness ) * ( 1.f - tile_map->get_friction()    );
		vector_offset.y *=         hardness    * ( 1.f - tile_map->get_restitution() );

		set_offset( vector_offset, true );

		return true;
	}
	else
	{
		position() = get_moved( direction, get_distance( _bl_fixed, _f32_rate ) );

		if( _bl_fixed )
		{
			shift_offset_y( _f32_gravity * _layer->get_gravity(),                             true, _f32_rate );
		}
		else
		{
			shift_offset_y( _f32_gravity * _layer->get_gravity() * ( sys::delta() * 1000.0 ), true, _f32_rate );
		}

		return false;
} }
Exemplo n.º 29
0
bool rocks_in_space::collides(const collision& col_a, const collision& col_b)
{
	auto delta = col_a.m_position - col_b.m_position;
	if (delta.magnitude() > (col_a.m_radius + col_b.m_radius))
	{
		return false;
	}

	auto segment_start = col_a.m_path.m_vertices[col_a.m_path.m_count - 1];
	return &col_a.m_path.m_vertices[col_a.m_path.m_count] != std::find_if(&col_a.m_path.m_vertices[0], &col_a.m_path.m_vertices[col_a.m_path.m_count], [&](const auto& v)
	{
		if (collides(col_b, { { segment_start + col_a.m_position, v + col_a.m_position } }))
		{
			return true;
		}
		segment_start += v;
		return false;
	});
}
bool DynamicObjectMagicRayLogicCalculator::checkIfMagicRayCollidesWithEnemiesAndUpdateEnemies()
{
	bool isColliding = false;

	std::map<int, AvatarModel*>::iterator enemiesIt = m_levelModel->getEnemyModels().begin();

	while(enemiesIt != m_levelModel->getEnemyModels().end())
	{
		if(collides(enemiesIt->second->getRect()))
		{
			if(!isColliding) isColliding = true;
			
			enemiesIt->second->setLifePoints(enemiesIt->second->getLifePoints()- m_dynamicObjectModel->getDamagePoints());

		}
		enemiesIt++;
	}
	return isColliding;

}