Java 类com.badlogic.gdx.math.Intersector 实例源码

项目:NoRiskNoFun    文件:GameScene.java   
/**

    /**
     * Checks if two specific coordinates are within a PolygonRegion
     * and sets tappedRegion to this region
     *
     * @param pointX absolute value of X coordinate
     * @param pointY absolute value of Y coordinate
     * @return true if in a region, false if not.
     */
    private boolean isPointInRegion(float pointX, float pointY) {

        for (AssetMap.Region region : data.getMapAsset().getRegions()) {
            tappedRegion = region;
            float[] vertices = region.getVertices();

            // for Intersector, we have to convert to percentual x/y coordinates. Simply divide by screen width/height
            if (Intersector.isPointInPolygon(vertices, 0, vertices.length, pointX / Gdx.graphics.getWidth(), pointY / Gdx.graphics.getHeight())) {
                clickedRegionLabel.setText("Region: " + region.getName());

                return true;
            }

        }
        clickedRegionLabel.setText("Region: None");
        return false;
    }
项目:enklave    文件:Enklave3D.java   
public boolean touchEnklave(PerspectiveCamera camera,int screenX,int screenY){
        coordonate = null;
        instanceModel.calculateBoundingBox(box).mul(instanceModel.transform);
        box.getCenter(position);
        box.getDimensions(dimensions);
        Ray ray = camera.getPickRay(screenX,screenY);
//        instanceModel.transform.getTranslation(position);
//        position.add(box.getCenter(new Vector3()));
//        Gdx.app.log("res"+ray.toString(),"position"+position);
        if(Intersector.intersectRayBoundsFast(ray,box)){ // position, box.getDimensions(new Vector3()).len(), null)) {
            coordonate = new SpaceCoordonate();
            coordonate.x = Math.abs(Math.abs(position.x) - Math.abs(camera.position.x)) / (Gdx.graphics.getHeight() * 0.026f);
            coordonate.y = Math.abs(Math.abs(position.y) - Math.abs(camera.position.y)) / (Gdx.graphics.getHeight() * 0.026f);
            coordonate.z = -(Math.abs((Gdx.graphics.getHeight() * 0.033f) - Math.abs(camera.position.z)) / (Gdx.graphics.getHeight() * 0.026f));
            if (box.getCenterX() < camera.position.x) {
                coordonate.x = -coordonate.x;
            }
            if (box.getCenterY() < camera.position.y) {
                coordonate.y = -coordonate.y;
            }
            return true;
        }
        return false;
    }
项目:ZombieInvadersVR    文件:ScreenBase.java   
public GameObject getObject (int screenX, int screenY) {
    Ray ray = camera.getPickRay(screenX, screenY);
    GameObject result = null;
    float distance = -1;
    for (ModelInstance item : instances) {
        if(item instanceof GameObject){
            GameObject gameObject = (GameObject) item;
            if(gameObject.enabled){
        Vector3 position = gameObject.transform.getTranslation(new Vector3());
        gameObject.updateBox();
          position.add(gameObject.center);
          float dist2 = ray.origin.dst2(position);
          if (distance >= 0f && dist2 > distance) continue;
          if (Intersector.intersectRayBoundsFast(ray, gameObject.bounds)) {
           result = gameObject;
              distance = dist2;
          }
            }
        }
    }
    return result;
}
项目:Kroniax    文件:RectLevelObject.java   
@Override
public boolean checkCollision(Vector2 p1, Vector2 p2) {
    // Intersect left edge
    if (Intersector.intersectSegments(p1.x, p1.y, p2.x, p2.y, mXPos, mYPos, mXPos, mYPos + mHeight, null))
        return true;

    // Intersect right edge
    if (Intersector.intersectSegments(p1.x, p1.y, p2.x, p2.y, mXPos + mWidth, mYPos, mXPos + mWidth,
            mYPos + mHeight, null))
        return true;

    // Intersect top edge
    if (Intersector.intersectSegments(p1.x, p1.y, p2.x, p2.y, mXPos, mYPos + mHeight, mXPos + mWidth,
            mYPos + mHeight, null))
        return true;

    // Intersect bottom edge
    if (Intersector.intersectSegments(p1.x, p1.y, p2.x, p2.y, mXPos, mYPos, mXPos + mWidth, mYPos, null))
        return true;

    return false;
}
项目:GdxDemo3D    文件:NavMesh.java   
/**
 * Make a ray test at this point, using a ray spanning from far up in the sky, to far down in the ground,
 * along the up axis.
 *
 * @param testPoint        The test point
 * @param out              The point of intersection between ray and triangle
 * @param allowedMeshParts Which mesh parts to test. Null if all meshparts should be tested.
 * @return The triangle, or null if ray did not hit any triangles.
 */
