Java Game Programming - aiming bullets

How to aim bullets in Java

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 10106 Views - Last Post: 10 March 2010 - 03:31 PM Rate Topic: -----

#1 sfoulk526  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 02-March 10

Java Game Programming - aiming bullets

Posted 02 March 2010 - 03:30 PM

Aloha all,
I am currently working on a Java game (very asteroids like) where I have to fire bullets at items floating in space. I have the code working pretty well except for the bullets. I created a Bullet object, and I can fire the bullets and keep updating them, but they do not go to where I am aiming at.
I am using a crosshair mouse cursor for the target, sending the coordinates of the cursor at the time of the mouse left click, I have a tracking Vector structure which works very well after a lot of hard work, but once fired I am not certain how to get the bullets to go in a straight line to the point at which I am aiming.

Here's my Bullet Class:

public class Bullet {

private int xLocation; // Current pixel x coord
private int yLocation; // Current pixel y coord
private int xTarget; // Target pixel x coord
private int yTarget; // Target pixel y coord
private int range; // How far the bullet has traveled
private int maxRange; // Maximum range (I want bullet to disappear after reaching certain distance
private int damagePoints;
private int seekingTarget; // Later incarnations will use this
private int xSpeed; // Pixel increments per cycle - x
private int ySpeed; // Pixel increments per cycle - y
private boolean alive; // Flag - if past range, no longer alive and bullet disappears


I have all the get/sets required for these fields. I am not certain how to aim. I am not asking for code, just a few clues. I can do the work, but am relatively new to Java in Game programming.

Please help!
Thanks,

Scott Foulk
IGD (in the works)
;-)

Is This A Good Question/Topic? 0
  • +

Replies To: Java Game Programming - aiming bullets

#2 Dogstopper  Icon User is online

  • The Ninjaducky
  • member icon



Reputation: 2860
  • View blog
  • Posts: 10,964
  • Joined: 15-July 08

Re: Java Game Programming - aiming bullets

Posted 02 March 2010 - 03:39 PM

Well, this is relatively simple geometry. When the bullet is instantiated, if the tagetX is less than the currentX, set speedX to decrement (By 1, 2, or 3, 4, ...), just make sure the x is negative so that it will go left. Also, you may need the tangent (or slope), so that you can determine how sharply to go.

If the targetX is greater than currentX, then move right at a specified speed. That should be the same as above, just positive number.

However, if the number of pixels to move needs to be 1/2, then what you should do is make the ySpeed larger. It's really a matter of simple trig. Tangents will undoubtedly be very important here.

Now that you have your xSpeed and ySpeed, all you have to do is update it every loop.
Was This Post Helpful? 1
  • +
  • -

#3 sfoulk526  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 02-March 10

Re: Java Game Programming - aiming bullets

Posted 03 March 2010 - 05:09 PM

View PostDogstopper, on 02 March 2010 - 02:39 PM, said:

Well, this is relatively simple geometry. When the bullet is instantiated, if the tagetX is less than the currentX, set speedX to decrement (By 1, 2, or 3, 4, ...), just make sure the x is negative so that it will go left. Also, you may need the tangent (or slope), so that you can determine how sharply to go.

If the targetX is greater than currentX, then move right at a specified speed. That should be the same as above, just positive number.

However, if the number of pixels to move needs to be 1/2, then what you should do is make the ySpeed larger. It's really a matter of simple trig. Tangents will undoubtedly be very important here.

Now that you have your xSpeed and ySpeed, all you have to do is update it every loop.

Was This Post Helpful? 0
  • +
  • -

#4 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10194
  • View blog
  • Posts: 37,646
  • Joined: 27-December 08

Re: Java Game Programming - aiming bullets

Posted 03 March 2010 - 05:13 PM

When you post code, don't forget to :code:
It makes it a lot easier for us to read your code. Thanks for helping us help you! :)
Was This Post Helpful? 0
  • +
  • -

#5 Dogstopper  Icon User is online

  • The Ninjaducky
  • member icon



