Hi,
I would like to apply an instant force to a Rigidbody so it reaches a point within a given time. Below is the code I have been using to accomplish this.
This code has been working very well for me. However, I would now like it to take into account the drag of the Rigidbody2D.
How can I adjust the above code so the Rigidbody2D can reach targetposition in the timetoreach with a single force and compensate for drag?
If you could leave a reply, I will be most grateful.
public Transform targetPosition;
public float timeToReach = 2.0f;
private Rigidbody2D rb2d;
float time;
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
force();
}
void Update()
{
time += Time.deltaTime;
if(Vector2.Distance(transform.position, targetPosition.position) <= 0.25f)
{
Debug.Log(time);
}
}
void force()
{
Vector2 initialPosition = rb2d.position;
Vector2 distance = (Vector2)targetPosition.position - initialPosition;
Vector2 acceleration = 2 * distance / (timeToReach * timeToReach);
// Calculate the force considering the drag
float mass = rb2d.mass;
Vector2 initialVelocity = Vector2.zero; // Assuming the object starts from rest
Vector2 force = mass * acceleration* initialVelocity;
// Apply the force to the Rigidbody2D
rb2d.AddForce(force, ForceMode2D.Impulse);
}