Loading...
Loading...
Set up 3D physics in Unity 6: Rigidbody movement and forces, colliders, triggers vs collisions, layer-based collision, raycasts, and joints. Use when adding a Rigidbody, handling OnCollisionEnter/OnTriggerEnter, tuning collision layers, casting rays, or when the user mentions Unity physics, AddForce, isKinematic, or linearVelocity.
npx skill4agent add gamedev-skills/awesome-gamedev-agent-skills unity-physicsFixedUpdateUnity 6 rename:is nowRigidbody.velocity(the old name is deprecated). Code copied from older tutorials will warn or fail to compile.Rigidbody.linearVelocity
RigidbodyColliderRigidbody2DCollider2Dphysics-tuningunity-input-systemRigidbodyColliderColliderRigidbodyFixedUpdateUpdatelinearVelocityMovePositionFixedUpdateAddForcelinearVelocityMovePositiontransform.positionOnCollisionEnterColliderIs TriggerOnTriggerEnterFixedUpdateusing UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class Mover : MonoBehaviour
{
[SerializeField] private float accel = 30f, maxSpeed = 8f;
private Rigidbody _rb;
private Vector3 _input; // set from Update / input system
private void Awake() => _rb = GetComponent<Rigidbody>();
private void FixedUpdate()
{
_rb.AddForce(_input * accel, ForceMode.Acceleration); // mass-independent accel
// Unity 6: linearVelocity (was 'velocity'). Clamp horizontal speed.
Vector3 flat = new(_rb.linearVelocity.x, 0, _rb.linearVelocity.z);
if (flat.magnitude > maxSpeed)
{
flat = flat.normalized * maxSpeed;
_rb.linearVelocity = new Vector3(flat.x, _rb.linearVelocity.y, flat.z);
}
}
}ForceModeForceAccelerationImpulseVelocityChange// Solid hit: both have colliders, this one has a (non-kinematic) Rigidbody.
private void OnCollisionEnter(Collision col)
{
Debug.Log($"Hit {col.gameObject.name} at {col.contacts[0].point}");
}
// Overlap: one collider has 'Is Trigger' = true. Requires a Rigidbody on at least one party.
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Pickup")) Destroy(other.gameObject);
}[SerializeField] private LayerMask groundMask; // set to your "Ground" layer in the Inspector
private bool IsGrounded()
{
// Cast a short ray down; only test colliders on groundMask.
return Physics.Raycast(transform.position, Vector3.down, out RaycastHit hit,
1.1f, groundMask);
}// isKinematic Rigidbody: not driven by forces, but MovePosition interpolates and carries
// resting bodies correctly (unlike moving the Transform directly).
private void FixedUpdate() => _rb.MovePosition(_rb.position + Vector3.right * (2f * Time.fixedDeltaTime));Rigidbody.velocitylinearVelocityangularVelocitytransform.positionMovePositionUpdateFixedUpdateRigidbodyContinuousContinuous DynamicMeshColliderSphereCastRaycastAllOverlapSphereLayerMaskFixedJointHingeJointConfigurableJointreferences/raycasting-and-joints.mdScriptReference/RigidbodyScriptReference/Physics.Raycastphysics-tuningunity-csharp-scriptingFixedUpdateUpdateunity-navmesh