Java-Gaming.org Hi !
Featured games (87)
games approved by the League of Dukes
Games in Showcase (672)
Games in Android Showcase (194)
games submitted by our members
Games in WIP (727)
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 3 ... 44
1  Game Development / Newbie & Debugging Questions / Re: Sound on Debian Jessie Linux on: 2016-04-26 02:46:16
Just to double check, because I'm not sure what you mean when you say you are using AWT's sound. AFAIK, there is no play() method for audio in the AWT library.

The main sound libraries for Java audio playback are contained in javax.sound.sampled. The output classes that should be already implemented and running on any system that runs Java are the Clip and the SourceDataLine. Are you trying to execute the play() method of a Clip?

What is the class of the "audio" variable you mentioned in your original post, as in "audio.play()"?
2  Game Development / Newbie & Debugging Questions / Re: Sound on Debian Jessie Linux on: 2016-04-24 02:43:50
Quote
  Most of the articles I've read have said to change a file and uncomment something, but the problem is that I do not have administrative access to even open these files, much less change them.

I don't know a lot about Linux, but isn't the deal for getting administrative access something like going to a control prompt (is the program named Terminal?) and typing "sudo" before the command that you want to execute? Of course, that assumes you know the admin password.
3  Games Center / WIP games, tools & toy projects / Re: Vangard on: 2016-04-24 02:38:54
I gave the program a go a few days ago. It took me a while to figure out what I was doing, and I still have questions. But overall, it was intriguing and seems like it must be working as designed.

The first time I tried it, I didn't have your summary instructions and really floundered. I didn't figure out that the center sprite was the one being controlled. I couldn't tell that anything was happening when the arrow keys were pressed, as there is a lot of movement going on at the same time. For example, hitting the up arrow (I now know) moves you "forward" but given that the AI or whatever might be pointing you in any direction, it is hard to pick out the right movement and infer the control. Or at least, it was for me. Also I expected the down arrow to allow backwards movements. And I mistakenly was expecting the keys to be left/right/up/down, not rotate/forward.

Second time, I had reviewed your instructions and I figured out a lot more. But was stumped by trying to pick an apple off of a tree. Third attempt, I realized that the interaction is via the menus that pop up, not clicks on the countryside depiction. I'm not sure how you find your hovel if you forget where it is. I guess, by giving control back to the AI and letting it go back to home?

Now, after having picked and sold a few apples, I am wondering about the character I was started with. As far as I can tell it sleeps at its hovel, then goes to the market and hangs out there doing ??, and then goes home and sleeps again. I was not able to observe its profession or get anywhere when trying to buy a shovel and go mining or farming. So, I remain puzzled as to how I might add value to whatever the AI is already doing for my character.

I guess the next step is to go watch several different characters, and learn what is going on that way.

I think the graphics are functioning quite well. I like them. I look forward to seeing how this neat project develops.
4  Java Game APIs & Engines / Java Sound & OpenAL / Re: Java OGG API with concurrent playback on: 2016-04-18 09:29:06
I would trust what princec has to say more than philfrei, and that goes double for philfrei of 2013.
5  Game Development / Game Play & Game Design / Re: Is a Binaural Sound Engine in Java possible? on: 2016-04-12 04:06:18
This thread has my first hack at 3D sound, using pure Java. Since the original question was about whether this is possible or not, it seemed useful to have a link here.
6  Games Center / WIP games, tools & toy projects / Re: Skullstone - a dungeon crawler game on: 2016-04-12 03:54:00
I like the audio tracks a lot. The loops are polished, expressive, and wear well, with good levels of tension, so they should work as game play gets tenser or relaxes. Getting game play to have dynamic arcs can be a challenge though. There's always a danger of: "oh there's another monster, kill it, walk walk walk, oh there is another monster, kill it..." which can get a bit flat.

I don't know if your audio system is set up to do this, but (small point) instead of looping a flaming torch sample (the sample you have sounds like a good one), can you play a continuous stream of slices from the torch sample? I'm thinking slightly overlapping 1/4 or 1/5 second slices, selected randomly from the sample. As long as the player is moving around, the torch audio is long enough that you don't hear the loop. But if a person stops by a torch, it can become apparent. Something similar to the treatment of the brook sound here might be a small but nice touch. Am happy to share the algo, but I don't know your audio system. Can you output a continuous PCM data stream as audio?
7  Games Center / WIP games, tools & toy projects / Re: PFTheremin on: 2016-04-10 19:21:12
PFTheremin, SoundHandler API

   SoundHandler sh = new SoundHandler();

