com.badlogic.gdx.math.MathUtils Java Examples

The following examples show how to use com.badlogic.gdx.math.MathUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FallingObject.java    From FruitCatcher with Apache License 2.0 6 votes vote down vote up
public FallingObject(ImageProvider imageProvider, TextureRegion [] textureRegions,
					 FallingObjectState state) {
    rect = new Rectangle();
    rect.width = width;
    rect.height = height;
    
    this.textureRegions = textureRegions;
    this.state = state;
    
    if(state.getPosX() < 0 || state.getPosY() < 0) {
    	rect.x = MathUtils.random(0, imageProvider.getScreenWidth()-width);
    	rect.y = imageProvider.getScreenHeight();
    }
    else {
    	rect.x = state.getPosX();
    	rect.y = state.getPosY();
    }
    
    state.setPosX((int) rect.x);
    state.setPosY((int) rect.y);
}
 
Example #2
Source File: WanderSteerer.java    From GdxDemo3D with Apache License 2.0 6 votes vote down vote up
public WanderSteerer(final SteerableBody steerableBody) {
	super(steerableBody);

	this.wanderSB = new Wander<Vector3>(steerableBody) {
		@Override
		protected SteeringAcceleration<Vector3> calculateRealSteering(SteeringAcceleration<Vector3> steering) {
			super.calculateRealSteering(steering);
			steering.linear.y = 0; // remove any vertical acceleration
			return steering;
		}
	};
	this.wanderSB.setWanderOffset(8) //
		.setWanderOrientation(0) //
		.setWanderRadius(0.5f) //
		.setWanderRate(MathUtils.PI2 * 4);

	this.prioritySteering.add(wanderSB);
}
 
Example #3
Source File: Moveset.java    From Unlucky with MIT License 6 votes vote down vote up
/**
 * Returns a Move array with 4 unique moves from a boss's movepool
 *
 * @param bossId
 * @return
 */
private Move[] getBossMoves(int bossId) {
    Array<Move> pool = rm.bossMoves.get(bossId);
    Move[] ret = new Move[4];
    int index;
    for (int i = 0; i < ret.length; i++) {
        index = MathUtils.random(pool.size - 1);
        Move randMove = pool.get(index);
        Move temp = null;

        if (randMove.type < 2)
            temp = new Move(randMove.type, randMove.name, randMove.minDamage, randMove.maxDamage);
        else if (randMove.type == 2)
            temp = new Move(randMove.name, randMove.minDamage, randMove.crit);
        else if (randMove.type == 3)
            temp = new Move(randMove.name, randMove.minHeal, randMove.maxHeal, randMove.dmgReduction);

        ret[i] = temp;
        //pool.removeIndex(index);
    }

    return ret;
}
 
Example #4
Source File: Enemy.java    From ud406 with MIT License 6 votes vote down vote up
public void update(float delta) {
    switch (direction) {
        case LEFT:
            position.x -= Constants.ENEMY_MOVEMENT_SPEED * delta;
            break;
        case RIGHT:
            position.x += Constants.ENEMY_MOVEMENT_SPEED * delta;
    }

    if (position.x < platform.left) {
        position.x = platform.left;
        direction = Direction.RIGHT;
    } else if (position.x > platform.right) {
        position.x = platform.right;
        direction = Direction.LEFT;
    }

    final float elapsedTime = Utils.secondsSince(startTime);
    final float bobMultiplier = 1 + MathUtils.sin(MathUtils.PI2 * (bobOffset + elapsedTime / Constants.ENEMY_BOB_PERIOD));
    position.y = platform.top + Constants.ENEMY_CENTER.y + Constants.ENEMY_BOB_AMPLITUDE * bobMultiplier;
}
 
Example #5
Source File: ClientSaveManager.java    From Cubes with MIT License 6 votes vote down vote up
public static Save createSave(String name, String generatorID, Gamemode gamemode, String seedString) {
  if (name != null) name = name.trim();
  if (name == null || name.isEmpty()) name = "world-" + Integer.toHexString(MathUtils.random.nextInt());
  FileHandle folder = getSavesFolder();
  FileHandle handle = folder.child(name);
  handle.mkdirs();
  Compatibility.get().nomedia(handle);
  Save s = new Save(name, handle);

  SaveOptions options = new SaveOptions();
  options.setWorldSeed(seedString);
  options.worldType = generatorID;
  options.worldGamemode = gamemode;
  s.setSaveOptions(options);

  return s;
}
 