Reputation: 2860
  • View blog
  • Posts: 10,964
  • Joined: 15-July 08

Re: Java Game Programming - aiming bullets

Posted 03 March 2010 - 05:19 PM

@, did you want to ask something? you just sort of quoted my post...
Was This Post Helpful? 0
  • +
  • -

#6 sfoulk526  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 02-March 10

Re: Java Game Programming - aiming bullets

Posted 03 March 2010 - 05:31 PM

Thanks Dogman - let me try this out. Here's what I have so far:
I have the sections quadrant'ed out -


-x -y-------- =x -------- +x -y
..............|..............
..............|..............
..............|..............
=y -----------S-------------- =y
..............|..............
..............|..............
..............|..............
-x +y ------- =x ---------+x +y


Quad 1 = -x -y
Quad 2 = -x +y
Quad 3 = +x +y
Quad 4 = +x -y
(counterclockwise, relative to my ship, S)

Now, since we are originating from the upper left corner with Y positive downwards,
I believe that I have to change my coords to cartesian system
y = height_in_pixels - y to get the standard cartesian coord system.
x s/b the same because it still grows larger from left to right

slope = shipY-targetY/shipX-targetX = tan (theta)

Distance = Math.sqrt(Math.pow((shipX-targetX),2) + Math.pow((shipY-targetY),2))

With me so far?

So, with this info, how come I cannot get the damn bullets to go toward a target properly?

I'm a little frustrated, though it is relative. It's way more fun doing Java games and being frustrated than being at work with embedded systems and being frustrated. Much less hair loss my friend!

;-)

Thanks again for your assistance. I will one day return the favor. I am relatively new to the Java game programming, but am a quick learner. I just found this site and am loving being a new D.I.C. Head!

This post has been edited by sfoulk526: 03 March 2010 - 05:38 PM

Was This Post Helpful? 0
  • +
  • -

#7 Dogstopper  Icon User is online

  • The Ninjaducky
  • member icon



Reputation: 2860
  • View blog
  • Posts: 10,964
  • Joined: 15-July 08

Re: Java Game Programming - aiming bullets

Posted 03 March 2010 - 05:49 PM

Why can't it? Well...that a super great question. Well, I don't know how you implemented it, but you have to set a specific xSpeed and ySpeed and every game loop, change the current ship's coordinates relative to the speed. Since I am still in high school and in trig right now, I am not altogether too knowledgeable about HOW exactly to do this...

The only advice that I can give right now is to try changing the x and y speeds to see if your bullet is responding to known speeds and then attempting the trig. Sorry I can't be of more help.

By the way, yes, you are right, the screen increases in y as you move downward and increases in x as you move right. That's what's hindering me on this math! Though I am interested in knowing the solution, as I am making a shooter game right now too!

I hope a more math-savvy person can help you here.


But your welcome for the assistance, and I hope you continue to enjoy DIC!
Was This Post Helpful? 0
  • +
  • -

#8 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10194
  • View blog
  • Posts: 37,646
  • Joined: 27-December 08

Re: Java Game Programming - aiming bullets

Posted 03 March 2010 - 06:05 PM

@sfoulk526: Given that you probably don't know the angle of firing, it is better to stick with (y2-y1)/(x2-x1) formula for slope. Also, if you are doing asteroidsd, shouldn't the bullets be going in one direction- up? For that, when you create a bullet, just use the current (x,y) position of your ship and decrement y. However, if you want to use multiple directions, best to use the (x,y) position of some coordinate (possibly the center) of your ship in the slope calculations.

If you need more help, we will have to see your code. Good luck! :)

@Dogstopper: Off-topic, but are you in a Precalc/Trig/Math Analysis course designed to get you into AP Calculus next year or do you take the Precalc/Analysis course next year?
Was This Post Helpful? 0
  • +
  • -

#9 sfoulk526  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 02-March 10

Re: Java Game Programming - aiming bullets

