Java-Gaming.org    
Featured games (79)
games approved by the League of Dukes
Games in Showcase (477)
Games in Android Showcase (107)
games submitted by our members
Games in WIP (536)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
   Home   Help   Search   Login   Register   
  Show Posts
Pages: [1] 2
1  Games Center / Showcase / Re: Generic Zombie Shooter on: 2013-10-16 17:58:56
After playing it for a while, I started to notice crackling and popping noises coming from the sound system. It seemed to start after I used the Sentry Gun and Assault Rifle in tandem. I'm assuming that because they use the same sound and are being loaded so often, this could be causing it, but I'm not sure. I'm using the TinySound library, and the sounds are all being stored as Music objects, rather than Sound objects, so I can stop/rewind/etc the sound effects. Anyone want to take a shot in the dark as to what's causing it?

Java just doesn't want me using sound in my game...  Sad
2  Games Center / Showcase / Re: Generic Zombie Shooter on: 2013-10-16 04:58:18
Yeah, sorry... typo.
3  Games Center / Showcase / Generic Zombie Shooter on: 2013-10-16 04:48:25
I've finally finished it! Version 1.0 is here! I originally started this game for Halloween 2012, thinking I could finish the game in a week, but... well... look how that turned out. Let's just say I didn't know everything I needed to in order to complete the project, so I got discouraged and dropped the project for almost a year. But I picked it back up in August and have been working on it for two months straight. And now, it's finally here!



To download the JAR, click here. There is a README included with the controls and game information. Make sure all the files are in the same folder and then run the BAT file to launch the JAR.

I've done a lot of play-testing, but there may still be some bugs to work out... luckily, there is a built-in error handling system that will show you the error and give you my contact information should an error occur. You can also send me the error here, and I'll respond as soon as I can. If anything else unexpected happens, just do your best to describe what you were doing when it happened and what happened.

That said, I hope you enjoy my first real game. I'm looking forward to finally starting work on my next one!
4  Game Development / Newbie & Debugging Questions / Re: Can't figure out how to do Java Audio properly. on: 2013-10-10 19:02:24
Alright, so I switched over to TinySound and got it working for the weapons. But there's one remaining problem. I went with the Music object, rather than Sound, so I could make the Flamethrower work (needed to be able to loop it and only play it if it's not already playing). The problem being that now the zombie moans are doing exactly what I originally set out to fix, being that I need them to overlap, and the Music object seems to restart the sound whenever the play() is called, which I understand... but how can I support playing the same sound over itself like I was doing with the AudioData class I made?

EDIT: Nevermind. I just decided to go with loading the sound every time it's played if it's designated as an overlapping sound (really only used for the moans) and playing that instead. Otherwise, it just uses the sound it loaded at the start. I realize this may not be very efficient, but I'm going to be making it so zombies only moan once after they're spawned so it doesn't cause too much of a burden.


Why is sound so troublesome in Java?
5  Game Development / Newbie & Debugging Questions / Re: Can't figure out how to do Java Audio properly. on: 2013-10-10 15:21:35
Phil, please read earlier in the thread. I already said I corrected the freezing issue... the sounds being cut short is unrelated. And just a few posts up is the code I'm currently using.
6  Game Development / Newbie & Debugging Questions / Re: Can't figure out how to do Java Audio properly. on: 2013-10-10 07:57:57
I once used a loop for a machine gun sound effect built from individual gunshots. From that I made a mental error.

Substitute the words flamethrower for machine gun. The above should still work.

That's the problem, though. What you posted is exactly what I was doing originally that caused the overlapping sounds to freeze the game.
7  Game Development / Newbie & Debugging Questions / Re: Can't figure out how to do Java Audio properly. on: 2013-10-10 04:28:54
Here'a an example of the basic form for adding a LineListener, and testing for an event:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
      clip.addLineListener(new LineListener()
      {
         @Override
         public void update(LineEvent arg0)
         {
            if (arg0.getType() == LineEvent.Type.STOP)
            {  
               // do something}
           }
         }
      });


But that begs the question of how a looping clip gets a signal to stop in the first place.

If we are talking about a machine gun with a fixed duration, e.g. short bursts, something like this is fine. (No LineListener needed. No while loop needed.)

