• ### What is your GameDev Story?

Public Group

This topic is 4974 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Currently I'm trying to create a basketball game. My main problem is with shooting. I want to make it so the ball travels the same speed to the basket no matter what angle it's shot at. My main problem is that the ball goes different speeds right now based on the angle. My code like look this.
void findtarget(double x, double y)
{
double tempx;
double tempy;
double xdifference;
double ydifference;
double modifier;

xdifference=abs(930-x);
ydifference=abs(369-y);
if(x>y)
{
if(ydifference==0)
{
xvel=2;
yvel=0;
return;
}

tempy=xdifference/ydifference;
modifier=30/(1+((xdifference*xdifference)/(ydifference*ydifference)));
yvel=modifier;
xvel=modifier*tempy;
if(x>930)
xvel=-xvel;
if(y>369)
yvel=-yvel;

}
else
{
if(xdifference==0)
{
xvel=0;
yvel=2;
return;
}

tempx=ydifference/xdifference;
modifier=30/(1+((ydifference*ydifference)/(xdifference*xdifference)));
yvel=modifier;
xvel=modifier*tempx;
if(x>930)
xvel=-xvel;
if(y>369)
yvel=-yvel;

}



##### Share on other sites
Trigonometry. I couldn't make heads or tails of you code, but that's because I don't know how you're trying to solve it.

Choose your velocity. Know the angle you're going to shoot at. Then finding the x veloicty and the y velocity are easy.

          /|         / |        /  |     V /   |      /    | Y     /     |    /      | A /_______|       X

A = angle of shot.
V = Velocity
X = X Veloctiy
Y = Y Velocity

You remember Sin and Cos, right? Sin(A) = Y/V, Cos(a) = X/V.

Since We're solving for Y and X, we end up using the following formulas:

X = V*Cos(a)
Y = V*Sin(a)

So as long as you know your velocity and angle, you can move a ball along that path by finding the X and Y velocities as stated above.

##### Share on other sites
Thanks that works a lot better and is a lot less code.

##### Share on other sites
In your code it seems your modifying the varible xvel (I assume thats representing the speed of the ball), instead of modifying it, make it a constant. Once you know what xvel is, the only question is how high (yvel) the ball has to go in order to reach the basket.

I'm thinking you need to figure out the distance betwen the launch point and the basket. Figure out how many times xvel goes into that distance, so time = distance/xvel. You then need to figure out how much the yvel should be, based on your system of gravity, so that the y position of the ball will be the height of the basket when timeelapsed = time.

Hope I understood what you're trying to do.

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 9
• 34
• 16
• 11
• 10
• ### Forum Statistics

• Total Topics
634122
• Total Posts
3015644
×