Class is located in the package: com.adonax.jtheremin

   // Following are methods of SoundHandler, e.g., sh.start();
   void start() // turns on audio thread
   void stop()  // turns off audio thread

   void startSync()  // save a reference sound frame and nanotime for internal event
             // used to schedule the pitch updates, can be called any time the
         // pitch updates develop lag beyond a built-in 1800 frames

   void setSynth(String name) // {"FM Sawtooth", "FM Square"}

   void startNote()  // theremin note starts playing, called by mouse-down
   void releaseNote()  // theremin note released, called by mouse-up
   void updateVolume(float normalizedFloat)  // Y-axis position scaled to float [0..1]
   void updatePitch(float pitch, long timeStamp) // pitch = actual Hz to be played
         // timeStamp (nanotime) = when that pitch occurs
         // the frame where the pitch will be scheduled is calculated from the
         // values stored in startSync()
   void updateVibDepth(float normalizeFloat) // vibrato affects both pitch and volume
   void updateVibRate(float normalizedFloat) // [0..1] corresponds to 2Hz..18Hz
         // distributed via a power function x^2
   void updateTimbre(float normalizedFloat)  // [0..1], corresponds to a range of values
         // preset in synth, sometimes referred to as FM Modulator Index
   void setModulatorFeedback(float normalizedFloat) // more FM stuff, affects timbre

   // control of Echo via the SoundHandler, e.g., sh.setEchoRunning(true);
   void setEchoRunning(boolean echoRunning)  // make the echo effect audible/quiet
   void setEchoMillis(int millis) // time until first echo
   void setEchoVolume(float normalizedFloat)  // volume of echo
   void setEchoFeedback(float d) //

**************
The following function may be useful for generating pitch values procedurally. Midi note values are linear, one per "piano key", with "middle C" = 36. Fractional notes are possible.

   double PitchFunctions.getHertzFromMidi(float midiNoteValue)

The package of this static class: com.adonax.pfaudio.midi

(Please message me if you want to use this as an external library in any game or application you are making.)
8  Games Center / WIP games, tools & toy projects / PFTheremin on: 2016-04-10 19:17:04


jar download > PFTheremin

Continuing on the theme of making scalable audio assets...a theremin in the works. The JavaFX GUI allows it to be played in real time.

I started writing about this and went overboard, so deleted everything. Minimum needed to know to try it out:

> mouse down in the orange area to get playback
> X-axis is pitch, Y-axis is volume (and optionally mapped "Expression Axis" features)

Next post will be an api for use as an external library, if you want to try incorporating this audio functionality in a game you are writing.
9  Game Development / Newbie & Debugging Questions / Re: Time, delays, etc on: 2016-04-01 07:42:57
Good suggestion. I'd like to add that there is also the option of a ConcurrentSkipListSet, where you could use your timestamp a Comparator. Part of the point is that this way one can have the set be invoked in the "game loop" but at the same time have asynchronous events, such as things driven by mouse or key actions, be added into the queue concurrently rather than as part of the game loop.
10  Game Development / Articles & tutorials / Re: Getting Started with JavaFX Game Programming (for Java Programmers) on: 2016-03-31 18:30:11
10,000+ views and counting and no comments or feedback. How should I interpret this?

-> Interest exists in the topic, but my writing is not so great or my examples not so useful?

Insecurely yours, Phil  Clueless
11  Game Development / Articles & tutorials / Re: Getting Started with JavaFX Game Programming (for Java Programmers) on: 2016-03-31 18:24:26
I just came across what seems like a good recommendation for the Node on which to place a Keyboard "listener." The suggestion is to use the Group node that is at the root of the node tree for the GUI, i.e., the node that is passed as a parameter to the Stage.

This is the practice used in the book "Learn JavaFX 8" by Kishori Sharan, Apress. From what I've seen so far (reading selections on Safari via local library account), this is a very useful book. Unlike many books on JavaFX, this one is receiving high evaluations, mostly 5's and 4's. It goes into depth on the specifics of the GUI and has good coverage of the use of the -fx api for using CSS commands directly to style GUI elements.

I still like "JavaFX for Dummies" for getting started, and for its excellent explanation of lambdas. Of the books I've checked out, these are the only two I recommend so far. There is another book that has separate chapters on using JavaFX for Android and iOS, but on first scan it seems like it could be dangerously sketchy (book has some low evaluations). From folks here at JGO, I'm hearing that the resulting code of the porting tools is not that great, but I haven't had a chance to test this myself and get a sense of just how much is lost in the translation.
12  Games Center / WIP games, tools & toy projects / Re: Vangard on: 2016-03-29 22:11:01
Walking living-challenged.
13  Games Center / WIP games, tools & toy projects / Re: Vangard on: 2016-03-29 22:05:11
I was more concerned about zombies and spells to set your foe on fire by mumbling the alphabet in reverse order.
It is often very important to get the order/reverse order thing correct. The spell for making a Golem from mud can turn the person who speaks the spell into mud if the wrong order is used.
14  Java Game APIs & Engines / JavaFX / JavaFX on Mobil and Embedded on: 2016-03-27 06:28:12
Quote
JavaFXPorts is the open source project that brings Java and JavaFX to mobile and embedded hardware, including iPhone, iPad, Android devices, and the Raspberry Pi.

http://gluonhq.com/open-source/javafxports/

Anyone here check this out yet?
15  Java Game APIs & Engines / Java Sound & OpenAL / Re: LibGDX audio not loud enough on: 2016-03-24 21:58:26
Libgdx has pan support and that's about it. If you use the AL backends you can make it 3D sound.

There isn't exactly a master volume setting as it just uses the gain function in AL to change the volume. Gain in OpenAL is a value between 0 and 1, (which is relative to the constant AL_MAX_GAIN which is normally 1 if I recall).

