Logo van Unity Physics

Unity Physics

Organisatie
Nice-Wolf-Studio
unity-physics

Unity 6 physics development guide. Use when working with Rigidbody, colliders, raycasting, triggers, collisions, joints, or physics simulation. Covers PhysX 5 (3D) and Box2D (2D) physics, FixedUpdate timing, layer masks, and contact data. Based on Unity 6.3 LTS documentation.

Overzicht

UitgeverNice-Wolf-Studio
Repositoryunity-claude-skills
Skillnaamunity-physics
Sterren
40
Forks
5
Meegeleverde bestanden
3
LicentieMIT
Links
  • Instructies in Markdown

    Een SKILL.md-bestand dat het model laadt wanneer nodig, zodat het alleen tokens kost als een verzoek er daadwerkelijk bij past.

  • Werkt met elk LLM

    AI-skills zijn gewone Markdown, geen aanbiederspecifieke code. Daardoor werken ze met GPT, Claude, Gemini, Grok of een lokaal model.

  • 3 meegeleverde bestanden

    Scripts, sjablonen en referentiemateriaal die het model tijdens het werken kan lezen. Bestanden zijn alleen-lezen en worden nooit uitgevoerd.

  • Open source

    Gepubliceerd door Nice-Wolf-Studio op GitHub. Lees de broninhoud voordat je de skill installeert.

Installatie

Installeer de AI-skill Unity Physics in TypingMind om deze met elke LLM te gebruiken, of voeg de skill toe aan een andere agent die SKILL.md kan lezen.

1

Installeren in TypingMind

TypingMind installeert een skill rechtstreeks vanuit de GitHub-map — het leest SKILL.md, bundelt de bijbehorende bestanden en slaat het resultaat lokaal op.

  1. Open de app en ga naar Plug-ins → Skills.
  2. Kies "Installeren via GitHub".
  3. Plak de onderstaande URL van de skillmap en bevestig.
    https://github.com/Nice-Wolf-Studio/unity-claude-skills/tree/main/skills/unity-physics
  4. Schakel de skill in elke chat in waarin je deze beschikbaar wilt hebben.
Plug-ins → Skills → Nieuwe skill → Via GitHub-URL. Plak vervolgens de map-URL en druk op Doorgaan.
2

Installeren in een andere agent

Elke agent die het Agent Skills-formaat kan lezen, kan deze skill gebruiken — kopieer de map naar de skillmap van die agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/Nice-Wolf-Studio/unity-claude-skills.git /tmp/unity-claude-skills
mkdir -p .claude/skills
cp -r /tmp/unity-claude-skills/skills/unity-physics .claude/skills/unity-physics
Start Claude Code na het kopiëren opnieuw op, zodat de nieuwe skill wordt herkend.

Gebruik deze skill in TypingMind

Schakel Unity Physics in een willekeurige chat in TypingMind in en het model doet de rest. De naam en beschrijving staan in de systeemprompt. Zodra een verzoek erbij past, laadt het model zelf de volledige instructies — je hoeft de skill nooit handmatig aan te roepen en deze kost pas tokens wanneer je de skill daadwerkelijk gebruikt.

Het model laadt Unity Physics automatisch zodra een verzoek erbij past.

Werkt met elk AI-model

AI-skills zijn gewone Markdown-instructies in plaats van aanbiederspecifieke code. Daardoor is Unity Physics niet gebonden aan het model waarvoor de skill is geschreven. Installeer de skill één keer in TypingMind en gebruik deze met GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama of een lokaal model dat je zelf draait — allemaal met je eigen API-sleutels.

  • Alleen geladen wanneer nodig

    De systeemprompt bevat alleen de naam en beschrijving. De instructies worden bij het eerste bijpassende verzoek opgehaald, dus een ongebruikte skill kost niets.

  • Wissel van model tijdens een chat

    Omdat de skill uit instructies bestaat en niet uit code, blijft deze werken als je van model wisselt — het volgende model leest hetzelfde SKILL.md-bestand.