Example #6
Source File: Player.java    From Radix with MIT License 6 votes vote down vote up
public int getBlockInHead(IWorld world) {
    int x = MathUtils.floor(getPosition().getX());
    int z = MathUtils.floor(getPosition().getZ());
    int y = MathUtils.floor(getPosition().getY() + HEIGHT);
    IChunk chunk = world.getChunk(x, z);
    if (chunk != null) {
        if (y >= world.getHeight()) return 0;
        try {
            return chunk.getBlockId(x & (world.getChunkSize() - 1), y, z & (world.getChunkSize() - 1));
        } catch (BlockStorage.CoordinatesOutOfBoundsException e) {
            e.printStackTrace();
            return 0;
        }
    } else {
        return 0;
    }
}
 
Example #7
Source File: Enemy.java    From ud406 with MIT License 6 votes vote down vote up
public void update(float delta) {
    switch (direction) {
        case LEFT:
            position.x -= Constants.ENEMY_MOVEMENT_SPEED * delta;
            break;
        case RIGHT:
            position.x += Constants.ENEMY_MOVEMENT_SPEED * delta;
    }

    if (position.x < platform.left) {
        position.x = platform.left;
        direction = Direction.RIGHT;
    } else if (position.x > platform.right) {
        position.x = platform.right;
        direction = Direction.LEFT;
    }

    final float elapsedTime = Utils.secondsSince(startTime);
    final float bobMultiplier = 1 + MathUtils.sin(MathUtils.PI2 * (bobOffset + elapsedTime / Constants.ENEMY_BOB_PERIOD));
    position.y = platform.top + Constants.ENEMY_CENTER.y + Constants.ENEMY_BOB_AMPLITUDE * bobMultiplier;
}
 
Example #8
Source File: EngineF40.java    From uracer-kotd with Apache License 2.0 6 votes vote down vote up
@Override
public void shiftUp () {
	if (UseGears) {
		if (gear > 0 && gear < MaxGear) {
			gear++;

			float dist = 2000;
			if (rpm >= dist + 1000) {
				// rpm -= dist;
			} else {
				// rpm = 1000;
			}
		}

		if (gear == 0) {
			gear++;
			// rpm = 1000;
		}

		rpm = MathUtils.clamp(rpm, 1000, 10000);
	}

	gear = MathUtils.clamp(gear, MinGear, MaxGear);
}
 
Example #9
Source File: FallingObjectFactory.java    From FruitCatcher with Apache License 2.0 6 votes vote down vote up
public FallingObject getFruit() {
    TextureRegion [] textureRegions = new TextureRegion[1];
    int fruitType = MathUtils.random(0, imageProvider.getFruitsCount() - 1);
    textureRegions[0] =  imageProvider.getFruit(fruitType);
    
    boolean inSeason = FruitType.isInSeason(fruitType, season);
    FallingObjectState state = new FallingObjectState();
    if (inSeason) {
    	state.setType(FallingObjectType.SeasonalFruit);
    }
    else {
    	state.setType(FallingObjectType.Fruit);
    }
    state.setIndex(fruitType);
    return new FallingObject(imageProvider, textureRegions, 
                             state);
}
 
Example #10
Source File: MoveResult.java    From dice-heroes with GNU General Public License v3.0 6 votes vote down vote up
public static Array<Grid2D.Coordinate> fillAvailableCoordinates(Array<Grid2D.Coordinate> coordinates, Creature creature) {
    World world = creature.world;
    if (world == null)
        return coordinates;
    if (!creature.get(Attribute.canMove)) {
        coordinates.add(new Grid2D.Coordinate(creature.getX(), creature.getY()));
        return coordinates;
    }
    int r = MathUtils.ceil(creature.description.profession.moveRadius);
    float r2 = creature.description.profession.moveRadius * creature.description.profession.moveRadius;
    for (int x = creature.getX() - r; x <= creature.getX() + r; x++) {
        for (int y = creature.getY() - r; y <= creature.getY() + r; y++) {
            if ((x == creature.getX() && y == creature.getY() || world.canStepTo(x, y))
                && tmp.set(x, y).dst2(creature.getX(), creature.getY()) <= r2) {
                coordinates.add(new Grid2D.Coordinate(x, y));
            }
        }
    }
    return coordinates;
}
 
