Skip to content

Latest commit

 

History

History
149 lines (113 loc) · 6.09 KB

physics.md

File metadata and controls

149 lines (113 loc) · 6.09 KB
title marp paginate math theme
Unity Cookbook. Physics
true
true
mathjax
borbtheme

Physics

Unity physics engines

  • Manual: Physics
  • A physics engine is used to calculate accelerations, collisions, gravity and other forces
    • In 3D, Unity uses NVIDIA's PhysX for its physics
    • In 2D, Unity uses Box2D
  • When you add a physics component to a GameObject, it is then part of the physics system
    • Rigidbody, Rigidbody2D

Built-in physics engines

Rigidbody

The Rigidbody components

  • Every rigidbody has a mass, which affects how much forces influence them
  • Note: If you have problems having two non-moving Rigidbody2Ds collide, set Sleeping Mode to Never Sleep

Types of rigidbodies

  • Dynamic
    • is part of the physics engine and behaves like a "regular" physics-based object
    • can be controlled indirectly (with forces)
  • Kinematic
    • is not affected by the physics system
    • only queries the physics engine for collisions
    • can be controlled directly:
      • in 2D, use Rigidbody2D.MovePosition, Rigidbody2D.MoveRotation
      • in 3D, manipulate transform.position
  • Static (only 2D)
    • an immovable object, can only collide with non-static rigidbodies

Interpolation

Constraints

Moving dynamic Rigidbodies

  • You should interact with the physics system in FixedUpdate, not Update

  • Script Reference: Rigidbody.AddForce

    if (Input.GetButton("Jump"))
    {
        //Apply a force to this Rigidbody in direction of this GameObjects up axis
        m_Rigidbody.AddForce(transform.up * m_Thrust);
    }
  • Script Reference: Rigidbody.AddTorque

    float turn = Input.GetAxis("Horizontal");
    rb.AddTorque(transform.up * torque * turn);

Force modes

  • When applying a force, you can give the function a second argument: the mode with which the force is applied
  • ScriptReference: ForceMode has a good example project showcasing all four modes
    • ForceMode.Force is the default: the resulting acceleration is dampened by the mass of the rigidbody
    • ForceMode.Acceleration gives acceleration directly, disregarding the mass of the body.
    • ForceMode.Impulse gives the body a velocity (dampened by its mass), not an acceleration, resulting in snappier movement
    • ForceMode.VelocityChange is like impulse, but disregards the mass of the body.
  • Note: Rigidbody2D only supports ForceMode.Force and ForceMode.Acceleration!

Extra: More functions

Changing the velocity directly

Gravity

  • Note: by default, gravitational acceleration is $9.81m/s^2$
  • You can change it from Unity settings
    • Edit > Project Settings > Physics (2D) > Gravity
    • for top-down 2d games, you want gravity to be zero

Extra: Raycasting

Links