Move a GameObject with the Physics Core 2D API
Configure a 2D physics script to update the Transform component of a GameObject.
Read time 2 minutesLast updated 11 days ago
By default, when you create an object with the Physics Core 2D API, the object isn't connected to GameObjects in the scene.
To move a GameObject, configure the physics object to update the Transform component of the GameObject.
Follow these steps:
-
To enable the physics body updating Transform components, set itsto
TransformWriteMode.Current -
To attach the Transform component of the GameObject to the physics body, set theproperty to the Transform component.
transformObject -
Make sure theproperty of the physics body is set to
type.PhysicsBody.BodyType.Dynamic
For example, attach the following script to a GameObject, then enter Play mode. The physics body falls under gravity, and updates the position in the Transform component in the Inspector window.
using UnityEngine;using Unity.U2D.Physics;public class MoveGameObject : MonoBehaviour{ public PhysicsWorld world; public PhysicsWorldDefinition worldDefinition = PhysicsWorldDefinition.defaultDefinition; void Awake() { // Enable physics bodies updating transforms worldDefinition.transformWriteMode = PhysicsWorld.TransformWriteMode.Fast2D; world = PhysicsWorld.Create(worldDefinition); } void Start() { // Create a body and shape PhysicsBody circleBody = world.CreateBody(); CircleGeometry circleGeometry = new CircleGeometry { radius = 2f }; circleBody.CreateShape(circleGeometry); // Set body to dynamic so it falls under gravity circleBody.type = PhysicsBody.BodyType.Dynamic; // Enable this physics body updating transforms circleBody.transformWriteMode = PhysicsBody.TransformWriteMode.Current; // Set the updated transform as the transform of this GameObject circleBody.transformObject = transform; }}
Rotate objects more quickly
By default, Unity sets a limit on how fast a physics body rotates, to avoid forces becoming too large and objects passing through each other incorrectly. To remove the limit, set the Fast Rotation Allowed property of the body to . This property is recommended only for circular objects.
trueInterpolate positions
By default, the physics body updates the Transform component after Unity finishes calculating the physics simulation. To interpolate positions between simulation steps instead, set the of the physics body to or .
TransformWriteModeInterpolateExtrapolate