Hi again
I wrote a little game where up to 4 players can
drive a little car and play against the other players.
You can use four keys to steer the car and two
keys to shoot some nasty little bullets (from a pneumatic stapler for example).
It works really well with different maps and special effects and runs
with up to 60 fps with Fullscreenmode.
The big problem is that sometimes the keyevents donât do what they should do.
The game should be played on one keyboard and even with only two players
errors already occur.
Sometimes when I realease the firekey, it keeps on firing
or I canât steer left or the other player is accelerating although he released the key.
Hereâs the code:
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(active){
int i = 0;
for(int[] q : SnS.keys){
int i2 = 0;
for(int q2 : q){
if(q2 == key){
keyDown[i][i2] = true;
}
i2++;
}
i++;
}
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if(active){
int i = 0;
for(int[] q : SnS.keys){
int i2 = 0;
for(int q2 : q){
if(q2 == key){
keyDown[i][i2] = false;
if(i2 == 0 || i2 == 1){//release steeringwheel
smoothSteering[pl[i].plIndex] = 0;
}
}
i2++;
}
i++;
}
}
}
public static int maxSmooth = 10;
public void move(){
int i = 0;
for(Player p : pl){
if(p.alive){
if(p.canMoveCar()){
if(keyDown[i][0]){
if(smoothSteering[p.plIndex] < 0){
smoothSteering[p.plIndex] = 0;
}else{
smoothSteering[p.plIndex]++;
smoothSteering[p.plIndex] = Math.min(smoothSteering[p.plIndex],maxSmooth);
}
p.angle += p.getMoveAngle(Math.abs(smoothSteering[p.plIndex]));
}
if(keyDown[i][1]){
if(smoothSteering[p.plIndex] > 0){
smoothSteering[p.plIndex] = 0;
}else{
smoothSteering[p.plIndex]--;
smoothSteering[p.plIndex] = Math.max(smoothSteering[p.plIndex],-1*maxSmooth);
}
p.angle -= p.getMoveAngle(Math.abs(smoothSteering[p.plIndex]));
}
if(keyDown[i][2]){
p.changeSpeed(-1);
}
if(keyDown[i][3]){
p.changeSpeed(+1);
}
}
if(keyDown[i][4]){
p.tryShot(p.angle);
}
if(keyDown[i][5]){
p.tryBackShot();
}
p.angle = p.angle%360;
move(p);
i++;
p.update();
}
}
checkMapForCollisions();
checkMapForWallCrash();
resetCrashedPlayer();
}
If you donât understand any of the code, please ask.
The smoothSteering is just so that the player has better
control of small angles.
int[][] keys contains the KeyEvent_VK⌠keycodes where the first dimension is for the 4 players
and the second dimension is for the 6 keys: up, down, left, right, shot, backshot.
boolean[][] keyDown is the same for the dimensions and just stores if a key is held down or not.
I played the red baron (http://marcin-kochanowski.com/RedBaron4K.html)
which was programmed for the java4k contest in 2009
with a friend for hours and it works well with many keys pressed at the same
time. (Up to 9 keys, when 3 people are playing)
Unfortunately the programmer didnât release the code, so
I couldnât learn from itâŚ
If you read this: please help me