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

项目:ExamensArbeteTD    文件:ShootingSystem.java   
public void setTurretAngle(Entity tower){
    AngleComponent angle = Mappers.ANGLE_M.get(tower);
    PositionComponent towerPos = Mappers.POSITION_M.get(tower);
    TargetComponent target = Mappers.TARGET_M.get(tower);

    if (target.getTarget() != null) {
        PositionComponent targetPos = Mappers.POSITION_M.get(target.getTarget());
        if(targetPos == null) return;
        double difX = targetPos.position.x - towerPos.position.x;
        double difY = targetPos.position.y - towerPos.position.y;
        // set direction
        float angleGoal = (float) Math.toDegrees(Math.atan2(difY, difX));
        angle.spriteAngle = MathUtils.lerpAngleDeg(angle.spriteAngle, angleGoal,
                Gdx.graphics.getDeltaTime() + 0.2f);
    }
}
项目:cocos2d-java    文件:BaseRandTimer.java   
@Override
    public boolean updateTimer(){
        if(!running){
            return false;
        }
        final long currentTime = BaseTimer.getEngineTime();
        if(currentTime > nextTime){
//          nextInterval();
            //�������
            long interval = MathUtils.random(start, end);
//          currentiInterval = MathUtils.random(intervals.length - 1);
            nextTime = currentTime + interval; // + intervals[currentiInterval];
            return true;
        }
        return false;
    }
项目:KyperBox    文件:ScrollingBackground.java   
@Override
public void draw(Batch batch, float parentAlpha) {
    if (background != null) {
        // draw background
        if (size > 1) {
            for (int i = 0; i < size; i++) {
                y = (i % (size / 3)) + yoff;
                x = (i / (size / 3)) + xoff;
                x_check = pos_x + (getWidth() * x);
                y_check = pos_y + (getHeight() * y);
                batch.draw(background, MathUtils.floor(getX() + x_check),MathUtils.floor( getY() + y_check), getWidth(), getHeight());
            }
        } else {
            batch.draw(background, MathUtils.floor(getX() + pos_x), MathUtils.floor(getY() + pos_y), getWidth(), getHeight());
        }

    }
    super.draw(batch, parentAlpha);
}
项目:Mindustry    文件:RepairTurret.java   
@Override
public void drawLayer2(Tile tile){
    PowerTurretEntity entity = tile.entity();

    if(entity.power >= powerUsed && entity.blockTarget != null && Angles.angleDist(entity.angleTo(entity.blockTarget), entity.rotation) < 10){
        Tile targetTile = entity.blockTarget.tile;
        Vector2 offset = targetTile.block().getPlaceOffset();
        Angles.translation(entity.rotation, 4f);
        float x = tile.worldx() + Angles.x(), y = tile.worldy() + Angles.y();
        float x2 = entity.blockTarget.x + offset.x, y2 = entity.blockTarget.y + offset.y;

        Draw.color(Hue.rgb(138, 244, 138, (MathUtils.sin(Timers.time()) + 1f) / 14f));
        Draw.alpha(0.3f);
        Draw.thickness(4f);
        Draw.line(x, y, x2, y2);
        Draw.thickness(2f);
        Draw.rect("circle", x2, y2, 7f, 7f);
        Draw.alpha(1f);
        Draw.thickness(2f);
        Draw.line(x, y, x2, y2);
        Draw.thickness(1f);
        Draw.rect("circle", x2, y2, 5f, 5f);
        Draw.reset();
    }
}
项目:school-game    文件:Player.java   
/**
 * Setzt die Anzahl der Lebenspunkte direkt.
 * Sollte so ehr selten benutzt werden.
 *
 * @see Player#applyDamage(int)
 * @see Player#heal(int)
 *
 * @param health die neue Anzahl Lebenspunkte
 */