If you'd actually want to amplify sounds, you'd have to get the PCB data of the sound, actually edit it yourself, and play it back again using AudioDevice.

That's useful info!

So, I'd check that the values used for playback are actually set to 1, and if needed, tweak the AL_MAX_GAIN if it is reachable. From what the OP has stated (that Audacity plays the audio at a high volume), chances are that PCM data is already as high as it can be without clipping. But there is a lingering doubt in my mind--it seems to me that this would have come up before if there was a big difference between playback via LibGDX and other DAWs or sound systems. That (to me) adds to the likelihood that the values being sent to AL are somehow not 100%, and that the issue may be specific to the OP's game.

How much work to test the following: load and play the same assets using TinySound and compare playback volumes. Not sure if that is useful or not.
16  Java Game APIs & Engines / Java Sound & OpenAL / Re: LibGDX audio not loud enough on: 2016-03-23 22:46:12
Funnily enough, the same audio file plays louder in Audacity than it plays in LibGDX.  Amplifying the music would just clip the sound, which doesn't work out in anyone's favor.

Yes. From what has been written here, it sounds more like the issue is the level that LibGDX uses for playback than one concerning the assets themselves. Audacity is really great for easily amplifying assets to the maximum volume just short of clipping. Some audio systems are more conservative than others in terms of how much volume they allow. LibGDX must be on the low side. I've not heard of similar problems with TinySound, but it doesn't attempt to run on as many platforms as LibGDX, and doesn't have any special support for 3D audio. (Does LibGDX support 3D audio?)

The source for LibGDX is available, though. I remember looking through it a couple years ago, and being annoyed at how they coded stereo/mono parameter as a boolean or int and with a slightly confusing name. At least that is what is left of my memory of my general experience code reading the audio portion.

Still, if you are willing to open up a copy (isn't it on github or somewhere like that? I used to have a fork) it is likely very possible to tweak things to raise the volume without causing other problems.
17  Java Game APIs & Engines / Engines, Libraries and Tools / Re: Java Library written IN Java on: 2016-03-22 18:13:37
Someone should write a software renderer for occlusion culling in java...

There are depth buffers in JavaFX. Doesn't the 3D rendering in JavaFX include occlusion culling? Isn't JavaFX 3D now a standard part of the JVM? I think the only limitation with it is whether or not the graphics cards support the functions being called.

What am I missing?
18  Java Game APIs & Engines / Engines, Libraries and Tools / Re: Java Library written IN Java on: 2016-03-20 22:11:28
JavaFX
19  Game Development / Newbie & Debugging Questions / Re: Procedural (never ending) map generation on: 2016-03-18 17:22:22
Quote
...procedural generation doesn't mean that the map is infinite. It just means that the map is generated algorithmically, not manually.

True. But that generation can be ever-varying.

Quote
no map can be infinitely huge.

Are talking about the fact that there are only so many Long values or Double values? If coded at an reasonable scale, those limits will never be reached.

Perlin/Simplex can go as far as numbers exist that are not out of range for the coded calculations. And even then, couldn't one just re-seed the origin, create a smooth transition to the new seed and continue?
20  Games Center / WIP games, tools & toy projects / Re: 3D audio test using JavaFX and procedural java sound on: 2016-03-18 17:12:59
@Catharsis -- More good and interesting thoughts, thank you.

Quote
Collecting anything even from a moderate success will rely on the ethics of the other party which is a risk. If it was a truly black swan event it'd be easy for the other party to simply not pay and make it a legal situation. Anything over values that could be collected in small claims court could get locked up in a costly legal battle.

I think at the end of the day, working with people, doing business, requires trust, and written documentation of any agreements made, if only as a way to help make all assumptions explicit and thus eliminate misunderstanding.

My knowledge of people who have made it big (e.g., Notch, or that fellow that made the game where the little bird gets pounded by pistons that went viral) is that they have plenty of integrity. I'm sure there are counter examples.

Quote
And at that as mentioned a free platform with some services that can be kept behind a paywall fits that pattern.
Kind of what I'm thinking. There can be "free" versions (various jars with api's) that provide different services. But the biggie isn't trying to make something general purpose, but to give me the tools to make the best, most dynamic game audio I can, or to have lots to bring to the party upon collaborating with other musicians/programmers towards making awesome and unique games.

Quote
In this case for a spherical wavefronts physics matches perception. IE a sound source with no walls / reflections adding to the direct sound. You may potentially futz with the coefficients to change things somewhat, but still follow an inverse square relationship.

I started experimenting with this. My initial (current jar) algo was to define a max audio distance and get the % of this (expressed as a normal N), and apply it to a N^6 mapping (via LUT). This seemed to create an acceptable drop-off.

I tried a couple more things last night: scaling the distance into "attenuation units" and then deriving the volume factor by putting this value in the inverse form: 1/N. Also tried 1/(N*N). I can't say that it is all that clear to me, from a listener's perspective that one is superior to the other, yet.

