AgentStack
SKILL verified MIT Self-run

Unity Physics

skill-nice-wolf-studio-unity-claude-skills-unity-physics · by Nice-Wolf-Studio

>

No reviews yet
0 installs
10 views
0.0% view→install

Install

$ agentstack add skill-nice-wolf-studio-unity-claude-skills-unity-physics

✓ scanned · ✓ verified — works with Claude Code, Cursor, and more.

Security review

✓ Passed

No issues found. Passed automated security review. · v0.1.0 How review works →

  • Prompt-injection patterns
  • Secret / credential exfiltration
  • Dangerous shell & filesystem operations
  • Untrusted network calls
  • Known-malicious package signatures

What it can access

  • Network access No
  • Filesystem access No
  • Shell / process execution No
  • Environment & secrets No
  • Dynamic code execution No

From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.

Are you the author of Unity Physics? Claim this listing to set pricing, connect Stripe payouts, and keep 70% of every sale.
Sign up to claim

About

Unity Physics

Physics System Overview

Unity provides different physics engine integrations for different project needs:

  • 3D Physics (PhysX): Nvidia PhysX engine integration for 3D object-oriented projects
  • 2D Physics (Box2D): Optimized 2D physics system with dedicated components
  • Both systems simulate gravity, collisions, forces, and constraints

Physics Timing

Physics runs on a fixed timestep via FixedUpdate, separate from the rendering frame rate:

void FixedUpdate()
{
    // All physics code belongs here, not in Update()
    rb.AddForce(Vector3.forward * speed);
}

Key timing rules:

  • FixedUpdate runs at a fixed interval (default 0.02s / 50Hz)
  • Multiple FixedUpdate calls can occur per frame, or none
  • Time.fixedDeltaTime controls the interval
  • Use Update for input, FixedUpdate for physics forces

Simulation Modes

Physics.simulationMode controls when the physics engine steps:

  • FixedUpdate (default): Automatic simulation each fixed timestep
  • Update: Simulate once per frame
  • Script: Manual control via Physics.Simulate()

Rigidbody Configuration

A Rigidbody component places a GameObject under physics engine control. A rigid body does not deform or change shape under physics forces.

Key Properties

| Property | Description | Default | |----------|-------------|---------| | mass | Mass in kg; affects force interactions | 1 | | linearDamping | Resistance to linear velocity | 0 | | angularDamping | Resistance to angular velocity | 0.05 | | useGravity | Whether gravity affects this body | true | | isKinematic | If true, not driven by physics forces | false | | interpolation | Smooths visual jitter between physics steps | None | | collisionDetectionMode | Algorithm for detecting collisions | Discrete |

Movement Methods

Rigidbody rb = GetComponent();

// Apply continuous force (call in FixedUpdate)
rb.AddForce(Vector3.forward * 10f);
rb.AddForce(Vector3.up * 5f, ForceMode.Impulse);

// Apply torque
rb.AddTorque(Vector3.up * 2f);

// Apply force at a world position (creates both force and torque)
rb.AddForceAtPosition(Vector3.forward * 10f, hitPoint);

// Kinematic movement (use for isKinematic=true bodies)
rb.MovePosition(rb.position + direction * speed * Time.fixedDeltaTime);
rb.MoveRotation(targetRotation);

ForceMode Options

| Mode | Description | |------|-------------| | ForceMode.Force | Continuous force, uses mass (default) | | ForceMode.Acceleration | Continuous force, ignores mass | | ForceMode.Impulse | Instant force, uses mass | | ForceMode.VelocityChange | Instant force, ignores mass |

Sleep State

When a Rigidbody's energy falls below the sleep threshold, the physics engine stops calculating it. Control manually with rb.Sleep() and rb.WakeUp().

Scale Warning

Unity assumes 1 world unit = 1 metre. Incorrect scale causes unrealistic physics behavior. Keep GameObjects at realistic proportions.


Colliders and Triggers

Colliders are invisible shapes that define a GameObject's physical boundaries. They do not need to match the visual mesh.

Collider Categories

| Category | Description | |----------|-------------| | Static Collider | Collider only, no Rigidbody. For immovable geometry (walls, floors). | | Dynamic Rigidbody Collider | Collider + Rigidbody (isKinematic=false). Fully simulated. | | Kinematic Rigidbody Collider | Collider + Rigidbody (isKinematic=true). Moved via script. |

Collider Shapes

  • Primitive: BoxCollider, SphereCollider, CapsuleCollider -- efficient, auto-scale
  • Compound: Multiple primitives on child GameObjects for complex shapes
  • MeshCollider: Matches exact mesh geometry; expensive, use sparingly
  • WheelCollider: Raycast-based, built-in vehicle physics
  • TerrainCollider: Matches terrain heightmap

Trigger Colliders

Triggers detect overlapping colliders without physical collision response:

// Set via Inspector: Collider > Is Trigger = true
// Or via script:
GetComponent().isTrigger = true;

Requirements for trigger events:

  • At least one GameObject must have a Rigidbody
  • The collider must have isTrigger enabled
  • Each overlapping pair needs its own Rigidbody for individual detection

Physics Materials

Colliders support PhysicsMaterial with adjustable friction and bounciness properties for surface interactions.


Raycasting

Raycasting projects invisible rays to detect colliders in the scene.

Physics.Raycast

// Basic: check if anything is ahead
Vector3 fwd = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(transform.position, fwd, 10))
    Debug.Log("Something ahead!");

