Kinematic Bodies
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 6 of 63.
Moving platforms, lifts and doors need to collide like solid objects, but they must not fall or be shoved around by whatever lands on them. That is a kinematic body: set rb.isKinematic = true, and gravity, forces and hits no longer move it. Its collider still counts, so a dynamic body (one physics moves) bumps into it as into a wall, and stands on it as on the floor. You move a kinematic body yourself, with rb.MovePosition.
This lift rises at lift m/s until it reaches top. MovePosition takes the position to be at after this step, so the code adds one step's worth of movement, using Time.fixedDeltaTime:
void Start()
{
rb = GetComponent<Rigidbody>();
rb.isKinematic = true;
}
void FixedUpdate()
{
if (rb.position.y < top)
{
rb.MovePosition(rb.position + Vector3.up * lift * Time.fixedDeltaTime);
}
}Why not set transform.position? That teleports the object, and physics never learns that it moved: a crate on a sliding platform would be left behind instead of riding along. MovePosition tells physics the body travelled to the new spot during the step, so what it touches is carried and pushed properly. AddForce does nothing on a kinematic body, and kinematic bodies never collide with static colliders or with each other: only dynamic bodies run into them.
Challenge
EasyThe barge hangs over the lava, and the arrows should slide it left and right along x at speed m/s (2 in the Inspector). Right now its Rigidbody is an ordinary one, so it drops into the lava.
- When the game starts, make the barge kinematic, so it hangs in the air and nothing that hits it can push it away.
- Move it with
MovePositioninFixedUpdate(), using the raw Horizontal axis.
Press Play and slide the barge, then Check.
Try it yourself
using UnityEngine;
public class Barge : MonoBehaviour
{
public float speed = 2f;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
// Make the barge kinematic
}
void FixedUpdate()
{
// Slide it along x with the arrows
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall