Just a forewarning: I'm new to java - I normally use UnrealScript and C# but I'm branching out, so there is likely one or two things I've done incorrectly or against the normal java convection (that would be more in align with convictions of those other two languages)
Feel free to point them out, and I'll mold myself to them accordingly
I'm making a JRPGish style game in java using BlueJ. I'm not aiming massively high, and am more doing it as a proof-of-concept rather than a full blown game.
So far its going ok. I'm got a sprite animation working using a sprite sheet and the player can walk around with the sprite changing to the correct animation depending on the direction.
However I'm having an issue when the player stops moving - there sometimes is a afterimage of the previous frame - In fairness, this may be happening all the time except you cant see it if the player stops moving on the first and last frame of the walking animations, as those take up the same pixel space and thus are hidden (if that makes sense)
Here is an image of the issue in action:
This is after the player has moved, and then stopped, leaving the last frame of the "moveRight" sprite behind.
I have created a small version of my project that has just the character animation playing when you press a key, and stopping when you release, in which the issue appears
The Skeleton class
The Character class
The GameManager class
The KeyManager class
To start the game run the Main method in GameManager
You'll need to save this image with the filename of "James.png" and place it in the same folder of the java project for it to work
Thanks in advance for any help given.
paintComponent() passes Graphics to drawCharactor(). drawCharactor() should not disposes that Graphics object unless you made a copy, this Graphics is shared.
Also, do not call repaint() from drawCharactor(). repaint() schedules another paint cycle. You already do call repaint() from a timer.
Do not use java.util.Timer use javax.swing.Timer for Swing painting. See How to Use Swing Timers
For more information and examples Performing Custom Painting and Painting in AWT and Swing.
Consider posting a minimal example.
Related
I am new to java and programming in general,and i am trying to write a little shooting game with a spaceship and aliens, but having a lot of trouble with the graphics. It seems that I am mixing a lot of different kind of components.
How should I do it right?
- Should I use Swing JFrame and then add it a Graphics object?
- Should I make a panel first and add the graphics on to it instead?
- Or maybe should I use a canvas instead of a JPanel?
There are a lot of options, and searching the net for answers makes me very confused. Some advise to use the paint() method while others demonstrates code while using the paintComponent()...
What is the preferred way in the right order for the graphics to be laid and what classes should I use?
For serious gaming, don't use Swing but rather other more game-specific GUI libraries such as the LWJGL. For simple Games, Swing is OK, but be sure to read the graphics tutorials first as your assumptions on how to draw may need to be changed (I know mine were). For instance you would not use a Graphics class field but would usually draw passively in a JComponent's paintComponent method.
For simple games, Swing is fine and you can rely on the followings:
Use Swing and forget about AWT. You will get far better results with a lot less code.
Use Swing Timer to pace your game
For each of your components, extends JComponent or JPanel and override paintComponent. In paintComponent perform only drawing operations (do not update your model or modify the state of your component).
Whenever when you want to draw something, modify your components state and then invoke repaint()
To handle layers, you can always use JLayeredPane
I can see the sense of using a game API as suggested by #Hovercraft, but feel that many simple games can do without it.
I agree with the first 2 points of #Guillaume, but would tend to go in a different direction after that.
Let us assume the game:
Is a fixed size (i.e. non-resizable).
Has no components appearing over it.
In that case, I would tend to do the rendering in a BufferedImage that is displayed in a label.
Answers to specific questions
Should I use Swing JFrame and than add it a Graphics object?
That would not compile. So ..no.
Should I make a panel first and add the graphics on to it instead?
That is basically what Guillaume is suggesting, though I prefer using an image as the canvas on which to paint.
Or maybe should I use a canvas instead of a JPanel?
If by 'canvas' you mean java.awt.Canvas then no.
If you mean a java.awt.image.BufferedImage then yes.
Some advise to use the paint() method while others demonstrates code while using the paintComponent()...
This is a common confusion since there is so much old and bad code out there in the World Wild Web.
The only components that overriding paint(Graphics) would work with are components of the AWT & Swing top-level containers such as JFrame, JApplet or JWindow.
AWT is last millennium's GUI component toolkit. We should use Swing this millennium.
It is unusual for an entire GUI to be custom painted. Instead it might be added as the major component amongst others that report player health, lives remaining, score etc. For that (and other) reasons, it is better to render to a 'non top-level container' which would leave us looking at doing custom painting in a JComponent or JPanel.
For custom painting in an extended panel or component, override paintComponent(Graphics). That is the correct way to do custom painting for those components.
Other tips
Each object of the game (e.g. Ship, Enemy, Missile) should know how to draw itself. Keep a reference to each of the game elements in the painting routine, and simply call gameElement.paint(Graphics) (or Graphics2D) on the instance of graphics it is painting.
If the game elements are drawn from Java-2D based Shape instances, or if a Shape can be defined from the existing sprite images, collision detection becomes simple. For details see:
This answer to Get mouse detection with a dynamic shape
This answer to Collision detection with complex shapes
I had to implement a lost-vikings like game for a course project and not having a single idea how to do it, had the exact same questions in mind.
I ended up writing methods that are responsible for drawing different elements(i.e., one to draw enemies, one for missiles, etc...), and then called them in paint() method. I called repaint() method in my main loop to redraw everything.
I am not sure if this is a good practice, but it worked. You can check the code here, though, I must warn you that it is a "damn, i must get it done" project. You should specifically have a look at GameFrame.java.
Here is my problem:
I currently have on Canvas in my main game activity that is constantly being drawn with OnDraw(). This is a board game with two players. When a player's turn begins, there are many options that the player can do, and I would like all of this to be put in a different class.
Also, this new class must draw NEW animations on top of the current canvas. These animations will came from attacks (I haven't even looked into animations yet). So basically I would like another canvas on top of the main one.
Furthermore, the OnDraw function in the main activity must PAUSE and wait for the other class with the canvas on top to complete.
Let me try and summarize this: I have a main game class with one canvas. This class handles the players' turns and setting up the game. It also draws the playing field. I need another class, when it is a player's turn, to draw animations and other things on top of the current canvas.
Can anybody help me with this?
NOTE : I looked into Fragments and FragmentManager, but it seems I can only use XML Views with that and not RenderViews.
Thank you!
You might want to consider using multiple bitmaps as buffers and then just add them on top of each other before rendering to the canvas.
There is a nice example in the "samples" pack that comes with the sdk that shows of how you can merge bitmaps on top of each other.
Let me know if you want to try this out and need some more pointers on how to do it :)
This program will have an infinite canvas (ie as long as the user scrolls, it becomes bigger) with a tiled background image, and you can drag and drop blocks and draw arrows between blocks. Obviously I won't use a layout manager for placing blocks and lines, since they will be absolutely positioned (any link on this, possibily with a snapping feature?). The problem arises with blocks and lines. Basically I'll have two options:
Using a simple layout for each building block. This is the simplest and clearest approach, but does it scale well when you have hundreds of objects? This may not be uncommon, just imagine a database with 50 tables and dozens of relationships
Drawing everything with primitives (rectangles, bitmaps, etc). This seems too complicated (especially things like text padding and alignment) but may be more scalable if you have a large number of objects. Also there won't be any event handler
Please give me some hints based on your experience. I have never drawn with Java before - well I did something rather basic with PHP and on Android. Here is a simple preview
DISCLAIMER
You are not forced to answer this. I am looking for someone who did something like this before, what's the use of writing I can check an open source project? Do you know how difficult it is to understand someone else's code? I'm talking about implementations details here... Moreover, there is no guarantee that he's right. This project is just for study and will be funny, I don't want to sell it or anything and I don't need your authorization to start it.
Measuring and drawing text isn't such a pain, since java has built in classes for doing that. you may want to take a look at the 2D Text Tutorial for more information. In fact, I did some text drawing computations with a different graphics engine which is much more primitive, and in the end it was rather easy (at least for the single-line drawing, for going multiline see the previous link).
For the infinite canvas problem, that's also something I always wanted to be able to do. A quick search here at stackoverflow gives this which sounds nice, althought I'm not sure I like it. What you can do, is use the way GIMP has a scroll area that can extend as you move - catch the click of the middle mouse button for marking the initial intention to move the viewport. Then, when the mouse is dragged (while the button is clicked) move the viewport of the jscrollpane by the offset between the initial click and the current position. If we moved outside the bounds of the canvas, then you should simply enlarge the canvas.
In case you are still afraid of some of the manual drawing, you can actually have a JPanel as your canvas, with a fixed layout. Then you can override it's paint method for drawing the connectors, while having child components (such as buttongs and text areas) for other interaction (and each component may override it's own paint method in case it wants to have a custom-painted rect).
In my last drawing test in java, I made an application for drawing bezier curves (which are basically curves made of several control points). It was a JPanel with overidden paint method that drew the curve itself, and buttons with custom painting placed on the location of the control points. Clicking on the control point actually was clicking on a button, so it was easy to detect the matching control point (since each button had one control point associated with it). This is bad in terms of efficiency (manual hit detection may be faster) but it was easy in terms of programming.
Anyway, This idea can be extended by having one child JPanel for each class rectangle - this will provide easy click detection and custom painting, while the parent will draw the connectors.
So in short - go for nested JPanels with custom drawing, so that you can also place "on-canvas" widgets (and use real swing widgets such as text labels to do some ready drawing) while also having custom drawing (by overriding the paint method of the panels). Note that the con of this method is that some swing look-and-feel's may interfere with your drawing, so may need to mess a bit with that (as far as I remember, the metal and nimbus look-and-feel's were ok, and they are both cross-platform).
Well I am going to bed right now, and in next 2 days I have to code a simple program with animation that will simulate an inverted broom on a cart (a pole balancing genetic algorithm problem) the cart has to be pushed constantly from both sides to prevent the broom from falling down
You can see it in this video
http://www.youtube.com/watch?v=Ums3eGIVgks
or this picture image http://lis.epfl.ch/research/projects/EvolutionOfAnalogNetworks/ArtificialNeuralNetworks/images/mechanik_small.png
Well, I need to simulate physical behavior of this, but I have very little time, so I need something that I can understand and start using fast (the assignment is more into physics and genetic programming, so the simulation has to be just to show how it works).
Thank you
I'd use HTML5 Canvas and pure javascript. It's super easy, you don't need to compile. All you need is notepad, Chrome/Firefox/IE9, and a little time. There are tons of examples out there:
http://3.paulhamill.com/node/36
If you want an application, create a java application which uses a JPanel in a JFrame. In the JPanel override the paintComponent(Graphics g) method, and look at the graphics class which allows you to draw simple shapes like lines, rectangles, and ellipses.
I'm trying to animate a chess piece in a board. First I created a java.util.Timer object that "scheduleAtFixedRate" a TimerTask implemented as a proxy function. So I kept a record of the piece to move (piece-moving-record) and when it's apropriate (when the user move the piece using the mouse) the TimerTask proxy function should be test if the record is not nil and execute the piece-moving function. The piece-moving function just updates the x and y coordinates of the piece, according to a vector pre-calculated. I put a add-watch on the piece-moving-record so when it changes it should repaint the board (canvas). The paint method tests if this piece-moving-record is not nil to paint it.
The problem is that the animation doesn't appear. The piece just jump to the destiny, without the movement between. There is some problem with the animation scheme ou there is a better way to do it?
Updates to Swing components should be done on the Event Dispatch Thread (EDT). So you should be usig a Swing Timer since any code executed when the Timer fires will be executed on the EDT.
All you should have to do is set the location of the chess piece and it will repaint itself automatiocally.
Read the section from the Swing tutorial on How to Use Timers for more information.
Swing doesn't do animation automagically it does not matter if you have a timer or not. If you want to animate movement you need to move the piece some distance at a time and repaint the canvas with every move so it gives the illusion so to speak of movement.
you can use Trident library : Here
There's a Animator demo in the JDK. It uses awt but it should give you some ideas.
jdk1.6.0_20\demo\applets\Animator
Another idea might be to look at the Processing visualisation framework from processing.org. It's a simple but powerful and well-documented programming language for animation and visualisation. The API is very straightforward , and has a very transparent Clojure wrapper named Rosado.