public Triangle verticalRayTest(Vector3 testPoint, Vector3 out, Bits allowedMeshParts) {
    tmpRayVerticalRayTest.set(
            tmpVerticalRayTest1.set(Constants.V3_UP).scl(500).add(testPoint),
            tmpVerticalRayTest2.set(Constants.V3_DOWN));
    Triangle hitTri = rayTest(tmpRayVerticalRayTest, 1000, allowedMeshParts);
    if (hitTri == null) {
        // TODO: Perhaps this should be Nan?
        out.set(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY);
        return null;
    } else {

        Intersector.intersectRayTriangle(tmpRayVerticalRayTest, hitTri.a, hitTri.b, hitTri.c, out);
        return hitTri;
    }
}
项目:Protoman-vs-Megaman    文件:GameUtils.java   
/**
 * checks if a game object is within the given camera's viewport.
 * 
 * @param camera game camera to check if the game object is within the view port
 * @param gameObj game object to check
 * 
 * @return <b>true</b> if game object is within camera viewport. <b>false</b> otherwise.
 */
public static boolean isWithinCameraView(Camera camera, GameObject gameObj) {
    if (cameraBounds == null) {
        // first call to this method
        // create a Rectangle instance and keep it for later use
        // it is better to keep an instance to avoid gc during update/render calls
        cameraBounds = new Rectangle();
    }

    cameraBounds.x = camera.position.x - camera.viewportWidth / 2;
    cameraBounds.y = camera.position.y - camera.viewportHeight / 2;
    cameraBounds.width = camera.viewportWidth;
    cameraBounds.height = camera.viewportHeight;

    return Intersector.overlaps(cameraBounds, gameObj.getBoundingRectangle());
}
项目:SpaceProject    文件:TestVoronoiScreen.java   
/**
 * Check if a line from a to b intersects with the convext hull. 
 * If so, the point of intersection is stored in the intersect vector.
 * @param a point one
 * @param b point two
 * @param intersect point of intersection
 * @return true if intersect. Point of intersection stored in intersect
 */
