Hi,
In Unity 2D I am trying to calculate the force required to move a gameobject to a specific position within a specified amount of seconds. The game I am programming is in a top down perspective, so gravity will not need to be accounted for, but the drag and the current velocity of the Rigidbody2D will need to be accounted for.
The Rigidbody2D should continue to travel after reaching the point after the time and the force should be applied using rb.AddForce().
If you can leave a reply, I will be most grateful.
The equations for physics (specifically kinematics / dynamics) contain all of this stuff, you know the usual high school physics f=ma and v=v0+at equations, etc.
Remember that computer physics simulations are discrete approximations of what is in fact a continuous process so you won’t get precisely-accurate results.
If you’re just looking for trajectory / ballistics / artillery aiming examples, start by googling “trajectory”
It certainly looks like it all boils down to solving the uniformly accelerated movement equation to get the required acceleration (since as @Kurt-Dekker stated, f = m*a and you already know m). I wonder about the drag, though. How is it’s contribution computed?
Yeah, I figured out the direction and force application part. That was kind of easy, the below code works fine when the rigidbody’s drag is 0.
public Transform targetPosition;
public float timeToReach = 2.0f;
private Rigidbody2D rb2d;
float time;
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
force();
}
private void Update()
{
time += Time.deltaTime;
if (Vector2.Distance(transform.position, targetPosition.position) <= 0.25f)
{
Debug.Log(time);
}
}
void force()
{
Vector2 direction = ((Vector2)targetPosition.position - rb2d.position).normalized;
float distanceToTarget = Vector2.Distance(rb2d.position, targetPosition.position);
Vector2 desiredVelocity = direction * (distanceToTarget / timeToReach);
Vector2 impulse = rb2d.mass * (desiredVelocity - rb2d.velocity);
rb2d.AddForce(impulse, ForceMode2D.Impulse);
}
Incorporating drag is the tricky part. I figured that as drag affects the velocity of the object exponentially, so maybe the force required to overtake drag at different points can be calculated and applied in the initial force. But I am not exactly sure.