public void setHealth(int health) {
    if (health > 100)
        health = 100;

    if (health < 0 || MathUtils.isZero(health))
    {
        if (cheatManager.isImmortal())
        {
            this.health = 100;
            return;
        }

        health = 0;
        if (deadCallback != null)
            deadCallback.run();
    }

    this.health = health;
}
项目:Klooni1010    文件:BaseScorer.java   
public void draw(SpriteBatch batch) {
    // If we beat a new record, the cup color will linear interpolate to the high score color
    cupColor.lerp(isNewRecord() ? Klooni.theme.highScore : Klooni.theme.currentScore, 0.05f);
    batch.setColor(cupColor);
    batch.draw(cupTexture, cupArea.x, cupArea.y, cupArea.width, cupArea.height);

    int roundShown = MathUtils.round(shownScore);
    if (roundShown != currentScore) {
        shownScore = Interpolation.linear.apply(shownScore, currentScore, 0.1f);
        currentScoreLabel.setText(Integer.toString(MathUtils.round(shownScore)));
    }

    currentScoreLabel.setColor(Klooni.theme.currentScore);
    currentScoreLabel.draw(batch, 1f);

    highScoreLabel.setColor(Klooni.theme.highScore);
    highScoreLabel.draw(batch, 1f);
}
项目:NanoUI    文件:ObjectSet.java   
/** Creates a new set with the specified initial capacity and load factor. This set will hold initialCapacity items before
 * growing the backing table.
 * @param initialCapacity If not a power of two, it is increased to the next nearest power of two. */
