Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am using gravity in a 2d environment for my game. The objects I use in my game all have x and y coordinates, they can be "thrown" into a level, meaning instantiated, then given a specific origin location and then given new coordinates each frame with the following gravity:

public void throwObject(float delta) {
    setX(getX() + velocity.x * delta);
    setY(getY() + velocity.y * delta);

velocity.y += gravity.y * delta;
}

with the following:

Vector2 GRAVITY = new Vector2(0, -10);     

From a given originx and originy, the objects "move" accordingly, this works well.

Now I would like to make the objects move to a a given destination, for example at:

destinationx = 50; 
destinationy = 350;

If I use a static origin x and originy, how can I calculate velocity.x and velocity.y so that the object is thrown with a projectile curve to the specified destination coordinates?

Edit: I have made some progress determining the calculation for velocity.x:

 velocity.x = (destinationx - originx) / 100; 

where 100 is the number of frames I have set as static. This works well.

For velocity.y, I have tried:

velocity.y = (destinationy - originy) / 100 * delta + Math.sqrt(gravity) * 2;

it gives a result that looks close from the right formula, but not exactly it

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
137 views
Welcome To Ask or Share your Answers For Others

1 Answer

First of all: There are infinitely many solutions. Including the "trivial" one, where the velocity is just the difference of the source and the target position, divided by "delta" (that is, the solution where the target would be reached in a single step, due to the velocity being "infinitely high").

But one intuitively can imagine what you want to achieve, so I'll stop nitpicking:

You want to specify the velocity in cartesian coordinates: (deltaX, deltaY). It is more convenient to think of this velocity in terms of polar coordinates: (angle, power), where "power" represents the magnitude of the initial velocity. (For conversion rules, see Wikipedia: Polar coordinate system).

Given a fixed initial velocity, there are either zero, one or two angles where the projectile will hit the target. Given a fixed initial angle, there may either be zero or one initial velocity where the projectile will hit the target. But if you can choose both, the velocity and the angle, then there is an infinite number of ballistic trajectories starting at the origin and passing through the target.

I slightly extended a Projectile Shooter example from one of my previous answers, using some of the formulas from wikipedia, mainly from Wikipedia: Trajectory of a projectile:

image

You can use the sliders to change the angle and the power, and use the mouse to drag the origin and the target. The text contains two important outputs:

  • Required angle: These are the two shooting angles at which the target may be hit, assuming that the power is not modified. If there is no solution (for example, when the target is out of range, regardless of the angle), then these angles may be NaN.
  • Required power: This is the power that is required for hitting the target, assuming that the angle is not modified. If there is no solution (for example, when the current angle simply points into the wrong direction), then this power may be NaN.

Depending on the degrees of freedom that you would like for your velocity, you may probably extract the relevant formulas. (Apologies for the missing comments, this "SSCCE" (Short, Self Contained, Compilable, Example) has gradually turned into a "LSCCE"...)

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class ProjectileShooterTest
{
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI()
    {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final ProjectileShooter projectileShooter = 
            new ProjectileShooter();
        final ProjectileShooterPanel projectileShooterPanel = 
            new ProjectileShooterPanel(projectileShooter);
        projectileShooter.setPaintingComponent(projectileShooterPanel);

        ProjectileShooterMouseControl mouseControl = 
            new ProjectileShooterMouseControl(
                projectileShooter, projectileShooterPanel);
        projectileShooterPanel.addMouseMotionListener(mouseControl);
        projectileShooterPanel.addMouseListener(mouseControl);

        JPanel controlPanel = new JPanel(new GridLayout(1,0));

        controlPanel.add(new JLabel("Angle: ", SwingConstants.RIGHT));
        final JSlider angleSlider = new JSlider(0, 180, 45);
        angleSlider.addChangeListener(new ChangeListener()
        {
            @Override
            public void stateChanged(ChangeEvent e)
            {
                int angleDeg = angleSlider.getValue();
                projectileShooter.setAngle(Math.toRadians(angleDeg));
            }
        });
        controlPanel.add(angleSlider);

        controlPanel.add(new JLabel("Power:", SwingConstants.RIGHT));
        final JSlider powerSlider = new JSlider(0, 50, 25);
        controlPanel.add(powerSlider);
        powerSlider.addChangeListener(new ChangeListener()
        {
            @Override
            public void stateChanged(ChangeEvent e)
            {
                int power = powerSlider.getValue();
                projectileShooter.setPower(power);
            }
        });

        JButton shootButton = new JButton("Shoot");
        shootButton.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                projectileShooter.shoot();
            }
        });
        controlPanel.add(shootButton);

        f.getContentPane().setLayout(new BorderLayout());
        f.getContentPane().add(controlPanel, BorderLayout.NORTH);
        f.getContentPane().add(projectileShooterPanel, BorderLayout.CENTER);
        f.setSize(1200,800);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }
}