More futzing and tweaking required. Come to think of it, I may have forgotten to compensate for the N^6 mapping done at the final stage. Hmmm. Have to work today--won't get a chance to think more on this for a while, except in the cracks/breaks.
21  Games Center / WIP games, tools & toy projects / Re: 3D audio test using JavaFX and procedural java sound on: 2016-03-17 22:30:35
@Catharsis -- Thanks again for lots of good info and feedback!

OSC is something I plan to look into in more depth. It ranks high on the to-study queue. All I know about it is that as a spec, it allows much more to be controlled than MIDI does. I'm thinking, in particular, once the updated theremin is built, I might draw from OSC methodology to control various expressive parameters of the theremin synth. Or, I might stick with something more like defining a control line as MIDI does and hook into the synth in this fashion. To be determined. One consideration: making synths that implement OSC or MIDI with any pretense to completeness is out of scope.

The notion of drawing ideas and algorithms from open specs of PD and SuperCollider is spot on. @nsigma has also provided links to implementations that are very helpful. I'm thinking of the source code, in particular, of a reverb unit that I was recently looking at.

Inverse square law for relating loudness to distance! Doh! Of course. I tried out several different power equations and settled on Math.pow(x, 6) as sounding the best, where x is a normalized fraction of a given audible distance range. I will try inverse square and compare. Theoretically, inverse square makes more sense. Ears and art don't always agree with physics, so I like to verify this sort of thing. (Who should I believe, experienced audio engineers or my own lying ears?)

For the 3D movement (not counting Y-axis as of yet), I'm relying on functionality built into JavaFX. I don't fully follow your example. I have what I'm calling an EarSet object. It's job is solely to manage the location of two "ears". To update it, I give it the X, Z and camera angle from the JavaFX PerspectiveCamera, once per game loop. To get pan and loudness, I use the EarSet's left and right ear coordinates at one end and the coordinates of the sounding object. No matrices involved, beyond what JavaFX manages behind the scenes via the PerspectiveCamera. This seems to be working pretty well.

Today, I put time into a Theremin front end rewrite, as I am hot on the trail with new things to implement based on how well the volume and pan smoothing worked on this demo. Maybe in a few days I'll get to the PD, SuperCollider or OSC research. But it seems like a good thing to build stuff and learn from the experience. No strategy is always right.

Money, money, money. Whatever. I fully understand the thinking of independents that don't want to spend anything. We build our own games, and already expect them to cost more than any income they might ever generate. I have been doing this for years. I understand dreaming. I call think of dreams as "Black Swan" events after the book I read on the subject. I am musing with the idea of sharing in the risk rather than asking for money up front. IF a game is a "Black Swan" success, the game maker can afford to pay something reasonable. Otherwise, no charge. It is a crazy business model, perhaps, trying to maximize the chance of participating in a black swan rather than up front income. But this is all very nebulous, and entirely moot, until the library shows it adds value, and that is still a ways into the future.
22  Games Center / WIP games, tools & toy projects / Re: 3D audio test using JavaFX and procedural java sound on: 2016-03-17 02:35:00
This is really cool. I experimented with the same thing just over a year ago, using a max/msp patch with my game. The results were promising, and it's since been my plan to revisit this approach more seriously, but my inexperience with sound programming makes the prospect seem kind of intimidating.

Is this meant as a new feature for PFAudio? Do you see that becoming a more general-purpose game audio library?

@boxsmith -- Thanks!  Smiley
I don't know much about how to patch things in. Is patching in max/msp similar to how one might patch in SuperCollider? How are games packaged in that scenario? Aren't those code bases rather large and come with restrictions?

Yes, this is meant to be part of PFAudio.

I am kind of overwhelmed with the task of adding the features and capabilities that push this library towards my vision of being a choice for procedural audio. I'd like to have a free version available. I have some objections/difficulties to spending the time to making it wholly general purpose. There is a lot to implement and support. For that sort of thing, I strongly recommend TinySound, which really is good for standard sound effects and music processing: cues can be loaded and played, mp3, ogg, etc. are accommodated, in addition to wav files.

I don't want to get into any backwards compatibility issues while I am still designing things. Things keep being radically turned around and experimented with. However, I'm open to the possibility of helping out with a custom version for a specific game, on an individual basis. Message me if you wish to discuss this some more! I am very sympathetic to DIY development.
23  Games Center / WIP games, tools & toy projects / Re: Vangard on: 2016-03-16 20:01:19
I was reading an interesting book the other day, that had a section that pertains to hunting. A key evolution for humans was the ability to sweat and thus not overheat. The hunting advantage was that a human could track and pursue for much longer periods than animals could flee--reducing the advantage the animal might have in speed. Animals apparently overheat more quickly than humans and need more cool-down periods. Thus, a team of hunters that spell one-another could be a deadly hunting team.

I wish I could remember the name of the book. It is about four ways human evolutionary advantages have become too successful in the modern context. The craving of salt, for example, that is part of the endurance advantage becomes more a hindrance when we don't need it to run marathons and high blood pressure becomes a health threat.
24  Games Center / WIP games, tools & toy projects / Re: 3D audio test using JavaFX and procedural java sound on: 2016-03-16 08:53:24
@Catharsis Thanks for your thoughts.