1  
2  
3  
   clip.start();  // assume looping, volume, etc. has already been set up.
  Thread.sleep(machineGunDuration);
   clip.stop();  // then maybe reset it to the starting frame so you can reuse it


Sometimes I break the Thread.sleep() into smaller increments and check a state variable before continuing to the next sleep, to make the duration more granular. The state variable should be volatile, of course, and will only be as accurate as the limited real time guarantees of the JVM/OS.

1  
2  
3  
4  
5  
6  
7  
   clip.start();
   for (int i = 0; i = 10; i++)
   {
      Thread.sleep(oneTenthMachineGunDuration);
      if (stopClip) break;
   }
   clip.stop();


Am just free-typing this. So, hopefully I didn't facepalm anything.

Even the 2nd example above uses vastly less cpu than leaving the thread spinning. I've only seen spinning threads in "spin locks" where the anticipated duration was very short.

Couple of suggestions/observations which may help in other regards:

 - It is kind of unusual to make a new Clip and play it with every play. Usually one restarts a given clip. If you are doing a single playback, a SourceDataLine starts quicker, so as not to incur the repeated i/o loading. Maybe you are doing this as a quick/dirty way to allow concurrent sounds?
 
 - Not every OS will support MASTER_GAIN, just a heads up.

 - Not every OS will support multiple outputs (for sure some Linux won't), hence the recommendation for TinySound which mixes all sounds into a single output line. Of course, to get TinySound, we are back at the annoying task of figuring out how to use GitHub. But since Git is such a common tool for sharing code, the "side trip" is worth it, imho.

Ok, can I just ask how the idea got started that I was talking about the machine gun? The machine gun is not looped, and the sound is played every time the gun is fired... the flamethrower is what's looped. That being said, it doesn't seem like anyone has a solution for this, so I'm gonna try my hand at TinySound.
8  Game Development / Newbie & Debugging Questions / Re: Can't figure out how to do Java Audio properly. on: 2013-10-09 04:45:08
It has probably something to do with threads. Using threads incorrectly can cause all kinds of weird random errors.

Is there a way I could convert it from its current functionality to maybe use a Line Listener like was suggested earlier? I'm not sure if that would correct the problem, but it's worth a try. My code as it is now is:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
public void play(final double gain, final boolean smoothLoop) {
    final Clip clip = createClip();
    FloatControl gainControl = (FloatControl)clip.getControl(FloatControl.Type.MASTER_GAIN);
    float dB = (float)(Math.log(gain) / Math.log(10.0) * 20.0);
    gainControl.setValue(dB);
    new Thread(new Runnable() {
        @Override
        public void run() {
            active = true;
            if(!smoothLoop) clip.start();
            else clip.loop(Clip.LOOP_CONTINUOUSLY);
            while(active) {
                if(!clip.isRunning() && !smoothLoop) active = false;
            }
            if(smoothLoop) clip.stop();
        }
    }).start();
}
9  Game Development / Newbie & Debugging Questions / Re: Can't figure out how to do Java Audio properly. on: 2013-10-08 22:03:04
Nobody? I really need to know why this is happening.
10  Game Development / Newbie & Debugging Questions / Re: Can't figure out how to do Java Audio properly. on: 2013-10-07 17:13:01
I understand what you're saying, but right now, I'd like to know why the sounds are being cut short when I run the JAR as opposed to the NetBeans Run Project button.
I may switch to TinySound after all, but first, I want to know what's causing this.
11  Game Development / Newbie & Debugging Questions / Re: Can't figure out how to do Java Audio properly. on: 2013-10-07 00:17:43
Oh, come on! Just when I thought I was in the clear...

Everything works fine when I run the game through NetBeans, but when I Clean & Build it into a JAR and run it, all the sound in the game is cut short... like it only plays half the sound. What could be causing this in the JAR, but not in NetBeans?
12  Game Development / Newbie & Debugging Questions / Re: Can't figure out how to do Java Audio properly. on: 2013-10-06 05:53:29
But now you have an infinite loop that puts 100% load on one CPU core.
That's what the LineListener is for. So you can react to the Clip stopping without needing a loop.
And as I already mentioned you can also use a MouseListener/KeyListener to react to buttons being pressed/released.

Also if you need an isRunning() method in the AudioData class you can define it like this
1  
2  
3  
4  
5  
6  
public synchronized boolean isRunning() {
    for(Clip clip: clipsPlaying) {
        if(clip.isRunning()) return true;
    }
    return false;
}


But I don't think you even need that. AudioData has a stop method. Just call it when the button is released.

I don't know how you think you get an infinite loop out of that. It's working fine as it is right now.
13  Game Development / Newbie & Debugging Questions / Re: Can't figure out how to do Java Audio properly. on: 2013-10-05 23:31:17
If there is only a 20ms delay I guess it's best to use loop(). And then call stop(), once the fire button has been released. You can do that by either making the flamethrower AudioData object globally accessible or by adding a MouseListener when the fire button is pressed. You can add as many MouseListeners to your game as you want. That listener will then stop the sound and remove itself.

Haha, oh wow... my new solution works perfectly for the Flamethrower, but now no other sounds will play... will I ever get this right?
Here's the code I have now for the play() method in the AudioData class.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
public void play(final double gain, final boolean smoothLoop) {
    final Clip clip = createClip();
    FloatControl gainControl = (FloatControl)clip.getControl(FloatControl.Type.MASTER_GAIN);
    float dB = (float)(Math.log(gain) / Math.log(10.0) * 20.0);
    gainControl.setValue(dB);
    active = true;
    new Thread(new Runnable() {
        @Override
        public void run() {
            if(!smoothLoop) clip.start();
            else clip.loop(Clip.LOOP_CONTINUOUSLY);
            while(active) {
                if(!clip.isRunning() && !smoothLoop) active = false;
            }
            clip.stop();
        }
    }).start();
}


Basically, I had a boolean set on each AudioData called active that determines if the sound is currently playing. It's set to true right before the clip starts playing. It then starts the clip and goes into a loop saying "if active, check to see if it's running, and if it's looped. If it's no longer active and isn't looped, set active to false". This ensures that when a clip is finished with playback, it automatically sets active to false and then stops the clip. The looped parameter is provided by the Sounds class. So basically, for normal clips that aren't looped, it sets active to true, then starts a thread in which it constantly checks that clip to see if it's still running. If it's no longer running, active is set to false, and then the clip stops. But for looped clips, like the Flamethrower, it will never set the active boolean to false, meaning it will continue to allow it to loop, never stopping. I then put in the setActive() method to set it to inactive when the mouse is released (among other conditions). So now the Flamethrower starts and stops like it's supposed to, but none of the other clips even play.

What am I doing wrong?

EDIT: Nevermind, I just had to check if the clip was looped and only call stop() if it was looped.
14  Game Development / Newbie & Debugging Questions / Re: Can't figure out how to do Java Audio properly. on: 2013-10-05 21:39:02
Wait, so you want to play the flamethrower sound only if it's not playing anymore. Can't you use loop()? Then it will automatically start playing again once it stopped.
Also, I edited my previous post. Take a look at the new code.

You're missing the point. I already said that when it was looped, I couldn't stop it because there is no way to stop the Clip once it has been created and started because that Clip only exists in the scope of the play() method in my sounds class. I would need access to that clip in my framework so I can call the stop() method on it under certain conditions. But simply returning the Clip from the play() method wouldn't work because it would return to the weapon class. So unless I made a global variable for the Flamethrower Clip that changed whenever it's played, which I think would be a hacky solution, but a bad idea, I can't get it to stop when the player lets go of the fire button.

Also, forget the "machine gun"... that weapon is not the issue, and works just fine. It's the Flamethrower that's the problem, because there is no delay (or rather, only 20 ms delay) in between creation of each particle, which causes the sound to be played very rapidly, causing the noise in question.

EDIT: Just looked at your modified solution, and that MAY work, but I still feel as if there might be a better option. I'll try it and get back to you.
15  Game Development / Newbie & Debugging Questions / Re: Can't figure out how to do Java Audio properly. on: 2013-10-05 21:18:45
The clip class has a loop and a stop method. But after you call stop the clip will get closed automatically so don't call start or loop on it after you stopped it.
For a machine gun effect you need a delay. You probably have to create another Thread for that. You can communicate with that Thread through a volatile variable.

Why would I need a delay? The sound is played when the fire() method is called on the gun, which already has a cooldown.
Anyway, I don't think you get what I'm saying. Whereas most weapons in my game have a cooldown before they can be used again, the Flamethrower just fires particles continuously as long as the player holds down the fire button. The problem being that the sound is played when it's fired, and since it's being looped, that means dozens, or even hundreds, of the Flamethrower sound clip are being created and looped all at once. I tried making it so it wasn't looped and just relied on the fire() event from the weapon to play the sound, but there are A LOT of particles coming out of this thing, so it still sounds like a machine gun of noise on crack. So what I'm asking is... how can I make it so the sound only plays if there is no Flamethrower sound currently being played? The play() method doesn't return the clip that is generated to play the audio, so I can't use that to determine if it's running.

I thought of using a boolean, but how would I determine when the last clip generated by the play() method stops so I can generate a new one?
16  Game Development / Newbie & Debugging Questions / Re: Can't figure out how to do Java Audio properly. on: 2013-10-05 17:08:23
But yeah, loading the sound files on the fly isn't going to work. It would cause too much latency. Like Jeremy said, for a machine gun (and my game happens to have an Assault Rifle), it just won't work. My sounds are used too often.

Then do it like this

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
public class AudioData {
    byte[] data;
    AudioFormat format;
    AudioData(String fileName) {
       try {
           AudioInputStream sounds = AudioSystem.getAudioInputStream(AudioData.class.getResource(fileName));
           format = sounds.getFormat();
           int size = sounds.available();
           data = new byte[size];
           sounds.read(data);
           sounds.close();
       } catch(Exception e) {
           e.printStackTrace();
       }
    }
    public Clip createClip() {
        try {
            final Clip clip = AudioSystem.getClip();
            clip.addLineListener(new LineListener() {
             public void update(LineEvent e) {
                 LineEvent.Type type = e.getType();
                 if(type == type.STOP) clip.close();
             }
            });
            clip.open(format, data, 0, data.length);
            return clip;
        } catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
}


and then you can make your machine gun with this code
1  
2  
3  
4  
5  
AudioData data = new AudioData("shoot.wav");
for(int i = 0; i < 100; i++) {
    data.createClip().start();
    Thread.sleep(100);
}


However of course it would be better to use Clip.loop for a machine gun but then the audio file may need some editing to make it sound correctly.

Ok, I've implemented this, but now I have one other question about how to use it... for sounds that I want to loop, but to stop when certain things happen (ie: flamethrower sound loop until player stops firing the weapon), how would I do that?

EDIT: I suppose answering the previous question might give me an idea on how to solve this one, but this is also a huge problem... there is no delay between the fire() calls to the Flamethrower weapon (whose sound is the only one in the game that loops), so they all play together REALLY rapidly, and it comes out as a raucous jumble of noise.
17  Game Development / Newbie & Debugging Questions / Re: Can't figure out how to do Java Audio properly. on: 2013-10-05 05:17:50
Why would I loop the sound for my Assault Rifle? It's a single shot that plays whenever a bullet is fired.

So anyway, what you're saying is that I could have a class with final static AudioData objects, and then when I need to play the clip, call the createClip() method and start it?
18  Game Development / Newbie & Debugging Questions / Re: Can't figure out how to do Java Audio properly. on: 2013-10-05 04:47:24
How do I do that? Is it a simple function that you could just post here?
19  Game Development / Newbie & Debugging Questions / Re: Can't figure out how to do Java Audio properly. on: 2013-10-05 04:30:40
Also, I noticed a couple of weird imports at the top... specifically, the "jeva" package. Was that a typo, or is that an external library? Can I just include this file and use it as is, or do I need a library to use with it?
20  Game Development / Newbie & Debugging Questions / Re: Can't figure out how to do Java Audio properly. on: 2013-10-05 04:05:01
You should stick to the Java Sound Library if you can, otherwise you don't get the advantage of plugging in other SPIs for different audio formats etc. Also, if you can it is always best to avoid any native dependencies.

I've put some code for loading audio files in the paste-bin. It is hacked up and it may not be 100% proper, but it should work fine. Any missing code you can write pretty easily.
http://www.java-gaming.org/?action=pastebin&id=730



I only use WAV files, so I don't see why I would need to worry about other audio formats. Also, I took a look at that Audio class you posted. Does it support the multiple plays of the same Clip simultaneously? Is it streamed? Like I said, streaming is absolutely not an option.
21  Game Development / Newbie & Debugging Questions / Re: Can't figure out how to do Java Audio properly. on: 2013-10-05 01:12:27
Except that if I close the sound, I have to reload the data, which isn't good for sounds that are played a lot. Also, when I said playing two sounds at the same time, I meant the SAME sound, not two different ones. So two calls to the same sound overlapping each other. THAT is why I use threads. Or at least, that's what some page on Google suggested.

Clip can't seem to do that, which is why it's not going to work out.

I don't think playing a clip in a new thread allows you to play them simultaneously, to play two audio files simultaneously, you'll need two clips.

That said, it isn't very difficult to do. You'll want to cache all open clips with SoftReferences (or WeakReferences, but SoftReferences are more appropriate for caching.) When they're playing keep a hard references to them, and when they aren't keep a softreferences (via some caching module) This allows you to very quickly reset an unused to clip if you want to play it again and it's not currently being played (but it doesn't solve the problem of playing two clips simultaneously yet.) If the JRE decides it needs more memory and destroys your clip instance, you'll need to make sure you close it before giving it away to the JRE.

You'll also want to softreferences their raw data (for clips you want to play simultaneously) that you use to initialize the clip. By doing this, you minimize filesystem IO by caching a copy of the file in memory (with a byte buffer etc) which will allow you to very quickly initialize a new clip instance.

If you use this method, it is then important that you use an uncompressed audio format (like WAV) to minimize the pre-processing overhead induced by the compression. Which is fine since compressing small audio files (like the moan of a zombie, or gun fire) is almost pointless to do individually.

DON'T do this for large audio files like background music since it will probably kick everything out of the cache eventually. If you want to do this for compressed audio formats you need cache their decompressed raw data, otherwise initializing the clip will be expensive (due to the redundant process of decompressing the cached data.)

There are other more clever ways of doing it, but you'd have to ask someone more experienced with the Java Sound API.

I don't want to seem stupid, but I didn't understand a lot of what you just said. Like I said, I don't have to stick to the Clip class... I was just hoping I could stay within the core Java packages.

I checked out TinySound, but I don't know how to include it in my project. I'm using NetBeans. I downloaded a ZIP of the TinySound repository on Github, but I'm not sure what to do with it. There aren't any JARs inside, so I can't use it as a library. How do I incorporate the .java files as a library?

Also, I removed the threads for playing the sound.

But yeah, loading the sound files on the fly isn't going to work. It would cause too much latency. Like Jeremy said, for a machine gun (and my game happens to have an Assault Rifle), it just won't work. My sounds are used too often.
22  Game Development / Newbie & Debugging Questions / Re: Can't figure out how to do Java Audio properly. on: 2013-10-04 22:45:55
Except that if I close the sound, I have to reload the data, which isn't good for sounds that are played a lot. Also, when I said playing two sounds at the same time, I meant the SAME sound, not two different ones. So two calls to the same sound overlapping each other. THAT is why I use threads. Or at least, that's what some page on Google suggested.

Clip can't seem to do that, which is why it's not going to work out.
23  Game Development / Newbie & Debugging Questions / Re: Can't figure out how to do Java Audio properly. on: 2013-10-04 21:42:42
Hi

Maybe try to use another Mixer. If you want to use a sound library, you can try Paul Lamb's Sound System or TinySound. Personally, I use Paul Lamb's Sound System with its plugin based on JOAL and my game works very well both with OpenJDK and Oracle Java  Grin

I gave TinySound a look and all I could find was a Github page. I downloaded the ZIP of the project, but I can't figure out how to include it in my project in NetBeans and use the library. What do I do with the ZIP? I've tried including it as a library, adding it to the project, etc... but I can't import anything from the kuusisto package, nor can NetBeans find the TinySound class.
24  Game Development / Newbie & Debugging Questions / Can't figure out how to do Java Audio properly. on: 2013-10-04 19:35:46
This is driving me insane. I have asked on Reddit and StackOverflow, and besides the fact that everyone is quick to jump down my throat about supposedly not "searching beforehand" (which I have, by the way... extensively), nobody has given me an answer.

The problem being, that I cannot seem to make the Clip class in Java's sampled sound package work the way I need it to. So I either need someone to look at the code for my Sounds class and tell me what fatal problem is causing my game to freeze up when I try to play the same sound multiple times simultaneously, or refer me to another library/package I can use.

So anyway, I'm trying to make use of the Clip class. (http://docs.oracle.com/javase/7/docs/api/javax/sound/sampled/Clip.html)
I'm pre-loading the various sounds into an enumerator class and calling them statically as needed (ie: Sounds.WHATEVER.play()), but once I added sounds that would be played several times at once, simultaneously, the game started freezing up. I can only assume that the Clip class is not capable of doing this, but just in case I'm just doing something wrong... can someone look at my Sounds class and tell me if that is the case, or if I'm just doing something wrong?

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
/**
    This file is part of Generic Zombie Shooter.

    Generic Zombie Shooter is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Generic Zombie Shooter is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Generic Zombie Shooter.  If not, see <http://www.gnu.org/licenses/>.
 **/

package genericzombieshooter.misc;

import java.io.IOException;
import java.net.URL;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

/**
 * Contains all pre-loaded sounds.
 * @author Darin Beaudreau
 */

public enum Sounds {
    // Weapon-Related
   POPGUN("shoot2.wav", false),
    RTPS("shoot1.wav", false),
    BOOMSTICK("shotgun1.wav", false),
    FLAMETHROWER("flamethrower.wav", true),
    THROW("throw2.wav", false),
    EXPLOSION("explosion2.wav", false),
    LANDMINE_ARMED("landmine_armed.wav", false),
    TELEPORT("teleport.wav", false),
   
    // Zombie-Related
   MOAN1("zombie_moan_01.wav", false),
    MOAN2("zombie_moan_02.wav", false),
    MOAN3("zombie_moan_03.wav", false),
    MOAN4("zombie_moan_04.wav", false),
    MOAN5("zombie_moan_05.wav", false),
    MOAN6("zombie_moan_06.wav", false),
    MOAN7("zombie_moan_07.wav", false),
    MOAN8("zombie_moan_08.wav", false),
    POISONCLOUD("poison_cloud.wav", false),
   
    // Game Sounds
   POWERUP("powerup.wav", false),
    PURCHASEWEAPON("purchase_weapon.wav", false),
    BUYAMMO("buy_ammo2.wav", false),
    POINTBUY("point_buy.wav", false),
    PAUSE("pause.wav", false),
    UNPAUSE("unpause.wav", false);
   
    private Clip clip;
    private boolean looped;

    Sounds(String filename, boolean loop) {
        openClip(filename, loop);
    }

    private synchronized void openClip(String filename, boolean loop) {
        try {
            URL audioFile = Sounds.class.getResource("/resources/sounds/" + filename);

            AudioInputStream audio = AudioSystem.getAudioInputStream(audioFile);
            AudioFormat format = audio.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, format);
            clip = (Clip) AudioSystem.getLine(info);

            clip.open(audio);
        } catch (UnsupportedAudioFileException uae) {
            System.out.println(uae);
        } catch (IOException ioe) {
            System.out.println(ioe);
        } catch (LineUnavailableException lue) {
            System.out.println(lue);
        }
        looped = loop;
    }

    public synchronized void play() {
        play(1.0);
    }
   
    public synchronized void play(final double gain) {
        Runnable soundPlay = new Runnable() {
            @Override
            public void run() {
                Clip clipCopy = (Clip)clip;
                FloatControl gainControl = (FloatControl)clipCopy.getControl(FloatControl.Type.MASTER_GAIN);
                float dB = (float)(Math.log(gain) / Math.log(10.0) * 20.0);
                gainControl.setValue(dB);
                if(!looped) reset(clipCopy);
                clipCopy.loop((looped)?Clip.LOOP_CONTINUOUSLY:0);
               
            }
        };
        new Thread(soundPlay).start();
    }
   
    public synchronized void reset() {
        reset(clip);
    }
   
    public synchronized void reset(Clip clipCopy) {
        clipCopy.setFramePosition(0);
    }

    public static void init() {
        values();
    }
}


