Adding a force to an object¶
The Rigidbody component allows you to apply physics-based forces to objects and make them respond to gravity, collisions, and other physical properties. In this tutorial, you will learn how to:
- Add a constant force to an object.
- Add an explosion force to an object.
Add a constant force to an object¶
To add a constant force to an object with rigidbody:
-
Add an object to the scene and make sure the object has a non-mesh collider attached to it.
-
In this tutorial, we use model Spikes_Normal to the scene by selecting it via Asset Box>Models.
-
The model added comes with a mesh collider, so we turn off the mesh collider and add a sphere collider.
-
-
Add a rigidbody to the object by choosing + Feature>Gameplay>Rigidbody, making it an YaEntity.
-
Add the following script to the entity to apply a constant force to it. For more information on how to add a script, see Creating or adding scripts.
local selfEntity = script:SelfEntity() -- Set a force of 3000 Newtons in a specific direction local force = 3000 local forwardForce = float3.Mul(float3.New(0, 0, 1), force) -- Set a 0.05-second delay before starting and 0.1 seconds to wait between events YaTimeAPI.ScheduleAtInterval(0.05, 0.1, function() -- Apply the force to the entity PhysicsAPI.AddForce(selfEntity, forwardForce) end)
In this example, we are applying a 3000-Newton force to the object in the forward direction of this object's Z-axis.
-
Save the script and enter Play Mode to playtest.
Add an explosion force to an object¶
Explosion force is a sphere that can be applied to an object to simulate explosion effects. You can call the AddExplosionImpulseForce function to add explosion force to an object.
-
Add an object to the scene and make sure the object has a non-mesh collider attached to it.
-
In this tutorial, we use model Transverse_Roadblocks to the scene by selecting it via Asset Box>Models.
-
The model comes with a mesh collider, so we turn off the mesh collider and add a sphere collider.
-
-
Add a rigidbody to the object by choosing + Feature>Gameplay>Rigidbody, making it a YaEntity.
-
Add the following script to the entity to apply a force to it. For more information on how to add a script, see Creating or adding scripts.
local selfEntity = script:SelfEntity() local cmp = script:GetYaComponent("YaMovableComponent") local explosionPosition = cmp:GetPosition() YaTimeAPI.WaitFor(5, function() PhysicsAPI.AddExplosionImpulseForce(selfEntity, 1000, explosionPosition, 15, 1000) end)
In this example, we are using the function PhysicsAPI.AddExplosionImpulseForce to apply an explosion force to the rigid body. After a 5-second delay, an explosion force of 1000 Newtons is applied at the specified position, with a radius of 15, and moved along the y-axis as if to lift the object upwards.
-
Save the script and enter Play Mode to playtest.