So I am making a small maze game. I want to add objects that when the ball touches it, they die. I have been practicing on another sketch. I’ve used classes for the aliens and the ball, as I thought this would be the best way to approach the situation, but I cant do it. Any ideas?
Alien[] aliens = new Alien[20];
Ball ball;
PImage[] imgs = new PImage[2];
void setup() {
size(700, 700);
imgs[0] = loadImage("alien1.png");
imgs[1] = loadImage("alien2.png");
for( int i = 0; i < aliens.length; i++){
aliens[i] = new Alien(i%2);
}
ball = new Ball();
}
void draw() {
background(255);
for( int i = 0; i < aliens.length; i++){
aliens[i].move();
aliens[i].display();
}
ball.display();
}
class Ball {
void display() {
fill(0);
ellipse(mouseX, mouseY, 30, 30);
}
}
class Alien {
int kind;
float positionX = random(width);
float positionY = random(height);
int dir = 1;
Alien(int t) {
kind = t;
}
void display() {
image(imgs[kind%2], positionX, positionY, 35, 35);
}
void move() {
if( kind == 0 ){ moveX(); }
if( kind == 1 ){ moveY(); }
}
void moveX() {
positionX = positionX + 1 * dir;
}
void moveY() {
positionY = positionY + 1 * dir;
}
}
Notice now that there is only one copy of each image. Also the aliens objects are now in an array. This lets me have more aliens very easily, because I can loop over the array to deal with all the aliens instead of having to call functions on each one individually.
Thanks. This is really helpful.
How would I make it so when the ball and an alien touch, a message pops up? So I tried using an if statement, but I don’t know how to write the code. When I tried doing this, a error message would pop up saying that there was a type mismatch, but I couldn’t fix it.
Also, how would I write code to prevent the alien from leaving the screen by changing the direction. I kinda know how to do this but im not sure where in the code this would go.
Here is an excellent tutorial by Abe Pazos on youtube on how to change directions when an object hits the edge of the screen.
And regarding where to place in your code. Go through your code and turn off each function one by one to see which function controls movement across the screen. That is where you’ll add the new code for changing direction.