If I need to use a different package or library, I will, but I really want to stick to core Java, at least for this project.

So, is there some fatal error with the way I'm handling this? Or is the Clip class just not capable of playing sound this way?
I can provide information on how I'm playing the sound if need be, but really, all I'm doing is statically calling the play method for the required sound when that sound is supposed to be played (ie: firing a weapon, zombies moaning, etc). I think the reason this freezing never occurred before is because I was never playing the same sound multiple times simultaneously.

So... can someone spare me the insanity and tell me what it is exactly that I'm doing wrong?
25  Games Center / Archived Projects / Re: Generic Zombie Shooter! on: 2013-09-06 23:32:10
Just thought I'd pop in and show off some of the latest changes. Most notable is the lighting, which isn't quite what I want, but will do for now. This method will not work once I added randomly generated buildings. I've also added a new weapon and a new item... the Popgun and the Shiny Sticks (Handgun and Flares). The Popgun has unlimited ammo and can be used as a default weapon in case you run out of ammo. The Shiny Sticks, well... light things up! So you can see enemies coming at you from far away. I've also added a screen for player death that shows a few statistics (number of zombies killed, final wave number, medkits collected, ammo collected).

I've got three more weapon slots to fill. I've decided not to do melee weapons because I couldn't figure out how to adapt my Weapon class to handle them. If anyone can think of some unique weapons to really spice the game up, I'd love to hear of them!