public ObjectSet (int initialCapacity, float loadFactor) {
    if (initialCapacity < 0) throw new IllegalArgumentException("initialCapacity must be >= 0: " + initialCapacity);
    initialCapacity = MathUtils.nextPowerOfTwo((int)Math.ceil(initialCapacity / loadFactor));
    if (initialCapacity > 1 << 30) throw new IllegalArgumentException("initialCapacity is too large: " + initialCapacity);
    capacity = initialCapacity;

    if (loadFactor <= 0) throw new IllegalArgumentException("loadFactor must be > 0: " + loadFactor);
    this.loadFactor = loadFactor;

    threshold = (int)(capacity * loadFactor);
    mask = capacity - 1;
    hashShift = 31 - Integer.numberOfTrailingZeros(capacity);
    stashCapacity = Math.max(3, (int)Math.ceil(Math.log(capacity)) * 2);
    pushIterations = Math.max(Math.min(capacity, 8), (int)Math.sqrt(capacity) / 8);

    keyTable = (T[])new Object[capacity + stashCapacity];
}
项目:odb-little-fortune-planet    文件:CardScriptSystem.java   
public E spawnStructure(String id, int layer) {
    Vector2 location = planetCreationSystem.getSpawnLocation();
    E e = E.E()
            .pos(location.x, location.y)
            .anim(id)
            .originX(0.5f)
            .originY(0.1f)
            .renderLayer(layer)
            .angle()
            .physics()
            .planetbound()
            .flammable()
            .tint(Tint.TRANSPARENT)
            .script(sequence(delay(MathUtils.random(0.1f, 0.4f)), add(new Mass(1.1f)), tween(Tint.TRANSPARENT, Tint.WHITE, 0.2f)))
            .orientToGravityIgnoreFloor(true);

    if (G.DEBUG_NO_ENTITY_RENDERING) {
        e.invisible();
    }

    return e;
}
项目:StarshipFighters    文件:CollisionHandling.java   
private void enemyBulletPlayerCollision() {
    // Check Collision for enemies hitting the player
    for (int i = 0; i < enemyBulletList.size; i++) {
        if (enemyBulletList.get(i).getBoundingBox().contains(player.getBoundingBox())
                || player.getBoundingBox().contains(enemyBulletList.get(i).getBoundingBox())) {
            // Play Explosion on Player
            explosionList.add(new Explosion((player.getX() + MathUtils.random(0, 32)),
                    player.getY() + MathUtils.random(0, 32), 0, 0, "data/hit_and_explosions/impactHit.png",
                    "data/audio/sound/Bomb Explosion.wav", "Player Hit", 3, 1, 3, 1, 1f / 40f, playState));

            // Reduce Player Health
            HealthBar tempHP = (HealthBar) playState.getHUD(0);
            tempHP.setHealthLeft(enemyBulletList.get(i).getDamageValue());

            // Remove Bullet
            enemyBulletList.get(i).dispose();
            enemyBulletList.get(i).removeBullets();
        }
    }
}
项目:bobbybird    文件:BirdEntity.java   
@Override
public void act(float delta) {
    if (getY() + getTextureRegion().getRegionHeight() > Gdx.graphics.getHeight()) {
        setY(Gdx.graphics.getHeight() - getTextureRegion().getRegionHeight());
        setYspeed(0.0f);
    }

    if (getY() + getTextureRegion().getRegionHeight() < 0) {
        dispose();
    }

    if (flying) {
        float percent = (getYspeed() + 1000) / 800;
        percent = MathUtils.clamp(percent, 0.0f, 1.0f);
        setRotation(120.0f * percent - 90.0f);
    } else {
        setRotation(0.0f);
    }
}
项目:conquest    文件:ConquestCamera.java   
public void handle() {
    if (Gdx.input.isKeyPressed(Input.Keys.W) || Gdx.input.isKeyPressed(Input.Keys.UP)) {
        translate(0, 10);
    }
    if (Gdx.input.isKeyPressed(Input.Keys.A) || Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
        translate(-10, 0);
    }
    if (Gdx.input.isKeyPressed(Input.Keys.S) || Gdx.input.isKeyPressed(Input.Keys.DOWN)) {
        translate(0, -10);
    }
    if (Gdx.input.isKeyPressed(Input.Keys.D) || Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
        translate(10, 0);
    }
    if (Gdx.input.isKeyPressed(Input.Keys.I)) {
        zoom -= 0.05;
    }
    if (Gdx.input.isKeyPressed(Input.Keys.O)) {
        zoom += 0.05;
    }

    zoom = MathUtils.clamp(zoom, 0.5f, 2);
    position.x = MathUtils.clamp(position.x, left, right);
    position.y = MathUtils.clamp(position.y, bottom, top);
}
项目:odb-little-fortune-planet    文件:PlanetMaskSystem.java   
private void smoothMask(Planet planet) {
    for (int y = 1; y < (SIMULATION_HEIGHT / GRADIENT_SCALE) - 1; y++) {
        if (G.INTERLACING_SIMULATION && y % 2 == lace) {
            for (int x = 1; x < (SIMULATION_WIDTH / GRADIENT_SCALE) - 1; x++) {
                planet.tempMask[y][x].temperature = planet.mask[y][x].temperature;
                for (int i = 0; i < 8; i++) {
                    planet.tempMask[y][x].temperature =
                            Math.max(
                                    (planet.mask[y + PlanetCell.directions[i][1]][x + PlanetCell.directions[i][0]].temperature) * TEMPERATURE_LOSS,
                                    planet.tempMask[y][x].temperature
                            );
                }
            }
        }
    }
    for (int y = 1; y < (SIMULATION_HEIGHT / GRADIENT_SCALE) - 1; y++) {
        for (int x = 1; x < (SIMULATION_WIDTH / GRADIENT_SCALE) - 1; x++) {
            planet.mask[y][x].temperature = MathUtils.clamp(planet.tempMask[y][x].temperature, -100f, StatusMask.MAX_TEMPERATURE) * 0.95f;
        }
    }
}
项目:Klooni1010    文件:VanishEffect.java   
@Override
public void draw(Batch batch) {
    vanishElapsed += Gdx.graphics.getDeltaTime();

    // vanishElapsed might be < 0 (delay), so clamp to 0
    float progress = Math.min(1f,
            Math.max(vanishElapsed, 0f) / vanishLifetime);

    // If one were to plot the elasticIn function, they would see that the slope increases
    // a lot towards the end- a linear interpolation between the last size + the desired
    // size at 20% seems to look a lot better.
    vanishSize = MathUtils.lerp(
            vanishSize,
            Interpolation.elasticIn.apply(cell.size, 0, progress),
            0.2f
    );

    float centerOffset = cell.size * 0.5f - vanishSize * 0.5f;
    Cell.draw(vanishColor, batch, cell.pos.x + centerOffset, cell.pos.y + centerOffset, vanishSize);
}
项目:TH902    文件:CircularDrawingStatic.java   
public void calcAnglePoint(int degrees, Vector2 out) {
    degrees = degrees % 360;
    degrees = degrees < 0 ? degrees + 360 : degrees;
    if (degrees >= 45 && degrees < 135) {
        out.y = 1f;
        out.x = out.y / (float) Math.tan(degrees * MathUtils.degreesToRadians);
    } else if (degrees >= 135 && degrees < 225) {
        out.x = -1f;
        out.y = out.x * (float) Math.tan(degrees * MathUtils.degreesToRadians);
    } else if (degrees >= 225 && degrees < 315) {
        out.y = -1f;
        out.x = out.y / (float) Math.tan(degrees * MathUtils.degreesToRadians);
    } else {
        out.x = 1f;
        out.y = out.x * (float) Math.tan(degrees * MathUtils.degreesToRadians);
    }
}
项目:TH902    文件:DanmakuS1L6.java   
@Override
public void Initialize(Entity entity) {
    Callable<Object> pause = () -> { return null; };
    yield.append(pause, 120);
    yield.append(() -> {
        for (int i=0; i<=1; i++) {
            Entity sprite = BaseSprite.Create(new Vector2(135 + i * 300, 730), i, 300 + i * 300);
            sprites[i] = sprite;
            final Transform tr = sprite.GetComponent(Transform.class);
            tr.scale.set(0.5f, 0.5f);
            sprite.AddComponent(new LambdaComponent(() -> {
                for (int angle=MathUtils.random(360), k=0; k<24; angle+=15, k++)
                    BaseProjectile.Create(tr.position.cpy(), BulletType.FormCircleLightM, BulletType.ColorYellow,
                            new EnemyJudgeCircle(13),
                            new MoveBasic(new Vector2(7.2f, 0).rotate(angle)));
            }, 40, 30));
            sprite.AddComponent(new MoveFunction(MoveFunctionTarget.VELOCITY, MoveFunctionType.ASSIGNMENT, (time) -> {
                return IMoveFunction.vct2_tmp1.set(0, time < 30 ? -8 : 0);
            }));
        }
    });
    yield.append(pause, 900);
}
项目:TH902    文件:AIS1LLastBoss.java   
public void part4() {
    if (flag4) {
        flag4 = false;
        existTime = 0;
        moveBasic.velocity.set(0, 0);
        moveBasic.acc.set(0, 0);
        Entity.postUpdate.add(() -> { GameHelper.clearEnemyBullets(); });
    }
    if (existTime > 60) {
        for (int i=0; i<2; i++)
        {
            final int c = MathUtils.random(3);
            final Entity proj = BaseProjectile.Create(transform.position.cpy(), BulletType.FormCircleS, color4s[c]);
            final ImageRenderer renderer = proj.GetComponent(ImageRenderer.class);
            proj.AddComponent(new EnemyJudgeCircle(5));
            proj.AddComponent(new LambdaComponent(() -> {
                renderer.image.setColor(1, 1, 1, alpha4s[c]);
            }, 5));
            proj.AddComponent(new MoveBasic(new Vector2(1, 0).rotate(MathUtils.random(360f)).scl(MathUtils.random(2f, 7f))));
        }
    }
    if (existTime % 20 == 0) {
        for (int i=0; i<4; i++)
            alpha4s[i] = MathUtils.randomBoolean() || alpha4s[i] < 0.4f ? 0.88f : 0.12f;
    }
}
项目:odb-little-fortune-planet    文件:MyCameraSystem.java   
@Override
protected void processSystem() {
    if (cooldown > 0 && !G.DEBUG_SKIP_INTRO) {
        if ( cooldown < 2f ) {
            starEffectSystem.active=false;
        }
        starEffectSystem.active = true;
        cooldown -= world.delta;
        if (cooldown < 0) cooldown = 0;
        camera.position.y = Interpolation.pow2In.apply(y, y + G.SCREEN_HEIGHT / 2, MathUtils.clamp(cooldown / VISIBLE_FOCUS_COOLDOWN,0f,1f));
        camera.update();
    } else  {
        if ( !introDone ) {
            introDone=true;
            gameScreenAssetSystem.playMusicInGame();
        }
        starEffectSystem.active = false;
    }
    super.processSystem();
}
项目:cocos2d-java    文件:AffineTransform.java   
/**
* //use degress
Rotation, equals
cos(angle)   sin(angle)   0
-sin(angle)  cos(angle)   0  * AffineTransform
0            0            1
*/
public static final AffineTransform AffineTransformRotate(final AffineTransform t, float anAngle, AffineTransform out) {
 float sine = MathUtils.sinDeg(anAngle);
   float cosine = MathUtils.cosDeg(anAngle);

   return AffineTransformMakeOut(t.a * cosine + t.c * sine,
                                   t.b * cosine + t.d * sine,
                                   t.c * cosine - t.a * sine,
                                   t.d * cosine - t.b * sine,
                                   t.tx,
                                   t.ty, out);
}
项目:cocos2d-java    文件:BaseRandTimer.java   
@Override
    /**ʹnextTimeָ����ȷ��ʱ�� */
    public final void updateNextTime() {
        long interval = MathUtils.random(start, end);
        nextTime = BaseTimer.getEngineTime() + interval; // + intervals[currentiInterval];      
//      nextTime = System.currentTimeMillis() + intervals[currentiInterval];
    }
项目:cocos2d-java    文件:Action.java   
/**
  * @param dt in seconds.
  * @js NA
  */
 public void step(float dt) {
    if(_boundarySet) {
        if(_boundaryFullyCovered) {
            return;
        }
        float tempX = _halfScreenSize.x - _followedNode.getPositionX();
float tempY = _halfScreenSize.y - _followedNode.getPositionY();
_target.setPosition(MathUtils.clamp(tempX, _leftBoundary, _rightBoundary),
        MathUtils.clamp(tempY, _bottomBoundary, _topBoundary));
    } else {
        _target.setPosition(_halfScreenSize.x - _followedNode.getPositionX(),
                _halfScreenSize.y - _followedNode.getPositionY());
    }
 }
项目:cocos2d-java    文件:Node.java   
public void setColor(float r, float g, float b) {
 _displayColor.r = _r = MathUtils.clamp(r, 0, 1);
 _displayColor.g = _g = MathUtils.clamp(g, 0, 1);
 _displayColor.b = _b = MathUtils.clamp(b, 0, 1);

 updateCascadeColor();
}
项目:school-game    文件:TutorialDummy.java   
@Override
public void render(Batch batch, float deltaTime)
{
    if (body == null) return;

    Color oldColor = batch.getColor();

    batch.setColor(1f, (health + 5)/10f, (health + 5)/10f, 1f);

    Vector2 pos = body.getPosition();
    pos.scl(Physics.PPM);

    TextureRegion region = MathUtils.isZero(hitTimer) ? dummy : dummy_hit;

    batch.draw(region,                                    // TextureRegion (front, back, side)
            pos.x - dummy.getRegionWidth() / 2,           // Offset to the X position (character center)
            pos.y,                                        // Y position is at the foots
            dummy.getRegionWidth() / 2,                   // Origin X (important for flipping)
            dummy.getRegionHeight(),                      // Origin Y
            dummy.getRegionWidth(),                       // Width
            dummy.getRegionHeight(),                      // Height
            1f,                                           // Scale X (-1 to flip)
            1f,                                           // Scale Y
            0f);                                          // Rotation

    batch.setColor(oldColor);
}
项目:homescreenarcade    文件:FieldViewManager.java   
/**
 * Saves scale and x and y offsets for use by world2pixel methods, avoiding repeated method
 * calls and math operations.
 */
