physics engine with multiple object groups - java

My java application requires a 2d physics engine for a horizontal world, however, looking at jbox2d and dyn4j, it seems that they don't offer what I need out-of-the-box. Specifically, they don't support defining which object groups can collide with others. Consider this simplified model: Bullets can collide with boxes. Planes pass through boxes, but they can collide with bullets.
How do I exclude certain groups of objects from colliding in a physics engine?

Dyn4j has the CategoryFilter. You create CategoryFilters with two longs and set those in your Fixtures. It's a little funny how the filters work because the category and mask are used in their binary forms to determine who can collide with who. To see this in practice check out this #Test from the Dyn4j repo.
Dyn4j also mentions this in the docs:
There are three Filter implementations provided, the Filter.DEFAULT_FILTER, the CategoryFilter (just like Box2D’s collision filter, int category + mask), and the TypeFilter.
So I'm assuming Box2D has this too (and jBox2d by extension). I'd say just about any physics engine at Box2D's or Dyn4j's level will have this ability in some form.

There is a solution in box2d (and jbox2d respectively).
The "PreSolve" method allows to disable a contact before colliding. See this question on gamedev which has pretty much the same problem as described here.
From documentation:
Pre-Solve Event
This is called after collision detection, but before collision resolution. This gives you a chance to disable the contact based on the current configuration. For example, you can implement a one-sided platform using this callback and calling b2Contact::SetEnabled(false). The contact will be re-enabled each time through collision processing, so you will need to disable the contact every time-step. The pre-solve event may be fired multiple times per time step per contact due to continuous collision detection.

Related

Reading controller triggers individually with LWJGL