Posted 06 March 2010 - 12:59 AM

View Postmacosxnerd101, on 03 March 2010 - 05:05 PM, said:

@sfoulk526: Given that you probably don't know the angle of firing, it is better to stick with (y2-y1)/(x2-x1) formula for slope. Also, if you are doing asteroidsd, shouldn't the bullets be going in one direction- up? For that, when you create a bullet, just use the current (x,y) position of your ship and decrement y. However, if you want to use multiple directions, best to use the (x,y) position of some coordinate (possibly the center) of your ship in the slope calculations.

If you need more help, we will have to see your code. Good luck! :)

@Dogstopper: Off-topic, but are you in a Precalc/Trig/Math Analysis course designed to get you into AP Calculus next year or do you take the Precalc/Analysis course next year?


Hmmm. I tried the slope, but my implementation did not work.

I have a moving ship (multi-direction) and I calculate relative to my center-of-ship position. I tried to break down the ratio of X to Y and splitting a maximum set of pixels.

For instance:

target location is at 1:00 o'clock, up (minus) 100 y-pixels, right (plus) 200 x-pixels. Therefore, if I allow a maximum of 30 pixels for speed, I divvy it up with 33% (10 pixels) of the speed going to the -Y direction, and 66% (20 pixels) going in the +X direction each cycle. First time the bullet is set, I set the trajectory, thereafter the speed remains constant until collision or reaching the display border.

Problem is, the bullet hits dead on sometimes and other times it misses by quite a few pixels. I have even drawn triangles with the rise over run so I can calculate it myself by hand.

This is the closest I've come to making it work, so I'm a bit frustated. The slope method did NOT work, but it may be I'm using the INT's instead of floats.

Please help. Show me how YOU would implement a bullet given source and target coordinates. I know it can be done, but I just can't figure it out from scratch, accurately anyway.

I would place my code up, but it's a bit confusing and pieces are in different spots within the program.

And hey, thanks for the help so far. I don't want you guys thinking I don't appreciate it. I do.
Was This Post Helpful? 0
  • +
  • -

#10 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10194
  • View blog
  • Posts: 37,646
  • Joined: 27-December 08

Re: Java Game Programming - aiming bullets

Posted 06 March 2010 - 04:56 AM

Quote

Show me how YOU would implement a bullet given source and target coordinates.


If you need help, we will be happy to help you debug code YOU wrote. However, we won't give out code without seeing a good faith effort.
Was This Post Helpful? 0
  • +
  • -

#11 sfoulk526  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 02-March 10

Re: Java Game Programming - aiming bullets

Posted 06 March 2010 - 07:44 AM

View Postmacosxnerd101, on 06 March 2010 - 03:56 AM, said:

Quote

Show me how YOU would implement a bullet given source and target coordinates.


If you need help, we will be happy to help you debug code YOU wrote. However, we won't give out code without seeing a good faith effort.


Okay then. I'll have to clean it up a bit but...

NOTE: bulletList is a type Vector full of bullets