public boolean collideWithHull(Vector2 a, Vector2 b, Vector2 intersect) {
    //for each line segment between two vertices
    float[] verticies = hullPoly.getTransformedVertices();
    for (int v = 0; v < verticies.length - 2; v += 2) {
        float xA = verticies[v];
        float yA = verticies[v + 1];
        float xB = verticies[v + 2];
        float yB = verticies[v + 3];
        // convex hull line between A and B
        Vector2 edgeA = new Vector2(xA, yA);
        Vector2 edgeB = new Vector2(xB, yB);

        if (Intersector.intersectSegments(edgeA, edgeB, a, b, intersect)) {
            //the two lines intersect. point of intersection is set in variable intersect
            return true;
        }

    }
    return false;
}
项目:Alien-Ark    文件:SolarScreen.java   
private boolean isColliding(Vector2 planetPosition, float planetRadius) {
    if (corner01.dst(planetPosition) < planetRadius) {
        return true;
    }
    if (corner02.dst(planetPosition) < planetRadius) {
        return true;
    }
    if (corner03.dst(planetPosition) < planetRadius) {
        return true;
    }
    if (corner04.dst(planetPosition) < planetRadius) {
        return true;
    }
    return Intersector.isPointInTriangle(planetPosition, corner01, corner02, corner03)
            || Intersector.isPointInTriangle(planetPosition, corner03, corner04, corner01);
}
项目:libgdx-demo-pax-britannica    文件:Collision.java   
private static void collisionCheck(Bullet bullet, Ship ship) {
    if (bullet.id!=ship.id && ship.alive) {

        for(int i = 0; i<ship.collisionPoints.size;++i) {
            if(Intersector.isPointInPolygon(bullet.collisionPoints, ship.collisionPoints.get(i))) {
                ship.damage(bullet.damage);
                GameInstance.getInstance().bulletHit(ship, bullet);
                bullet.alive = false;
                return;
            }
        }

        for(int i = 0; i<bullet.collisionPoints.size;++i) {
            if(Intersector.isPointInPolygon(ship.collisionPoints, bullet.collisionPoints.get(i))) {
                ship.damage(bullet.damage);
                GameInstance.getInstance().bulletHit(ship, bullet);
                bullet.alive = false;
                return;
            }
        }
    }
}
项目:libgdx-demo-pax-britannica    文件:GameScreen.java   
@Override
public boolean touchDown(int x, int y, int pointer, int button) {
    collisionRay = cam.getPickRay(x, y);

    if(numPlayers >0 && Intersector.intersectRayBoundsFast(collisionRay, touchAreaP1) && GameInstance.getInstance().factorys.size>0) {
        ((FactoryProduction) GameInstance.getInstance().factorys.get(0)).button_held = true;
        pointerP1 = pointer;
        touchedP1 = true;
    } 
    if(numPlayers >1 && Intersector.intersectRayBoundsFast(collisionRay, touchAreaP2) && GameInstance.getInstance().factorys.size>1) {
        ((FactoryProduction) GameInstance.getInstance().factorys.get(1)).button_held = true;
        pointerP2 = pointer;
        touchedP2 = true;
    } 
    if(numPlayers >2 && Intersector.intersectRayBoundsFast(collisionRay, touchAreaP3) && GameInstance.getInstance().factorys.size>2) {
        ((FactoryProduction) GameInstance.getInstance().factorys.get(2)).button_held = true;
        pointerP3 = pointer;
        touchedP3 = true;
    } 
    if(numPlayers >3 && Intersector.intersectRayBoundsFast(collisionRay, touchAreaP4) && GameInstance.getInstance().factorys.size>3) {
        ((FactoryProduction) GameInstance.getInstance().factorys.get(3)).button_held = true;
        pointerP4 = pointer;
        touchedP4 = true;
    } 
    return false;
}
项目:Ampel-Bird    文件:GameWorld.java   
public void updateRunning(float delta) {
    if (delta > .15f) {
        delta = .15f;
    }

    bird.update(delta);
    scroller.update(delta);

    if (scroller.collides(bird) && bird.isAlive()) {
        scroller.stop();
        bird.die();
        AssetLoader.deadSound.play();
    }

    if (Intersector.overlaps(bird.getBoundingCircle(), ground)) {
        scroller.stop();
        bird.die();
        bird.decelerate();
        currentState = GameState.GAMEOVER;
    }
}
项目:old48_29_game    文件:Level.java   
public void placeOilFactory() {
    float oilRectWidth = 2f;
    Rectangle factoryRect = new Rectangle(president.getX()
            + President.WIDTH / 2f - oilRectWidth / 2f, president.getY() - 4, oilRectWidth, 1);

    for (Entity ent : levelEntities.get(OilField.class)) {
        final OilField field = (OilField) ent;

        if (field.isHasFactory())
            continue;

        if (Intersector.intersectRectangles(field.bounds, factoryRect,
                tmpRect)) {
            levelEntities.get(OilFactory.class).add(
                    new OilFactory(field.getX() + field.getWidth()/2f - OilFactory.WIDTH / 2f));
            field.setHasFactory(true);
            GameScore.getInstance().incDemocracyLevel();

            break;
        }
    }
}
项目:old48_29_game    文件:InterceptionManager.java   
private void damagePresident() {
    @SuppressWarnings("unchecked")
    List<Bullet> bullets = (List<Bullet>) (Object) level.levelEntities
            .get(Bullet.class);
    President pres = level.president;

    for (Bullet bullet : bullets) {
        if (bullet.isMarkedToDelete())
            continue;

        for (Rectangle bound : pres.getBounds()) {
            if (Intersector.intersectRectangles(bound, bullet.bounds,
                    tmpRect)) {
                pres.doDamage(Constants.TERR_DAMAGE);
                bullet.markDeleted();
                break;
            }
        }
    }

}
项目:old48_29_game    文件:InterceptionManager.java   
private void destroyKamaz() {
    @SuppressWarnings("unchecked")
    List<Rocket> rockets = (List<Rocket>) (Object) level.levelEntities
            .get(Rocket.class);
    @SuppressWarnings("unchecked")
    List<TntVehicle> vehicles = (List<TntVehicle>) (Object) level.levelEntities
            .get(TntVehicle.class);

    for (Rocket rocket : rockets) {
        for (TntVehicle vehicle : vehicles) {
            if (rocket.isMarkedToDelete() || vehicle.isDestroyed())
                continue;
            if (Intersector.intersectRectangles(rocket.bounds,
                    vehicle.bounds, tmpRect)) {
                rocket.markDeleted();
                vehicle.setDestroyed(true);
                Assets.kamazExpSound.play();
                GameScore.getInstance().priceTNTVehicle();
                   level.bum(vehicle.getX(), vehicle.getY());
            }
        }
    }
}
项目:PongWithLibgdx    文件:PongBoard.java   
private void checkForPaddleCollision() {
    for (Paddle hitPaddle : paddleList) {
        if (Intersector.overlaps(hitPaddle, ball)) {
            paddleHits++;
            ball.xVel *= -1;
            if (ball.xVel > 0) {ball.xVel += 20;} else {ball.xVel -= 20;}

            paddleCollisionSound.play();
            startScreenShake();
            if (hitPaddle.name.equals("paddle1")) {
                ball.setPosition((hitPaddle.x + hitPaddle.width), ball.y);
            } else if (hitPaddle.name.equals("paddle2")) {
                ball.setPosition((hitPaddle.x - ball.width), ball.y);
            }
        }
    }
}
项目:Escape-of-the-Ninja    文件:GameModel.java   
public void checkItems() {
    for(Item i : items) {
        if(Intersector.overlaps(i,player.getR())) {
            switch(i.getType()) {
            case KILL:
                setLost(true);
                break;
            case FLY:
                velocityY = Constants.velocityY*2f;
                /*if(velocityX >0)
                        velocityX = Constants.velocityX;
                    else
                        velocityX = -Constants.velocityX;*/
                break;
            }
        }
    }

}
项目:Vloxlands    文件:Game.java   
public Chunk pickVoxelRay(Island island, Vector3 selVoxel, boolean lmb, int x, int y) {
    Chunk selectedChunk = null;
    Ray ray = camera.getPickRay(x, y);

    float distance = 0;

    for (Chunk c : island.getChunks()) {
        if (c == null) continue;
        if (c.inFrustum && !c.isEmpty()) {
            tmp1.set(island.pos.x + c.pos.x, island.pos.y + c.pos.y, island.pos.z + c.pos.z);
            tmp2.set(tmp1.cpy().add(Chunk.SIZE, Chunk.SIZE, Chunk.SIZE));

            bb.set(tmp1, tmp2);
            if (Intersector.intersectRayBounds(ray, bb, null) && c.pickVoxel(ray, tmp5, tmp6)) {
                float dst = ray.origin.dst(tmp5);
                if ((distance == 0 || dst < distance) && dst <= pickRayMaxDistance) {
                    distance = dst;
                    selVoxel.set(tmp6).add(c.pos);
                    selectedChunk = c;
                }
            }
        }
    }

    return selectedChunk;
}
项目:ead    文件:Handles.java   
/**
 * Aligns all the given handles with this handle
 * 
 * @param aligned
 *            the handles to align
 * @param originAngle
 *            the angle of the line that pass for this handle
 * @param targetAngle
 *            the angle of the line that pass for the given handles
 *            (perpendicular to originAngle)
 */