public void cacheScaleAndOffsets() {
    zoom = maxZoom;
    // Don't zoom if game is over or multiball is active.
    if (zoom<=1.0f || !field.getGameState().isGameInProgress() || field.getBalls().size()>1) {
        zoom = 1.0f;
        cachedScale = getScale();
        // Center the entire table horizontally and put at at the top vertically.
        // Negative offsets so the 0 coordinate will be on the screen.
        float horizontalSpaceLeft = view.getWidth() - (field.getWidth() * cachedScale);
        cachedXOffset = (horizontalSpaceLeft > 0) ? -horizontalSpaceLeft/(2*cachedScale) : 0;
        float verticalSpaceLeft = view.getHeight() - (field.getHeight() * cachedScale);
        cachedYOffset = (verticalSpaceLeft > 0) ? -verticalSpaceLeft/cachedScale : 0;
    }
    else {
        List<Ball> balls = field.getBalls();
        float x=-1, y=-1;
        if (balls.size()==1) {
            Ball b = balls.get(0);
            x = b.getPosition().x;
            y = b.getPosition().y;
        }
        else {
            // use launch position
            List<Float> position = field.layout.getLaunchPosition();
            x = position.get(0);
            y = position.get(1);
        }
        float maxOffsetRatio = 1.0f - 1.0f/zoom;
        cachedXOffset = x - field.getWidth()/(2.0f * zoom);
        cachedXOffset = MathUtils.clamp(cachedXOffset, 0, field.getWidth()*maxOffsetRatio);

        cachedYOffset = y - field.getHeight()/(2.0f * zoom);
        cachedYOffset = MathUtils.clamp(cachedYOffset, 0, field.getHeight()*maxOffsetRatio);
        cachedScale = getScale();
    }
    cachedHeight = view.getHeight();
}
项目:fluffybalance    文件:Balanceball.java   
private void renderBall() {
    // render ball
    mSpriteBatch.draw(mBallTextureRegion,
            mBall.x - mBall.radius,
            mBall.y - mBall.radius,
            mBall.radius,
            mBall.radius,
            mBall.radius * 2,
            mBall.radius * 2,
            1.f,
            1.f,
            mBallBody.getAngle() * MathUtils.radDeg
    );
}
项目:Mindustry    文件:LaserTurret.java   
@Override
public void drawLayer2(Tile tile){
    TurretEntity entity = tile.entity();

    if(entity.target != null &&
            Angles.angleDist(entity.rotation, Angles.angle(tile.worldx(), tile.worldy(), entity.target.x, entity.target.y)) <= cone){
        Angles.translation(entity.rotation, 4f);

        float x = tile.worldx() + Angles.x(), y = tile.worldy() + Angles.y();
        float x2 = entity.target.x, y2 = entity.target.y;

        float lighten = (MathUtils.sin(Timers.time()/1.2f) + 1f) / 10f;

        Draw.color(Tmp.c1.set(beamColor).mul(1f + lighten, 1f + lighten, 1f + lighten, 1f));
        Draw.alpha(0.3f);
        Draw.thickness(4f);
        Draw.line(x, y, x2, y2);
        Draw.thickness(2f);
        Draw.rect("circle", x2, y2, 7f, 7f);
        Draw.alpha(1f);
        Draw.thickness(2f);
        Draw.line(x, y, x2, y2);
        Draw.thickness(1f);
        Draw.rect("circle", x2, y2, 5f, 5f);

    }

    Draw.reset();
}
项目:odb-little-fortune-planet    文件:IceCellSimulator.java   
@Override
public void process(CellDecorator c, float delta) {
    final float temperature = c.mask().temperature;
    if ( temperature > 0 && MathUtils.random(100) < temperature ) {
        c.setNextType(PlanetCell.CellType.WATER);
    }
}
项目:Climatar    文件:PoliticalController.java   
@Override
protected void tick() {
    for(Nation n : Nation.values()) {
        setRelationDelta(n, MathUtils.random(-1f, 1f));
        setWalletDelta(n, MathUtils.random(-5, 5));
    }

}
项目:enklave    文件:CombatFitght.java   
public void renderCercle(OrthographicCamera camera,float amt, Color c){
    float start = 0f;
    float end = amt * 360f;

    lookup.bind();
    renderer.begin(camera.combined, GL20.GL_TRIANGLE_STRIP);
    Gdx.gl.glEnable(GL20.GL_BLEND);
    Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
    int segs = (int)(24 * Math.cbrt(r));
    end += 90f;
    start += 90f;
    float halfThick = thickness/2f;
    float step = 360f / segs;
    for (float angle=start; angle<(end+step); angle+=step) {
        float tc = 0.5f;
        if (angle==start)
            tc = 0f;
        else if (angle>=end)
            tc = 1f;

        float fx = MathUtils.cosDeg(angle);
        float fy = MathUtils.sinDeg(angle);

        float z = 0f;
        //renderer.
        renderer.color(c.r, c.g, c.b, c.a);
        renderer.texCoord(tc, 1f);
        renderer.vertex(cx + fx * (r + halfThick), cy + fy * (r + halfThick), z);

        renderer.color(c.r, c.g, c.b, c.a);
        renderer.texCoord(tc, 0f);
        renderer.vertex(cx + fx * (r + -halfThick), cy + fy * (r + -halfThick), z);
    }
    renderer.end();
}
项目:Planet-Generator    文件:Ring.java   
public void setMinimumRadius(float minimumRadius) {
    this.minRadius = minimumRadius;
    if(maxRadius < minRadius) {
        maxRadius = minRadius + 1;
    }
    for(Orbiter ringObj : objects) {
        ringObj.setRadius(MathUtils.random(minRadius, maxRadius));
    }
}
项目:gdx-fireapp    文件:ImageHelper.java   
/**
 * Creates texture region from byte[].
 * <p>
 * GWT platform requires additional step (as far as i know) to deal with Pixmap. It is need to load Image element
 * and wait until it is loaded.
 *
 * @param bytes    Image byte[] representation, not null
 * @param consumer Consumer where you should deal with region, not null
 */