Let me know what you think!



26  Game Development / Newbie & Debugging Questions / Re: Multiple AlphaComposite Sources? on: 2013-09-06 19:55:02
Quick tips on this stuff. First it is faster to draw images then gradients in java2D and you can use images as lights and color them on the fly.  Second, the way you have it right now, simply drawing multiple radial gradiant paints on top of your scene should be fine but don't use a bufferedImage back buffer because it is very very slow. Second, stay away from java's Area class.  Super slow.

What I recommend. Keep using the gradients as you probably do not need hundreds of lights. Set the rgba of the color of a light to what ever you want. Then instead of clearing to black, clear with a color of (0,0,0,0), empty. Instead of using a BufferedImage to draw with, create a compatible volatileiamge and draw all the lights to that with the SCR_OVER rule. Once done, composite that over the scene like you are doing.  Drawing with/clipping with polygons is rather fast. Go with that.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
   public void render(Graphics g)
   {
      if(!LIGHT_ON) // mapg2d is the Graphics a a VolatileImage
        return;
      clear();
      mapg2d.setColor(ambientColor);
      mapg2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, ambientLight));
      mapg2d.fillRect(offX,offY,mapWidth,mapHeight);
       for(int i = 0; i <= lights.size()-1;i++)
      {
         lights.get(i).render(mapg2d);
      }

      Graphics2D g2d = (Graphics2D) g.create();
      g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, colorBlend)); // the amount of color we want from the light map to be composited into the scene
     g2d.drawImage(lightmap,0,0,scrWidth,scrHeight,null);
      g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_ATOP, 1));
      g2d.drawImage(lightmap,0,0,scrWidth,scrHeight,null);
      g2d.dispose();
   }
   
   private void clear()
   {
      mapg2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC)); // this line may not be necessary.
     mapg2d.setColor(BLANK); // a static blank Color of (0,0,0,0);
     mapg2d.fillRect(0, 0, mapWidth, mapHeight);
   }