How would SuperCollider integrate with Java or JavaFX? My impression is that it is very powerful, and large. The latter fact is the main reason I've been avoiding it. I'm not as concerned with achieving that level of power. I'm mostly interested in bringing a useful subset of procedural functionality to Java game programming.

It would be good to tool around and compare, though. Having an actual 3D environment really makes a big difference. For example, when I was using volume panning, it was really easy to hear how using 0..1 pan setting and Left = n, Right = 1-n is very uneven. Spinning around in place next to a sound source, it is quite clear that left = 1, right = 0 or left =0, right = 1 is considerably louder than left = 0.5 and right = 0.5. I found that an equation that beefs up the center gives a much more even sense of volume while spinning, e.g., left = sin(n * PI/2), right = sin((1-n) * PI/2). In this case the 50% point gives (approximately) left = 0.7, right = 0.7, which is a better match for the all-at-one-side cases.

Voices would be interesting to hear.

I want to learn a bit more about filtering. The setup I'm using with a dedicated delay pipeline should work well with a low pass filter. I think a common simple design is to have a bell-shaped distribution of the sound value, e.g., 10%, 20%, 40%, 20%, 10% over five adjacent sound frames. But I'm not clear on how to derive the particular frequency effect of a given filter from the distributions. Presumably, as the percentage gets higher in the middle, there is less rolloff. But beyond that I'm still a novice.

If I manage to get code in place to play around with filters, I may only take things to the point of getting one or two decent occlusion algos and something for front/back. My sense for the front/back stuff is that the frequency area involved is principally the "presence" area (around 5K Hz) and maybe also a bit of the sibilants. That is the sense I've gotten from some car listening this most recent early Sunday morning (few cars going by so can listen carefully, comparing from behind and in front).
25  Games Center / WIP games, tools & toy projects / 3D audio test using JavaFX and procedural java sound on: 2016-03-16 02:26:53


File is here.

Am in a bit of a rush--so quickly:

I am working on a 3D audio system.
I made a quickie 3D chess board with JavaFX. You can tool around using the arrow keys.
The purple towers that come and go each emit a sound generated via a procedural FM synthesizer. There are six towers and five have pretty much the same frequency (slight variations in the amounts and rates of lfo and other tweaks) and one is considerably deeper in pitch.

The main thing: I'm using TIME to create a pan effect.
1) put the audio output of each tower onto a delay line
2) calculate the distance of each tower to the "ears" of the camera (the ears are separated by 32 pixels)
3) use the difference in distance to control two variable pointers into the delay line, one for each ear.

There is NO volume panning being used. Both ears are getting the exact same data, just with a time offset.

I had a pretty good volume pan going, but here's the problem with that: if you get up close to a tower and make one ear next to it, and the other away, the tower is pretty much silent in the far ear, allowing one to hear other stuff on the board.

In reality, if you are standing next to a jackhammer, the volume of the jackhammer masks both ears. It doesn't create an audio shadow that allows the sound to disappear in the far ear. With the temporal pan, the masking is much more correct.

I haven't yet tried putting in any filters to replicate front-back cone-of-confusion disambiguation. Nor even tried a slight front-back volume difference, which might be helpful. I do plan to get to this.

There is a bunch to do, in that first it has to work, then you improve performance and design. I seem to have to do things wrong a few ways before I can figure out a more reasonable way to do things.

Patting self on back: the changes in pan and volume are smooth, no zippering. I might try making my camera ears the equivalent of 35 centimeters apart instead of 32. There are undoubtedly other things to fix, too.
26  Java Game APIs & Engines / Java Sound & OpenAL / Re: Comparing binaural methods on: 2016-03-16 01:58:30
Just posted a redo of the above jar. Here it is again. I meant to do more with it, but only got the following done: a bit more info about the "distance" and time implied by the difference in frames for the second panning method. Also, got a standard sort of calculation relating values to db's. But the pan that uses volumes could still be improved. In particular, the energy at the ends is greater than the perceived volume in the middle. Something like a sine function that has the middle be 0.7 + 0.7 (left and right) instead of 0.5 + 0.5, it turns out, sounds better.

27  Game Development / Game Mechanics / Re: Best way for LWJGL to AWT in 3? on: 2016-03-09 19:15:50
Quote
The requirements are that it must render to a swing BufferedImage so I can scale, and manipulate it through a UI later. Using OGL 2.0 with shaders for the calculating the texturecoords.

I am curious if JavaFX has been considered for this or not. And if so, what are the drawbacks of using JavaFX 3D? From what I can tell, most transforms are available with mesh objects, and these can use images for texture/surfaces.
28  Discussions / General Discussions / Re: Best way to play sound? on: 2016-03-09 19:08:51
@StephenJSweeney - I understand that you have a solution and I don't mean to suggest you change anything. I just wanted to add this for people coming across your topic, that there is another option that seems quite viable: using JavaFX's AudioClip. AudioClips have more capabilities than javax.sound.sampled.Clip.

I was reading about them in the following book: Beginning Java 8 Games Development This book also has a good section on optimizing PCM files using Audacity, worth checking out, regardless of sound library.
29  Discussions / Miscellaneous Topics / Re: What I did today on: 2016-03-07 04:04:26
I've been working on setting up a 3D environment in order to have something to use with testing 3D audio. Yesterday I got a 3D chessboard set up with a camera that tools around over the squares, using JavaFX. Today, instead of continuing that, I took a break to write a little "Getting started with JavaFX" tutorial.

