After successfully programming Pong, I've decided to undertake Space Invaders. This time, I want to implement classes and objects into my sketch.
So far I have the "mothership", which the player controls. In attempting to create three enemy aliens to move back and forth, I discovered that they didn't move in a uniform manner. What I mean is, once one creature (a rectangle at this point) hits, let's say, the right hand wall, instead of having the other two move over at the same time, only that one that hit it moves over. The other two continue moving along until they hit, causing my creatures to overlap.
I have an inkling to create three separate classes for my aliens instead of just one, as I did before. I think the solution to my problem may lie in having all three classes use the same speed variable, but different location variables. Yet I'm not sure how to go about setting a variable in one class that can be used by another class as well.
I'm only up to the chapter on Objects in Daniel Shiffman's book (chapter eight). Below is my code so far for the mothership (just a simple rectangle moving along, controlled by the mouse). In my sketch I have the Ship class in another tab, but to make it all visible, I'll copy and paste it to my main sketch tab and paste the full code.
Code:
Ship motherShip;
void setup() {
size(800,600);
smooth();
motherShip=new Ship(550,150,20);
}
void draw() {
background(255);
motherShip.display();
}
class Ship {
float ypos;
float wrect;
float hrect;
Ship(float tempYpos, float tempWrect, float tempHrect) {
ypos=tempYpos;
wrect=tempWrect;
hrect=tempHrect;
}
void display() {
fill(0);
rectMode(CENTER);
rect(mouseX,ypos,wrect,hrect);
}
}
I know it's nothing much (yet). Can anyone give me some pointers on how to make this code cleaner, or is it pretty good so far? I understand I very well could have achieved the same outcome in less than five lines, but I'm wanting to use objects and classes to enhance my project.
Thanks very much!