public static void createTextureFromBytes(byte[] bytes, final Consumer<TextureRegion> consumer)
{
    String base64 = "data:image/png;base64," + new String(Base64Coder.encode(bytes));
    final Image image = new Image();
    image.setVisible(false);
    image.addLoadHandler(new LoadHandler()
    {
        @Override
        public void onLoad(LoadEvent event)
        {
            ImageElement imageElement = image.getElement().cast();
            Pixmap pixmap = new Pixmap(imageElement);
            Gdx.app.log("ImageHelper", "pixmap: " + pixmap.getWidth() + "/" + pixmap.getHeight());
            final int orgWidth = pixmap.getWidth();
            final int orgHeight = pixmap.getHeight();
            int width = MathUtils.nextPowerOfTwo(orgWidth);
            int height = MathUtils.nextPowerOfTwo(orgHeight);
            final Pixmap potPixmap = new Pixmap(width, height, pixmap.getFormat());
            potPixmap.drawPixmap(pixmap, 0, 0, 0, 0, pixmap.getWidth(), pixmap.getHeight());
            pixmap.dispose();
            TextureRegion region = new TextureRegion(new Texture(potPixmap), 0, 0, orgWidth, orgHeight);
            potPixmap.dispose();
            RootPanel.get().remove(image);
            consumer.accept(region);
        }
    });
    image.setUrl(base64);
    RootPanel.get().add(image);
}
项目:Planet-Generator    文件:NoiseGenerator.java   
public static float[][] GenerateWhiteNoise(int width, int height) {
    float[][] noise = new float[width][height];

    for (int i = 0; i < width; i++) {
        for (int j = 0; j < height; j++) {
            noise[i][j] = (float) MathUtils.random.nextDouble() % 1;
        }
    }

    return noise;
}
项目:Planet-Generator    文件:ObjectGenerator.java   
public Orbiter createObjectInRing(Ring ring) {
    Orbiter.OrbiterBlueprint blueprint = new Orbiter.OrbiterBlueprint();
    blueprint.angle = MathUtils.random(0, 360);
    blueprint.radius = MathUtils.random(ring.getMinimumRadius(), ring.getMaximumRadius());
    blueprint.zTilt = ring.getZTilt();
    blueprint.xTilt = ring.getXTilt();
    blueprint.angularVelocity = ring.getAngularVelocity();

    Orbiter ringObject = new Orbiter(createMoonSprite(MathUtils.random(4, 6)), blueprint, ring.getColors().random());
    //scene.addSpaceObject(ringObject);
    scene.addRingObject(ringObject);
    ring.addObject(ringObject);
    return ringObject;
}
项目:StarshipFighters    文件:SamusShipBoss.java   
private void checkWingStatus() {
    // Check if Wings are dead
    if (rightWingHealth <= 0 && !isRightWingDead) {
        if (TimeUtils.timeSinceMillis(rightWingExplosionTimer) > 200 && rightWingExplosionCounter < 10) {
            // Add delayed explosions
            explosionList.add(new Explosion((x + 148) + MathUtils.random(-48, 48), y, 48, height, playState));
            rightWingExplosionTimer = TimeUtils.millis();
            rightWingExplosionCounter++;
        }

        // Kill Right Wing
        if (rightWingExplosionCounter == 10) {
            setRightWingDead(true);
        }
    }

    if (leftWingHealth <= 0 && !isLeftWingDead) {
        if (TimeUtils.timeSinceMillis(leftWingExplosionTimer) > 200 && leftWingExplosionCounter < 10) {
            // Add delayed explosions
            explosionList.add(new Explosion(x + MathUtils.random(-48, 48), y, 48, height, playState));
            leftWingExplosionTimer = TimeUtils.millis();
            leftWingExplosionCounter++;
        }

        // Kill Left Wing
        if (leftWingExplosionCounter == 10) {
            setLeftWingDead(true);
        }
    }

    // If Both wings are dead, then set middle to be vulnerable
    if (isLeftWingDead && isRightWingDead && isMiddleInvincible) {
        isMiddleInvincible = false;
    }
}
项目:Climatar    文件:WeatherController.java   
@Override
protected void tick() {
    for(Nation n : Nation.values()) {
        setPrecipitationDelta(n, MathUtils.random(-1f, 1f));
        setTemperatureDelta(n, MathUtils.random(-1f, 1f));
    }
}
项目:NanoUI    文件:IntMap.java   
/** Reduces the size of the backing arrays to be the specified capacity or less. If the capacity is already less, nothing is
 * done. If the map contains more items than the specified capacity, the next highest power of two capacity is used instead. */