Most of the online tutorials I found via browsing are for the old version of JavaFX, not the Java 8 version. There were a number of annoying things I had to figure out, such as which of several options of game loops formats to use, and how to read keyboard input. So, the tutorial (posted in our tutorials and articles section) covers those annoying sorts of basics. Also covered an Eclipse/JavaFX bug that probably also stops a few beginners in their tracks.

My apologies to anyone trying to read it when I was first posting. My current browser is Firefox, and with the changeover to Windows 10, I got saddled with a weird new version of Internet Explorer that I haven't come to terms with yet. Need to download Chrome or something. So there was a fair bit of thrashing while the article was loaded, proofed, deleted, edited, reloaded, proofed, deleted, edited, several iterations of this.
30  Game Development / Articles & tutorials / Getting Started with JavaFX Game Programming (for Java Programmers) on: 2016-03-07 03:48:43
Getting Started with JavaFX Game Programming

I'm a Java programmer in the process of learning JavaFX, and was surprised by the lack of current tutorials on this subject. Much of what I found online was for an obsolete version of JavaFX, not the JavaFX current in Java 8. The following is meant to help with some of the annoying speed bumps encountered, not to teach game programming. I'm assuming you already know what a game loop is, for example.

Sections that follow:
I. Basic setup and installation (with notes on an Eclipse bug)
II. Basic graphics
III. Basic game loop (AnimationTimer)
IV. Simple Keyboard Input


Intro: Why JavaFX?
  • JavaFX is relatively fast and powerful. As an example, check out this particle generator written by Roland C. "The video shows 28000 particles running at 60 fps in full-hd screen resolution."
  • JavaFX has advantages over AWT/Swing. Oracle has stopped development of AWT/Swing, and is committed to advancing JavaFX as the main GUI for Java, going forward. As a rewrite of Java's GUI, the API is better designed and easier to learn and to code than Swing. While I'm told that not all of Swing's features have been implemented, the vast majority of the functionality has, and JavaFX makes 3D programming and many additional special effects available.
  • JavaFX has some advantages over LWJGL-based graphics systems. The main advantage is that it is easy to integrate widgets (buttons, sliders, etc.) with the 3D graphics. Adding Swing widgets to a LWJGL-based system is difficult. There is also an easier learning curve because the coding, even for 3D, remains "Java-like", whereas with LWJGL one has to get into learning Open-GL and deal with a C-influenced syntax. There are probably legitimate arguments that a system, such as LibGDX will be more powerful, but maybe not by much, as well as back and forth about the comparative advantages of the OpenGL paradigm versus the JavaFX 3D system. But this is something that I am unqualified to address.

I. Basic Setup & Installation

JavaFX now comes standard with Java 8. If you use Java 8 or better, no additional or external libraries need to be imported. I'm not aware of a way to make use of the current JavaFX with earlier Java builds.

As of this writing, Eclipse (and this includes my current installation of NEON) requires an annoying extra step in order to access the JavaFX library. For some reason, the JRE System Library must be removed and reattached before JavaFX will be found. The following steps only have to be done once per project.

After creating a new Java Project:
  • Open the Java Build Path property (right click the Project, select Build Path > Configure Build Path...)
  • Open the Libraries tab, select the JRE System Library and "Remove" it. The system library may be named something like "JRE System Library[JavaSE-1.8]".
  • Click "Add Library...", in the next popup, select "Java System Library" (should be the first choice), and on the next screen "Workspace default JRE (jre[VERSION#])" (should be the last radio button), and "Finish".
If you are making use of another JRE, I'm guessing you will probably know how to alter the above steps to load your preferred JRE System Library. I just use of the default.

At this point, Eclipse should have no problems finding JavaFX objects and methods.


II. BASIC GRAPHICS

The entry class for a JavaFX project has to extend javafx.application.Application. Then, we "launch" the  JavaFX GUI from the main method. The method launch executes the start method. This method provides the programmer with a Stage instance. All of the JavaFX functionality occurs within the context of this Stage instance.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
    import javafx.application.Application;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.stage.Stage;

    public class BasicGraphicsDemo extends Application{

        public static void main(String[] args) {

            launch(args);
        }

        @Override
        public void start(Stage stage) throws Exception {

            Group root = new Group();
            Scene scene = new Scene(root, 600, 400);

            stage.setScene(scene);
            stage.show();
        }    
    }


A Stage functions as a top level frame. A Stage can display a Scene. A program may have more than one Scene.

A Scene holds a tree of the type Node. Most of the objects we use in JavaFX are subclasses of Node. By convention, the very first Node of the tree is named root, and is the object Group. A Group is an object that holds a collection of Nodes.

In the above code, the constructor for the Scene includes the root, and the dimension in pixels (width, height) of a display window. There are various other constructors one can use, as can be found in the API for Scene.

The following code adds a blue circle to the display.

