so i am dabbling in making a game and i am a fairly messy worker and then i go back and tidy it up. So please ignore any stupid naming conventions or methods or anything. As I go back later and tidy up.
So basically I am trying to make a main menu, i just want to draw something to the screen and have it stay there. I am writing the graphics to a image ATM and displaying the image as i tried just drawing to the canvas and it just flickered up onto the screen and then it went blank. I changed it to a runnable so i could put in sleep() to try and error hunt. I've removed all my error hunting code now. It turns out when i have a sleep() before or after the image is put on the screen for longer than 50ms the rectangle stays on screen and doesn't flicker away like 1ms after it was drawn.
I'm not sure what's going on. I am probably not that clear and I apologies.
import java.awt.Canvas;
import java.awt.Graphics;
import javax.swing.JFrame;
public class test extends Thread{
public static void main(String[] args){
test t = new test();
t.start();
}
#Override
public void run() {
JFrame f = new JFrame("Test");
Canvas c = new Canvas();
Graphics g;
c.setSize(400, 400);
f.add(c);
f.pack();
f.setVisible(true);
c.setVisible(true);
try {
sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
g = c.getGraphics();
g.drawRect(10, 10, 40, 68);
}
}
Basically, this is not how painting in AWT works. Painting should be done within the context of a component's paint method. In AWT Canvas seems to be the preferred base component to use.
You should never use getGraphics, apart from been able to return null, it will only represent the Graphics context from the last paint cycle, anything added to it could be wiped about by newer paint events...which is probably happening to you.
Take a look at Painting in AWT and Swing for details about how painting works.
Having said all that, I would discourage you from using AWT based API as it was replaced by Swing some 15 years ago.
Take a look at Performing Custom Painting for more details about painting in Swing
You're kind of getting the idea, but there are a few standard design patterns of creating a game, for starters check out this code.
Basically, you'll need something called a game loop which will update and render to the display a certain amount of times every second (framerate or fps). When it renders, it will clear and redraw the image in a new location at a certain interval, if your fps was 60 you would be rendering (clearing, and redrawing) 60 times a second. We can also introduce more advanced concepts such as buffer strategies (shown in the example above) to reduce tearing and flickering.
To sum it up, you're kind of there, you just need to constantly do that g = c.getGraphics() so...
while (true) {
g = c.getGraphics();
// set color
// draw a rectangle
g.dispose();
}
Note how I added the dispose, this will just free up any unused memory. Just to clarify, this is by no means good code, but it will give you a place to start :)
The flickering is due to only having 1 screen, to stop this flickering you need a buffer strategy. Basically having two buffers is like having two screens, whilst you render on one 'screen' you can clear and draw the next step on the second screen and switch between the two buffers; this reduces the flickering.
Related
I need a code, more specifically a game, in which meteorites fall down and the user has to dodge them with the arrow keys.
Moving the player is not my problem. I will do this at the end.
I figured out how to create an animated object falling down, from top to bottom.
How can I create a loop which creates one new falling element every 2 seconds? The position of the element should be randomized.
This is my code at the moment:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Game extends JPanel {
int x = 135;
int y = 0;
private void moveBall() {
y = y + 1;
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillOval(x, y, 30, 30);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Meteorites");
Game game = new Game();
frame.add(game);
frame.setSize(300, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
game.moveBall();
game.repaint();
Thread.sleep(10);
}
}
}
You will need a game loop (gl) first of all. The gl updates the state and position of every object on the screen and other state related objects not seen on the screen.
It should be easy for objects to register themselves to the gl. The gl is not responsible for updating the state of every object, but it does call back every registered object to update themselves (or update other objects that it is responsible for, for example the collision detection object will update any objects on the screen that have collided).
The gl passes the current time in nano-seconds (typically) to all the objects that have registered with the gl. For example check out the AnimationTimer in Javafx. In JavaFX, by creating an AnimationTimer, and calling the start method on it, JavaFX will call your handle method on every frame... essentially registering it to JavaFX's main thread (or game loop).
So you will need to create a gl. Register objects to it, maybe create an interface or abstract class similar to JavaFX's AnimationTimer so that objects can register themselves to your gl. The gl should not have any Thread.sleeps in it, but if it does it should be very short and I imagine you would add it in only if your gl is going to fast, because maybe there is not a lot of stuff being calculated (hence no use crippling the CPU), but you can adjust this. I know that working on JavaFX games I can tell you that we work very hard to keep any delays in he gl down to a minimum, hence no Thread sleeps, as this will halt the smooth flow of your animation.
The objects that get updated will track the passage of time and can execute events based on how much time has passed by. For example you can have an object that registers itself to the gl and is responsible for putting new falling animated objects on the screen. It can have a field for how long to wait before dropping the next item. Since it is called every frame by the gl, it can see how much time is passing by, and when x seconds pass by, it can create and drop the next object, then reset its timer.
The animated objects falling would also be called by the gl so they can smoothly drop down. At every frame these falling objects will calculate their new position. Typically this is done using an interpolator (its a good idea to look into this). Interpolators make it easy to abstract out where the position of an animating object should be relative to a fraction of time passing by. For example if I am moving an item linearly over X distance and Y time, an interpolater will tell you how far along X distance the object should be after a percentage of Y time has passed. Interpolators are very powerful because you can create an interpolator that moves your object not just linearly but can slow it up or speed it up (like gravity effect), it can even add bouncing effects to your objects. So you'll want to get a firm understanding of this. JavaFX comes with interpolators. There are also online tools I have seen in the past that let you construct your own JavaFX interpolators based on the kind of animation effect you are trying to get.
So to put it all together, have a gl, have an object that registers to the gl that is responsible for putting new falling objects on the screen, lets call this object ObjectDropper. The ObjectDropper will implement something like AnimationTimer so it can get called every frame by your gl. It will decide when to drop objects and can also decide the random point from where that object will drop. You will have objects that will drop, they will be given information like where their starting point is, where their ending point is, and how long it will take to drop, and maybe even an interpolator. These objects will also be registered to the gl and be called every frame so that they can adjust their position according to their interpolator.
This is all a very broad generic outline that tends to be true for most animated games. There might be tools and libraries that make this all easily implemented in Swing. As you can see JavaFX was already designed to handle many of these concepts.
I'm working on a game framework inspired by XNA. Almost every day I find a new problem with this or that. Today, it's going from window mode to full-screen and back. The gist of it is:
If I start the game in windowed mode it works fine. When I go full-screen in works fine too. After switching back from full-screen something goes wrong and nothing is drawn on the screen. Going to full-screen again works fine. I just get this problem in windowed mode unless the game started in it.
I set the window this way:
public void setW(){
jFrame.setVisible(false);
if(graphicDevice.getFullScreenWindow() != null && jFrame.isDisplayable())graphicDevice.getFullScreenWindow().dispose();
graphicDevice.setFullScreenWindow(null);
jFrame.setResizable(false);
jFrame.setUndecorated(false);
jFrame.getContentPane().setPreferredSize(new Dimension(width, height));
jFrame.setVisible(true);
jFrame.pack();
graphics = (Graphics2D)jFrame.getContentPane().getGraphics();
fullScreen = false;
}
Full-screen is set like this
public void setFS(){
jFrame.setVisible(false);
if(jFrame.isDisplayable())jFrame.dispose();
jFrame.setResizable(false);
jFrame.setUndecorated(true);
graphicDevice.setFullScreenWindow(jFrame);
graphicDevice.setDisplayMode(new DisplayMode(width, height, 32, 60));
graphics = (Graphics2D)jFrame.getContentPane().getGraphics(); // graphicDevice.getFullScreenWindow().getGraphics(); does the same thing
fullScreen = true;
}
Then I use this method to draw... deviceManager.getGraphics().draw...(actually i use an intermediary bufferImage) I use a game loop so this happens continuously.
public Graphics2D getGraphics(){
return graphics;
}
Now if I use this method:
public Graphics2D getGraphics(){
if(fullScreen)
return (Graphics2D)graphics;
else
return (Graphics2D)jFrame.getContentPane().getGraphics();
}
I'm sure I'm doing something wrong. Thew windowed mode works, this I know. Why does it go pear-shaped when I return from full-screen. The window just stays gray with nothing being painted on it.
However if I create a method like this:
public void assignGraphics(){
graphics = (Graphics2D)jFrame.getContentPane().getGraphics()
}
And call it later(one game cycle passed) it fixes the problem. That's why the second mode-switching method works, since it gets Graphics from the JFrame every cycle.
Worked on the problem quite a bit since starting this question and I thing here is the real crux of it: Why can't I get the Graphics for a Window in the same cycle I leave full-screen?
EDT. How come the problem is always where I'm not looking. Yes, the problem was that my game-loop is swing.timer-based. It's a rookie mistake and the fact, that it took me almost a week to figure it out, came down heavy on my ego.
Apparently many of swing operations go of on the EDT and using it for updating and drawing not only clogged the sucker up, but resulted in this questions' problem.
Now I'm going for variable time-step loop using while() in the main thread. (Even with a basic while loop with only update() and draw() the problem is gone)
Should have at least read one article on game loops before starting on my program. Live and learn(and waste a week being stumped).
-Hi all! I'm making a Java applet that simulates wave interference, which I have almost finished (will license under GPL). However, I have two questions regarding the AWT paint cycle that I am having difficulty finding answers to.
I want to make an 'about' overlay that appears when I press a button. The way I want to do this is to draw over the entire applet window with my static message and legend objects. The problem is stopping the AWT components from drawing themselves in the foreground without using remove(). Is there a way I can stop AWT from drawing itself temporarily?
For my standing waves mode I want to have node and anti-node markers calculated and drawn to a secondary graphics every time the standing wave reaches a maximum amplitude (all of which I can do myself), but drawn to the primary graphics (and thus displayed) every paint cycle. Could someone explain the steps to do so? I imagine it would involve creating a second graphics object, drawing to it once, then drawing it to the primary graphics every cycle.
If you are able to answer either of my questions I would be very grateful!
Cheers, Jack Allison
Responding to your first question:
You can't disable the paint()/paintComponent() method if you've inlcluded it in your code. If its there, it runs. However, you can create a flag so that only if the flag is true, the stuff gets drawn. Let me show you what I mean:
boolean flag;
...
public void paintComponent(Graphics comp) {
if (flag) {
Graphics2D comp2D = (Graphics2D) comp;
//drawing statements
}
}
public void actionPerformed(ActionEvent event) {
flag = true;
repaint();
}
I have a slight problem with BufferedImage and JPanel. I am creating a game with some 2d animation.
Basically i have an animationHandler that will loop through the pictures and depending on the rotation will also display it correctly. But the problem is - when I load in the pictures my Jpanel wont draw anything. It doesnt event matter if I comment out the custom paint methods - the paintComponent method wont draw anything and it seems like it skips the paintCompontent method. Even though the game doesnt crash and the timer still is running - it wont use the paintComponent method in an extended JPanel.
The class that contains the timer - calls the JPanel throught JPanel.repaint();
Here is the loadImg method
/**
* Test method to check animationHandler and bufferedImgs
*/
private void loadImages() {
BufferedImage b_1;
BufferedImage b_2;
BufferedImage b_3;
BufferedImage b_4;
BufferedImage b_5;
BufferedImage[] imgs = new BufferedImage[5];
try {
b_1 = ImageIO.read(new File("warlock1.png"));
b_2 = ImageIO.read(new File("warlock2.png"));
b_3 = ImageIO.read(new File("warlock3.png"));
b_4 = ImageIO.read(new File("warlock4.png"));
b_5 = ImageIO.read(new File("warlock5.png"));
imgs[0] = b_1;
imgs[1] = b_2;
imgs[2] = b_3;
imgs[3] = b_4;
imgs[4] = b_5;
animationHandler.addAnimation(imgs);
} catch (Exception e) {
e.printStackTrace();
}
}
Cheers!
You're could possibly be loading images on the Swing event thread or EDT (Event Dispatch Thread), and since the EDT is responsible for all Swing graphics and user interactions, this will freeze your Swing application until the loading is complete. The solution: load the images on a background thread such as can be obtained from a SwingWorker object. Please check out the Concurrency in Swing tutorial for more on this subject.
Also, if possible, and if the images aren't too large, it is usually best to load the images once and then hold a reference to them or to an ImageIcon.
And finally, whatever you do, don't load images inside of the paintComponent(...) method. This method must be lean and mean -- as fast as possible, and it should concern itself only with painting and nothing else. Else your program's responsiveness could become pitifully slow.
Also, regarding:
it wont use the paintComponent method in an extended JPanel.
You might want to show us this code.
I've been working on a java game recently, and I have a lot of it figured out. One thing still plagues me, however. The way it's set up, a player moves across a background (the game board). Currently, every time the player moves, it repaints the whole frame, including the background. This causes a brief, yet annoying screen flicker whenever the player moves.
I've separated out my code to draw the background separately from the things that need to be repainted:
public void drawMap(Graphics pane) {...}
public void drawPlayer(Graphics pane) {...}
The problem is that I can't find a way to make the board stay on the screen when I use repaint(); , a necessity for the player to move. Any suggestions?
You should look into double buffering, basically you paint an image to the buffer, then paint the buffer. It should remove the flickering effect you are talking about. Below are a few helpful links:
http://docs.oracle.com/javase/tutorial/extra/fullscreen/doublebuf.html
http://content.gpwiki.org/index.php/Java:Tutorials:Double_Buffering
http://www.ecst.csuchico.edu/~amk/classes/csciOOP/double-buffering.html
Just comment if your having trouble understanding it.
UPDATE: I would also suggest you look in 'Killer game programming in java'. You can get a free ebook of one of the older versions. Some of it is a bit out dated, but the first few chapters about setting up a game loop and drawing to the screen etc are still very much relevant.
UPDATE 2: From the second link, try something like this:
private void drawStuff() {
BufferStrategy bf = this.getBufferStrategy();
Graphics g = null;
try {
g = bf.getDrawGraphics();
drawMap(g);
drawPlayer(g);
} finally {
// It is best to dispose() a Graphics object when done with it.
g.dispose();
}
// Shows the contents of the backbuffer on the screen.
bf.show();
//Tell the System to do the Drawing now, otherwise it can take a few extra ms until
//Drawing is done which looks very jerky
Toolkit.getDefaultToolkit().sync();
}
UPDATE 3: This post here gives a nice code sample that you can play with and adapt, that should give you the best idea on how to do double buffering
I suggest to avoid redrawing everything with every change. Instead draw the whole frame at a fixed interval, e.g. every 50ms. Just keep the status of every element in a class and if something changes just change the data value. Due to the fixed redrawing interval the display will pick up any changes at the next redraw.