public void shrink (int maximumCapacity) {
    if (maximumCapacity < 0) throw new IllegalArgumentException("maximumCapacity must be >= 0: " + maximumCapacity);
    if (size > maximumCapacity) maximumCapacity = size;
    if (capacity <= maximumCapacity) return;
    maximumCapacity = MathUtils.nextPowerOfTwo(maximumCapacity);
    resize(maximumCapacity);
}
项目:odb-artax    文件:ParticleSystem.java   
public void sprinkleSand(int percentageChance) {
    for (E e : allEntitiesWith(SandSprinkler.class)) {
        if (MathUtils.random(0, 100f) <= percentageChance) {
            triggerSprinkler(e);
        }
    }
}
项目:StarshipFighters    文件:SamusShipBoss.java   
private void checkMiddleHP() {
    if (healthbar < 0) {
        dx = 0;
        dy = 0;
        if (TimeUtils.timeSinceMillis(bossDeathExplosionTimer) > 200 && bossDeathExplosionCounter < 15) {
            // Add delayed explosions
            explosionList.add(new Explosion(x + (0.5f * MathUtils.random(0, width)),
                    (y + (0.5f * MathUtils.random(0, height))), width, height, playState));
            bossDeathExplosionTimer = TimeUtils.millis();
            bossDeathExplosionCounter++;
            isDead = true;
        }
    }
}
项目:fluffybalance    文件:BallEntity.java   
public void onGameStart() {
    PhysicsComponent physicsComponent = getComponentByType(PhysicsComponent.class);
    physicsComponent.body.setTransform(mBallStartPosition.x, mBallStartPosition.y, 0);
    physicsComponent.body.setLinearVelocity(MathUtils.randomBoolean() ? -10.f : 10.f, 0.f);
    physicsComponent.body.setAngularVelocity(0.f);

    PositionComponent positionComponent = getComponentByType(PositionComponent.class);
    positionComponent.position.set(mBallStartPosition.x, mBallStartPosition.y);
}
项目:jenjin    文件:RegionSequenceAttachment.java   
public float[] updateWorldVertices (Slot slot, boolean premultipliedAlpha) {
    if (regions == null) throw new IllegalStateException("Regions have not been set: " + this);

    int frameIndex = (int)(slot.getAttachmentTime() / frameTime);
    switch (mode) {
    case forward:
        frameIndex = Math.min(regions.length - 1, frameIndex);
        break;
    case forwardLoop:
        frameIndex = frameIndex % regions.length;
        break;
    case pingPong:
        frameIndex = frameIndex % (regions.length << 1);
        if (frameIndex >= regions.length) frameIndex = regions.length - 1 - (frameIndex - regions.length);
        break;
    case random:
        frameIndex = MathUtils.random(regions.length - 1);
        break;
    case backward:
        frameIndex = Math.max(regions.length - frameIndex - 1, 0);
        break;
    case backwardLoop:
        frameIndex = frameIndex % regions.length;
        frameIndex = regions.length - frameIndex - 1;
        break;
    }
    setRegion(regions[frameIndex]);

    return super.updateWorldVertices(slot, premultipliedAlpha);
}
项目:typing-label    文件:ShakeEffect.java   
@Override
protected void onApply (Glyph glyph, int localIndex) {
    // Make sure we can hold enough entries for the current index
    if (localIndex >= lastOffsets.size / 2) {
        lastOffsets.setSize(lastOffsets.size + 16);
    }

    // Get last offsets
    float lastX = lastOffsets.get(localIndex * 2);
    float lastY = lastOffsets.get(localIndex * 2 + 1);

    // Calculate new offsets
    float x = getLineHeight() * distance * MathUtils.random(-1, 1) * DEFAULT_DISTANCE;
    float y = getLineHeight() * distance * MathUtils.random(-1, 1) * DEFAULT_DISTANCE;

    // Apply intensity
    float normalIntensity = MathUtils.clamp(intensity * DEFAULT_INTENSITY, 0, 1);
    x = Interpolation.linear.apply(lastX, x, normalIntensity);
    y = Interpolation.linear.apply(lastY, y, normalIntensity);

    // Apply fadeout
    float fadeout = calculateFadeout();
    x *= fadeout;
    y *= fadeout;
    x = Math.round(x);
    y = Math.round(y);

    // Store offsets for the next tick
    lastOffsets.set(localIndex * 2, x);
    lastOffsets.set(localIndex * 2 + 1, y);

    // Apply changes
    glyph.xoffset += x;
    glyph.yoffset += y;
}