Skillinstructies

Dit is de inhoud van SKILL.md die het model laadt. Lees deze vóór de installatie — een skill bestaat uit instructies die je model zal volgen.

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:

csharp
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

PropertyDescriptionDefault
massMass in kg; affects force interactions1
linearDampingResistance to linear velocity0
angularDampingResistance to angular velocity0.05
useGravityWhether gravity affects this bodytrue
isKinematicIf true, not driven by physics forcesfalse
interpolationSmooths visual jitter between physics stepsNone
collisionDetectionModeAlgorithm for detecting collisionsDiscrete

Movement Methods

csharp
Rigidbody rb = GetComponent<Rigidbody>();

// 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

ModeDescription
ForceMode.ForceContinuous force, uses mass (default)
ForceMode.AccelerationContinuous force, ignores mass
ForceMode.ImpulseInstant force, uses mass
ForceMode.VelocityChangeInstant 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

CategoryDescription
Static ColliderCollider only, no Rigidbody. For immovable geometry (walls, floors).
Dynamic Rigidbody ColliderCollider + Rigidbody (isKinematic=false). Fully simulated.
Kinematic Rigidbody ColliderCollider + 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:

csharp
// Set via Inspector: Collider > Is Trigger = true
// Or via script:
GetComponent<BoxCollider>().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

csharp
// 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 << LayerMask.NameToLayer("Enemies");
if (Physics.Raycast(origin, direction, out hit, maxDist, layerMask))
    Debug.Log("Hit enemy: " + hit.collider.gameObject.name);

// Mouse-to-world raycast
Ray ray = Camera.main.ScreenPointToRay(Mouse.current.position.ReadValue());
if (Physics.Raycast(ray, out hit, 100))
    Debug.DrawLine(ray.origin, hit.point);

RaycastHit Properties

PropertyTypeDescription
pointVector3World-space hit position
normalVector3Surface normal at hit point
distancefloatDistance from ray origin
colliderColliderCollider that was hit
transformTransformTransform of the hit object

Other Cast Methods

MethodDescription
Physics.RaycastAll()Returns all intersections along the ray
Physics.RaycastNonAlloc()Fills a pre-allocated buffer (no GC alloc)
Physics.SphereCast()Sweeps a sphere along a direction
Physics.BoxCast()Sweeps a box along a direction
Physics.CapsuleCast()Sweeps a capsule along a direction
Physics.Linecast()Checks for colliders between two points

Overlap Queries (no direction, area check)

MethodDescription
Physics.OverlapSphere()Find all colliders within a sphere
Physics.OverlapBox()Find all colliders within a box
Physics.OverlapCapsule()Find all colliders within a capsule
Physics.CheckSphere()Returns true if any collider overlaps the sphere
Physics.CheckBox()Returns true if any collider overlaps the box
Physics.CheckCapsule()Returns true if any collider overlaps the capsule

QueryTriggerInteraction

Controls whether casts/overlaps detect trigger colliders:

  • QueryTriggerInteraction.UseGlobal -- uses Physics.queriesHitTriggers
  • QueryTriggerInteraction.Collide -- always detect triggers
  • QueryTriggerInteraction.Ignore -- never detect triggers

Collision Detection

Collision Detection Modes

ModeDescriptionUse Case
DiscreteChecks collisions at end of each physics step. High efficiency.Default for most objects
ContinuousChecks collisions over the entire step. Prevents tunneling.Fast objects hitting static geometry
Continuous DynamicContinuous detection against both static and dynamic collidersFast objects hitting other fast objects
Continuous SpeculativePredictive CCD using speculative contactsKinematic bodies, general CCD

Collision Callbacks

csharp
void OnCollisionEnter(Collision other) {  // First frame of contact
    if (other.gameObject.CompareTag("Player"))
        Debug.Log("Player hit this object");
}
void OnCollisionStay(Collision other) { }  // Every physics frame while touching
void OnCollisionExit(Collision other) { }  // Contact ended