At the most, there will probably only be 4-5 lights at a time... the one over the player, and the ones created by Flares. I'm not going to do anything crazy like create a light for every Flamethrower fire particle... that would be nonsense. But how can I give the effect of the fire particles lighting up? It seems strange for fire not to light up the surrounding area.
27  Game Development / Newbie & Debugging Questions / Re: Multiple AlphaComposite Sources? on: 2013-09-06 18:16:33
It should be relatively simple to add coloured lighting, and by altering the geometry of what you draw to the shadow mask you can do simple directional light volumes too.  (CAG with the Area class would be a quick and dirty way of doing it)

I could just make a polygon in the shape of a front-facing cone and use a regular gradient paint on it, right?
Also, for colored lighting, could I just change the color values passed to the gradient?
28  Game Development / Newbie & Debugging Questions / Re: Multiple AlphaComposite Sources? on: 2013-09-06 17:00:19
If you see obfuscated code, you must have the wrong file, the code isn't obfuscated but the variable names are not the best as he had to fit it into 4 kb to fit the competition.

https://mojang.com/notch/j4k/l4kd/G.java

if it was obfuscated, you would literally have no idea whats going on, some things can give you hints, and you could probably be able to rename the variables to better ones, or comment sections of code to what is happening.

put the code into your IDE and just start changing stuff if needed to figure out what it does.