Example #11
Source File: EntityFactory.java    From xibalba with MIT License 6 votes vote down vote up
/**
 * Create entrance entity.
 *
 * @param mapIndex Map to place it on
 * @return The entrance entity
 */
public Entity createEntrance(int mapIndex) {
  Map map = WorldManager.world.getMap(mapIndex);

  int cellX;
  int cellY;

  do {
    cellX = MathUtils.random(0, map.width - 1);
    cellY = MathUtils.random(0, map.height - 1);
  } while (WorldManager.mapHelpers.isBlocked(mapIndex, new Vector2(cellX, cellY))
      && WorldManager.mapHelpers.getWallNeighbours(mapIndex, cellX, cellY) >= 4);

  Vector2 position = new Vector2(cellX, cellY);
  Entity entity = new Entity();
  entity.add(new EntranceComponent());
  entity.add(new PositionComponent(position));

  entity.add(new VisualComponent(
      Main.asciiAtlas.createSprite("1203"), position
  ));

  return entity;
}
 
Example #12
Source File: Player.java    From Unlucky with MIT License 6 votes vote down vote up
/**
 * Increments level and recalculates max exp
 * Sets increase variables to display on screen
 * Recursively accounts for n consecutive level ups from remaining exp
 *
 * @param remainder the amount of exp left after a level up
 */
public void levelUp(int remainder) {
    level++;

    hpIncrease += MathUtils.random(Util.PLAYER_MIN_HP_INCREASE, Util.PLAYER_MAX_HP_INCREASE);
    int dmgMean = MathUtils.random(Util.PLAYER_MIN_DMG_INCREASE, Util.PLAYER_MAX_DMG_INCREASE);

    // deviates from mean by 0 to 2
    minDmgIncrease += (dmgMean - MathUtils.random(1));
    maxDmgIncrease += (dmgMean + MathUtils.random(1));
    // accuracy increases by 1% every 10 levels
    accuracyIncrease += level % 10 == 0 ? 1 : 0;
    // smoveCd reduces every 10 levels
    if (smoveCd > 1) smoveCd -= level % 10 == 0 ? 1 : 0;

    int prevMaxExp = maxExp;
    maxExp = Util.calculateMaxExp(level, MathUtils.random(3, 5));
    maxExpIncrease += (maxExp - prevMaxExp);

    // another level up
    if (remainder >= maxExp) {
        levelUp(remainder - maxExp);
    } else {
        exp = remainder;
    }
}
 
Example #13
Source File: Enemy.java    From ud406 with MIT License 6 votes vote down vote up
public void update(float delta) {
    switch (direction) {
        case LEFT:
            position.x -= Constants.ENEMY_MOVEMENT_SPEED * delta;
            break;
        case RIGHT:
            position.x += Constants.ENEMY_MOVEMENT_SPEED * delta;
    }

    if (position.x < platform.left) {
        position.x = platform.left;
        direction = Direction.RIGHT;
    } else if (position.x > platform.right) {
        position.x = platform.right;
        direction = Direction.LEFT;
    }

    final float elapsedTime = Utils.secondsSince(startTime);
    final float bobMultiplier = 1 + MathUtils.sin(MathUtils.PI2 * (bobOffset + elapsedTime / Constants.ENEMY_BOB_PERIOD));
    position.y = platform.top + Constants.ENEMY_CENTER.y + Constants.ENEMY_BOB_AMPLITUDE * bobMultiplier;
}
 