class ProjectileShooterMouseControl 
    implements MouseListener, MouseMotionListener
{
    private final ProjectileShooter projectileShooter;
    private final ProjectileShooterPanel projectileShooterPanel;

    private boolean draggingOrigin = false;
    private boolean draggingTarget = false;

    ProjectileShooterMouseControl(
        ProjectileShooter projectileShooter, 
        ProjectileShooterPanel projectileShooterPanel)
    {
        this.projectileShooter = projectileShooter;
        this.projectileShooterPanel = projectileShooterPanel;
    }

    private Point2D toWorld(Point2D screen)
    {
        return new Point2D.Double(screen.getX(), 
            projectileShooterPanel.getHeight() - screen.getY());
    }

    @Override
    public void mouseMoved(MouseEvent e)
    {
    }

    @Override
    public void mouseDragged(MouseEvent e)
    {
        Point2D p = toWorld(e.getPoint());
        if (draggingOrigin)
        {
            projectileShooter.setOrigin(p);
        }
        else if (draggingTarget)
        {
            projectileShooter.setTarget(p);
        }
    }

    @Override
    public void mousePressed(MouseEvent e)
    {
        Point2D p = toWorld(e.getPoint());

        Point2D origin = projectileShooter.getOrigin();
        Point2D target = projectileShooter.getTarget();
        if (origin.distance(p) < 10)
        {
            draggingOrigin = true;
        }
        else if (target.distance(p) < 10)
        {
            draggingTarget = true;
        }
    }

    @Override
    public void mouseReleased(MouseEvent e)
    {
        draggingOrigin = false;
        draggingTarget = false;
    }

    @Override
    public void mouseClicked(MouseEvent e)
    {
    }

    @Override
    public void mouseEntered(MouseEvent e)
    {
    }

    @Override
    public void mouseExited(MouseEvent e)
    {
    }

}


class ProjectileShooter
{
    private static final double TIME_SCALE = 20;
    static final double GRAVITY = 9.81 * 0.1;

    private double angleRad = Math.toRadians(45);
    private double power = 25;

    private final Point2D origin = new Point2D.Double(50, 50);
    private final Point2D target = new Point2D.Double(500, 100);

    private Projectile projectile;
    private JComponent paintingComponent;

    void setPaintingComponent(JComponent paintingComponent)
    {
        this.paintingComponent = paintingComponent;
    }

    void setOrigin(Point2D origin)
    {
        this.origin.setLocation(origin);
        this.paintingComponent.repaint();
    }

    Point2D getOrigin()
    {
        return new Point2D.Double(origin.getX(), origin.getY());
    }

    void setTarget(Point2D target)
    {
        this.target.setLocation(target);
        this.paintingComponent.repaint();
    }

    Point2D getTarget()
    {
        return new Point2D.Double(target.getX(), target.getY());
    }

    void setAngle(double angleRad)
    {
        this.angleRad = angleRad;
        this.paintingComponent.repaint();
    }

    double getAngle()
    {
        return angleRad;
    }


    void setPower(double power)
    {
        this.power = power;
        this.paintingComponent.repaint();
    }

    double getPower()
    {
        return power;
    }

    double computeY(double x)
    {
        // http://de.wikipedia.org/wiki/Wurfparabel
        //  #Mathematische_Beschreibung
        double g = GRAVITY;
        double b = angleRad;
        double v0 = power;
        if (b > Math.PI / 2)
        {
            b = Math.PI - b;
        }
        double cb = Math.cos(b);
        return x * Math.tan(b) - g / (2 * v0 * v0 * cb * cb) * x * x;
    }

    double computeRange(double h0)
    {
        // http://de.wikipedia.org/wiki/Wurfparabel
        //  #Reichweite_bei_von_Null_verschiedener_Anfangsh.C3.B6he
        double g = GRAVITY;
        double b = angleRad;
        double v0 = power;
        double sb = Math.sin(b);
        double f0 =(v0 * v0) / (g + g) * Math.sin(b + b);
        double i = 1.0 + (2 * g * h0) / (v0 * v0 * sb * sb);
        double f1 = 1.0 + Math.sqrt(i);
        return f0 * f1;
    }

    Point2D computeRequiredAngles()
    {
        // http://en.wikipedia.org/wiki/Trajectory_of_a_projectile
        //  #Angle_required_to_hit_coordinate_.28x.2Cy.29
        double v0 = power;
        double g = GRAVITY;
        double vv = v0 * v0;
        double dx = target.getX() - origin.getX();
        double dy = target.getY() - origin.getY();
        double radicand = vv * vv - g * (g * dx * dx + 2 * dy * vv);
        double numerator0 = vv + Math.sqrt(radicand);
        double numerator1 = vv - Math.sqrt(radicand);
        double angle0 = Math.atan(numerator0 / (g*dx));
        double angle1 = Math.atan(numerator1 / (g*dx));
        return new Point2D.Double(angle0, angle1);
    }

    double computeRequiredPower()
    {
        // WolframAlpha told me so...
        double R = target.getX() - origin.getX();
        double h0 = origin.getY() - target.getY();
        double g = GRAVITY;
        double b = angleRad;
        double sb = Math.sin(b);
        double isb = 1.0 / sb;
        double v0 = 
            Math.sqrt(2) * Math.sqrt(g) * R * 
            Math.sqrt(1 / Math.sin(2*b)) /
            Math.sqrt(h0 * Math.sin(2*b) * isb * isb + 2*R);
        return v0;
    }



    void shoot()
    {
        Thread t = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                executeShot();
            }
        });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...