You don't call that obfuscated? And yes, that's the file I have. None of his variable names are descriptive, there's no commenting, and everything is just one big mess of code.
29  Game Development / Newbie & Debugging Questions / Re: Multiple AlphaComposite Sources? on: 2013-09-06 16:59:22
I am so confused... there's no simpler way to do this? That's an awful lot of code for what seems like it should be a simple effect. Are there other methods of achieving this that don't involve composites?

That's an entire application, so you can see it running in situ.


If you want only the relevant code, here it is:
Create the shadow mask; do this once, and keep it around:

1  
2  
      BufferedImage shadowBuffer = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_ARGB);
      Graphics2D sg = (Graphics2D)shadowBuffer.getGraphics();


Then, each frame....
Clear the shadow mask:

1  
2  
3  
4  
5  
6  
// clear the shadow buffer
        sg.setComposite(AlphaComposite.Src);
         sg.setColor(Color.BLACK);
         sg.fillRect(0, 0, WIDTH,HEIGHT);
         // and ready it for this frame's shadows
        sg.setComposite(AlphaComposite.DstIn);


Then draw each light source onto the shadow mask:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
         for(int i = 0;i < LIGHT_COUNT;i++) {
             int radius = 100;
             float [] dist = {0.0f, 1.0f};
             Color [] colors = {new Color(0.0f, 0.0f, 0.0f, 0.0f), Color.BLACK};
             RadialGradientPaint p = new RadialGradientPaint(new Point(lightsX[i], lightsY[i]),
                                                                             radius, dist, colors);
             sg.setPaint(p);
             // there might be an 'off by one' bug here. Haven't spent the time thinking whether fillRect bounds match circle+/-radius.
            sg.fillRect(lightsX[i]-radius, lightsY[i]-radius, radius*2, radius*2);
             
         }