Example #14
Source File: ReliablePacketController.java    From riiablo with Apache License 2.0 6 votes vote down vote up
private void updateSentBandwidth() {
  int baseSequence = (sentPackets.getSequence() - config.sentPacketBufferSize + 1 + Packet.USHORT_MAX_VALUE) & Packet.USHORT_MAX_VALUE;

  int bytesSent = 0;
  float startTime = Float.MAX_VALUE;
  float finishTime = 0f;
  int numSamples = config.sentPacketBufferSize / 2;
  for (int i = 0; i < numSamples; i++) {
    int sequence = (baseSequence + i) & Packet.USHORT_MAX_VALUE;
    SentPacketData sentPacketData = sentPackets.find(sequence);
    if (sentPacketData == null) continue;
    bytesSent += sentPacketData.packetSize;
    startTime = Math.min(startTime, sentPacketData.time);
    finishTime = Math.max(finishTime, sentPacketData.time);
  }

  if (startTime != Float.MAX_VALUE && finishTime != 0f) {
    float sentBandwidth = bytesSent / (finishTime - startTime) * 8f / 1000f;
    if (MathUtils.isEqual(this.sentBandwidth, sentBandwidth, TOLERANCE)) {
      this.sentBandwidth += (sentBandwidth - this.sentBandwidth) * config.bandwidthSmoothingFactor;
    } else {
      this.sentBandwidth = sentBandwidth;
    }
  }
}
 
Example #15
Source File: Targeting.java    From libgdx-demo-pax-britannica with MIT License 6 votes vote down vote up
/**
 * return a random ship of the desired type that's in range
 */
private static Ship getTypeInRange(Ship source, Array<Ship> ships, float range) {
	Array<Ship> shipsInRange = new Array<Ship>();
	float range_squared = range * range;

	for (int i = 0; i < ships.size; i++) {
		Ship ship = ships.get(i);
		float currentDistance = source.collisionCenter.dst(ship.collisionCenter);

		if (ship.alive && source.id != ship.id && onScreen(ship.collisionCenter) && (currentDistance < range_squared)) {
			shipsInRange.add(ship);
		}
	}

	if (shipsInRange.size > 0) {
		return shipsInRange.get(MathUtils.random(0, shipsInRange.size - 1));
	} else {
		return null;
	}
}
 
Example #16
Source File: ExtendedColorPicker.java    From vis-ui with Apache License 2.0 6 votes vote down vote up
@Override
protected void updateValuesFromCurrentColor () {
	int[] hsv = ColorUtils.RGBtoHSV(color);
	int ch = hsv[0];
	int cs = hsv[1];
	int cv = hsv[2];

	int cr = MathUtils.round(color.r * 255.0f);
	int cg = MathUtils.round(color.g * 255.0f);
	int cb = MathUtils.round(color.b * 255.0f);
	int ca = MathUtils.round(color.a * 255.0f);

	hBar.setValue(ch);
	sBar.setValue(cs);
	vBar.setValue(cv);

	rBar.setValue(cr);
	gBar.setValue(cg);
	bBar.setValue(cb);

	aBar.setValue(ca);

	verticalBar.setValue(hBar.getValue());
	palette.setValue(sBar.getValue(), vBar.getValue());
}
 
Example #17
Source File: TypeTransformer.java    From gdx-vr with Apache License 2.0 6 votes vote down vote up
public static EyeParams transform(Viewport viewport) {
	int eye = viewport == VirtualReality.head.getLeftEye() ? 0 : 1;
	EyeParams eyeParams = new EyeParams(eye);

	eyeParams.getViewport().setViewport(viewport.getScreenX(), viewport.getScreenY(), MathUtils.nextPowerOfTwo(viewport.getScreenWidth()),
			MathUtils.nextPowerOfTwo(viewport.getScreenHeight()));

	float fov = ((PerspectiveCamera) viewport.getCamera()).fieldOfView;
	eyeParams.getFov().setLeft(fov);
	eyeParams.getFov().setRight(fov);
	eyeParams.getFov().setTop(fov);
	eyeParams.getFov().setBottom(fov);

	for (int i = 0; i < 16; i++) {
		eyeParams.getTransform().getEyeView()[i] = viewport.getCamera().view.val[i];
	}

	for (int i = 0; i < 16; i++) {
		eyeParams.getTransform().getPerspective()[i] = viewport.getCamera().projection.val[i];
	}

	return eyeParams;
}
 