Trigger Callbacks

csharp
void OnTriggerEnter(Collider other) {  // Entered trigger volume
    if (other.CompareTag("Player"))
        Debug.Log("Player entered trigger zone");
}
void OnTriggerStay(Collider other) {   // Each frame inside trigger
    other.attachedRigidbody?.AddForce(Vector3.up * 12f, ForceMode.Acceleration);
}
void OnTriggerExit(Collider other) { } // Left trigger volume

Collision Matrix

PairCollision EventsTrigger Events
Static + DynamicYes--
Static + KinematicNo--
Static + StaticNo--
Dynamic + DynamicYes--
Dynamic + KinematicYes--
Kinematic + KinematicNo--
Trigger + Dynamic/Kinematic--Yes
Static Trigger + Dynamic/Kinematic--Yes

At least one dynamic (non-kinematic) Rigidbody is required for collision events. The physics engine only applies forces to GameObjects with Rigidbody or ArticulationBody components.


Joints

Joints connect Rigidbody components together or to fixed points in space.

Joint TypeDescriptionUse Case
FixedJointLocks two bodies together (implemented as a spring)Attaching objects, breakable connections
HingeJointRotation around a single axisDoors, pendulums, chains
SpringJointElastic connection maintaining distanceBungees, tethers
CharacterJointBall-and-socket with constrained anglesRagdolls (hips, shoulders)
ConfigurableJointFully customizable constraintsAny specialized connection

Joint Properties

  • Connected Body: The other Rigidbody (null = fixed to world)
  • Anchor / Connected Anchor: Local-space attachment points
  • Break Force / Break Torque: Threshold to destroy the joint
  • Enable Preprocessing: Stabilizes the joint simulation

For industrial/robotics applications requiring precise articulation, use ArticulationBody instead of regular joints.


2D Physics Differences

Unity's 2D physics uses a separate engine optimized for 2D workflows.

Aspect3D2D
EnginePhysXBox2D
RigidbodyRigidbodyRigidbody2D
ColliderColliderCollider2D
Physics classPhysicsPhysics2D
VectorsVector3Vector2
RotationQuaternion (3-axis)float (Z-axis only)
GravityVector3Vector2
ForceModeForceModeForceMode2D

Rigidbody2D Body Types

TypeDescription
DynamicFully simulated, responds to forces and gravity
KinematicMoved via script, detects collisions but not affected by forces
StaticImmovable, for level geometry

2D Collider Types

BoxCollider2D, CircleCollider2D, CapsuleCollider2D, PolygonCollider2D, EdgeCollider2D, CompositeCollider2D, TilemapCollider2D

2D-Specific Features

  • Effectors 2D: Area, Buoyancy, Platform, Point, Surface effectors for force interactions
  • Constant Force 2D: Applies persistent force/torque
  • Physics Material 2D: Friction and bounce properties
  • LowLevelPhysics2D API: Independent low-level physics pathway

See reference file references/physics2d-api.md for full 2D API details.


Common Patterns

Player Movement with Rigidbody

csharp
public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed = 5f;
    public float jumpForce = 7f;

    private Rigidbody rb;
    private bool jumpRequested;

    void Awake()
    {
        rb = GetComponent<Rigidbody>();
    }

    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

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

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

csharp
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)

csharp
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

csharp
// 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

csharp
// 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

csharp
// 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

csharp
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