private void updateAligned(Handle[] aligned, float originAngle,
        float targetAngle) {
    if (aligned != null) {
        for (Handle handle : aligned) {
            Vector2 p1 = tmp1.set(getX(), getY());
            Vector2 p2 = tmp2.set(1, 0).rotate(originAngle).add(p1);

            Vector2 q1 = tmp3.set(handle.getX(), handle.getY());
            Vector2 q2 = tmp4.set(1, 0).rotate(targetAngle).add(q1);

            Intersector.intersectLines(p1, p2, q1, q2, tmp5);
            handle.setX(tmp5.x);
            handle.setY(tmp5.y);
        }
    }
}
项目:penguins-in-space    文件:BoundsComponent.java   
public boolean overlaps(BoundsComponent other) {
    if (getBounds() instanceof Rectangle && other.getBounds() instanceof Rectangle) {
        return Intersector.overlaps((Rectangle) getBounds(), (Rectangle) other.getBounds());
    } else if (getBounds() instanceof Circle && other.getBounds() instanceof Circle) {
        return Intersector.overlaps((Circle) getBounds(), (Circle) other.getBounds());
    } else if (getBounds() instanceof Circle && other.getBounds() instanceof Rectangle) {
        return Intersector.overlaps((Circle) getBounds(), (Rectangle) other.getBounds());
    } else if (getBounds() instanceof Rectangle && other.getBounds() instanceof Circle) {
        return Intersector.overlaps((Circle) other.getBounds(), (Rectangle) getBounds());
    }
    throw new RuntimeException("Cannot compare " + this.getBounds() + " and " + other.getBounds());
}
项目:arcadelegends-gg    文件:LevelScreen.java   
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    lastMousePos.set(screenX, screenY);
    Ray ray = camera.getPickRay(screenX, screenY);
    Vector3 worldcoor = new Vector3();
    Intersector.intersectRayPlane(ray, arcadeWorld.getMapHitbox(), worldcoor);
    log.debug("Clicked: " + worldcoor.toString());
    Vector2 mapCoord = new Vector2(Math.round(worldcoor.x), Math.round(worldcoor.y));
    switch (button) {
        case Input.Buttons.LEFT:
            CharacterComponent input = arcadeWorld.getEntityWorld().getComponentOf(playerEnt, CharacterComponent.class);
            input.move.set((int) mapCoord.x, (int) mapCoord.y);
            break;
        case Input.Buttons.RIGHT:
            Tile t = arcadeWorld.getTile(mapCoord);
            try {
                int id = t.getEntities().first();
                input = arcadeWorld.getEntityWorld().getMapper(CharacterComponent.class).get(playerEnt);
                input.targetId = id;
                log.debug("{}", id);
            } catch (IllegalStateException ex) {

            }
            break;
    }

    return false;
}
项目:arcadelegends-gg    文件:Character.java   
/**
 * Sandbox method for getting the mouse-position.
 *
 * @return the mouse-position
 */