Example #18
Source File: Icicles.java    From ud405 with MIT License 6 votes vote down vote up
public void update(float delta) {
    if (MathUtils.random() < delta * Constants.ICICLE_SPAWNS_PER_SECOND) {
        Vector2 newIciclePosition = new Vector2(
                MathUtils.random() * viewport.getWorldWidth(),
                viewport.getWorldHeight()
        );
        Icicle newIcicle = new Icicle(newIciclePosition);
        icicleList.add(newIcicle);
    }

    for (Icicle icicle : icicleList) {
        icicle.update(delta);
    }

    icicleList.begin();
    for (int i = 0; i < icicleList.size; i++) {
        if (icicleList.get(i).position.y < -Constants.ICICLES_HEIGHT) {
            // TODO: Increment count of icicles dodged

            icicleList.removeIndex(i);
        }
    }
    icicleList.end();
}
 
Example #19
Source File: CircularMotion.java    From ud405 with MIT License 6 votes vote down vote up
@Override
    public void render() {
        viewport.apply();

        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        renderer.setProjectionMatrix(viewport.getCamera().combined);
        renderer.begin(ShapeType.Filled);

        float elapsedNanoseconds = TimeUtils.nanoTime() - initialTime;
        float elapsedSeconds = MathUtils.nanoToSec * elapsedNanoseconds;
        float elapsedPeriods = elapsedSeconds / PERIOD;
        float cyclePosition = elapsedPeriods % 1;

        float x = WORLD_SIZE / 2 + MOVEMENT_RADIUS * MathUtils.cos(MathUtils.PI2 * cyclePosition);
        float y = WORLD_SIZE / 2 + MOVEMENT_RADIUS * MathUtils.sin(MathUtils.PI2 * cyclePosition);

        renderer.circle(x, y, CIRCLE_RADIUS);

        // Uncomment the next line to see the sort of beautiful things you can create with simple movement
//         drawFancyCircles(renderer, elapsedPeriods, 20);
        renderer.end();
    }
 
Example #20
Source File: Biome.java    From Radix with MIT License 6 votes vote down vote up
private int[] getColor(int elevation, int[][] corners) {
    float adjTemp = MathUtils.clamp(temperature - elevation*0.00166667f, 0, 1);
    float adjRainfall = MathUtils.clamp(rainfall, 0, 1) * adjTemp;

    getColTmp[0] = adjTemp - adjRainfall;
    getColTmp[1] = 1 - temperature;
    getColTmp[2] = rainfall;

    float red = 0, green = 0, blue = 0;
    for(int i = 0; i < 3; i++) {
        red += getColTmp[i] * corners[i][0/*red*/];
        green += getColTmp[i] * corners[i][1/*green*/];
        blue += getColTmp[i] * corners[i][2/*blue*/];
    }

    return new int[]{
            (int)MathUtils.clamp(red, 0, 255),
            (int)MathUtils.clamp(green, 0, 255),
            (int)MathUtils.clamp(blue, 0, 255)
    };
}
 
Example #21
Source File: Player.java    From Unlucky with MIT License 5 votes vote down vote up
public Player(String id, ResourceManager rm) {
    super(id, rm);

    inventory = new Inventory();
    equips = new Equipment();

    // attributes
    hp = maxHp = previousHp = Util.PLAYER_INIT_MAX_HP;
    accuracy = Util.PLAYER_ACCURACY;
    minDamage = Util.PLAYER_INIT_MIN_DMG;
    maxDamage = Util.PLAYER_INIT_MAX_DMG;

    level = 1;
    speed = 50.f;

    exp = 0;
    // offset between 3 and 5
    maxExp = Util.calculateMaxExp(1, MathUtils.random(3, 5));

    // create tilemap animation
    am = new AnimationManager(rm.sprites16x16, Util.PLAYER_WALKING, Util.PLAYER_WALKING_DELAY);
    // create battle scene animation
    bam = new AnimationManager(rm.battleSprites96x96, 2, Util.PLAYER_WALKING, 2 / 5f);

    moveset = new Moveset(rm);
    // damage seed is a random number between the damage range
    moveset.reset(minDamage, maxDamage, maxHp);

    statusEffects = new StatusSet(true, rm);
    smoveset = new SpecialMoveset();
}
 
Example #22
Source File: BlockingWindow.java    From dice-heroes with GNU General Public License v3.0 5 votes vote down vote up
@Override public void act(float delta) {
    super.act(delta);
    colorOffset += delta / colorTime;
    float colorListBlend = colorOffset /** (float) colors.size*/;
    int from = MathUtils.floor(colorListBlend);
    int to = MathUtils.ceil(colorListBlend);
    Color fromColor = colors.get(from % colors.size);
    Color toColor = colors.get(to % colors.size);
    setColor(blend(fromColor, toColor, colorListBlend - from));

    scaleOffset += delta / disappearTime;
    setScale(1 - scaleOffset % 1f);
}
 
