Skip to content

Interfacing with Voxelmetric

AlexSTV edited this page Jun 21, 2015 · 5 revisions

Interacting with the terrain is done through the static Voxelmetric class. You can call Voxelmetric functions from any c# script in the same unity project.

Example destroying the block clicked on:

if (Input.GetMouseButtonDown(0))
{
    RaycastHit hit;
    var mousePos = Camera.main.ScreenToWorldPoint(new Vector3(
        Input.mousePosition.x,
        Input.mousePosition.y,
        10
    ));

    Vector3 direction = mousePos - transform.position;

    if (Physics.Raycast(transform.position, direction, out hit, 100))
    {
        Voxelmetric.SetBlock(hit, "air");
    }
}
Adjacent parameter

The adjacent parameter is used to decide if you should use the block you're hovering on or the block adjacent to the face you're pointing at. Normally this is set as false for replacing a block with air and true to place a new block where you're pointing.

Block parameter

This decided what block to place at the given location, you can either create a block object here or you can just use the block's name as a string since there is an implicit string conversion for blocks (block names are cached so this is pretty fast). You can also use the type of the block as a byte but this isn't recommended as blocks can change index.

Functions

Voxelmetric.GetBlockPos(RaycastHit hit, bool adjacent = false)

Returns the position of the block hit by a raycast.

Voxelmetric.SetBlock(RaycastHit hit, Block block, bool adjacent = false)

Replaces a block at the end of a raycast with a given block. Set adjacent to true for placing a block.

Voxelmetric.SetBlock(BlockPos pos, Block block)

Replaces the block at the given coordinates with a given block.

Voxelmetric.GetBlock(RaycastHit hit)

Gets the block hit by a raycast.

Voxelmetric.GetBlock(BlockPos pos)

Gets the block at the given coordinates.

Voxelmetric.SaveAll()

Saves all currently loaded chunks to files (unloaded chunks are saved automatically) and returns a SaveProgress object so you can see how much has saved. Use .GetProgress() on the SaveProgress object to get a percentage progress indication, saving is only complete once this progress reaches 100.

Demo

The VoxelmetricExample class uses some of these functions for a free moving camera that can place and destroy blocks. Have a look there to see how these functions are implemented.

Eventually we should have more examples with advanced features like bombs and building.