public Vector2 getMousePos() {
    Ray ray = arcadeWorld.getCam().getPickRay(AL.input.getX(), AL.input.getY());
    Vector3 vec = new Vector3();
    Intersector.intersectRayPlane(ray, arcadeWorld.getMapHitbox(), vec);
    return new Vector2(vec.x, vec.y);
}
项目:arcadelegends-gg    文件:Character.java   
/**
 * Same as {@link Character#getMousePos()}, only returning rounded coordinates.
 *
 * @return the rounded mouse-position
 */
public Vector2 getRoundMousePos() {
    Ray ray = arcadeWorld.getCam().getPickRay(AL.input.getX(), AL.input.getY());
    Vector3 vec = new Vector3();
    Intersector.intersectRayPlane(ray, arcadeWorld.getMapHitbox(), vec);
    return new Vector2(Math.round(vec.x), Math.round(vec.y));
}
项目:KyperBox    文件:CollisionController.java   
@Override
public void update(GameObject object, float delta) {
    if (tree == null) {
        tree = object.getGameLayer().getSystem(QuadTree.class);
    }

    if (tree != null) {
        CollisionData.getPool().freeAll(collisions);
        collisions.clear();
        Array<GameObject> possible_collisions = tree.getPossibleCollisions(object);
        for (int i = 0; i < possible_collisions.size; i++) {
            GameObject target = possible_collisions.get(i);
            CollisionController target_controller = target.getController(CollisionController.class);
            if (target == object || target_controller == null)
                continue;
            if (Intersector.overlaps(object.getCollisionBounds(), target.getCollisionBounds())) {
                CollisionData data = CollisionData.getPool().obtain();
                Rectangle self_bounds = object.getCollisionBounds();
                Rectangle target_bounds = target.getCollisionBounds();

                //create a quad for the collision
                float x = self_bounds.x > target_bounds.x ? self_bounds.x : target_bounds.x;                        //X
                float y = self_bounds.y > target_bounds.y ? self_bounds.y : target_bounds.y;                        //Y
                float w = self_bounds.x > target_bounds.x ? target_bounds.x + target_bounds.width - self_bounds.x   //WIDTH
                        : self_bounds.x + self_bounds.width - target_bounds.x;                                  
                float h = self_bounds.y > target_bounds.y ? target_bounds.y + target_bounds.height - self_bounds.y  //HEIGHT
                        : self_bounds.y + self_bounds.height - target_bounds.y;

                data.init(object, target, this, x, y, w, h);
                collisions.add(data);
            }
        }
    } else
        object.getState().log("tree is null.");

}
项目:GangsterSquirrel    文件:InteractiveMapTileObject.java   
/**
 * This method returns the properties of an object in a collision layer by checking the player rectangle and object rectangle for an intersection
 * @param layerIndex the index of the layer in which to search for objects
 * @return the collided object
 */