Example #23
Source File: GigaGal.java    From ud406 with MIT License 5 votes vote down vote up
private void continueJump() {
    if (jumpState == JumpState.JUMPING) {
        float jumpDuration = MathUtils.nanoToSec * (TimeUtils.nanoTime() - jumpStartTime);
        if (jumpDuration < Constants.MAX_JUMP_DURATION) {
            velocity.y = Constants.JUMP_SPEED;
        } else {
            endJump();
        }
    }
}
 
Example #24
Source File: Draggable.java    From vis-ui with Apache License 2.0 5 votes vote down vote up
private void getStageCoordinatesWithDeadzone (final InputEvent event) {
	final Actor parent = mimic.getActor().getParent();
	if (parent != null) {
		MIMIC_COORDINATES.set(Vector2.Zero);
		parent.localToStageCoordinates(MIMIC_COORDINATES);
		final float parentX = MIMIC_COORDINATES.x;
		final float parentY = MIMIC_COORDINATES.y;
		final float parentEndX = parentX + parent.getWidth();
		final float parentEndY = parentY + parent.getHeight();
		if (isWithinDeadzone(event, parentX, parentY, parentEndX, parentEndY)) {
			// Keeping within parent bounds:
			MIMIC_COORDINATES.set(event.getStageX() + offsetX, event.getStageY() + offsetY);
			if (MIMIC_COORDINATES.x < parentX) {
				MIMIC_COORDINATES.x = parentX;
			} else if (MIMIC_COORDINATES.x + mimic.getWidth() > parentEndX) {
				MIMIC_COORDINATES.x = parentEndX - mimic.getWidth();
			}
			if (MIMIC_COORDINATES.y < parentY) {
				MIMIC_COORDINATES.y = parentY;
			} else if (MIMIC_COORDINATES.y + mimic.getHeight() > parentEndY) {
				MIMIC_COORDINATES.y = parentEndY - mimic.getHeight();
			}
			STAGE_COORDINATES.set(MathUtils.clamp(event.getStageX(), parentX, parentEndX - 1f),
					MathUtils.clamp(event.getStageY(), parentY, parentEndY - 1f));
		} else {
			getStageCoordinatesWithOffset(event);
		}
	} else {
		getStageCoordinatesWithOffset(event);
	}
}
 
Example #25
Source File: CubesShaderProvider.java    From Cubes with MIT License 5 votes vote down vote up
@Override
public void begin(ShaderProgram program, Camera camera, RenderContext context) {
  WorldClient worldClient = ((WorldClient) Cubes.getClient().world);
  float distance = Settings.getIntegerSettingValue(Settings.GRAPHICS_VIEW_DISTANCE) * Area.SIZE_BLOCKS;
  float fogDistance = MathUtils.clamp(distance * 0.1f, 8f, 16f);

  program.setUniformf(u_cameraposition, Cubes.getClient().player.position);
  program.setUniformf(u_skycolor, worldClient.getSkyColour());
  program.setUniformf(u_fogdistance, fogDistance);
  program.setUniformf(u_minfogdistance, distance - fogDistance);
}
 
Example #26
Source File: MapDijkstra.java    From xibalba with MIT License 5 votes vote down vote up
/**
 * Find a wandering path in water.
 *
 * @param start Starting position
 * @return A path
 */
public Array<Vector2> findWanderWaterPath(Vector2 start) {
  if (map.hasWater) {
    return wanderWater[MathUtils.random(0, wanderWater.length - 1)].findPath(start);
  } else {
    return null;
  }
}
 
