Time to fix that!
Explosionade is our next game, and it features lots of grenades and plenty of explosions. We'll have the official announcement shortly, but I wanted to pull some physics-y code from it for your use!
Here's my game-ready grenade velocity function. It's simple parabolic motion, straight out of wikipedia, but for some reason, sometimes, I'm too lazy too even look that up and rework the equation! So I reworked it for you (and my lazy future-self, when I need it again).
Here's some C# code for the equation.
// targetPos is what you want to hit
// throwPos is where the grenade starts
// Tweak flyTime to make the grenade take longer or shorter to get there
// This simple returns the velocity at which to throw the grenade, and your target is toast!
static float flyTime= 2.0f;
protected Vector2 ThrowGrenadeVel(Vector2 targetPos, Vector2 throwPos)
Vector2 diff = (targetPos - throwPos);
startVel.X = (diff.X) / travelTime; // we don't factor in gravity for X
|The player mech on the left anticipates a grenade hit from the enemy Horronyms on the right. Horronyms conveniently have three arms, two for holding their gun, one for throwing grenades, natch.|
Simple enough, it uses s = s0 + v0t + 1/2at^2 but reworks it for the initial velocity (v0) here. You just need to have your Grenade.gravityY specified as static public float in your Grenadeclass (or whatever you're using there). I used a gravityY of about 500.0f. Two seconds felt pretty good, giving the player some time to dodge it or shoot it in Explosionade. But you can tweak the flyTime to take longer or shorter. Be aware this does no checking for ceilings, or walls. You'll have to do line of sight tests for those.
If you use the equation and have any problems just leave a comment. Good luck throwing!