How do I get the mouse position. I have tried:
int mouseX = MouseInfo.getPointerInfo().getLocation().x;
int mouseY = MouseInfo.getPointerInfo().getLocation().y;
But that does it for the whole screen. Anyway to do it relative to the JPanel/JFrame
If I'm only using Graphics JFrame and JPanel that is being repainted every millisecond, should I have buffers? Or will it be fine?
How do I add a mouseAcionEvent only to the frame so it gets X() and Y() of mouse but only in frame?
Use a MouseListener instead of MouseInfo. MouseListener will trigger events which are contextual to the component which raised them, which means you won't need to translate the events into the component space as the event will already be converted to within the component context.
See How to write a mouse listener for more details
How should I update my game rePaint() every millisecond or another way?
Use a javax.swing.Timer...
See How to use Swing Timers for more details...
Should I use buffers?
That will depend. Swing components are already double buffered, but if you use a more complex timing mechanism (AKA game loop), you might find it useful, even to roll your own.
I, personally, would start simple
How can I improve the way I thought out my code in the first place? Is it right having 10 loops or only all in 1 to reduce lag ect.
There are probably lots of things, but start with broader idea...
Breakdown entities to their own responsibilities, for example, the player should know where it is and how it should be painted. It could even know how it's suppose to move based on the current state of the game. This way you could create any number of entities, all with there own set of rules which are isolated and easily updated.
Devise a controller mechanism which is responsible for taking in keyboard and mouse events and simply updating the current state of the game model. That is, rather than going "the user pressed the 'left' key, move player to the left", it would simply raise a flag in the game model that the "left" state has been triggered (or untriggered) and the engine would, on the next update loop, ensure that each entity knew about the change
Don't use magic or hard coded numbers, instead provide some kind of ability to scale the scene. For example, you could decide what is shown on the screen based on the size of the window...
Related
I need some help with a Java assignment I have, I'm required to build a clone of Pac-Man.
The problem is, I don't know how to draw the movements of the Pac-Man or the Ghosts. I'm thinking I should only draw the walls once, and continiously redraw the characters, but I don't know how I should do it or what methods of drawing I should use.
Generally speaking, it is no good idea not to redraw the complete GUI of any game you write several times each second (the quotient of complete redraws over a second is referred to as the 'frame-rate' of a game). If you do not do this, you might observe weird effects like: The contents look strange if you resize or move the window in case its not displayed in full-screen, there might by weird graphical effects, and, most important, the images of your game-characters won't disappear at their previous positions, if you do not draw the background over them again.
Common approach is to set up a Thread that is not doing anything else but invoking some redraw methods about 60 times each second (60 fps (frames per second) appear fluent to the human eye as our temporal resolution lies in that scale) and to use another Thread that updates the position data of the characters and passes it to the draw-Thread together with the static wall-position-data.
I'm running a game/simulation on JavaFX and when I started it seemed reasonable to add an AnimationTimer to perform the tick updates. My Entity's are composed of a Polygon that holds their shape and position. I added the Polygon's to the scene via a Group and everything renders like magic. However, since it's an simulation, I now want to run millions of ticks with no rendering, to advance to the future and see the results. The problem is, since my Entity's (x,y) positions are inside the Polygon, every time handle() is called in the animation, it seems that the screen is updated.
What is the proper way to split the game loop and render, to be able to call render only after some amount of ticks?
I thought of creating my own MyPolygon class to hold the simulation data, and then when the time comes to draw, create on the fly one Polygon per Entity, but that seems also overkill for me (but maybe I'm wrong).
Also, I'm not sure how to change the ticks per second rate on the AnimationTimer. So I'm not sure it is suited for this specific need.
It seems like a very simple design choice, so there has to be a proper way to do it with JavaFX...
I am currently programming a gui with JavaFX 2.0, which is resizable. When the user resizes the window, a big rectangle resizes with it. Now I need to push the new boundaries of this rectangle on to an image which floats inside the rectangle and may not cross its borders.
I thought of updating the boundaries via a ChangeListener, but I don't want it to update the boundaries that often. The perfect solution would be a "ChangeIsOverListener" which updates the boundaries once at the end of a change.
Can anybody help me out?
Thanks in advance! :)
You may be able to trap mouse-down and mouse-up events on either side of the window resizing - but whether you see those events will depend on the AWT system and may depend on the O/S too.
Otherwise you will have to use a timer within the window sizing event to trip a separate event some number of ms after the last window sizing event, such that you consider the size to be "done" if it hasn't be changed in the last, say, 1/2 a second. The amount of time will be a compromise between the user's perceived lag and the number of resizes you want to process.
Maybe you could compare the size of the window every x milliseconds, and when it doesn't change in this time interval, you know that the change is over.
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).
I'm creating an application with Java and SWT, and have a workspace generated on a Canvas. I need to make certain areas (controls) on the canvas trigger an event when mouseover-ed or clicked. Of course this could be done by listening to the MouseMoveEvent and checking the location of the mouse manually, but I would like to know if SWT provides an easier way to do this.
Thanks
As far as I know, there is no facility to automate this. You will need to register mouse listeners and investigate the x & y coordinates manually.
A different approach might be adding individual Canvas objects onto an enclosing Canvas. This way, you could add listeners to the individual controls. This will, however, use more memory (as the underlying object has a buffer, as well as the control on top) and redrawing will be more CPU intensive.
My personal preference goes to the first technique.
Thanks for the answer, Paul. I finally created an ArrayList of Rectangle objects for each control. Whenever the mousemove event triggers, I loop through each Rectangle and call Rectangle.contains() with the mouse coordinates. This solution turned out to be very organized.
In my case, the control events are homogenous (they all do the same thing), but if anyone has multiple control actions, Rectangle.data can be used to contain a Command object.