VirtualController: API Practice
Use this skill when you need to quickly choose the correct method and avoid getting physics/prediction regression 😎
Freshness reference: git log/blame with cutoff 2024-02-20.
What to download
references/fresh-pattern-catalog.md- register of methods with freshness marking (Use/Limited).references/rejected-snippets.md- risky places and misuse practices.references/docs-context.md- how to read docs without conflicting with the code.
Quick API selection
- You need a controller for the physics step: inherit from
VirtualControllerand implementUpdateBeforeSolve/UpdateAfterSolve. - You need order between controllers: add
UpdatesBefore/UpdatesAftertobase.Initialize(). - You need control over velocity/impulse: use
SetLinearVelocity,ApplyLinearImpulse,SetBodyStatus, damping setters. - You need an entity management relay: use
SetRelay/RemoveRelay. - You need manual mobility mathematics:
Friction,Accelerate,GetWishDir/SetWishDir. - You need a container/movement link through “climbing out”:
ForciblySetClimbing. - We need a safe climb pipeline:
CanVault->TryClimb. - We need predicted control on the client:
UpdateIsPredictedEventhandlers.
API by group
1) VirtualController contract
Initialize()- registers before/after solve hooks and metrics.UpdateBeforeSolve(bool prediction, float frameTime)- pre-solver logic.UpdateAfterSolve(bool prediction, float frameTime)- post-solver logic.BeforeMonitor/AfterMonitor- measurement of the cost of a specific controller.
2) Ordering API
UpdatesBefore.Add(typeof(...))- this controller goes before the target.UpdatesAfter.Add(typeof(...))- this controller comes later than the target.- Both lists must be configured to
base.Initialize().
3) Physics mutators
SetLinearVelocity(...)- safe setting of linear speed.ApplyLinearImpulse(...)- impulse for dynamics/pulling.SetBodyStatus(..., BodyStatus.InAir/OnGround)— body mode for special mechanics.SetLinearDamping(...)/SetAngularDamping(...)— runtime damping.SetBodyType(...)- conscious change of body mode.
4) Relay API
SetRelay(uid, relayEntity)— create/update a relay link.RemoveRelay(uid)— remove the relay and bring the prediction state to a consistent state.- Client prediction hooks (
UpdateIsPredictedEvent) must take into account the relay chain.
5) Movement helper API
GetWishDir(...)/SetWishDir(...)- control of the desired direction.Friction(...)(vector/scalar) - controlled speed decay.Accelerate(...)- limited acceleration to the wish direction.ResetCamera(...)/GetParentGridAngle(...)- correct operation of the angle/orientation.
6) Climb API
CanVault(...)— climb/vault pre-validation.TryClimb(...)— launching the climb procedure with do-after and checks.ForciblySetClimbing(...)- forced safe exit to the surface.
7) Conveyor and Pull practical points
- Conveyor:
CanRun(...),UpdateBeforeSolve(...), combination of conveyor vector withwishDir. - Pull: impulse towards the target + settle shutdown + reverse impulse in special conditions.
Unusual use cases
- Relay piloting: mechs, station-eye, manned clothing, proxy-control objects in special modes.
- Container-eject pipeline: after extracting the entity, use
ForciblySetClimbingto avoid sticking. - Client prediction gating: for relay target and pullable via
UpdateIsPredictedEvent.
Patterns
- Set up the controller order (
UpdatesBefore/After) tobase.Initialize(). - In
UpdateBeforeSolvefilter unsuitable bodies (prediction,body.Predict, static/sleeping cases). - For
KinematicControlleruse helper friction + explicit setting of speeds. - For relay scripts, use only
SetRelay/RemoveRelay. - For gravity/space pull scenarios, take into account the pair impulse if required by the mechanics.
- For climb-flow, always do
CanVaultbeforeTryClimb. - For ejection from a container/cryo/scanner, use
ForciblySetClimbingas a post-action step. - For conveyor logic, calculate the direction separately, apply the result after the parallel part.
- For client prediction, adjust
IsPredicted/BlockPredictionthrough the appropriate events. - Use
SetBodyStatusonly in clearly justified special mechanics. - For APIs that are called frequently, cache queries and avoid unnecessary allocations.
- Check the actual freshness of the example before reusing it.
Anti-patterns
- Add order dependencies after
base.Initialize(). - Pull
SetBodyStatus(InAir)as a universal “patch”. - Change relay manually through direct
RemComp/EnsureCompwithout lifecycle methods. - In the predicted controller, use nondeterministic logic without protections.
- Copy TODO-heavy pieces from pull/contact/solver as “best practice”.
- Rely on the empty client conveyor class as the source of behavior.
- Use pre-cutoff legacy fragments as a reference.
- Mix transform shifts and impulses without an explicit order model.
- Skip the
CanVaultchecks and immediately force the climb-flow. - Ignore update prediction events in relay/pullable scenarios.
- Try to “treat” mispredict only with visual guards.
- Do not check the consequences of an API change on server/shared/client at the same time.
Code examples
1) Basic controller template
public sealed class ExampleController : VirtualController
{
public override void Initialize()
{
UpdatesAfter.Add(typeof(SomeOtherController));
base.Initialize();
}
public override void UpdateBeforeSolve(bool prediction, float frameTime)
{
// There is only deterministic pre-solver logic here.
}
}
2) Explicit ordering API
public override void Initialize()
{
UpdatesBefore.Add(typeof(TileFrictionController));
UpdatesAfter.Add(typeof(SharedMoverController));
// Important: we set the order before base.Initialize().
base.Initialize();
}
3) Relay lifecycle via API, not manually
// We connect the pilot control to the proxy entity.
_mover.SetRelay(pilotUid, proxyUid);
// We remove the relay correctly, updating the prediction state.
_mover.RemoveRelay(pilotUid);
4) Movement math helper: friction + accelerate
var velocity = body.LinearVelocity;
// First attenuation, then acceleration towards the target direction.
_mover.Friction(minimumFrictionSpeed, frameTime, friction, ref velocity);
SharedMoverController.Accelerate(ref velocity, targetDir, accel, frameTime);
PhysicsSystem.SetLinearVelocity(uid, velocity, body: body);
5) Physics mutators in pull mechanics
var impulse = accel * physics.Mass * frameTime;
PhysicsSystem.WakeBody(targetUid, body: physics);
PhysicsSystem.ApplyLinearImpulse(targetUid, impulse, body: physics);
6) Safe climb pipeline
if (_climb.CanVault(climbable, user, target, out _) &&
_climb.TryClimb(user, target, climbableUid, out var doAfter, climbable))
{
// Climb started normally, doAfter is stored for continuation.
component.DoAfterId = doAfter;
}
7) Container eject -> ForciblySetClimbing
_container.Remove(containedUid, bodyContainer);
// After extraction, we transfer the entity to the correct “outside” state.
_climb.ForciblySetClimbing(containedUid, containerOwnerUid);
8) Prediction hook for pullable on the client
private void OnUpdatePullablePredicted(Entity<PullableComponent> ent, ref UpdateIsPredictedEvent args)
{
if (ent.Comp.Puller == _playerManager.LocalEntity)
args.IsPredicted = true;
else if (ent.Comp.Puller != null)
args.BlockPrediction = true;
}
9) Conveyor + wish direction
var targetDir = conveyorDir;
var wishDir = _mover.GetWishDir(entityUid);
if (Vector2.Dot(wishDir, targetDir) > 0f)
targetDir += wishDir;
SharedMoverController.Accelerate(ref velocity, targetDir, 20f, frameTime);
Rule of application
- First select methods from
fresh-pattern-catalog.md. - First check any legacy/TODO fragment with
rejected-snippets.md. - If the script involves prediction, check server/shared/client behavior at the same time.
- If there is a discrepancy between the docs and the code, always fix the decision in favor of the code.
Keep the API layer predictable: the right method and the right lifecycle are more important than a “short” call :)