Long story short, I’m making a racing game in Java. I’m self-taught using some books and my knowledge of math logic and I’ve only been programming for three weeks so I’m still learning the ins and outs of it all. Here’s some background:
I’ve got a player image surrounded by a bounding rectangle and the code will check to see when that player rectangle intersects a rectangle that is the finish line. Each time it successfully intersects the line, p1Laps gets incremented. When the value reaches a certain point, the game is over and the player is declared the winner.
Here’s the problem and the questions:
My problem is that Java is counting multiple intersects each time the rectangles cross. Usually 8 intersects so p1Laps gets incremented 8 times. This would not be a problem if it happened consistently, but sometimes the laps increment at different values. I’ve encountered increments of 4,7, and 8 so it’s hard to set a value to ensure that the race will end after a certain number of laps.
My first question is “why?” Why is java counting so many intersects when the two rectangles cross? I’m assuming it has something to do with them both being 2D shapes, but I could be wrong.
My second question is how to make the increments happen at a consistent value? Preferably “1” but that is not paramount as I can just adjust the finishing value.
Here is the code that seems relevant (a lot of code is removed):
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.applet.AudioClip;
public class RacerDoom extends JFrame {
//lap counter
int p1Laps=0;
//bouding rectangles
Rectangle p1 = new Rectangle(WIDTH/9,HEIGHT/2,WIDTH/30,WIDTH/30);
Rectangle finishtop = new Rectangle(WIDTH/9,(HEIGHT/2)-HEIGHT/9,(int)((WIDTH/9)*1.5),HEIGHT/70);
//check for intersect
if(p1.intersects(finishtop)&&p1Direction==UP){
p1Laps++;}
//choose winner
if(p1Laps>=24) {
if(!winnerChosen) {
winnerChosen = true;
break;
}
}
As stated, the increments usually go up by 8, but I’ve had them go by 7 for (seemingly) no reason and they go up by only 4 if “Boost” is enabled (doubles the speed of player).
Thanks for your help.
The reason is probably that it takes a few frames for the car to move across the finish line. You can solve this by keeping track of whether each car already has intersected the finish line. Use a
booleanvariable for each car, e.g.Modify your
ifto check whether the car intersects the finish line andp1IsOnFinishLineisfalse– this means that it is the first frame in which the car hits the line. If so, increasep1Lapsand setp1IsOnFinishLinetotrue. Now, in the next frame, the car will still intersect the finish line, but sincep1IsOnFinishLineistrue, you know that you already have counted that lap, so you don’t need to do it again. When the car no longer intersects the finish line, you can setp1IsOnFinishLinetofalse, so that you’re ready for the next crossing.