-
Notifications
You must be signed in to change notification settings - Fork 7
Getting Started in 2D
Here's the basics for how to get stuff working using Sandbox.Sdf.Sdf2DWorld
.
sbox-dev_nI0l9nYq2R.mp4
On the server, create a SDF 2D world like this:
using Sandbox.Sdf;
// ...
var sdfWorld = new Sdf2DWorld
{
// Rotate so that Y is up
LocalRotation = Rotation.FromRoll( 90f )
};
In this example we've rotated it by 90 degrees, so that the Y axis when doing 2D operations becomes the Z (up) axis in world space.
Still in server-side code, you can modify the SDF world like this:
// Shape that we want to add
var circle = new CircleSdf( new Vector2( localPos.x, localPos.y ), radius );
// Load the material to use
var material = ResourceLibrary.Get<Sdf2DLayer>( "layers/sdf2d/checkerboard.sdflayer" );
// Draw the circle!
sdfWorld.Add( circle, material );
// Move the circle to the right, then subtract it!
sdfWorld.Subtract( circle.Translate( new Vector2( 32f, 0f ) ), baseMat );
You can create your own .sdflayer
resource by selecting "New SDF 2D Layer" when creating a new asset.
SDF 2D Layers control the appearance and physical properties of a layer. You can leave any of the front, back or cut material properties as empty to skip generating geometry for that face. If you remove all collision tags, the layer will have no physics shapes.
Let's say you have an SDF image like this:
You can convert it into a shape that you can add to / subtract from the world like this:
var fpSdfTexture = await Texture.LoadAsync( FileSystem.Mounted, "textures/facepunch_sdf.png" );
var fpSdf = new TextureSdf( fpSdfTexture, 64, 1024f );
var baseMat = ResourceLibrary.Get<Sdf2DLayer>( "layers/sdf2d/checkerboard.sdflayer" );
var backMat = ResourceLibrary.Get<Sdf2DLayer>( "layers/sdf2d/background.sdflayer" );
sdfWorld.Add( fpSdf, baseMat );
sdfWorld.Add( fpSdf.Expand( 16f ), backMat );
Be careful to give the correct width of the gradient in pixels (64 in this example), so that any operations you perform on the SDF will be scaled correctly.
You can move SDFs around like this:
var moved = someSdf.Translate( new Vector2( x, y ) );
Or do arbitrary transformations:
var transformed = someSdf.Transform( new Vector2( x, y ), angle, scale );
Expand the surface of the shape like this:
var expanded = someSdf.Expand( distance );
Negative values will shrink the surface. This may not work perfectly for SDFs loaded from an image, and definitely won't work for large distances.