Use 2D physics in 3D space using the LowLevelPhysics2D API
Create a 2D physics world at any angle in 3D space, instead of the traditional x, y plane that faces the camera.
Read time 2 minutesLast updated 13 days ago
Create a 2D physics world at any angle in 3D space, instead of the traditional x, y plane that faces the camera. This allows you to use 2D physics in a 3D game.
Follow these steps:
- Create a physics world.
- Set the property of the world to either
transformPlaneorXZ.ZY
The physics system continues to use 2D coordinates and vectors, but Unity converts the final positions to 3D space according to the :
Vector2transformPlane- means the x-axis remains horizontal and the y-axis remains vertical, so that the world faces the camera in 3D space. This is the default.
XY - means the x-axis remains horizontal but the y-axis becomes depth, so that the world lies flat in 3D space.
XZ - means the x-axis becomes depth but the y-axis remains vertical, so that the world stands upright in 3D space.
ZY
To convert coordinates manually between 2D and 3D types, use the helper methods in the API.
Vector2Vector3PhysicsMathThe following example uses the plane, which creates a 2D physics world that lies flat on the ground in 3D space.
XZTo check the effect, you might need to set the Scene view to 3D mode. For more information, refer to Gizmos menu.
using Unity.Collections;using UnityEngine;using UnityEngine.LowLevelPhysics2D;public class CreateXZPlane : MonoBehaviour{ public PhysicsWorld world; private void Start() { // Create a world with a transform plane of XZ, which is the floor in 3D space. PhysicsWorldDefinition worldProperties = new PhysicsWorldDefinition { transformPlane = PhysicsWorld.TransformPlane.XZ, gravity = Vector2.zero }; world = PhysicsWorld.Create(worldProperties); // Create a square boundary PhysicsBody boundary = world.CreateBody(); using NativeList<Vector2> extentPoints = new NativeList<Vector2>(Allocator.Temp) { new(-4f, 4f), new(4f, 4f), new(4f, -4f), new(-4f, -4f) }; ChainGeometry boundaryWalls = new ChainGeometry(extentPoints.AsArray()); boundary.CreateChain(boundaryWalls, PhysicsChainDefinition.defaultDefinition); // Create a body and set it moving PhysicsBodyDefinition bodyDefinition = new PhysicsBodyDefinition(); bodyDefinition.type = PhysicsBody.BodyType.Dynamic; bodyDefinition.linearVelocity = new Vector2(7.3f, 5.7f); bodyDefinition.angularVelocity = 0f; PhysicsBody body = world.CreateBody(bodyDefinition); // Add a shape with a bouncy material body.transformObject = transform; PhysicsShapeDefinition shapeDefinition = new PhysicsShapeDefinition(); shapeDefinition.surfaceMaterial = new PhysicsShape.SurfaceMaterial{bounciness = 1f, friction = 0f}; body.CreateShape(new CircleGeometry { radius = 1f }, shapeDefinition); } private void OnDisable() { world.Destroy(); }}