protected MapObject getCollidingMapObject(int layerIndex) {
    MapObjects mapObjects = map.getLayers().get(layerIndex).getObjects();

    for (MapObject mapObject : mapObjects) {
        MapProperties mapProperties = mapObject.getProperties();

        float width, height, x, y;
        Rectangle objectRectangle = new Rectangle();
        Rectangle playerRectangle = new Rectangle();

        if (mapProperties.containsKey("width") && mapProperties.containsKey("height") && mapProperties.containsKey("x") && mapProperties.containsKey("y")) {
            width = (float) mapProperties.get("width");
            height = (float) mapProperties.get("height");
            x = (float) mapProperties.get("x");
            y = (float) mapProperties.get("y");
            objectRectangle.set(x, y, width, height);
        }

        playerRectangle.set(
                playScreen.getPlayer().getX() * MainGameClass.PPM,
                playScreen.getPlayer().getY() * MainGameClass.PPM,
                playScreen.getPlayer().getWidth() * MainGameClass.PPM,
                playScreen.getPlayer().getHeight() * MainGameClass.PPM
        );

        // If the player rectangle and the object rectangle is colliding, return the object
        if (Intersector.overlaps(objectRectangle, playerRectangle)) {
            return mapObject;
        }
    }

    // If no colliding object was found in that layer
    return null;
}
项目:cykacommander    文件:GameBasic.java   
boolean hitbox(Circle eggLeft, Circle eggRight, Rectangle... rects) {
    return  Intersector.overlaps(eggLeft, rects[0]) ||
            Intersector.overlaps(eggRight, rects[1]) ||
            Intersector.overlaps(rects[2], rects[0]) ||
            Intersector.overlaps(rects[2], rects[1]) ||
            Intersector.overlaps(rects[3], rects[0]) ||
            Intersector.overlaps(rects[3], rects[1]);
    //rects[0] = frontPipe, rects[1] = backPipe, rects[2] = engines, rects[3] = body
}
项目:Argent    文件:LandscapeWorldActor.java   
public LandscapeCell rayIntesects(Ray ray, Vector3 intersection) {
    List<Vector3> triangleList = new ArrayList<>();
    packedCells().forEach(c -> triangleList.addAll(c.trianglePoints()));
    if(Intersector.intersectRayTriangles(ray, triangleList, intersection)) {
        for (LandscapeCell cell : packedCells) {
            if(cell.rayIntersects(ray)) return cell;
        }
    }
    return null;
}
项目:Argent    文件:PointLight.java   
public void testHit(Mesh mesh, Ray ray) {
    int numVertices = mesh.getNumVertices();
    float[] vertices = new float[numVertices];
    mesh.getVertices(vertices);

    int numIndices = mesh.getNumIndices();
    short[] indices = new short[numIndices];
    mesh.getIndices(indices);

    Vector3 intersection = new Vector3();
    if (Intersector.intersectRayTriangles(ray, vertices, indices, mesh.getVertexSize(), intersection))
        hit(ray, intersection);
}
项目:Fruit-Destroyer    文件:CollisionHandler.java   
public void update(Application APP, Player player, Music gameMusic, float delta)
{
    for (int i = 0; i < currentEnemies.size; i++)
    {
        bulletLoop:
        for (int j = 0; j < currentBullets.size; j++)
        {
            // IF ENEMY COLLIDES WITH BULLET
            if (Intersector.overlapConvexPolygons(currentEnemies.get(i).getBounds(), currentBullets.get(j).getBounds()))
            {
                // DAMAGE THE ENEMY
                currentEnemies.get(i).renderHit = true;
                currentEnemies.get(i).playSquishSound();
                currentEnemies.get(i).setHitTexture();
                currentEnemies.get(i).reduceHealth(Bullet.getWeapon().getDamage());

                // KNOCKBACK ENEMY
                currentEnemies.get(i).knockback(Bullet.getWeapon().getKnockbackPower());
                currentEnemies.get(i).applyVelocityToPosition(delta);

                // REMOVE THE HIT BULLET
                currentBullets.get(j).isUsed = false;
                currentBullets.get(j).isOutOfScreen = false;
                currentBullets.removeIndex(j);
                break bulletLoop;
            }
        }

        // IF ENEMY COLLIDES WITH PLAYER
        if (Intersector.overlapConvexPolygons(currentEnemies.get(i).getBounds(), player.getBounds()))
        {
            Input.touchDown = false;
            APP.setScreen(deadScreen);
            gameMusic.stop();
        }
    }
}
项目:spacegame    文件:GameObject.java   
public boolean isOverlapingWith(GameObject g) {
    boolean result = false;

    float distance = Vector2.dst(this.getCenter().x, this.getCenter().y, g.getCenter().x, g.getCenter().y);
    float totalRadios = this.getRadio() + g.getRadio();

    //Solo se comprueba la colisión si la distancia entre los centros es menor a la suma de los radios
    if (distance < totalRadios)
        result = Intersector.overlapConvexPolygons(this.getLogicShape(), g.getLogicShape());

    return result;
}
项目:ChessGDX    文件:ObjectPicker.java   
/**
 * Checks for a intersections between chess piece bounding boxes and the
 * pick ray. Stores the ones that intersect in a list.
 * 
 * @param pieceGridPairs
 *            list of grid locations
 * @param ray
 *            a ray from the camera position to the destination of the mouse
 *            click
 */
private void fillIntersectedBoxList(Array<GridLocation> pieceGridPairs, Ray ray) {

    for (GridLocation pair : pieceGridPairs) {
        if (pair.chessPiece != null) {
            if (Intersector.intersectRayBoundsFast(ray, pair.chessPiece.getBoundingBox())) {
                mIntersectedBoxList.add(pair);
            }
        }
    }
}
项目:Mario-Libgdx    文件:CastleFirebar.java   
@Override
public boolean overlaps(AbstractSprite sprite) {

    Polygon spritePolygon = new Polygon(new float[]{sprite.getBounds().getX(), sprite.getBounds().getY(),
            sprite.getBounds().getX(), sprite.getBounds().getY() + sprite.getBounds().getHeight(),
            sprite.getBounds().getX()+ sprite.getBounds().getWidth(), sprite.getBounds().getY() + sprite.getBounds().getHeight(),
            sprite.getBounds().getX()+ sprite.getBounds().getWidth(), sprite.getBounds().getY()});

    return Intersector.overlapConvexPolygons(spritePolygon, polygon);               
}
项目:libgdx-inGameConsole    文件:Box2DTest.java   
/** Creates an explosion that applies forces to the bodies relative to their position and the given x and y values.
 *
 * @param maxForce The maximum force to be applied to the bodies (diminishes as distance from touch increases). */
