Skip to content

Instantly share code, notes, and snippets.

@wh00ops
Last active February 16, 2022 18:02
Show Gist options
  • Save wh00ops/5c983eb373c27a74062df2886c210238 to your computer and use it in GitHub Desktop.
Save wh00ops/5c983eb373c27a74062df2886c210238 to your computer and use it in GitHub Desktop.
[Unity] An example of the code of how to calculate the force of a RigidBody in order to achieve the specified speed characteristics
using UnityEngine;
/// <summary>
/// An example of the code of how to calculate the force of a Rigidbody in order to achieve the specified speed characteristics.
/// </summary>
public class ForceProcessor : MonoBehaviour
{
/// <summary>
/// Target speed;
/// </summary>
public float speed = 10f;
/// <summary>
/// Direction of movement.
/// </summary>
public Vector3 movementDirection = Vector3.forward;
/// <summary>
/// Cached reference to Rigidbdoy component.
/// </summary>
Rigidbody m_rigidbody;
/// <summary>
/// Component initialization.
/// </summary>
private void Start()
{
// Get reference to a Rigidbody.
m_rigidbody = GetComponent<Rigidbody>();
// Configure th Rigidbody.
// Disable gravity.
m_rigidbody.useGravity = false;
// Set drag.
// The code not working with 0 drag factor, you need to set any value that greate than zero.
m_rigidbody.drag = 1f;
}
/// <summary>
/// Update component each physiscs frame.
/// </summary>
void FixedUpdate()
{
// Calculate drag factor.
float dragFactor = 1f - Time.fixedDeltaTime * m_rigidbody.drag;
// If the dragFactor is less than zero or close to, the component will not be able to calculate the actual force to achieve the specified speed characteristics.
// To fix the situation, you need to increase the number of frames for physics or reduce the Drag parameter.
if (dragFactor < 0.001f)
Debug.LogWarning("The Fixed Timestep and Darg of Rigidbody does not provide the ability to make calculations with sufficient precision. You need to increase frame rate (set less Timestep) or set less Darg.");
// Calculating the force capable of accelerating an object to the specified speeds.
Vector3 force = (speed * movementDiretion.normalized * m_rigidbody.drag) / dragFactor;
// Apply the force to the Rigidbody.
// Note: you need to use Acceleration mode to ignore the Rigidbody mass factor, in ohter cases you will add many factors, that prevent to achive the target speed.
m_rigidbody.AddRelativeForce(force, ForceMode.Acceleration);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment