Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am making a game which needs an "arrow" to be shot from a stationary location (a set coordinate). The arrow's trajectory is based on the location that the user Clicks in the GUI. This is essentially an Aiming feature. I cant get the arrow to follow a working path, any equations ie used have led to weird, glitchy, and buggy results.

Java
public class ReShoot implements ActionListener
{
    public void actionPerformed(ActionEvent e){
        ArrowShoot shoot = new ArrowShoot();
        shoot.ReShoot();
    }
}
public class ArrowShoot implements ActionListener
{
    public Timer T = new Timer(5, this);
    Arrow A = new Arrow();


    public void ReShoot(){
        T.start();
        arrow_x=0;
        arrow_y=200;
        A.setBounds(0,200,10,10);
    }
    // MAIN: y=-16t^2 + Vy * t + h
    //Vy = v * sin(a)
    //Vx = v * cos(a)
    //a = arctan( (200-mouse_y)/v
    //v = Mouse_x - Arrow_x
    //t = x / Vx


    public void actionPerformed(ActionEvent e)
    {//arrow_y = 0.0025 * Math.pow((mouse_x-arrow_x), 2)+ mouse_y;
        Container container_arrow = getContentPane();
        container_arrow.setLayout(null);
        container_arrow.add(A);
        A.setBounds(0,200,10,10);
            arrow_x++;

            double v = mouse_x/2; //height change
            double a = 50* Math.atan((200-mouse_y) / (v)); 
            double Vy = v * Math.sin(a);
            double Vx = v * Math.cos(a);
            double t = arrow_x/Vx;
            double h = 200;

            arrow_y = (16) * Math.pow(t, 2) + (Vy * t) + h;

            int x = (int)Math.round(arrow_x);
            int y = (int)Math.round(arrow_y);
            A.setBounds(x, y,10,10);
        if (arrow_y>=500)
            T.stop();

    }

I am pretty sure im doing this all wrong, and there has to be a more effective method to accomplish this task.
Posted
Updated 20-May-15 8:47am
v2

1 solution

You are not even trying to calculate the trajectory/timing of the motion. "Weird" and "glitchy" motion may exist in your code, but not in reality.

In first approximation, the motion of the projectile is described by simple equation: motion with constant acceleration (Earth gravity, in this case):
x = x0 + vx*t;
y = y0 + vy*t + g*t2;
You correctly calculate components of the speed from the angle.

Isn't it obvious?! And in next approximation, you can try to take into account the air resistance. In analytic calculation, it may look difficult, but you can simply model the motion numerically, point to point.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900