private void createExplosion (float x, float y, float maxForce) {
    float force;
    Vector2 touch = new Vector2(x, y);
    for (int i = 0; i < bodies.length; i++) {
        Body b = bodies[i];
        Vector2 v = b.getPosition();
        float dist = v.dst2(touch);

        if (dist == 0)
            force = maxForce;
        else
            force = MathUtils.clamp(maxForce / dist, 0, maxForce);

        float angle = v.cpy().sub(touch).angle();
        float xForce = force * MathUtils.cosDeg(angle);
        float yForce = force * MathUtils.sinDeg(angle);

        Vector3 touch3, v3, boundMin, boundMax, intersection;
        touch3 = new Vector3(touch.x, touch.y, 0);
        v3 = new Vector3(v.x, v.y, 0);
        boundMin = new Vector3(v.x - 1, v.y - 1, 0);
        boundMax = new Vector3(v.x + 1, v.y + 1, 0);
        intersection = Vector3.Zero;

        Intersector.intersectRayBounds(new Ray(touch3, v3), new BoundingBox(boundMin, boundMax), intersection);

        b.applyForce(new Vector2(xForce, yForce), new Vector2(intersection.x, intersection.y), true);
    }
}
项目:GdxDemo3D    文件:GameEngine.java   
@Override
public float addSingleResult(LocalRayResult rayResult, boolean normalInWorldSpace) {
    float hitFraction = rayResult.getHitFraction();
    btCollisionObject hitObj = rayResult.getCollisionObject();
    Entity entity = getEntity(hitObj.getUserPointer());

    if (entity instanceof GameModel) {
        GameModel model = (GameModel) entity;
        if (hitFraction < this.hitFraction && (layers == null || model.visibleOnLayers.intersects(layers))) {
            this.hitFraction = hitFraction;
            super.addSingleResult(rayResult, normalInWorldSpace);
            return hitFraction;
        }

    } else if (entity.getId() == scene.navmeshBody.getId()) {
        Triangle triangle = scene.navMesh.rayTest(ray, rayDistance, layers);
        if (triangle == null) {
            // Triangle is not on allowed layer
            return 1;
        }
        Intersector.intersectRayTriangle(ray, triangle.a, triangle.b, triangle.c, tmp);
        hitFraction = rayFrom.dst(tmp) / rayFrom.dst(rayTo);
        if (hitFraction < this.hitFraction) {
            this.hitFraction = hitFraction;
            rayResult.setHitFraction(hitFraction);
            super.addSingleResult(rayResult, normalInWorldSpace);
            return hitFraction;
        }
    }
    return 1;
}
项目:GdxDemo3D    文件:NavMesh.java   
/**
 * Calculate a triangle graph path between two triangles which are intersected by the rays.
 *
 * @param fromRay
 * @param toRay
 * @param allowedMeshParts
 * @param distance
 * @param path
 * @return
 */
public boolean getPath(Ray fromRay, Ray toRay, Bits allowedMeshParts,
                       float distance, NavMeshGraphPath path) {

    Triangle fromTri = rayTest(fromRay, distance, allowedMeshParts);
    if (fromTri == null) {
        Gdx.app.debug(TAG, "From triangle not found.");
        return false;
    }
    Vector3 fromPoint = new Vector3();
    Intersector.intersectRayTriangle(fromRay, fromTri.a, fromTri.b, fromTri.c, fromPoint);

    return getPath(fromTri, fromPoint, toRay, allowedMeshParts, distance, path);
}
项目:GdxDemo3D    文件:NavMesh.java   
/**
 * Calculate a triangle graph path from a start triangle to the triangle which is intersected by a ray.
 *
 * @param fromTri
 * @param fromPoint
 * @param toRay
 * @param allowedMeshParts
 * @param distance
 * @param path
 * @return
 */