// heres the calcs that set the trajectory
private void setTrajectory(int bullet_no){
		
		// Simplify so we don't have to write out the entire bulletList object for each field of Bullet
		int xTarget = bulletList.elementAt(bullet_no).getXTarget() - 3;  // -3 and -25 are adjusts for the cursor
		int yTarget = bulletList.elementAt(bullet_no).getYTarget() - 25;
		int xLocation = bulletList.elementAt(bullet_no).getXLocation();   // x and y Location are the bullet current position
		int yLocation = bulletList.elementAt(bullet_no).getYLocation();
		int maxSpeed = bulletList.elementAt(bullet_no).getMaxSpeed();    // This is split between the x & Y speeds
		// Get the quadrant -c counterclockwise from top left
		int quad = getCursorQuadrant(xTarget, yTarget);
		// Slope calculations
		// Determine DELTA X
		float xDelta   = Math.abs(xTarget - xLocation);
		// Determine DELTA Y
		float yDelta   = Math.abs(yTarget - yLocation);
		// Add them together
		float totalXY  = xDelta + yDelta;
		// Figure out the percentages so we know how much speed to place in X and Y
		xPercent = xDelta / totalXY;
		yPercent = 1 - xPercent;
		// Divide up the maximum speed - give X & Y their percentages of max speed
		xMove = (int) (xPercent * (float) maxSpeed);
		yMove = (int) (yPercent * (float) maxSpeed);

		// Losing speed on the smaller integer so add it back here
		if (xMove < yMove)
			xMove++;
		if (yMove < xMove)
			yMove++;
		
		// Now add or subtract based on the quadrant
		if (quad == 0)   // Upper left - Quad I  X- Y-
		{
			xMove = -Math.abs(xMove);
			yMove = -Math.abs(yMove);
		}
		else if (quad == 1)   // Lower left - Quad II  X- Y+
		{
			xMove = -Math.abs(xMove);
			yMove =  Math.abs(yMove);					
		}
		else if (quad == 2)   // Lower right - Quad III  X+ Y+
		{
			xMove = Math.abs(xMove);
			yMove = Math.abs(yMove);					
		}
		else if (quad == 3)   // Upper right - Quad IV  X+ Y-
		{
			xMove =  Math.abs(xMove);
			yMove =  -Math.abs(yMove);
		}
		
		
		bulletList.elementAt(bullet_no).setXSpeed(xMove);
		bulletList.elementAt(bullet_no).setYSpeed(yMove);
		// Set for later updates
		bulletList.elementAt(bullet_no).setXLocation(xLocation + xMove);
		bulletList.elementAt(bullet_no).setYLocation(yLocation + yMove);
		
		bulletList.elementAt(bullet_no).setAlive(false);
	}




Was This Post Helpful? 0
  • +
  • -

#12 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10194
  • View blog
  • Posts: 37,646
  • Joined: 27-December 08

Re: Java Game Programming - aiming bullets

Posted 06 March 2010 - 03:14 PM

I think you're doing a little too much of the work here, and not letting your computer do enough of it. First, you have your slope calculations off here, as slope = deltaY/deltaX, and deltaY and deltaX can be negative. Then given that, we can also use the slope formula y = mx+b to determine the position. I understand that you are trying to do this parametrically, but since you aren't relating your position equations to time, you should stick to slope.

float xDelta   = Math.abs(xTarget - xLocation); 
float yDelta   = Math.abs(yTarget - yLocation); 
float totalXY  = xDelta + yDelta; 
  
xPercent = xDelta / totalXY; 
yPercent = 1 - xPercent; 
  
xMove = (int) (xPercent * (float) maxSpeed); 
yMove = (int) (yPercent * (float) maxSpeed); 


I see what you are trying to do here with speed by accelerating as you travel towards your target. However, I'm not sure why you are dividing deltaX/(deltaX+deltaY). To me the formula for totalXY resembles the distance formula a little, which I don't know if that's what you're going for. Also, the xMove formula xPercent * maxSpeed could allow your bullet to travel past the target if it is at a short distance relative to max speed. Again, you should really relate everything back to x, making sure not to keep going if you hit a target.
Was This Post Helpful? 1
  • +
  • -

#13 sfoulk526  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 02-March 10

Re: Java Game Programming - aiming bullets

Posted 07 March 2010 - 02:57 PM

View Postmacosxnerd101, on 06 March 2010 - 02:14 PM, said:

I think you're doing a little too much of the work here, and not letting your computer do enough of it. First, you have your slope calculations off here, as slope = deltaY/deltaX, and deltaY and deltaX can be negative. Then given that, we can also use the slope formula y = mx+b to determine the position. I understand that you are trying to do this parametrically, but since you aren't relating your position equations to time, you should stick to slope.

float xDelta   = Math.abs(xTarget - xLocation); 
float yDelta   = Math.abs(yTarget - yLocation); 
float totalXY  = xDelta + yDelta; 
  
