Skip to content

Add physics

This tutorial gives the sphere a dynamic physics body and a script that pushes it.

Continue from Your first prefab, or use any sphere in your scene.

With the sphere selected in the Scene Hierarchy:

  1. Open the Physics Body section.
  2. Set Body Type to Dynamic. The ball now reacts to gravity, collisions, and forces.
  3. File -> Save Scene (Ctrl+S).

Play, and the ball falls and rolls. The demo player can shove it with their body before you add a script.

The API reaches a physics body through GetComponent<PhysicsBody>(). ApplyImpulse adds a one-frame kick.

Create bindings/Kolpa.Demo/KickBall.cs:

using Kolpa.Engine;
namespace Kolpa.Demo;
public class KickBall : MonoBehaviour
{
public float Impulse = 6f;
public override void OnUpdate(float deltaTime)
{
if (!Input.GetMouseButtonDown(MouseButton.Left))
return;
PhysicsBody body = GetComponent<PhysicsBody>();
if (body != null)
body.ApplyImpulse(transform.forward * Impulse);
}
}

transform.forward is the object’s forward axis. If you attach this to the camera, the kick follows where you look.

  1. Select the object that should do the kicking.
  2. Add Component -> Script.
  3. Set Behaviour to Kolpa.Demo.KickBall, Kolpa.Demo.
  4. Play, click, and watch the ball move.

Change Impulse in the source and rebuild to tune the strength. A light sphere with 6f launches with a firm nudge.

To kick whatever is under the crosshair, cast a ray and read the body from the hit:

if (Input.GetMouseButtonDown(MouseButton.Left) &&
Physics.Raycast(transform.position, transform.forward, 5f, out Physics.SceneHit hit, ulong.MaxValue, gameObject))
{
PhysicsBody body = hit.Object.GetComponent<PhysicsBody>();
body?.ApplyImpulse(transform.forward * Impulse);
}

Physics.Raycast returns false on a miss. hit.Object is the GameObject that was hit. gameObject is ignored so you never kick yourself.

Previous: Write your first script: a spinner script.

Next: Scene settings and sky: sun, sky, and environment.