// With hit info
RaycastHit hit;
if (Physics.Raycast(transform.position, -Vector3.up, out hit, 100.0f))
    Debug.Log("Distance to ground: " + hit.distance);

// With layer mask
int layerMask = 1 ();
    }

    void Update()
    {
        // Capture input in Update (legacy Input Manager; see unity-input for new Input System)
        if (Input.GetButtonDown("Jump"))
            jumpRequested = true;
    }

    void FixedUpdate()
    {
        // Apply physics in FixedUpdate (legacy Input; see unity-input)
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        Vector3 move = new Vector3(h, 0f, v) * moveSpeed;
        rb.linearVelocity = new Vector3(move.x, rb.linearVelocity.y, move.z);

        if (jumpRequested)
        {
            rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
            jumpRequested = false;
        }
    }
}

Ground Check with SphereCast

// Cache collider reference in Awake() -- avoid GetComponent in hot paths
private CapsuleCollider capsule;
void Awake() => capsule = GetComponent();

public bool IsGrounded()
{
    float radius = 0.3f;
    return Physics.SphereCast(transform.position, radius, Vector3.down,
        out _, (capsule.height / 2f) - radius + 0.1f,
        LayerMask.GetMask("Ground"));
}

Hover Pad with Trigger

public class HoverPad : MonoBehaviour
{
    public float hoverForce = 12f;

    void OnTriggerStay(Collider other)
    {
        if (other.attachedRigidbody != null)
            other.attachedRigidbody.AddForce(Vector3.up * hoverForce, ForceMode.Acceleration);
    }
}

Non-Allocating Raycast (Zero GC)

private readonly RaycastHit[] hits = new RaycastHit[10];

void DetectEnemies()
{
    int count = Physics.RaycastNonAlloc(transform.position, transform.forward,
        hits, 50f, LayerMask.GetMask("Enemies"));
    for (int i = 0; i < count; i++)
        Debug.Log("Hit: " + hits[i].collider.name);
}

Anti-Patterns

Do NOT use Update for physics forces

// BAD: Forces applied at variable frame rate cause inconsistent behavior
void Update()
{
    rb.AddForce(Vector3.forward * 10f); // WRONG
}

// GOOD: Use FixedUpdate for physics
void FixedUpdate()
{
    rb.AddForce(Vector3.forward * 10f); // CORRECT
}

Do NOT move Rigidbody with Transform

// BAD: Bypasses physics, breaks collision detection
transform.position += Vector3.forward * speed * Time.deltaTime; // WRONG

// GOOD: Use Rigidbody methods
rb.MovePosition(rb.position + Vector3.forward * speed * Time.fixedDeltaTime); // CORRECT
// Or apply forces:
rb.AddForce(Vector3.forward * speed);

Do NOT use MeshCollider when primitives suffice

MeshCollider on a simple box-shaped object is wasteful. Use BoxCollider instead -- much cheaper and equally accurate for simple shapes. Reserve MeshCollider for complex concave geometry.

Do NOT allocate in physics callbacks

// BAD: GC allocation every collision
void OnCollisionEnter(Collision other) {
    var enemies = GameObject.FindGameObjectsWithTag("Enemy"); // WRONG
}
// GOOD: Cache in Start(), reuse in callbacks

Do NOT ignore layer masks in raycasts

Physics.Raycast(origin, direction, out hit);                        // BAD: hits everything
Physics.Raycast(origin, direction, out hit, 100f,
    LayerMask.GetMask("Ground", "Obstacles"));                      // GOOD: filtered

Key API Quick Reference

| Category | Key Members | |----------|-------------| | Physics (static) | Raycast, RaycastAll, RaycastNonAlloc, SphereCast, BoxCast, CapsuleCast, Linecast, OverlapSphere, OverlapBox, CheckSphere, CheckBox, ClosestPoint, ComputePenetration, Simulate, SyncTransforms | | Physics properties | gravity, defaultContactOffset, bounceThreshold, sleepThreshold, defaultSolverIterations, queriesHitTriggers, queriesHitBackfaces, simulationMode | | Rigidbody | mass, linearDamping, angularDamping, useGravity, isKinematic, linearVelocity, angularVelocity, interpolation, collisionDetectionMode, AddForce(), AddTorque(), MovePosition(), MoveRotation(), Sleep(), WakeUp() | | Callbacks | OnCollisionEnter(Collision), OnCollisionStay, OnCollisionExit, OnTriggerEnter(Collider), OnTriggerStay, OnTriggerExit |

See references/physics3d-api.md for full method signatures, parameters, and overloads. See references/physics2d-api.md for the complete 2D physics API.


CharacterController

For non-physics-driven character movement (FPS controllers, NPCs), use CharacterController instead of Rigidbody. It handles slopes, steps, and collision sliding without physics simulation. See [references/character-controller.md](references/character-controller.md) for full API, patterns, and CharacterController vs Rigidbody comparison.

Related Skills

  • unity-foundations -- GameObject hierarchy, components, transforms, layers
  • unity-scripting -- MonoBehaviour lifecycle (Update vs FixedUpdate), coroutines
  • unity-2d -- 2D game development patterns, sprite rendering

Additional Resources

Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

Install and usage instructions live in the source repository linked above.

Reviews

No reviews yet — be the first.

Versions

  • v0.1.0 Imported from the upstream source.