public boolean getPath(Triangle fromTri, Vector3 fromPoint, Ray toRay, Bits allowedMeshParts,
                       float distance, NavMeshGraphPath path) {
    Triangle toTri = rayTest(toRay, distance, allowedMeshParts);
    if (toTri == null) {
        Gdx.app.debug(TAG, "To triangle not found.");
        return false;
    }
    Vector3 toPoint = new Vector3();
    Intersector.intersectRayTriangle(toRay, toTri.a, toTri.b, toTri.c, toPoint);

    return getPath(fromTri, fromPoint, toTri, toPoint, path);
}
项目:lets-code-game    文件:FieldActor.java   
@Override
public Actor hit(float x, float y, boolean touchable) {
    if (super.hit(x, y, touchable) != null) {
        tmpPos.set(x, y);
        if (Intersector.isPointInTriangle(tmpPos, leftPoint, centerPoint, rightPoint)) 
            return this;
    }
    return null;
}
项目:SpaceProject    文件:TestVoronoiScreen.java   
private void drawIntersectingLines(DelaunayCell cell, Vector2 mid, Vector2 edgeA, Vector2 edgeB) {
    Vector2 intersect = new Vector2();
    if (Intersector.intersectSegments(edgeA, edgeB, cell.circumcenter, mid, intersect)) {
        shape.setColor(Color.GREEN);
        shape.line(mid, intersect);
        shape.circle(intersect.x, intersect.y, 3);
    }
}
项目:killingspree    文件:WorldBodyUtils.java   
public void destroyEntities(ServerBomb bomb, float radius, Vector2 position) {
    Body body = bomb.body;
    circle.set(position, radius);
    for (ServerEntity entity: worldManager.entities) {
        if (entity.body == body || entity.body.toDestroy) {
            continue;
        }
        if (Intersector.overlaps(circle, entity.body.rectangle)) {
            Vector2 step = entity.body.getPosition();
            float length = position.dst(step);
            step.sub(position);
            float max = Math.max(step.x, step.y);
            step.scl(4 / max);
            Body otherBody = Ray.findBody(world,
                    body, step, length, true);
            if (otherBody == null) {
                if (entity instanceof LivingCategory) {
                    if (((LivingCategory)entity.body.getUserData()).kill()) {
                        if (bomb.bomber != entity.body.getUserData())
                            bomb.bomber.addKill();
                        else {
                            bomb.bomber.reduceKill();
                        }
                    }
                }
            }
        }
    }
}
项目:ZombieCopter    文件:DebugRenderer.java   
private void renderSpawnZones(){
    GameEngine engine = App.engine;
    Systems systems = engine.systems;
    float units = engine.PIXELS_PER_METER;

    spawnRect.set(engine.entityBounds);
    camRect.set(systems.camera.getCameraRect(units));
    camRect.width /= systems.camera.getCamera().zoom;
    camRect.height /= systems.camera.getCamera().zoom;

    sr.setProjectionMatrix(scaledProjection);
    sr.begin(ShapeType.Line);

    //draw camera view rectangle (independent of camera zoom so you can zoom out and see it)
    sr.setColor(cameraViewColor);
    sr.rect(camRect.x,camRect.y,camRect.width,camRect.height);

    //draw the Entity boundary / spawnable area
    sr.setColor(entityBoundaryColor);
    sr.rect(spawnRect.x,spawnRect.y,spawnRect.width,spawnRect.height);

    //Spawn zones
    for (SpawnZone z : systems.spawn.getZones()){
        sr.setColor(spawnZoneColor);
        sr.rect(tmpRect.x,tmpRect.y,tmpRect.width,tmpRect.height);
        tmpRect.set(z.rectangle);

        //Draw the legal spawn area             
        if (Intersector.intersectRectangles(z.rectangle,spawnRect,tmpRect)){
            if (camRect.overlaps(tmpRect)) sr.setColor(spawnZoneIllegalColor);
            else sr.setColor(spawnZoneLegalColor);
            sr.rect(tmpRect.x,tmpRect.y,tmpRect.width,tmpRect.height);
        }
    }   

    sr.end();
}
项目:ZombieCopter    文件:SpawnSystem.java   
@Override
public void update(float deltaTime) {
    if (App.engine.getEntityCount() > maxEntities) return;


    camRect = App.engine.systems.camera.getCameraRect(1/units);
    boundsRect.setCenter(camRect.getCenter(cameraCenter));

    for (SpawnZone z : points){
        z.time += deltaTime;

        //Spawn new entity
        if (z.time > z.delay && z.count < z.maximum){
            boolean withinBounds = Intersector.intersectRectangles(z.rectangle,boundsRect,tmpRect);
            boolean outsideCamera = !camRect.overlaps(z.rectangle);
            z.time = 0;

            if (withinBounds && outsideCamera){
                z.count++;
                spawnPoint.x = MathUtils.random(tmpRect.x,tmpRect.x+tmpRect.width);
                spawnPoint.y = MathUtils.random(tmpRect.y,tmpRect.y+tmpRect.height);
                App.engine.factory.build(z.type,spawnPoint);
            }
        }

        //Retire spawn point if it has reached max spawn count
        if (z.maximum > 0 && z.count > z.maximum){
            deadPoints.add(z);
        }
    }

    //Remove the retired spawn points
    for (SpawnZone p : deadPoints){
        points.removeValue(p, true);
    }
    deadPoints.clear();
}