We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I'm doing the game project of spaceship moving around the asteroids. The problem is that I can't figure out how make the collision work when the spaceship touches the asteroid and it will say Game Over. Here are the codes. Don't give me some complicated codes. I'm new to this. Thanks! :)
// Main class
PFont font;
Star s1;
Spaceship sP1;
Asteroids a1;
void setup() { size(900, 500); background(0); colorMode(HSB);
s1 = new Star();
sP1 = new Spaceship();
a1 = new Asteroids();
}
void draw() { background(0); s1.display(); sP1.display(); a1.move(); a1.display();
if (hit(s))
{
println("Game Over");
youLose();
}
}
void youLose() { font = loadFont("AdobeFanHeitiStd-Bold-48.vlw"); textFont(font); text("Game Over! Click Mouse to Restart", 26, 30, 260, 200); } void reset() { setup(); }
void mousePressed() { reset(); }
/////////////////////////////////////////////////////// // Asteroids class
class Asteroids
{
float diam;
float xPos;
float yPos;
float xDir = random(-5, -1);
Asteroids()
{
xPos = random(width);
yPos = random(height);
diam = random(30.0, 60.0);
}
void move() { xPos = xPos + xDir; if (xPos < 0) { xPos = width; } }
void display() { fill(#FF0000); stroke(#000066); ellipse(xPos, yPos, diam, diam); }
boolean hit(Spaceship s) { float distance = dist (s.xPos, s.yPos, this.xPos, this.yPos); if (distance < (s.diam + this.diam) / 2.0) { return true; } else { return false; } } }
Answers
A simple instruction then... :)
Leave an empty line after, one before, highlight your code, hit ctrl-o.
Code formmated for the forum so people can read it.
;)
just loop over the asteroids
when dist() (see reference) between this asteroid position (plus radius) and ship (dito) is < 120 HIT
assuming that the asteroid is more or less round but it should be accurate enough
https://www.processing.org/reference/
I got everything worked but now I am trying to figure out how to make lots of astroids. I only made one asteroid but I want more.
well you set up 15 asteroids in setup()
just display them in draw() with a for loop and check the collision for each as well
It works fine in the setup. But I am trying to figure out how to fix the error in "if (aField.hit(sP1))". It might be something different but I don't know. I made some changes.
??
you wrote
answer:
if (aField[0].hit(sP1))
or later with the for-loop
if (aField[i].hit(sP1))
Ahh that's what I want! Thank you for helping!