1  
2  
3  
4  
5  
6  
7  
              Circle circle = new Circle();
              circle.setCenterX(100);
              circle.setCenterY(200);
              circle.setRadius(40);
              circle.setFill(Color.BLUE);

              root.getChildren().add(circle);


The object Circle is one of several javafx.scene.shape options. Setting attributes is pretty straightforward. Experienced Java programmers should have no problem consulting the API for additional properties and variations.

Adding the Circle node to the root node is a little tricky, but once the pattern is learned, you will find that the same form is consistent over many situations. The collection of nodes held by the Group variable is returned by the method getChildren. Standard practice is to chain the add method onto this collection, as done in the above example. You can consult the API to learn about different forms of adding.

In the next code fragment, a caption is given to the top-level Stage, and the blue Circle is added to the display. When run, the image following this code fragment is displayed.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
    @Override
    public void start(Stage stage) throws Exception {

        stage.setTitle("Basic JavaFX demo");

        Group root = new Group();
        Scene scene = new Scene(root, 600, 400);

        Circle circle = new Circle();
        circle.setCenterX(100);
        circle.setCenterY(200);
        circle.setRadius(40);
        circle.setFill(Color.BLUE);
        root.getChildren().add(circle);
   
        stage.setScene(scene);
        stage.show();
    }      



 

III. Basic Game Loop