I would like to use a controller with a game I'm writing. I use the LWJGL Controller class to read the controller state.
The state of the triggers seems to have been summarised into a single value that represents the sum of the state of both triggers. The left trigger state is a value that varies between -1 and 0, the right between 0 and 1.
I currently use the getAxisValue() method to get the combined state.
I would like to be able to read these values separately. Is there any way I can do this?
The "Combined trigger axis" issue is caused by DirectInput. JInput uses DirectInput to poll the 360 controller. In this article is explained that the combining of axis was an intentional change to keep compatability with legacy games.
Quoting the article:
The combination of the left and right triggers in DirectInput is by design. Games have always assumed that DirectInput device axes are centered when there is no user interaction with the device. However, the Xbox 360 controller was designed to register minimum value, not center, when the triggers are not being held. Older games would therefore assume user interaction.
The solution was to combine the triggers, setting one trigger to a positive direction and the other to a negative direction, so no user interaction is indicative to DirectInput of the "control" being at center.
In order to test the trigger values separately, you must use XInput. `
LWJGL can not offer separate trigger values because it in effect relies on DirectInput.
The best course of action would be to find java bindings for XInput, which does allow separate trigger values.

Bx2D body Sprite synch

seeing as how box2D bodies cannot be resized, I have a problem with bodies and my animated sprites.
here's the situation which I have no doubt is not unique:
my sprite's dimensions slightly change during different motions like attacking, walking, jumping. seeing as how I was about to use box2D body for collision detection this can cause quite a problem.
so far I thought of 3 ways to solve this issue.
1- not use box2d bodies for collision detection , just use them for object's physical behavior
2- delete and recreate body before each render. or on animation change.
3- trying to recheck the collision on bodies to see if it actually collides with the sprite itself. then act.
and here's the problem I have with each of these solutions.
1- this way makes using box2d as a whole seem rather absurd, also I'll be using not one, but two world logic and trying to keep them in sync. seems like a big headache.
2- this doesn't look very optimized, also I doubt I can just make objects pop in and out of existence in a physics world without side effects.
3- I'm not sure how or even if this can be done, actually this option is the one I require more advice on. will this cause any difficulties in the long run, or cause conflicts in physics.
please let me know if there is a efficient way to solve this , or if any of the above solutions is worth working on.
my thanks
Edit:
It was more of a general question since I still don't have proper graphics for the game I'm writing, but here's my practice material:
walking waiting (standing)
attacking
A body can have multiple fixtures, so you can add all fixtures for each state to the body. If you make them zero density it should not affect the physics behavior of the body. Keep in mind though, that at least one fixture on the body should be non-zero density - you could make one fixture to act as the main fixture, which has density to give the body some mass.
If you just need to detect when these fixtures are touching something, you could make them sensor fixtures, and use your contact listener to keep track of what other things they are currently touching. The contact listener would give you callbacks about all of the fixtures regardless of which state your character is in, and for each state you would keep a list of which things the fixtures for that state are touching.
If you need the fixtures to have physical interaction but only when their state is active, you could do the above but also in BeginContact you would do contact->setEnabled(false) if the contact is for a fixture that is not currently in active state.

JAVA Checking if a 3D object is within another 3D object/Bounds

I am working on a project on particle simulation and, in order to simulate a correct physical behavior, I need to make my objects collide and bounce off. The thing is that I also need to check whether or not a particle is within the central object (a cone).
I know that in the Sphere class , as well as in other primitives from vecmath, there is a function .intersect(), which is perfect for collisions. However, I do not find a function .contains() to check whether one object is within another (like in the 2D library).
Any of you got any suggestions and/or other libraries to implement that?
Thanks a lot

robocode engine: how to design (write) the runtime engine -- the robot world

IBM has (had) a free learn-Java program called RoboCode, in which custom robots could be written that would then do battle in a 2D space. I would like to write the environment that supports such robots, but don't know what pattern or design to use. Each robot is a thread. Each thread is given a certain (indeterminate) amount of run-time by the JRE. A robot world engine would start by building a list of the players/robots, then enter a loop that allows each player in turn to do whatever it likes: move forward, turn left, fire toward the northwest corner, whatever. Each robot is also informed of events of interest: an enemy or several enemies are within range, it has been hit by a bullet, etc.
The combination of handling threads that are also event listeners (are they also producers?) confuses me; it seems that there's more to the game engine. Even some general ideas would help.
I'm Robocode engine developer. I joined 2 years ago and spent most of the time by refactoring Robocode engine. I wrote couple of articles during the time as my understanding grown. Not all of them are up to date, thought.
There are several difficult parts about it:
1) synchronization: we solved it by 'sending' messages between robot and battle. Updating the UI and other components is producer/consumer with non-mutable messages about each new state (game tick)
2) sandboxing malicious code (go and learn from our code)
3) design of API and rules to be constant for long years, because engine evolves, old robots stay same, but they must run and score same way as before. We hit several troubles here, for example people use the classes from API in their own logic. This wasn't intention. We had to make the classes final and with protected constructors. But now we can't change it to not broke existing robots.
For your question about events in Robocode. They all come each tick, we populate EventManager (priority queue) and then robot pulls one by one. Call is dispatched back to robot's implementation for each event. The subscription is automatic, implementation is always present in base class and you could override it in robot class. There is single thread for robot.
BTW: Next big thing seems to be extension of Robocode to allow for custom/plugable rules. It's design challenge. We are looking for smart, hard working people to join Robocode project to help us. Interested ?

How can I best apply OOP principles to games and other input-driven GUI apps?

Whenever I try to write graphical programs (whether a game or really any GUI app) I always wind up with one or two god classes with way too many methods (and long methods, too), and each class having far too many responsibilities. I have graphics being done at the same time as calculations and logic, and I feel like this is a really bad way to go about organizing my code. I want to get better at organizing my code and abstracting out responsibilities to different classes. Here's an example of where I'd like to start - I want to write a Minesweeper clone, just sort of as practice and to try to improve my software engineering skills. How would I go about making this nice and object-oriented? For the sake of discussion, let's just say I'm using Java (because I probably will, either that or C#). Here's some things I would think about:
should each tile inherit from JButton or JComponent and handle drawing itself?
or should the tiles just be stored as some non-graphical MinesweeperTile object and some other class handles drawing them?
is the 8-segment display countdown timer (pre-Vista, at least) a separate class that handles drawing itself?
when the user clicks, do the tiles have mouse event listeners or does some other collision detection method loop through the tiles and check each one to see if it's been hit?
I realize that there's not just one way to write a GUI application, but what are some pretty basic things I can start doing to make my code more organized, manageable, object-oriented, and just over all write better programs?
edit: I guess I should add that I'm familiar with MVC, and I was originally going to incorporate that into my question, but I guess I didn't want to shoehorn myself into MVC if that's not necessarily what I need. I did searched for topics on MVC with GUI apps but didn't really find anything that answers my specific question.
edit2: Thanks to everyone who answered. I wish I could accept more than one answer..
Here is a simple (but effective) OO design to get you started:
First create a Game object that is pure Java/C# code. With no UI or anything else platform specific. The Game object handles a Board object and a Player object. The Board object manages a number of Tile objects (where the mines are). The Player object keeps track of "Number of turns", "Score" etc. You will also need a Timer object to keep track of the game time.
Then create a separate UI object that doesn't know anything about the Game object. It is completely stand alone and completely platform dependent. It has its own UIBoard, UITile, UITimer etc. and can be told how to change its states. The UI object is responsible for the User Interface (output to the screen/sound and input from the user).
And finally, add the top level Application object that reads input from the UI object, tells the Game what to do based on the input, is notified by the Game about state changes and then turns around and tells the UI how to update itself.
This is (by the way) an adaption of the MVP (Model, View, Presenter) pattern. And (oh by the way) the MVP pattern is really just a specialization of the Mediator pattern. And (another oh by the way) the MVP pattern is basically the MVC (Model, View, Control) pattern where the View does NOT have access to the model. Which is a big improvement IMHO.
Have fun!
use a MVC framework that handles all the hard organization work for you. there's a ton of MVC framework topics on SO.
using high quality stuff written by others will probably teach you faster - you will get further and see more patterns with less headache.
I'm not suggesting this is the only way to do it, but what I would suggest is something like the following. Other people, please feel free to comment on this and make corrections.
Each tile should inherit from something and handle drawing itself. A button seems like the best solution because it already has the button drawing functionality (pressed, unpressed, etc) built in.
Each tile should also be aware of its neighbors. You would have eight pointers to each of its eight neighbors, setting them to null of course if there is no neighbor. When it goes to draw, it would query each neighbor's IsMine() function and display the count.
If none of its neighbors are a mine, it would then recurse into each neighbor's Reveal() method.
For the 7-segment display, each digit is its own class that handles drawing. Then I would make a CountdownSegmentDigit class that inherits from this class, but has additional functionality, namely CountDown(), Set(), and Reset() methods, as well as a HitZero event. Then the display timer itself is a collection of these digits, wired up to propagate zeroes left. Then have a Timer within the timer class which ticks every second and counts down the rightmost digit.
When the user clicks, see above. The tile itself will handle the mouse click (it is a button after all) and call its Reveal() method. If it is a mine, it will fire the MineExploded event, which your main form will be listening to.
For me, when I think of how to encapsulate objects, it helps to imagine it as a manufacturing process for physical parts. Ask yourself, "How can I design this system so it can be most efficiently built and reused?" Think about future reuse possibilities too. Remember the assembly process takes small pieces and builds them up into larger and larger pieces until the entire object is built. Each bit should be as independent as possible and handle its own logic, but be able to talk to the outside world when necessary.
Take the 7-segment display bit, you could have another use for it later that does not count down. Say you want a speedometer in a car or something. You will already have the digits that you can wire up together. (Think hardware: stock 7-segment displays that do nothing but light up. Then you attach a controller to them and they get functionality.)
In fact if you think hard enough, you might find you want CountUp() functionality too. And an event argument in HitZero to tell whether it was by counting up or down. But you can wait until later to add this functionality when you need it. This is where inheritance shines: inherit for your CountDownDigit and make a CountUpOrDownDigit.
Thinking about how I might design it in hardware, you might want to design each digit so it knows about its neighbors and count them up or down when appropriate. Have them remember a max value (remember, 60 seconds to a minute, not 100) so when they roll over 0, they reset appropriately. There's a world of possibilites.
The central concern of a Graphic User Interface is handling events. The user does X and you need to response or not respond to it. The games have the added complexity in that it needs to change state in real time. In a lot of cases it does this by transforming the current state into a new state and telling the UI to display the results. It does this in a very short amount of time.
You start off with a model. A collection of classes that represents the data the user wants to manipulate. This could represent the accounts of a business or vast frontiers of an unknown world.
The UI starts with defining a series of forms or screens. The idea is that is for each form or screen you create a interface that defines how the UI Controller will interact with it. In general there is one UI Controller classes for each form or screen.
The form passes the event to the UI Controller. The UI Controller then decides which command to execute. This is best done through the Command design pattern where each command is it own class.
The Command then is executed and manipulate the model. The Command then tells the UI Controller that a screen or a portion of a screen needs to be redraw. The UI Control then looks at the data in the model and uses the Screen Interface to redraw the screen.
By putting all the forms and screen behind a interface you can rip out what you have and put something different in. This includes even not having any forms at all but rather mock objects. This is good for automated testing. As long as something implements the Screen Interface properly the rest of the software will be happy.
Finally a game that has to operate in real time will have a loop (or loops) running that will be continually transforming the state of the game. It will use the UI Controller to redraw what it updated. Commands will insert or change information in the model. The next time the loop comes around the new information will be used. For example altering a vector of a object traveling through the air.
I don't like the MVC architecture as I feel it doesn't handle the issues of GUIs well. I prefer the use of a Supervising Controller which you can read about here. The reason for this is that I believe automated tests are one of the most important tools you have. The more you can automate the better off you are. The supervising presenter pattern makes the forms a thin shell so there is very little that can't be tested automatically.
Sorry to say it, but it seems you have mess in your head trying to improve your coding too much in one step.
There is no way to answer your question as such, but here we go.
First start with OOP, think about what objects are required for your game/GUI and start implementing them a little at a time, see if there are chances to break up these objects further, or perhaps reunite some objects that make no sense on their own, then try to figure out if you have repeated functionality among your objects, if you do, figure out if this repeated functionality is a (or many) base class or not.
Now this will take you a few days, or weeks to really grok it well, then worry about dividing your logic and rendering.
I have some tutorials that are written in C#. It discusses this very same topic. It is a starting point for a RogueLike game.
Object Oriented Design in C# Converting Legacy Game
Object Oriented Design: Domain Type Objects
Object Oriented Design: Rethinking Design Issues
BROKEN LINK - Object Oriented Design: Baby Steps in Acceptance Testing

Categories