Hey!!
New user here but been around the website for a while, usually just reading articles and tutorials.
Anyways! I'm stuck and I need help with an exercise I'm doing. I am reading a book called Mathematics and Physics for Programmers (2nd edition), currently at the very end of chapter 7, exercise 7.2.
This is the only exercise I'm struggling to work out. I'm using the following formula to calculate the position of the ball at time t: (the length is the cannon's length, the velocity is the speed)
[ (length + time * velocity)cosθ, (length + time * velocity)sinθ - gravity * time ^ 2 / 2 ]
I am calculating the time t by using the following formula: (let u = speed)
t = u sin(θ) + sqrt(u^2 * sin(θ)^2 + 20 * length * sin(θ) / 10
I am currently hard coding the angle (θ) to 30° because I can't seem to be able to calculate the 'best angle' at which to aim the cannon so as to hit the point. The author recommends to use an approximation method to approach the solution iteratively:
QuoteYou can start by creating a function that tests whether the current aim is high or low (by working out the ball’s y position when its x position is p1). This function should return 1 for high, −1 for low, and 0 for a hit or close to it. Notice first of all that if you aim the cannon directly at the target point, it will always fall short. If you use this angle as your baseline, then work up in increments until you find a firing angle that is aiming high. You can then use a simple binary approximation method to find the solution.
I just didn't understand how...
Here is my attempt so far:
#define GRAVITY 9.81
struct Vector2D
{
double m_X;
double m_Y;
};
double aimCannon(double cannonLength, double muzzleSpeed, Vector2D aimPoint)
{
double Time = 0.0;
double AngleTheta = 0.523599; // Equivalent to 30 degrees in radians
Time = (muzzleSpeed * sin(AngleTheta) + (sqrt(pow(muzzleSpeed, 2) * pow(sin(AngleTheta), 2) + 20 * cannonLength * sin(AngleTheta)))) / 10;
Vector2D aimPoint;
aimPoint.m_X = (cannonLength + (Time * muzzleSpeed)) * cos(AngleTheta);
aimPoint.m_Y = (cannonLength + (Time * muzzleSpeed)) * sin(AngleTheta) - (GRAVITY * pow(Time, 2)) / 2;
return 0;
}
int main()
{
Vector2D tempAimCoords;
double Speed = 20;
double CannonLength = 2.0;
tempAimCoords.m_X = 10.0f; tempAimCoords.m_Y = 15.0f;
aimCannon(CannonLength, Speed, tempAimCoords);
return 0;
}
My function doesn't return an angle yet..
I appreciate any guidance as I seem a bit lost and confused
Thanks and sorry for the lengthy post.