xPercent = xDelta / totalXY; 
yPercent = 1 - xPercent; 
  
xMove = (int) (xPercent * (float) maxSpeed); 
yMove = (int) (yPercent * (float) maxSpeed); 


I see what you are trying to do here with speed by accelerating as you travel towards your target. However, I'm not sure why you are dividing deltaX/(deltaX+deltaY). To me the formula for totalXY resembles the distance formula a little, which I don't know if that's what you're going for. Also, the xMove formula xPercent * maxSpeed could allow your bullet to travel past the target if it is at a short distance relative to max speed. Again, you should really relate everything back to x, making sure not to keep going if you hit a target.


Macman,
This trajectory is only set once - a flag is changed, so every cycle afterward the bullet object is only updated by the xMove and yMove calculated in getTrajectory, and stored in it's xSpeed and ySpeed variable.

The bullet disappears after reaching the edge of space (Height or Width) of panel. I may make it disappear, but that's not a problem right now. Aiming is my objective here.

I'm still not sure how to implement the line formula y=mx+b here though.

// Slope
float m = (float) (yTarget-yLocation)/(xTarget-xLocation);
// y-intercept
float b = (float) yLocation - (m * xLocation);
// Next X and Y
float nextX = ????;
float nextY = ????;



I know I've been on this but I'm not quite getting it, though I keep trying.
Was This Post Helpful? 0
  • +
  • -

#14 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10194
  • View blog
  • Posts: 37,646
  • Joined: 27-December 08

Re: Java Game Programming - aiming bullets

Posted 07 March 2010 - 03:12 PM

You're still thinking parametrically, not linearly as you should not need a ySpeed variable if you have slope, the starting point of the bullet, the location of the target, and the xSpeed. All you have to do is iteratively change y according to the formula and the change in x position. So if you move 1 x position every 3 seconds (so you can visually see the change), then you can use a Swing Timer and recalculate y. So for example:
//I'm going to assume this class implements
//ActionListener for the purpose of the example
Timer t = new Timer(3000, this); 

/*
   variables: 
     -m: slope
     -originalX: starting point of bullet
     -offset: number of x positions from originalX
     -y: current y-pos of bullet 
     -b: y-intercept
*/
public void actionPerformed(ActionEvent e){
    offset++; //move over 1 x
    y = m*(originalX + offset)+b; //and recalculate slope
    repaint(); 
}


Was This Post Helpful? 1
  • +
  • -

#15 sfoulk526  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 02-March 10

Re: Java Game Programming - aiming bullets

Posted 10 March 2010 - 02:44 PM

View Postmacosxnerd101, on 07 March 2010 - 02:12 PM, said:

You're still thinking parametrically, not linearly as you should not need a ySpeed variable if you have slope, the starting point of the bullet, the location of the target, and the xSpeed. All you have to do is iteratively change y according to the formula and the change in x position. So if you move 1 x position every 3 seconds (so you can visually see the change), then you can use a Swing Timer and recalculate y. So for example:
//I'm going to assume this class implements
//ActionListener for the purpose of the example
Timer t = new Timer(3000, this); 

/*
   variables: 
     -m: slope
     -originalX: starting point of bullet
     -offset: number of x positions from originalX
     -y: current y-pos of bullet 
     -b: y-intercept
*/
public void actionPerformed(ActionEvent e){
    offset++; //move over 1 x
    y = m*(originalX + offset)+b; //and recalculate slope
    repaint(); 
}



Thank you Mac man! I do appreciate the timer info. I figured out a great big problem. When I calculated the slope, I was using INTs. The calcs showed up incorrectly on my debug (drawString()) screen, and I have been ever frustrated. I couldn't even get the angle using Math.atan() function.

Finally, I did a double cast on the denominator and the numerator, and suddenly my calcs were accurate. So thanks for this info. I will try again, as I see why the ySpeed is unnecessary now.

Thanks again for your time. I will definitely give you acknowledgement in the credits of my first game!
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2