Calculate dash distance before dash?

Hey!

Is it possible to calculate the exact distance for a dash, so that you can check if the player would dash against a wall before he/she actually performs the dash?

My code for the dash looks like this (adding a force for a certain amount of time):

        if(currentForceTime > 0f)
        {
            currentForceTime -= Time.fixedDeltaTime;
            rb.velocity = new Vector2(forceDirection.x * forceAmountHorizontal, forceDirection.y * forceAmountVertical) * Time.fixedDeltaTime;
        }

Thanks already for answers!

You could Raycast to see where it might hit the wall.

You should generally avoid mixing terms. Velocity has a very specific meaning, Force has a very specific meaning.

You’re NOT “adding a force” above.

What is actually happening is that you named many variables using the word “force” (forceDirection, forceAmountVertical and forceAmountHorizontal) but you are using them to set a velocity.

I suggest instead perhaps replacing force with dash in the above variables, as this far more accurately captures what you are doing.

yea, ive done it a few times. The basic idea requires some basic knowledge in physics, and maybe some calculus if your functions are more complex. for your case, you have v(t), the velocity as a function of time. you want to calculate how much distance the object will cover in T time, where T = total time applying the force.

Technical approach with calculus:
The change in position between time=0 and time=T is the integral of the velocity function between time=0 and time=T.

Simple explanation:
“the integral” is just the area under a curve or line between 2 points. your velocity function is linear (just a line without curves), so calculating the area under it is simple geometry (area of triangle and rectangle).

lets say r = new Vector2(forceDirection.x * forceAmountHorizontal, forceDirection.y * forceAmountVertical)
and R = the magnitude of r
so v(t) = r * t, or Speed(t) = R * t
you should find the area under that line (or integral) to be equal to 0.5 * R * T * T

I simplified it a bit by assuming the velocity increases with time, rather than decreases, but it should only really affect if your number is positive or negative. Hope this makes one person hate calculus a little bit less :slight_smile:

Also theres another simple method you could use for your example, since the velocity function is linear.

let v_average = (v_start + v_final) / 2 = (0 + (R * T)) / 2
so v_average = 0.5 * R * T

you can just pretend that the velocity is a constant v_average between the times with v_start and v_final, and not a function of time.
distance = rate * time //velocity is our ‘rate’
so distance = v_avg * time_dashing = (0.5 * R * T) * T