Finally, once you've rendered everything else in your world, draw the shadow mask over the top:
1  
bg.drawImage(shadowBuffer,0,0,null);


It's basically the code you posted, wrapped in a for loop, with a few extra lines of initialisation. Simples.

Got it! It wasn't so hard after all. Now I'm going to create a LightSource class to store the light's information in and add a new item to the game... Flares!

30  Game Development / Newbie & Debugging Questions / Re: Multiple AlphaComposite Sources? on: 2013-09-06 16:40:47
Are there other methods of achieving this that don't involve composites? I was hoping for a method similar to that used by Notch in the game Left 4k Dead.

https://mojang.com/notch/j4k/l4kd/

Yes, you can do the lighting yourself at a per-pixel level.
That's probably how notch did it in L4KD; you can see for yourself, he did make the code available.

Doing it this way is far more flexible (you can do your own shadow casting calculations and such), but obviously it's a lot more complicated too.

Yeah, I have the code downloaded, but it's obfuscated and not commented, so I don't know what to do with it. I think it's a raycasting system, but like I said above, I'm not sure how to do that.
Pages: [1] 2
 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

Riven (18 views)
2014-07-29 18:09:19

Riven (13 views)
2014-07-29 18:08:52

Dwinin (12 views)
2014-07-29 10:59:34

E.R. Fleming (31 views)
2014-07-29 03:07:13

E.R. Fleming (12 views)
2014-07-29 03:06:25

pw (42 views)
2014-07-24 01:59:36

Riven (41 views)
2014-07-23 21:16:32

Riven (28 views)
2014-07-23 21:07:15

Riven (29 views)
2014-07-23 20:56:16

ctomni231 (60 views)
2014-07-18 06:55:21
HotSpot Options
by dleskov
2014-07-08 03:59:08

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:58:24

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:47:22

How do I start Java Game Development?
by ra4king
2014-05-17 11:13:37

HotSpot Options
by Roquen
2014-05-15 09:59:54

HotSpot Options
by Roquen
2014-05-06 15:03:10

Escape Analysis
by Roquen
2014-04-29 22:16:43

Experimental Toys
by Roquen
2014-04-28 13:24:22
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!