Skip to main content
GameDev.net gamedev.net
🔒 Locked

How to create multiple bullet in j2me??

Started by i4ba1 May 12, 2010 at 6:12 AM 10 replies 4.8k views
Original Post
i4ba1
i4ba1
hai i on developing my ship game. in my game the ship can fire. and i want to create multiple bullet when the ship firing bullet?. can you help me to solve this problem and give me some reference or sample code??. [Edited by - i4ba1 on May 12, 2010 11:04:55 AM]
CyJackX
CyJackX
Have you been able to make it fire one bullet already?

If it has, then I'm assuming it has a starting position for the bullet, so just make two bullets that have slightly different starting positions?
i4ba1
i4ba1
yes, i have. but idon't have idea how to make multiple bullet fire with different position. can you help me please??.
demonkoryu
demonkoryu
Store the bullets in a collection (Array) and loop over each of them, doing what you do with your single bullet.
CyJackX
CyJackX
Quote:
Original post by i4ba1
yes, i have. but idon't have idea how to make multiple bullet fire with different position. can you help me please??.


Can you show us your code?
i4ba1
i4ba1
here is my code in Buller class

package com;import java.io.IOException;import javax.microedition.lcdui.Image;import javax.microedition.lcdui.game.Sprite;public class Bullet extends Sprite {	private boolean active = true;		private int xDirection = 0;	private int yDirection = 0;		private static int HEIGHT = 25;	private static int WIDTH = 25;	private int[] sequence;	private static final int FRATE = 1;			public Bullet(Image image, int w, int h)throws IOException {		super(image, w, h);		// TODO Auto-generated constructor stub				WIDTH = w;		HEIGHT = h;		defineReferencePixel(WIDTH/2, HEIGHT/2);	}		public Bullet(Image image,int w,int h, int x, int y, int xDirection, int yDirection) throws IOException {		//Initialized bullet		super(image, w, h);				WIDTH = w;		HEIGHT = h;				setFrameSequence(sequence);		defineReferencePixel(WIDTH/2, HEIGHT/2);		this.xDirection = xDirection;		this.yDirection = yDirection;		this.setRefPixelPosition(x, y);	}		public void setSpeed(int speed)	{		this.yDirection = speed;	}		public int getSpeed()	{		return this.yDirection;	}		public void advanced(int tick)	{		//bullet rate		if (tick%FRATE==0 && active == true) {			if (this.getRefPixelY() > 0 && this.getRefPixelX() > 0) {				//System.out.println("y "+yDirection);				this.setSpeed(yDirection);				System.out.println("xDirection "+xDirection+" yDirection "+yDirection);				this.move(xDirection, -yDirection);				//this.move(-xDirection, yDirection);			}			else			{				super.setVisible(false);				active = false;			}		}	}		public void shot(int w, int h)	{		active = true;		this.setRefPixelPosition(w, h);		this.setVisible(true);	}		public void shot2(int w, int h)	{		active = true;		this.setRefPixelPosition(w, h);		this.setVisible(true);	}		public boolean isAppear()	{		return active;	}		public void destroy()	{		super.setVisible(false);		active = false;	}}


[Edited by - Zahlman on May 13, 2010 12:30:56 AM]
Zahlman
Zahlman
OK, now how about the code where you create a Bullet and use it?
i4ba1
i4ba1
here is my code in Ship.java

i call the bullet constructor
public void initBullet(Image image, int w, int h) throws IOException {		bullet = new Bullet(image, w, h);	}i create metho Bullet fire. here i call setSpeed and shot method in bullet classpublic Bullet fire(int ticks) {		if (ticks - fireTick > shoot_rate) {			fireTick = ticks;			bullet.setSpeed(BULLET_SPEED,90);			bullet.shot(this.getRefPixelX(), this.getRefPixelY());			return bullet;		} else {			return null;		}	}Here is my code that create image for bullet in GameManager.javafirst i create image for bulet, call the bullet constructor, call the methode init bullet in ship class.bulletImage = Image.createImage(BULLET_IMAGE);		bullet = new Bullet(bulletImage, BULLET_WIDTH, BULLET_HEIGHT);		ship.initBullet(bulletImage, BULLET_WIDTH, BULLET_HEIGHT);and here is the code that run bullet when fire button pressedif ((keyState & canvas.FIRE_PRESSED) != 0) {			try {				newBullet = ship.fire(ticks);// fire new bullet				// throw old bullet away				if (newBullet != null) {					this.remove(bullet);					bullet = newBullet;					this.append(bullet);				}			} catch (Exception e) {				System.out.println("Object created " + e.toString());			}		}		if (bullet!= null)            bullet.advanced(ticks);        if (!bullet.isAppear())            this.remove(bullet);

i need your hel guys. help me please to make multiple iring bullet with different position?

[Edited by - Zahlman on May 13, 2010 9:10:38 PM]
Lord_Evil
Lord_Evil
It's quite hard to follow your code since there are a lot of fragments missing, but here are some observations I made skimming over it:

1. you have this code (second code post, I did neither see a method name nor an enclosing class):

this.remove(bullet);
bullet = newBullet;
this.append(bullet)

This indicates your are already using a list or vector to store the bullets. So just add a new bullet upon firing, loop over all bullets in the list and remove those that aren't alive anymore.

2. in your constructor Bullet(Image image, int w, int h) you set static WIDTH and HEIGHT to w and h. This is a bad idea since they are used by all Bullet instances and could change with every new instance. If they need to be static don't change them from your bullet instances, otherwise remove the static keyword.

That's it for now, hope that helps.

[Edited by - Lord_Evil on May 14, 2010 1:07:04 AM]
If I was helpful, feel free to rate me up ;)If I wasn't and you feel to rate me down, please let me know why!
i4ba1
i4ba1
here is my ship code:

package com;import java.io.IOException;import javax.microedition.lcdui.Image;import javax.microedition.lcdui.game.Sprite;public class Ship extends Sprite {	private int rate = 5;	protected int speedX = 5;	protected int speedY = 5;	private static final int BULLET_SPEED = 25;	private int h, w;	private static final int[] SEQUENCE = {0};	private int sequenceIndex = 0;	private static final int MAX_HP = 1000;	private static final int DAMAGE_RATE = 20;	private int fireTick = 0;	private int current_hp = MAX_HP;	private int shoot_rate = 50;	private boolean destroyed = false;	private int damageTick;	private Bullet bullet;	public Ship(Image image, int w, int h) throws IOException {		super(image, w, h);		this.w = w;		this.h = h;		setFrame(0);		//setFrameSequence(SEQUENCE);		//setFrame(SEQUENCE[0]);		defineReferencePixel(w / 2, h / 2);		this.setTransform(this.TRANS_MIRROR_ROT270);	}	public void initBullet(Image image, int w, int h) throws IOException {		bullet = new Bullet(image, w, h);	}	public void advanced(int ticks) {		if (ticks % rate == 0) {			//nextFrame();		}	}	public void moveLeft() {		if (this.getRefPixelX() > 0) {			this.move(-speedX, 0);		}	}	public void moveRight(int m) {		if (this.getRefPixelX() < m) {			this.move(speedX, 0);		}	}	public void moveUp() {		if (this.getRefPixelY() > 0) {			this.move(0, -speedY);		}	}	public void moveDown(int m) {		if (this.getRefPixelY() < m) {			this.move(0, speedY);		}	}	public Bullet fire(int ticks) {		if (ticks - fireTick > shoot_rate) {			fireTick = ticks;			bullet.setSpeed(BULLET_SPEED);			bullet.shot(this.getRefPixelX(), this.getRefPixelY());			bullet.shot2(this.getRefPixelX(), this.getRefPixelY());			return bullet;		} else {			return null;		}	}	public void collised(int ticks, int damage) {		if (!destroyed)			if (ticks > damageTick + DAMAGE_RATE) {				current_hp -= damage;				if (current_hp <= 0) {					destroyed = true;				}				damageTick = ticks;			}	}	public boolean isDestroyed() {		return destroyed;	}	public double getHPPercentage() {		if (!destroyed)			return ((double) current_hp / (1.0 * MAX_HP));		else			return 0;	}	public boolean isDamageable(int ticks) {		return (ticks > damageTick + DAMAGE_RATE);	}	public Bullet getBullet() {		return bullet;	}}here is my GameManager.javapackage com;import java.io.InputStream;import javax.microedition.lcdui.Graphics;import javax.microedition.lcdui.Image;import javax.microedition.lcdui.game.LayerManager;public class GameManager extends LayerManager {	// ship	private Image shipImage;	private static final String SHIP_IMAGE = "/blue_ship.png";	private static final int SHIP_WIDTH = 40;	private static final int SHIP_HEIGHT = 33;	// bullet Image bullet	private Image bulletImage;	private static final String BULLET_IMAGE = "/shot.png";	private static final int BULLET_WIDTH = 25;	private static final int BULLET_HEIGHT = 25;	// game windows	private int canvasX, canvasY;	private int leftPosX = 0, leftPosY = 0;// game windows	private int height, width;	// variables and objects	protected MyCanvas canvas;	private Ship ship;	private Bullet bullet;	private Bullet newBullet;	public GameManager(int x, int y, int height, int width, MyCanvas canvas)			throws Exception {		super();		this.canvasX = x;		this.canvasY = y;		this.width = width;		this.height = height;		this.canvas = canvas;		// ---------------------------------------------------------------------		// LOAD SHIP		// ---------------------------------------------------------------------		// load ship images		shipImage = Image.createImage(SHIP_IMAGE);		// create space ship		ship = new Ship(shipImage, SHIP_WIDTH, SHIP_HEIGHT);		InputStream in = getClass().getResourceAsStream("/shooting.wav");		ship.setRefPixelPosition(height / 2, width / 2);		this.append(ship);		bulletImage = Image.createImage(BULLET_IMAGE);		bullet = new Bullet(bulletImage, BULLET_WIDTH, BULLET_HEIGHT);		ship.initBullet(bulletImage, BULLET_WIDTH, BULLET_HEIGHT);	}	public void paint(Graphics g) {        // paint graphics        paint(g,canvasX,canvasY);	}		// To move ship	public void advanced(int ticks) {		int keyState = canvas.getKeyStates();		// turn shift to right		if ((keyState & canvas.RIGHT_PRESSED) != 0) {			ship.moveRight(width);		}		if ((keyState & canvas.LEFT_PRESSED) != 0) {			ship.moveLeft();		}		if ((keyState & canvas.UP_PRESSED) != 0) {			ship.moveUp();		}		if ((keyState & canvas.DOWN_PRESSED) != 0) {			ship.moveDown(height);		}		if ((keyState & canvas.FIRE_PRESSED) != 0) {			try {				newBullet = ship.fire(ticks);// fire new bullet				// throw old bullet away				if (newBullet != null) {					this.remove(bullet);					bullet = newBullet;					this.append(bullet);				}			} catch (Exception e) {				System.out.println("Object created " + e.toString());			}		}		if (bullet!= null)            bullet.advanced(ticks);        if (!bullet.isAppear())            this.remove(bullet);        		// advance ship		//ship.advanced(ticks);	}}here is my bullet codepackage com;import java.io.IOException;import javax.microedition.lcdui.Image;import javax.microedition.lcdui.game.Sprite;public class Bullet extends Sprite {	private boolean active = true;		private int xDirection = 0;	private int yDirection = 0;		private static int HEIGHT = 25;	private static int WIDTH = 25;	private int[] sequence;	private static final int FRATE = 1;			public Bullet(Image image, int w, int h)throws IOException {		super(image, w, h);		// TODO Auto-generated constructor stub				WIDTH = w;		HEIGHT = h;		defineReferencePixel(WIDTH/2, HEIGHT/2);	}		public Bullet(Image image,int w,int h, int x, int y, int xDirection, int yDirection) throws IOException {		//Initialized bullet		super(image, w, h);				WIDTH = w;		HEIGHT = h;				setFrameSequence(sequence);		defineReferencePixel(WIDTH/2, HEIGHT/2);		this.xDirection = xDirection;		this.yDirection = yDirection;		this.setRefPixelPosition(x, y);	}		public void setSpeed(int speed)	{		this.yDirection = speed;	}		public int getSpeed()	{		return this.yDirection;	}		public void advanced(int tick)	{		//bullet rate		if (tick%FRATE==0 && active == true) {			if (this.getRefPixelY() > 0 && this.getRefPixelX() > 0) {				//System.out.println("y "+yDirection);				this.setSpeed(yDirection);				System.out.println("xDirection "+xDirection+" yDirection "+yDirection);				this.move(xDirection, -yDirection);				//this.move(-xDirection, yDirection);			}			else			{				super.setVisible(false);				active = false;			}		}	}		public void shot(int w, int h)	{		active = true;		this.setRefPixelPosition(w, h);		this.setVisible(true);	}		public void shot2(int w, int h)	{		active = true;		this.setRefPixelPosition(w, h);		this.setVisible(true);	}		public boolean isAppear()	{		return active;	}		public void destroy()	{		super.setVisible(false);		active = false;	}}here is my canvas.javapackage com;import java.io.IOException;import javax.microedition.lcdui.Graphics;import javax.microedition.lcdui.game.GameCanvas;public class MyCanvas extends GameCanvas implements Runnable {	protected GameManager gameManager;	protected boolean running;	private int tick = 0;	private static int width;	private static int height;	private int mDelay = 20;	private int cps = 0;	private int cyclesThisSecond = 0;	private long lastCPSTime = 0;	protected MyCanvas() throws Exception {		super(true);		gameManager = new GameManager(5, 5, getHeight() - 10, getWidth() - 10,				this);	}	public void run() {		while (running) {			// draw graphics			render(getGraphics());			// advance to next graphics			// tick += 5;			// System.out.println("tick " + tick);			// System.out.println("System.currentTimeMillis() "			// + System.currentTimeMillis() + " lastCPSTime "			// + lastCPSTime);			//System.out.println("cps "+cyclesThisSecond);						if (System.currentTimeMillis() - lastCPSTime > 1000) {				lastCPSTime = System.currentTimeMillis();				cps = cyclesThisSecond;				cyclesThisSecond = 0;			} else {				//cyclesThisSecond++;				// System.out.println("cyclesThisSecond " + cyclesThisSecond);			}						advanced(tick+=5);			// display			flushGraphics();			try {				Thread.sleep(mDelay);			} catch (InterruptedException ie) {			}		}	}	public void advanced(int ticks) {		// advance to next game canvas		gameManager.advanced(ticks);		this.render(getGraphics());	}	public void start() {		this.running = true;		Thread t = new Thread(this);		t.start();	}	public void stop() {		running = false;	}	public void render(Graphics g) {		width = getWidth();		height = getHeight();		// Clear the canvas		g.setColor(0, 0, 50);		g.fillRect(0, 0, width - 1, height - 1);		// draw border		// draw border		g.setColor(200, 0, 0);		g.drawRect(0, 0, width - 1, height - 1);		// draw game canvas		gameManager.paint(g);	}}


please help me to create multiple firing bullet.

[Edited by - Zahlman on May 15, 2010 10:25:24 PM]
Lord_Evil
Lord_Evil
OK, first, please post code enclosed by &91;source&93; tags. Wonder why your previous code appears in those nice scrollable boxes that makes reading it easier? I guess Zahlmann added those tags for you [smile]

Second, for handling multiple bullets use a List (provided the JME version you're using has Generics) instead of a single bullet variable in your ship and/or your GameManager (I'm not sure why you have that list in both, since either ship or GameManager should update the bullet's state, but not both). Since you're often adding and removing bullets, a first optimization step would be to use a LinkedList. (There are better optimizations but I'd say those are too complicated for now.)

In the following, I assume the bullets are managed by GameManager, since bullet that was fired wouldn't depend on the ship anymore.

So, firing a bullet would consist of:
- create and initialize new Bullet instance
- add the new Bullet instance to the GameManager's bullet list

Each frame you could then do something like this:
- for each bullet in the GameManager's list
-- call bullet.shot(...) //btw, what's the difference between shot and shot2 and why do you call both?
-- call bullet.advance(...)
-- handle impact or end of life
-- if the bullet is not active anymore, remove it from the list
If I was helpful, feel free to rate me up ;)If I wasn't and you feel to rate me down, please let me know why!
Zahlman
Zahlman
Quote:
Original post by Lord_Evil
OK, first, please post code enclosed by [source] tags. Wonder why your previous code appears in those nice scrollable boxes that makes reading it easier? I guess Zahlmann added those tags for you [smile]


Yep. I did it again, but that's it.

i4ba1: Read the sticky thread. Learn to use source tags properly.

And please understand that we cannot just read your source code and tell you what to fix. Programming is for people who like to solve their own problems.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.