Firing bullet from gun's current position to mouse x & y position

Please help I’m kinda lost in my coding.

So I’ve created a bullet class:

package javagame.states;

import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Vector2f;
import org.newdawn.slick.state.StateBasedGame;

public class Bullet {

    private Vector2f pos;
    private Vector2f speed;
    private int lived = 0;

    private boolean aktiv = true;

    private static int MAX_LIFETIME = 2000;

    public Bullet (Vector2f pos, Vector2f speed){
        this.pos = pos;
        this.speed = speed;
    }

    public Bullet(){
        aktiv = false;
    }

    public void update(int t){

        rotation++;

        if(aktiv){
            Vector2f realSpeed = speed.copy();
            realSpeed.scale((t/1000.0f));
            pos.add(realSpeed);

            lived += t;
            if(lived > MAX_LIFETIME) aktiv = false;
        }
    }

    public void init(GameContainer gc, StateBasedGame sbg) throws SlickException{
    }

    public void render(GameContainer gc, Graphics g) throws SlickException {

        if(aktiv){
            g.setColor(Color.red);
            g.fillOval(pos.getX(), pos.getY(), 10, 10);
        }
    }

    public boolean isAktiv(){
        return aktiv;
    }
}

then called the bullet class here in my robot class:

package javagame.states;

import java.util.Iterator;
import java.util.LinkedList;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Vector2f;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;

public class Robot2 extends BasicGameState{

    private LinkedList<Bullet> bullets;

    @Override
    public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
        bullets = new LinkedList<Bullet>();
    }

    @Override
    public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
        for(Bullet b : bullets){
            b.render(gc, g);
        }       
    }

    @Override
    public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
        Iterator<Bullet> i = bullets.iterator();
        while(i.hasNext()){
            Bullet b = i.next();
            if(b.isAktiv()){
                b.update(delta);
            }else{
                i.remove();
            }
        }

        Input input = gc.getInput();
        int mouseX = input.getMouseX();
        int mouseY = input.getMouseY();

        int xDistance = (int) (RobotX() + Robotwidth() / 2 - mouseX); //RobotX is the robot image x position same to RobotY
        int yDistance = (int) (RobotY() + Robotheight() / 2 - mouseY);
        double angleToTurn = Math.toDegrees(Math.atan2(yDistance, xDistance));

            if(mouseX != 0){
            angleToTurn += 270;
            }else{
            if(mouseY != 0)
            angleToTurn += 180;
            }
            robot.setRotation((float) angleToTurn); //robot is an image. didn't included the code here to shorten my codes

                if(gc.getInput().isMousePressed(Input.MOUSE_LEFT_BUTTON)){
            bullets.add(new Bullet(new Vector2f(Sprites.getRobotX(), Sprites.getRobotY()), new Vector2f(mouseX, mouseY)));
        }
    }

    @Override
    public int getID() {
        return States.ROBOT;// has an integer value
    }

}

The robot is rotating perfectly according to mouse’s cursor movement but when I hit the mouse’s left button to fire a bullet, it doesn’t follow the mouse’s cursor location. This is what I’ve got when i run these codes and pressing the left button of my mouse. Please check my sample image.

http://s12.postimg.org/kwsr41p71/Untitled_1.jpg

What I want to achieve is to correct the direction of the bullet according to mouse cursor location.

Any help would be greately much appreciated. Thank you very much.

This question has been asked numerous times before, I suggest you use the search bar in the top right before you create a topic next time!
Anyways, here’s a link to a topic with a good answer. Best of luck.

http://www.java-gaming.org/topics/creating-projection-of-a-projectile-using-linear-algebra/28310/msg/256834/view.html

this might help you this is my projectile class it works fine!

package com.zgr.Projectile;

import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.Random;
import java.util.Vector;

import com.zgr.Traps.ProjectileLauncher.ProjectileType;
import com.zgr.assets.Map;
import com.zgr.assets.Vector2F;
import com.zgr.tile.Tile;

public class Projectile extends Rectangle{

	final int width = 8;
	final int height = 8;
	
	ProjectileType type;

	float timeStep=60f/60f;
	
	float turretX=0f;
	
	float turretY=0f;
	
	float bulletSpeed;
	
	float bulletX;
	float bulletY;
	
	boolean isAlive;
	/*
	 * Fix The Detection Radius For the Projectile Trap
	 * Fix 2 Networking tutorials
	 * Fix So Projectile Shoots the bullets past player if thay dont hit
	 * Fix So Projectiles Rotate!
	 */

	public Projectile(float startX, float startY, float bulletSpeed, ProjectileType type) {
		isAlive = true;
		turretX = startX;
		turretY = startY;
		bulletX=turretX;
		bulletY=turretY;
		
		Random ran = new Random();
		int random = ran.nextInt(200);
		if(random > 150){
			bulletSpeed = random;
		}
		
		dirX = (float) (Map.player.xpos + 12 + Map.xOffset - turretX);
		dirY = (float) (Map.player.ypos + Map.yOffset - turretY);
		setBounds((int) (bulletX - Map.xOffset), (int) (bulletY - Map.yOffset), width, height);
		this.bulletSpeed = bulletSpeed;
		this.type = type;
	}
	
	public void render(Graphics2D g){
		if(isAlive){
			
			switch(type){
			
				case BOX:
					g.drawRect((int) (bulletX - Map.xOffset),(int) (bulletY - Map.yOffset), width, height);
				break;
				case ROUND:
					g.drawOval((int) (bulletX - Map.xOffset),(int) (bulletY - Map.yOffset), width, height);
				break;
			}
			
		}
		
	}
	float dirX;
	float dirY;
	public void tick(double deltaTime){
		if(isAlive){
			setBounds((int) (bulletX - Map.xOffset), (int) (bulletY - Map.yOffset), width, height);
			
			float dirLength= (float) Math.sqrt(dirX*dirX + dirY*dirY);
			dirX=dirX/dirLength;
			dirY=dirY/dirLength;
			
			bulletX=bulletX+(dirX*bulletSpeed*timeStep);
			bulletY=bulletY+(dirY*bulletSpeed*timeStep);
			
		}
	}

	public void setAlive(boolean b) {
		isAlive = b;
	}
	
	public boolean isAlive() {
		return isAlive;
	}
	
}

This should actually be in the Newbie & Debugging board. Now what VIrtueeL works great but if you know anything of vector math, you can get the job done a lot easier like this:


public class Bullet {

     Vector2d pos;
     Vector2d dir;

     public Bullet(int x, int y) {
          pos = new Vector2d(x, y);
          dir = new Vector2d(new Vector2d(mousex, mousey).sub(pos).normalise());
     }

     public void render() {
          // Render bullet at pos.x and pos.y
     }

     public void update() {
          pos.add(dir); // Moves position to direction aka mouse. To have the bullet follow the mouse like a homing missle you would have to constantly keep updating the dir vector
     }

}

That should do it. By the way, I used to use Java2D. I actually made a complete game out of it, however, I wouldn’t recommend it in the long term. It’s just not made for games IMO. I’m sure your mind set is if I use a library I’m cheating, right? Well I’m here to tell you, all of us on this forum use libraries. It’s not cheating, It’s just being efficient. So I recommend you go and check out these 2 great libraries:

Slick2D: (This is where I went to after leaving J2D and still use it now)
Download
Beginner Tutorials

LibGDX: (Cross-platform support and apparently super easy (I find it confusing but I’m an idiot so ::slight_smile: ))
Download
Beginner Tutorials

Good luck! Choose wisely! :wink: