Phippre
Phippre

Reputation: 53

Shooting bullet towards mouse position in Java/Slick2D

I'm trying to implement a method for shooting a bullet towards the mouse position. I don't know the math or the logic for it. It's a 2D top-down game. I have the bullet firing to the right and ending at a certain point. I need to know the logic for firing towards the mouse position, rather than just adding 1 to the x position.

Upvotes: 1

Views: 3685

Answers (2)

Phippre
Phippre

Reputation: 53

This is my code for spawning the projectiles.

    public void spawnProjectile(Input input) {

    double mouseX = 0;
    double mouseY = 0;
    double xVel;
    double yVel;
    double angle;

    if (timer > 0) {
        timer--;
    }

    if (input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON)) {
        mouseX = input.getMouseX();
        mouseY = input.getMouseY();
        if (projectiles.size() < 1 && timer <= 0) {
            projectiles.add(new Projectile((int) x + 8, (int) y + 8, 8, 8));
        }
    }

    if (projectiles.size() > 0) {
        for (int i = 0; i < projectiles.size(); i++) {
            projectiles.get(i).update(input);
            double originX = x;
            double originY = y;

            angle = Math.atan2(mouseX - originX, mouseY - originY);
            xVel = (bulletVel) * Math.cos(angle);
            yVel = (bulletVel) * Math.sin(angle);

            projectiles.get(i).x += xVel;
            projectiles.get(i).y += yVel;

            if (projectiles.get(i).timer == 0) {
                projectiles.remove();
            }
        }
    }
}

Upvotes: 0

Casey Price
Casey Price

Reputation: 778

Use atan2 to find the angle between the origin of the bullet and the mouse cursor. Then use Sin and Cos to calculate the x and y velocity of the bullet.

psuedo-code

    public void ShootBullet()
    {
        double bulletVelocity = 1.0; //however fast you want your bullet to travel
        //mouseX/Y = current x/y location of the mouse
        //originX/Y = x/y location of where the bullet is being shot from
        double angle = Math.Atan2(mouseX - originX, mouseY - originY);
        double xVelocity = (bulletVelocity) * Math.Cos(angle);
        double yVelocity = (bulletVelocity) * Math.Sin(angle);
    }

Upvotes: 4

Related Questions