JavaFX offers several animation methods, with varying degrees of usefulness for game programming. I initially tried the "Many Balls" animation from "JavaFX for Dummies". This otherwise excellent book (the explanation of Lambdas is the best I've found anywhere) makes use of a method of animation that employs a KeyFrame and a Timeline. The resulting animation is unsatisfactory, as there are noticeable jitters. So, I recommend skipping that and making use of the vastly superior animation method employed in the Particle Generator program cited at the top of this article.

The key Object is named AnimationTimer. The most common practice I've seen is to create an AnimationTimer as in the following:

1  
2  
3  
4  
5  
6  
7  
8  
9  
    AnimationTimer animator = new AnimationTimer()
    {
        @Override
        public void handle(long arg0)
        {
            // update
            // render
        }
    };


The code in the handle method is executed repeatedly when the start method of the AnimationTimer is called, and the repetitions are halted when the stop method is called. The argument arg0 that becomes available to the coder is the clock time at the start of the given repetition, measured in nanoseconds.

I was thrown, initially, by the fact that there is no way to set the frequency or timing of the repetitions. What the JavaFX designers have done is to implement a target repetition rate of 60 frames per second, where a frame corresponds to one iteration of the handle method. If your handle method takes longer than that to execute, then the frame rate slows down accordingly. A new iteration does not start until the current iteration has completed. If your handle method executes more quickly, the system waits rather than running at an fps that is faster than 60.

The following code animates the ball in the previous example, from side to side.

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  
    import javafx.animation.AnimationTimer;
    import javafx.application.Application;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.Circle;
    import javafx.stage.Stage;

    public class BasicGraphicsDemo2 extends Application{

        final int WIDTH = 600;
        final int HEIGHT = 400;
       
        double ballRadius = 40;
        double ballX = 100;
        double ballY = 200;  
        double xSpeed = 4;
   
        public static void main(String[] args) {
   
            launch(args);
        }
       
        @Override
        public void start(Stage stage) throws Exception {

            stage.setTitle("Basic JavaFX demo");

            Group root = new Group();
            Scene scene = new Scene(root, WIDTH, HEIGHT);

            Circle circle = new Circle();
            circle.setCenterX(ballX);
            circle.setCenterY(ballY);
            circle.setRadius(ballRadius);
            circle.setFill(Color.BLUE);
            root.getChildren().add(circle);

            stage.setScene(scene);
            stage.show();

            AnimationTimer animator = new AnimationTimer(){

                @Override
                public void handle(long arg0) {

                    // UPDATE
                    ballX += xSpeed;

                    if (ballX + ballRadius >= WIDTH)
                    {
                        ballX = WIDTH - ballRadius;
                        xSpeed *= -1;
                    }
                    else if (ballX - ballRadius < 0)
                    {
                        ballX = 0 + ballRadius;
                        xSpeed *= -1;
                    }

                    // RENDER
                    circle.setCenterX(ballX);
                }      
            };

            animator.start();    
        }
    }



IV. SIMPLE KEYBOARD INPUT

The JavaFX Event System has many similarities to Java. There are plenty of good and clear examples of usage in the Java Tutorials, JavaFX section. But the tutorial example provided for KeyEvent was overly complicated for my taste. The following is provided as a quick introduction to the basic form.

In this example, EventHandler<KeyEvent> is implemented by the main class (BasicGraphicsDemo3). Alert! When importing KeyEvent, make sure to import from the javafx library (javafx.scene.input.KeyEvent) and not java.awt.event.KeyEvent. I inadvertently did this and wasted a fair bit of time puzzling over the resulting error messages.

A class which implements EventHander must override the method handle(KeyEvent keyEvent).

1  
2  
3  
4  
5  
6  
7  
8  
    @Override
    public void handle(KeyEvent arg0) {

        if (arg0.getCode() == KeyCode.SPACE )
        {
            xSpeed *= -1;
        }
    }


In this example, the KeyEvent variable provided by the event is inspected. If the code matches KeyCode.SPACE, we reverse the direction of the ball. The JavaFX API documents all the available KeyCodes, and includes all the letters, and code names for the arrow keys: KeyCode.UP, KeyCode.DOWN, KeyCode.RIGHT, KeyCode.LEFT.

You can also inspect the API of KeyEvent for other information provided by this variable the event occurs. I don't illustrate more common usages, such as separately tracking pressing and releasing, or handling simultaneous keys. These issues are similar enough to the Java equivalents.

How is the handle method triggered? This is done from a Node, using the method setOnKeyPressed. Other options are also available, e.g., setOnKeyReleased, setOnKeyTyped.  There are two requirements for the Node: it must be part of the Scene that is currently being shown, and, it has to contain the focus.

1  
2  
3  
4  
5  
6  
7  
8  
9  
    // need to attach KeyEvent caller to a Node of some sort.
    // How about an invisible Box? (arbitrary choice)
    final Box keyboardNode = new Box();
    keyboardNode.setFocusTraversable(true);
    keyboardNode.requestFocus();

    keyboardNode.setOnKeyPressed(this); // call to the EventHandler

    root.getChildren().add(keyboardNode);


The choice of Box was totally arbitrary on my part. There is probably a more appropriate subclass of Node to use. The JavaFX tutorial code example uses a StackPane. I suppose I could have also used the existing Circle node for the ball. But it seems more sensible that the keyboard handler be a dedicated Node rather than serve multiple functions.

Giving the node the focus required two steps. First, the node is set to be "FocusTraversable". Once that is done, it is  given the focus with the method requestFocus.

Complete program BasicGraphicsDemo3.java:
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  
    import javafx.animation.AnimationTimer;
    import javafx.application.Application;
    import javafx.event.EventHandler;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.input.KeyCode;
    import javafx.scene.input.KeyEvent;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.Box;
    import javafx.scene.shape.Circle;
    import javafx.stage.Stage;
     
    public class BasicGraphicsDemo3 extends Application
                  implements EventHandler <KeyEvent>
    {
        final int WIDTH = 600;
        final int HEIGHT = 400;
       
        double ballRadius = 40;
        double ballX = 100;
        double ballY = 200;  
        double xSpeed = 4;
       
        public static void main(String[] args) {
             
            launch(args);
        }
       
        @Override
        public void start(Stage stage) throws Exception {
       
            stage.setTitle("Basic JavaFX demo");
             
            Group root = new Group();
            Scene scene = new Scene(root, WIDTH, HEIGHT);
             
            // Bouncing Ball
            Circle circle = new Circle();
            circle.setCenterX(ballX);
            circle.setCenterY(ballY);
            circle.setRadius(ballRadius);
            circle.setFill(Color.BLUE);
            root.getChildren().add(circle);
             
            // need to attach KeyEvent caller to a Node of some sort.
            // How about an invisible Box?
            final Box keyboardNode = new Box();
            keyboardNode.setFocusTraversable(true);
            keyboardNode.requestFocus();
            keyboardNode.setOnKeyPressed(this);
           
            root.getChildren().add(keyboardNode);
             
            stage.setScene(scene);
            stage.show();
           
            AnimationTimer animator = new AnimationTimer(){
 
                @Override
                public void handle(long arg0) {
       
                    // UPDATE
                    ballX += xSpeed;
                           
                    if (ballX + ballRadius >= WIDTH)
                    {
                        ballX = WIDTH - ballRadius;
                        xSpeed *= -1;
                    } else if (ballX - ballRadius < 0) {
                        ballX = 0 + ballRadius;
                        xSpeed *= -1;
                    }
       
                    // RENDER
                    circle.setCenterX(ballX);
                }
            };
 
            animator.start();
        }
 
        @Override
        public void handle(KeyEvent arg0) {
             
            if (arg0.getCode() == KeyCode.SPACE )
            {
                xSpeed *= -1;
            }
        }
    }
Pages: [1] 2 3 ... 44
 
IanParcs (55 views)
2016-04-18 14:18:53

KaiHH (51 views)
2016-04-18 08:35:41

KaiHH (81 views)
2016-04-15 12:43:58

theagentd (83 views)
2016-04-14 02:16:17

theagentd (99 views)
2016-04-14 02:15:43

IanParcs (122 views)
2016-04-12 03:51:16

IanParcs (53 views)
2016-04-12 03:50:03

IanParcs (49 views)
2016-04-12 03:49:54

IanParcs (47 views)
2016-04-12 03:49:52

IanParcs (55 views)
2016-04-12 03:49:52
Website offering 3D Models specifically for games for free
by vusman
2016-05-06 11:10:21

Website offering 3D Models specifically for games for free
by vusman
2016-04-29 12:56:17

List of Learning Resources
by SilverTiger
2016-02-05 09:39:47

List of Learning Resources
by SilverTiger
2016-02-05 09:38:38

List of Learning Resources
by SilverTiger
2016-02-05 09:35:50

Rendering resources
by Roquen
2015-11-13 14:37:59

Rendering resources
by Roquen
2015-11-13 14:36:58

Math: Resources
by Roquen
2015-10-22 07:46:10
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!