CategoryKey Members
Physics (static)Raycast, RaycastAll, RaycastNonAlloc, SphereCast, BoxCast, CapsuleCast, Linecast, OverlapSphere, OverlapBox, CheckSphere, CheckBox, ClosestPoint, ComputePenetration, Simulate, SyncTransforms
Physics propertiesgravity, defaultContactOffset, bounceThreshold, sleepThreshold, defaultSolverIterations, queriesHitTriggers, queriesHitBackfaces, simulationMode
Rigidbodymass, linearDamping, angularDamping, useGravity, isKinematic, linearVelocity, angularVelocity, interpolation, collisionDetectionMode, AddForce(), AddTorque(), MovePosition(), MoveRotation(), Sleep(), WakeUp()
CallbacksOnCollisionEnter(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 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

Meegeleverde bestanden

Het model leest deze bestanden wanneer nodig terwijl de skill geladen is. Ze worden beschikbaar gesteld als leesbare bestanden en worden nooit uitgevoerd.

Veelgestelde vragen

Wat doet de AI-skill Unity Physics?

Unity 6 physics development guide. Use when working with Rigidbody, colliders, raycasting, triggers, collisions, joints, or physics simulation. Covers PhysX 5 (3D) and Box2D (2D) physics, FixedUpdate timing, layer masks, and contact data. Based on Unity 6.3 LTS documentation.

Waarom Unity Physics gebruiken in TypingMind?

Omdat je deze skill één keer installeert en met elk model kunt gebruiken. Unity Physics bestaat uit gewone Markdown in plaats van aanbiederspecifieke code. Dezelfde skill werkt dus met GPT-5, Claude, Gemini, Grok of een lokaal model, en je kunt midden in een chat van model wisselen zonder dat de skill niet meer werkt. TypingMind werkt met je eigen API-sleutels, dus je betaalt aanbieders rechtstreeks in plaats van een abonnement per gebruikersplek. Je skills en chats blijven in je eigen opslag.

Hoe installeer ik Unity Physics in TypingMind?

Open Plug-ins → Skills → Installeren vanaf GitHub in TypingMind en plak https://github.com/Nice-Wolf-Studio/unity-claude-skills/tree/main/skills/unity-physics. TypingMind leest het bestand SKILL.md, bundelt de bijbehorende bestanden en installeert het geheel als een skill die je per chat kunt inschakelen.

Welke AI-modellen kunnen Unity Physics gebruiken?

Elk model dat je in TypingMind koppelt. AI-skills bestaan uit gewone Markdown-instructies in plaats van aanbiederspecifieke code. GPT, Claude, Gemini, Grok en lokale modellen kunnen deze skill dus allemaal laden wanneer een verzoek erbij past.

Hoeveel AI-modellen kan ik met Unity Physics gebruiken?

Zoveel als je wilt. Zolang een model skills ondersteunt, kun je Unity Physics ermee gebruiken: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama en meer. Allemaal in TypingMind met je eigen API-sleutels.

Is de AI-skill Unity Physics gratis?

Ja. Deze skill is door Nice-Wolf-Studio op GitHub gepubliceerd onder de licentie MIT. Je betaalt alleen je eigen AI-aanbieder voor de tokens die je gebruikt.

Wat zijn AI-skills?

Een AI-skill is een herbruikbare bundel instructies die een AI-model leert hoe het één specifieke taak moet uitvoeren. Deze volgt het open Agent Skills-formaat: een bestand met de naam SKILL.md met een naam en beschrijving, plus eventuele scripts, sjablonen of referentiebestanden die het model nodig heeft. Het model leest de instructies alleen als je verzoek bij de skill past. Een geïnstalleerde skill kost dus niets zolang deze niet wordt gebruikt.

Waarin verschillen AI-skills van plug-ins of MCP-servers?

Een plug-in of MCP-server geeft een model nieuwe tools om aan te roepen: code die ergens wordt uitgevoerd en een resultaat teruggeeft. Een AI-skill geeft het model juist kennis en een werkwijze: hoe het een taak moet aanpakken, welke stappen het moet volgen en hoe goede uitvoer eruitziet. Skills bestaan uit gewone Markdown en hebben dus geen server, API-sleutel of runtime nodig. Ze werken met elk model.

Toon alles

Maak nu je eigen AI-werkruimte

Schrijf je in voor onze nieuwsbrief en blijf op de hoogte van nieuwe functies en toekomstige weggeefacties 👇