Example usage for com.badlogic.gdx.physics.box2d RayCastCallback RayCastCallback

List of usage examples for com.badlogic.gdx.physics.box2d RayCastCallback RayCastCallback

Introduction

In this page you can find the example usage for com.badlogic.gdx.physics.box2d RayCastCallback RayCastCallback.

Prototype

RayCastCallback

Source Link

Usage

From source file:com.tnf.ptm.entities.planet.PlanetObjectsBuilder.java

License:Apache License

private void addDeco0(PtmGame game, float groundHeight, Vector2 planetPos, Map<Vector2, List<Dra>> collector,
        DecoConfig dc) {/*w  ww. j  a v  a  2s  . c o m*/
    World w = game.getObjMan().getWorld();
    ConsumedAngles consumed = new ConsumedAngles();

    final Vector2 rayCasted = new Vector2();
    RayCastCallback rcc = new RayCastCallback() {
        @Override
        public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) {
            if (!(fixture.getBody().getUserData() instanceof TileObject)) {
                return -1;
            }
            rayCasted.set(point);
            return fraction;
        }
    };

    int decoCount = (int) (2 * PtmMath.PI * groundHeight * dc.density);
    for (int i = 0; i < decoCount; i++) {
        float decoSz = PtmMath.rnd(dc.szMin, dc.szMax);
        float angularHalfWidth = PtmMath.angularWidthOfSphere(decoSz / 2, groundHeight);

        float decoAngle = 0;
        for (int j = 0; j < 5; j++) {
            decoAngle = PtmMath.rnd(180);
            if (!consumed.isConsumed(decoAngle, angularHalfWidth)) {
                consumed.add(decoAngle, angularHalfWidth);
                break;
            }
        }

        PtmMath.fromAl(rayCasted, decoAngle, groundHeight, true);
        rayCasted.add(planetPos);
        w.rayCast(rcc, rayCasted, planetPos);
        float decoDist = rayCasted.dst(planetPos);

        float baseAngle = PtmMath.windowCenter(decoAngle, DECO_PACK_ANGULAR_WIDTH);
        float baseDist = PtmMath.windowCenter(decoDist, DECO_PACK_SZ);
        Vector2 basePos = PtmMath.fromAl(baseAngle, baseDist).add(planetPos);
        Vector2 decoRelPos = new Vector2(rayCasted).sub(basePos);
        PtmMath.rotate(decoRelPos, -baseAngle - 90, true);
        float decoRelAngle = decoAngle - baseAngle;

        TextureAtlas.AtlasRegion decoTex = PtmMath.elemRnd(dc.texs);
        if (dc.allowFlip && PtmMath.test(.5f)) {
            decoTex = game.getTexMan().getFlipped(decoTex);
        }

        RectSprite s = new RectSprite(decoTex, decoSz, dc.orig.x, dc.orig.y, decoRelPos, DraLevel.DECO,
                decoRelAngle, 0, PtmColor.WHITE, false);
        List<Dra> ss = collector.get(basePos);
        if (ss == null) {
            ss = new ArrayList<Dra>();
            collector.put(new Vector2(basePos), ss);
        }
        ss.add(s);
        PtmMath.free(basePos);
    }
}

From source file:headmade.arttag.Guard.java

License:Apache License