Example #27
Source File: LivingEntity.java    From Radix with MIT License 5 votes vote down vote up
public void updateMovement(MovementHandler handler, float seconds) {
    if (this.onGround) {
        this.yVelocity = Math.max(this.yVelocity, 0);
    }

    float deltaY = yVelocity * seconds;
    if (!handler.checkDeltaCollision(this, 0, deltaY, 0)) {
        this.getPosition().offset(0, deltaY, 0);
    } else {
        if (yVelocity < 0) {// falling down and failed because we hit the ground
            // prevent overshoot causing the player to not reach the ground
            int x = MathUtils.floor(getPosition().getX());
            int y = MathUtils.floor(getPosition().getY());
            int z = MathUtils.floor(getPosition().getZ());
            int cx = x & (RadixClient.getInstance().getWorld().getChunkSize() - 1);
            int cz = z & (RadixClient.getInstance().getWorld().getChunkSize() - 1);

            IChunk chunk = RadixClient.getInstance().getWorld().getChunk(x, z);
            if (chunk != null) {
                // go directly to ground
                for (int downY = y; downY > y + deltaY; downY--) {
                    try {
                        Block block = chunk.getBlock(cx, downY, cz);
                        if (block != null && block.isSolid()) {
                            getPosition().set(getPosition().getX(),
                                    block.calculateBoundingBox(chunk, cx, downY, cz).max.y + 0.015f,
                                    getPosition().getZ());
                        }
                    } catch (BlockStorage.CoordinatesOutOfBoundsException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }

        yVelocity = 0;
    }

}
 
Example #28
Source File: WorldRenderer.java    From SIFTrain with MIT License 5 votes vote down vote up
private void drawTapZones() {
    float centerX = this.positionOffsetX + width / 2;
    float centerY = this.positionOffsetY + height - height * 0.25f;
    float size = height * 0.2f;
    for (TapZone tapZone : world.getZones()) {

        TextureRegion region = tapZoneIdle;

        if (tapZone.getState(TapZone.State.STATE_WARN)) {
            region = tapZoneWarn;
        }

        if (tapZone.getState(TapZone.State.STATE_PRESSED)) {
            tapZone.touchTime = time;
        }

        final float x = centerX + tapZone.getPosition().x * ppuX - size / 2;
        final float y = centerY + tapZone.getPosition().y * ppuY - size / 2;
        spriteBatch.draw(region, x, y, size, size);

        float alpha = 1f - MathUtils.clamp((time - tapZone.touchTime) * 5f, 0f, 1f);
        if (alpha > 0) {
            Color c = spriteBatch.getColor();
            spriteBatch.setColor(c.r, c.g, c.b, Interpolation.pow2In.apply(alpha));
            spriteBatch.draw(tapZonePressed, x, y, size, size);
            spriteBatch.setColor(c);
        }
    }
}
 
Example #29
Source File: Audio.java    From riiablo with Apache License 2.0 5 votes vote down vote up
public Instance play(String id, boolean global) {
  if (id.isEmpty()) return null;
  Sounds.Entry sound = Riiablo.files.Sounds.get(id);
  if (sound == null) return null;
  if (sound.Group_Size > 0) {
    int randomId = sound.Index + MathUtils.random.nextInt(sound.Group_Size);
    sound = Riiablo.files.Sounds.get(randomId);
  }

  return play(sound, global);
}
 
Example #30
Source File: Map.java    From xibalba with MIT License 5 votes vote down vote up
private void paintCave() {
  map = new MapCell[width][height];

  for (int x = 0; x < geometry.length; x++) {
    for (int y = 0; y < geometry[x].length; y++) {
      if (geometry[x][y] == MapCell.Type.FLOOR) {
        Sprite floor = Main.asciiAtlas.createSprite("0915");
        Color color = Colors.get("caveFloor-" + +MathUtils.random(1, 3));
        floor.setColor(color);
        map[x][y] = new MapCell(floor, MapCell.Type.FLOOR, "a cave floor");
      } else {
        int neighbours = getGroundNeighbours(x, y);

        if (neighbours > 0) {
          Sprite wall = Main.asciiAtlas.createSprite("1113");
          wall.setColor(Colors.get("caveWall"));
          map[x][y] = new MapCell(wall, MapCell.Type.WALL, "a cave wall");
        } else {
          Sprite nothing = Main.asciiAtlas.createSprite("0000");
          map[x][y] = new MapCell(nothing, MapCell.Type.NOTHING, "nothing");
        }
      }

      map[x][y].sprite.setPosition(x * Main.SPRITE_WIDTH, y * Main.SPRITE_HEIGHT);
    }
  }

  if (MathUtils.random() > .75f) {
    createWater();
    createBridge();
  }
}