I am making a game in android in which enemies are randomly spawned at the top of the screen and move down. I am able to create 1 enemy that does this, but I can't think of a good way to create many enemies that are all drawn on the same canvas. I have tried many things, and I could really use some help.
Thanks!
The easiest way to do this is to create a class Enemy (name it whatever you like) and instantiate as many as you need using a for loop. You could use an array to store each instance.
An example could be the following:
Enemy[] arrayOfEnemies = new Enemy[sizeOfArray];
for(int i = 0; i < arrayOfEnemies.length; i++) {
arrayOfEnemies[i] = new Enemy();
}
Then you can use an enhanced for (or for each) loop to display them wherever you'd like on your canvas.
Related
I am meant to create a game in Java that specifically uses looping Arraylists to create a 4x4 grid. I have a Grid class, made up of an ArrayList of 4 Rows, a Row Class made up of an ArrayList of Squares, and Squares Class. As well as other classes of objects, such as a hero and various enemies that will move to a random adjacent spot on the grid or "board" on each new turn.
I have methods in place to randomly assign starting positions, to find all possible adjacent positions and then select a random position out of those possible positions, etc.
The end product should look similar to this:
Is a GUI necessary or is there a much more primitive, simple way to model to the user the 'Grid' with the objects in their current containers?
You can use System.out.println("...") to print out the info to the terminal. You can just put everything in a String and print it out. You'll be able to see each time you make a move and see previous moves and add in more verbose info if you want. Assuming your grid is in an Arraylist grid, the following code should help you see how it can work.
for (Row row: grid){
String str = "";
for(Square square:row){
str += square;
}
System.out.println(str);
}
You can use the Java Scanner to grab input from the user instead of buttons.
I want my game to draw coins from a sprite and then my main character would be able to pick them up. I'm trying to use array list for this but i have no idea how to implement this feature. Do I make an array list of Sprites I need to draw and then reuse it ? If so , how ?
Or do I use some other function ? I'm a begginer , so sorry if this question seems odd .
I recommend using Libgdx's Array class instead of a Java ArrayList, as it is optimized for game performance.
Create an Array to hold all the active coins.
Array<Sprite> activeCoins = new Array<Sprite>();
Then create a coin pool. A pool is a helper for creating copies of something without causing garbage collection hiccups. You need to make a subclass of Pool to use. It describes how to create a new coin when one is needed.
public class CoinPool extends Pool<Sprite> {
TextureRegion coinTextureRegion;
public CoinPool(TextureRegion coinTextureRegion){
this.coinTextureRegion = coinTextureRegion;
}
protected Sprite newObject(){
return new Sprite(coinTextureRegion);
}
}
Then create an instance of CoinPool to use in your game.
Now whenever you want a new coin, pull one from the pool. It will only instantiate a new one if necessary. Otherwise, it will hand you a recycled one from earlier. And once you get it, set it's position and other parameters wherever you want it. Keep in mind it might still have old values attached to it, so if you are rotating your coins and moving them around or changing color, you'll want to be sure you reset position and rotation, and color.
Sprite newCoin = coinPool.obtain();
newCoin.setPosition(x,y,z); //as desired
newCoin.setRotation(0); //if you are rotating them
newCoin.setColor(Color.WHITE); //if you have been changing their color
activeCoins.add(newCoin); //Add your new coin to the list of active coins
And whenever you are done with a coin (when it has been collected), you need to remove it from the active coins list and return it to the pool:
for (Sprite coin : activeCoins){
boolean grabbed = isCoinGrabbed(coin); //however you want to do this
if (grabbed){
coinGrabbed(); //whatever you want to happen when a coin is grabbed
activeCoins.remove(coin);
coinPool.free(coin); //return it to the pool
}
}
And to draw them, you can just submit all the sprites currently in the activeCoins list to the sprite batch.
I recently designed a game in Java that was a 2D side scrolling role playing game. Part of the game was to walk around and pick up items like swords and armor.
The way that I accomplished loading the sprites to my game was to give a JLabel my image (which was retrieved locally on start of the game) by setting it's icon to the image.
Next I would randomly place my JLabel on the game map. I didn't use an array list, although you could if you had multiple types of swords, or coins, etc.
The array list could contain types of swords (JLabel's with their icon set to a sprite) such as a bronze, silver, and a gold sword.
Once your JLabel('s) is loading to your map you can give them a hit box and if your character moves inside the hit box then remove the JLabel from the map and into the players backpack (or whatever it is, maybe append a coin amount?).
I'm currently developping a roguelike game, using Swing. I'm using an array of JLabel to display the tiles. When the user input a direction, I redraw the whole tab using the following method (I'm using simplified variable name here) :
for (int i=0 ; i<array.length ; i++){
for(int j=0 ; j<array[i].length ; j++){
this.remove(array[i][j]);
array[i][j] = new JLabel(new ImageIcon(TILEARRAY[i][j]));
this.add(array[i][j]);
this.validate();
}
}
But it's very heavy to deal with, about 0.5s to redraw the whole panel, and when I press the direction, it can't draw fast enough to have a real-time display (it actually does the loop, along the waiting time, and when the whole displacement has been done, draws). I'd like to know if there's a easier and faster way to achieve this, with a " smooth " feeling (let's say like in Stone Soup Dungeon Crawl (tiles version)), using Swing.
Every suggestion on an efficient 2D library for Java is welcome too. I know there is Slick2D, but is there any good other library for this kind of games ?
Thanks
(sorry if my english is bad, I'm not a native speaker of English)
Call the this.validate(); just once after both loops to avoid layout preferences recalculations
UPDATE. Keep ImageIcons in a Map and reuse them rather than recreating. Key could be i+"_"+j String
I got some difficulties because i dont know how to code efficient.
I'm creating a vertical scrolling shooter & i wanna spawn a large number of enemies.
At certain y-coordinates of the map & give them a certain x coordinate.
If been doing testing this with a couple of enemies and in my Enemy-class the code i'm using now looks like this:
if (Background.bgY == -3972 && active == 0) {
active = 1;
type = 1;
centerX = enemyXstart4;
KnightmareGame.activated = 1;
KnightmareGame.activatedatY = Background.bgY;
}
Which basically looks for if the scrolled background is at coordinate Y, activate an enemy(bomb) of type 1 and give it starting coordinate centerX, activatedatY.
This means that for every single enemy im writing this block of code...
Then in my KnightmareGame Class (which holds the routine where the enemies get drawn on screen) i'm drawing every enemy manually, which looks osmething like this:
g.drawImage(currentBomb, bo1.getCenterX(), bo1.getCenterY(), this);
g.drawImage(currentBomb, bo2.getCenterX(), bo2.getCenterY(), this);
g.drawImage(currentBomb, bo3.getCenterX(), bo3.getCenterY(), this);
And in my collision detection method Im also checking every enemy 1 by 1:
if (projectileRect.intersects(KnightmareGame.bo1.bombRectangle)) {
visible = false;
if (KnightmareGame.bo1.health > 0) {
KnightmareGame.bo1.health -= 1;
}
if (KnightmareGame.bo1.health == 0) {
Enemy.animateFire= true;
etc., etc.
The problem is that the total amount of enemiess i exceeds 50, so if i would continue coding them 1 by 1 the code would get real messy.
What i was thinking of was that I might make an array list of all the y coordinates where i wanna spawn enemies with their subsequent x coordinate.
For example at -3900 i wanna spawn an enemy at x coordinate 200. At -3800 at x coordinate 300, etc. So an array list where every position holds 2 variables (x,y)
I just dont know (first of all) how to code for this array list.
And second. I have got no clue of how to automate my draw method like
g.drawImage(currentBomb, bo1.getCenterX(), bo1.getCenterY(), this);
I'm thinking of a loop, but dont know how the code...
Collision detection: here i also collision detect in ONE block of code for every enemy instead of compare every enemy in a single seperate block of code with my projectile.
Does any1 know how to do this? Or maybe if I should do it differently then what i'm thinking of right now?
Help will be very much appreciated!
Handling multiple enemies
Create an ArrayList<Enemy> enemies;
Then use
for (Enemy bo : enemies) {
// logic for each enemy.
}
Don't forget to remove old enemies after destroying or going out of screen.
Don't keep creating new objects every time. Use a object pool for efficiency.
Improving collision efficiency
For large number of entities to be checked for collision, generally a broadphase algorithm is used.
See if it is required in your case.
You might also try some spatial optimizations like quad-trees.
These might just be wiki links, but I suppose you can search further if you know what to search for.
Hope this helps.
Good luck.
I made shoot em up like game.But I have only one ememy which fallows me on screen.But I want to make lots of enemys like each 10 second they will across on screen together 5 or 10 enemys.
ArrayList<Enemies> enemy = new ArrayList<Enemies>();
for (Enemies e : enemy) {
e.draw(g);
}
is it good creating array list and then showing on screen?
And Do I have to make some planing movements thoose enemies in my code ? I want that they vill appear not on same pozition.Like First 5 enemies will come top of screen then the other 5 or 10 enemies will come from left side.. so on.What is best solution for this?
And I have problem where to fullfiel this array like
enemy.add(new Enemies(750,60))
But this doesnt work ((
Use for example a random property and onScreen property. And set them when you show them on the screen.
Yes you can create an ArrayList for enemies, it's a common solution.
You can randomize the starting position ofthe enemies using the Random class. At the point where you create the enemy select Random coordinates for each.
You may want to have each enemy run in its own thread so that they move independent of each other too.