public void update(ArtTagScreen artTag, float delta) {
    if (body == null) {
        return;//from www  .j a v  a2  s . c  om
    }
    isRunning = isAlert || isCautious;
    moveSpeed = isRunning ? maxMoveSpeed * runFactor
            : isSuspicious ? maxMoveSpeed * 0.75f : isHeardPlayer ? 0.5f : maxMoveSpeed;
    final Vector2 oldMoveVec = targetMoveVec.cpy();

    Vector2 targetPoint = null;
    Float distanceToPlayer = null;
    if (isLightOn) {
        for (final Fixture fixture : playerInView) {
            targetPoint = fixture.getBody().getWorldCenter().cpy();
            final Vector2 diffVec = body.getWorldCenter().cpy().sub(targetPoint);
            boolean seesPlayer = false;
            distanceToPlayer = diffVec.len();
            if (distanceToPlayer < 1f) {
                seesPlayer = true;
            } else {
                final Vector2 outOfBodyVec = diffVec.scl(fixture.getShape().getRadius() * 1.01f);
                targetPoint.add(outOfBodyVec);
                seesPlayer = light.contains(targetPoint.x, targetPoint.y);
            }
            // Gdx.app.log(TAG, light.contains(targetPoint.x, targetPoint.y) + " diffVec.length " + diffVec.len());
            if (seesPlayer) {
                // Gdx.app.log(TAG, "Guard sees player");
                playerLastSeenVec = fixture.getBody().getWorldCenter().cpy();
                if (!isAlert) {
                    Assets.instance.playSound(AssetSounds.whosThere);
                }
                isAlert = true;
                Player.instance.isSpotted = true;
                reactionTime = 0f;
            } else {
                if (isAlert) {
                    Assets.instance.playSound(AssetSounds.huh);
                    reactionTime = MAX_REACTION_TIME;
                    isCautious = true;
                }
                isAlert = false;
            }
        }
    }

    // handle hearing
    if (Player.instance.isRunning && (Player.instance.isMoveDown || Player.instance.isMoveUp
            || Player.instance.isMoveLeft || Player.instance.isMoveRight) && null != Player.instance.body) {
        if (distanceToPlayer == null) {
            distanceToPlayer = body.getWorldCenter().cpy().sub(Player.instance.body.getWorldCenter()).len();
        }
        if (distanceToPlayer < MAX_LIGHT_CONE_LENGTH * 0.9f) {
            sumDeltaSinceHeardPlayer = 0;

            final RayCastCallback callback = new RayCastCallback() {
                @Override
                public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) {
                    // Gdx.app.log(TAG, "reportRayFixture " + point + " normal " + normal);
                    if (fixture.isSensor()) {
                        // Gdx.app.log(TAG, "Raycast ignoring sensor");
                        return 1;
                    }
                    if (body.equals(fixture.getBody())) {
                        // this is the guards body so there is nothing inbetween them
                        // Gdx.app.log(TAG, "Guard CAN see the point where the noise happened" + Player.instance.body.getWorldCenter());
                        // playerLastHeardVisibleVec = Player.instance.body.getWorldCenter().cpy();
                        return 1;
                    }
                    // Gdx.app.log(TAG, "Fall through");
                    isHearingObstructed = true;
                    return 0;
                }
            };
            try {
                isSuspicious = true;
                playerLastHeardVec = Player.instance.body.getWorldCenter().cpy();
                isHearingObstructed = false;
                // Gdx.app.log(TAG, "###################################");
                // Gdx.app.log(TAG, "Guard " + body.getWorldCenter());
                // Gdx.app.log(TAG, "Player " + playerLastHeardVec);
                artTag.world.rayCast(callback, playerLastHeardVec, body.getWorldCenter());
                if (!isHearingObstructed) {
                    playerLastHeardVisibleVec = Player.instance.body.getWorldCenter().cpy();
                }
            } catch (final Exception e) {
                Gdx.app.error(TAG, "Error Raycasting :(", e);
            }
        } else {
            sumDeltaSinceHeardPlayer += delta;
        }
    } else {
        sumDeltaSinceHeardPlayer += delta;
    }
    isHeardPlayer = playerLastHeardVisibleVec != null || sumDeltaSinceHeardPlayer < 3;

    if (isTouchingPlayerLightCone && Player.instance.isLightOn) {
        // isAlert = true;
    }

    // handle backToPath
    if (isAlert || isCautious || (isSuspicious && playerLastHeardVisibleVec != null)) {
        if (lastVisibleVecBackToPath == null) {
            lastVisibleVecBackToPath = body.getWorldCenter();
        }

        Vector2 checkPoint = path.get(currentPathIndex);
        if (backToPath.size > 0) {
            checkPoint = backToPath.get(backToPath.size - 1);
        }
        if (BODY_RADIUS < checkPoint.dst(body.getWorldCenter())) {
            // not touching checkpoint
            // Gdx.app.log(TAG, "Goard not touching checkpoint");
            final RayCastCallback callback = new RayCastCallback() {
                @Override
                public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) {
                    // Gdx.app.log(TAG, "reportRayFixture adds new backToPathPoint" + lastVisibleVecBackToPath);
                    backToPath.add(lastVisibleVecBackToPath.cpy());
                    return 0;
                }
            };
            try {
                artTag.world.rayCast(callback, body.getWorldCenter(), checkPoint);
            } catch (final Exception e) {
                Gdx.app.error(TAG, "Error Raycasting :(", e);
            }
        }
        lastVisibleVecBackToPath = body.getWorldCenter();
    }

    // determine targetPoint
    if (isAlert && playerInView.size > 0 && Player.instance.body != null) {
        targetPoint = Player.instance.body.getWorldCenter();
    } else if (isCautious && playerLastSeenVec != null) {
        targetPoint = playerLastSeenVec;
        if (BODY_RADIUS / 10 > targetPoint.dst2(body.getPosition())) {
            // Lost player
            Assets.instance.playSound(AssetSounds.hm);
            Gdx.app.log(TAG, "Guard no longer cautious");
            isCautious = false;
            isSuspicious = true;
        }
    } else if (isSuspicious && playerLastHeardVisibleVec != null) {
        targetPoint = playerLastHeardVisibleVec;
        // Gdx.app.log(TAG, "Guard going to playerLastHeardVisibleVec");
        if (BODY_RADIUS / 10 > targetPoint.dst2(body.getPosition())) {
            // Lost player
            Assets.instance.playSound(AssetSounds.hm);
            Gdx.app.log(TAG, "Guard no longer suspicious");
            isSuspicious = false;
            playerLastHeardVisibleVec = null;
        }
    } else {
        lastVisibleVecBackToPath = null;
        if (backToPath.size > 0) {
            // following Path back to path
            targetPoint = backToPath.get(backToPath.size - 1);
            if (BODY_RADIUS / 10 > targetPoint.dst(body.getPosition())) {
                // Gdx.app.log(TAG, "Guard reached target back to path point " + targetPoint);
                backToPath.pop();
            }
        } else {
            // following path
            isSuspicious = false;
            targetPoint = path.get(currentPathIndex);
            if (BODY_RADIUS > targetPoint.dst(body.getPosition())) {
                // Gdx.app.log(TAG, "Guard reached target point " + targetPoint);
                currentPathIndex++;
                if (currentPathIndex >= path.size) {
                    currentPathIndex = 0;
                }
                targetPoint = path.get(currentPathIndex);
                // Gdx.app.log(TAG, "New target point " + targetPoint);
            }
        }

    }

    targetMoveVec = targetPoint.cpy().sub(body.getPosition());
    targetMoveVec.nor().scl(moveSpeed);

    if (MathUtils.isEqual(0f, oldMoveVec.angle(targetMoveVec))) {
        sumDeltaSinceMoveChange += delta;
    } else {
        // movment direction changed
        sumDeltaSinceMoveChange = 0f;
    }

    final float alpha = reactionTime > 0 ? MathUtils.clamp(sumDeltaSinceMoveChange / reactionTime, 0.1f, 1f)
            : 1f;
    body.setLinearVelocity(targetMoveVec);

    final Vector2 bodyRotVec = new Vector2(1f, 0f);
    bodyRotVec.setAngleRad(body.getAngle());
    float angleDiff;
    if (!isAlert && !isSuspicious && isHeardPlayer && null == playerLastHeardVisibleVec
            && null != playerLastHeardVec) {
        // look at last heard
        angleDiff = bodyRotVec.angleRad(playerLastHeardVec.cpy().sub(body.getWorldCenter()).rotate90(-1));
    } else {
        angleDiff = bodyRotVec.angleRad(targetMoveVec.cpy().rotate90(-1));
    }
    final float rotByRad = MathUtils.clamp(angleDiff, -(MAX_ROTATION_SPEED * delta) / reactionTime,
            MAX_ROTATION_SPEED * delta / reactionTime);
    // Gdx.app.log(TAG, "angleDiff: " + angleDiff + " rotByRad: " + rotByRad + " bodyRotVec: " + bodyRotVec + " - targetMoveVec:
    // "
    // + targetMoveVec);

    // is moving?
    if (!MathUtils.isEqual(targetMoveVec.len2(), 0f)) {
        if (Player.instance.body != null) {
            final float dist = body.getPosition().dst(Player.instance.body.getPosition());
            float volume = isRunning ? STEP_VOLUME * 2 : STEP_VOLUME;
            if (dist > 1) {
                volume = volume / dist;
            }
            sound.setVolume(stepSoundId, volume);
            sound.setPitch(stepSoundId, isRunning ? runFactor : 1f);
            body.setTransform(body.getPosition(), body.getAngle() + rotByRad);
        }
    } else {
        sound.setVolume(stepSoundId, 0f);
        sound.setPitch(stepSoundId, 1f);
    }

    light.setActive(isLightOn);
}

