We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi, I'm new here and having a bit of trouble with some basic Space Invaders code.
Here is my code:
int x = (200);
int y = (450);
int a = 0;
int b = 54;
int c = 85;
int xPos = 25;
int yPos = 25;
int xdir = 3;
int ydir = 40;
int counter = 0;
int[][] enemies = generateEnemies();
int[][] generateEnemies() {
int[][] enem = new int[54][2];
int counter = 0;
for (int xi = 0; xi < 9; xi++) {
for (int yi = 0; yi < 6; yi++) {
enem[counter][0] = xi * 50 + xPos;
enem[counter][1] = yi * 25 + yPos;
counter++;
}
}
return enem;
}
void setup() {
size(500, 500);
frameRate(60);
}
void draw() {
background(0);
player();
drawEnemies();
moveEnemiesRight();
}
void player() {
fill(0, 255, 0);
rect(x, y, 100, 20);
}
void drawEnemies() {
fill(255, 215, 0);
for (int i = 0; i < 54; i++) {
rect(enemies[i][0], enemies[i][1], 40, 20);
}
}
void moveEnemiesRight() {
xPos += 5;
}
This is super messy and lots of crap going on. This is due to me being very inexperienced in the language. My main problem is that I am unable to make the Enemies move down and across the screen. I tried to adjust their position using the xPos variable but could see it wasn't working and can't seem to see a solution.
Any help or guidance is appreciated. Thank you.
Answers
https://forum.Processing.org/two/discussion/8081/from-several-arrays-to-classes
https://Processing.org/tutorials/objects/
Read up about classes and OOP (Object Oriented Programming), GoToLoop has already given you a link to it.
Thanks guys - I have been throuroughly reading the arrays to classes link GoToLoop sent but can't see how that integrates with my generateenemies 2d array. :S
This code will start you off. It has a class called Enemy and a 2D array of Enemy objects. It should get you started but just ask if you don't understand any of the code.
Then you need to add moveDownLeft() function to the Enemy class.
How can I space the bricks out further as I changed it to have 10 columns by 6 rows and all of the bricks are squished together? Really appreciate this guys, thank you.
Okay no worries with the spacing now, I've sorted it.
For a a moveDownLeft() function would I be using px and py to translate the aliens around?
I really need help creating a Bullet array to make my ship shoot when I press the spacebar. Here is my current code:
Along completely different lines to the question, why do you need to use a 2D array?? It just seems really useless now, after shifting to OOP.
As to the bullets question, you would be better off using ArrayList and not arrays.
Example from Daniel Shiffman - https://processing.org/examples/arraylistclass.html.
I also see another potential flaw - a global variable dir that is changed by position of individual instances of the Enemy class. (Line 27)