From source file:org.destinationsol.game.planet.PlanetObjectsBuilder.java

License:Apache License

private void addDeco0(SolGame game, float groundHeight, Vector2 planetPos, Map<Vector2, List<Dra>> collector,
        DecoConfig dc) {//from  w w  w  .j  av  a2 s.com
    World w = game.getObjMan().getWorld();
    ConsumedAngles consumed = new ConsumedAngles();

    final Vector2 rayCasted = new Vector2();
    RayCastCallback rcc = new RayCastCallback() {
        @Override
        public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) {
            if (!(fixture.getBody().getUserData() instanceof TileObject)) {
                return -1;
            }
            rayCasted.set(point);
            return fraction;
        }
    };

    int decoCount = (int) (2 * SolMath.PI * groundHeight * dc.density);
    for (int i = 0; i < decoCount; i++) {
        float decoSz = SolMath.rnd(dc.szMin, dc.szMax);
        float angularHalfWidth = SolMath.angularWidthOfSphere(decoSz / 2, groundHeight);

        float decoAngle = 0;
        for (int j = 0; j < 5; j++) {
            decoAngle = SolMath.rnd(180);
            if (!consumed.isConsumed(decoAngle, angularHalfWidth)) {
                consumed.add(decoAngle, angularHalfWidth);
                break;
            }
        }

        SolMath.fromAl(rayCasted, decoAngle, groundHeight, true);
        rayCasted.add(planetPos);
        w.rayCast(rcc, rayCasted, planetPos);
        float decoDist = rayCasted.dst(planetPos);

        float baseAngle = SolMath.windowCenter(decoAngle, DECO_PACK_ANGULAR_WIDTH);
        float baseDist = SolMath.windowCenter(decoDist, DECO_PACK_SZ);
        Vector2 basePos = SolMath.fromAl(baseAngle, baseDist).add(planetPos);
        Vector2 decoRelPos = new Vector2(rayCasted).sub(basePos);
        SolMath.rotate(decoRelPos, -baseAngle - 90, true);
        float decoRelAngle = decoAngle - baseAngle;

        TextureAtlas.AtlasRegion decoTex = SolMath.elemRnd(dc.texs);
        if (dc.allowFlip && SolMath.test(.5f))
            decoTex = game.getTexMan().getFlipped(decoTex);

        RectSprite s = new RectSprite(decoTex, decoSz, dc.orig.x, dc.orig.y, decoRelPos, DraLevel.DECO,
                decoRelAngle, 0, SolColor.W, false);
        List<Dra> ss = collector.get(basePos);
        if (ss == null) {
            ss = new ArrayList<Dra>();
            collector.put(new Vector2(basePos), ss);
        }
        ss.add(s);
        SolMath.free(basePos);
    }
}