Libgdx Ashley Entity Collision - java

I'm attempting to make a game with libgdx and ashley. I have a basic understanding of both and was wondering how to handle a entity collision.
I saw a ContactListener in Box2D, but I am unsure of how to link this with entities in ashley.
I just want to prevent entities from passing through other entities.

Here is one approach, that I implement myself:
Define interface CollisionListener:
public interface CollisionListener {
void onBeginContact(Body bodyA, Body bodyB);
}
Create CollisionListenerSystem that register itself as world contact listener, and notifies your other systems about collisions:
public class CollisionSystem implements ContactListener {
private final List<CollisionListener> collisionListeners;
public CollisionSystem(World world, List<CollisionListener> collisionListeners) {
world.setContactListener(this);
this.collisionListeners = collisionListeners;
}
#Override
public void beginContact(Contact contact) {
for (CollisionListener collisionListener : collisionListeners)
collisionListener.onBeginContact(contact.getFixtureA().getBody(), contact.getFixtureB().getBody());
implement CollisionListener in any system, that should process collisions and pass it in the collisionListener list in CollisionSystem constructor

Related

In an (JavaFX) MVC architecture with a separated control, is it normal to have most your Event Handlers just calling view methods?

So I'm learning JavaFX programming and MVC. The control is also its own class and isn't integrated into the view (Which I've heard is one way to go at it). I want it to be separated from the view but because I'm trying to encapsulate everything and leave everything private with limited access to the controls/nodes, I find myself using methods to do almost anything inside of my object almost entirely when using event handlers in the control.
Example (Not an actual program, just wrote it here because I have no short examples.):
View:
public class SamplePane extends BorderPane {
private TextField tfScoreOne;
private Button btnScore, btnPenalty;
private int scoreOne;
public SamplePane() {
// Some constructor
}
public void giveScore() {
scoreOne++;
tfScoreOne.textProperty().setValue("Score: " + Integer.toString(scoreOne);
}
public void takeScore() {
scoreOne--;
tfScoreOne.textProperty().setValue("Score: " + Integer.toString(scoreOne);
}
}
public void btnScoreAddHandler(EventHandler<ActionEvent> handler) {
btnOneAdd.setOnAction(handler);
}
public void btnPenaltyAddHandler(EventHandler<ActionEvent> handler) {
btnOneAdd.setOnAction(handler);
}
Control:
public class SampleController {
public ModuleSelectionController() {
// Some contorller stuff again
samplePaneObj.btnScoreAddHandler(btnScoreHandler);
samplePaneObj.btnPenaltyAddHandler(btnScoreHandler);
}
private class btnScoreHandler implements EventHandler<ActionEvent> {
public void handle(ActionEvent arg0) {
samplePaneObj.giveScore();
}
}
private class btnPenaltyHandler implements EventHandler<ActionEvent> {
public void handle(ActionEvent arg0) {
samplePaneObj.takeScore();
}
}
}
This is mostly pseudocode so forgive me if there are any errors but do you get the point? It seems very arbitrary to just be calling methods but without passing the TextField in the example its hard to not do everything without a method doing all the work.
But is that decoupled enough for MVC? I don't really wanna break encapsulation is the main issue so I can't make the controls public and operate on them directly in the controller.
Is this all just normal? I want to make sure I'm grasping it right.
There is too much that could be said about this here. I'd advise you to have a look at a JavaFX application framework and read its documentation. I learned a lot from it. E.g., have a look here: https://github.com/sialcasa/mvvmFX
Don't make the mistake and try to derive some implementation patterns yourself from all the hello world examples out there on the internet. They all don't teach you how things should be done so that they scale well for real-world projects.

Java inversion of control on an MVC based application

I'm building an MVC based java application/game and trying to use IoC to separate object creation from application logic.
Let's assume I have just 2 entity : Board and Player where
each one has a Model class, a View class and a Controller class.
The BoardModel needs a PlayerModel (to handle some app logic) and the BoardView needs a PlayerView (to render it inside its space ).
To create a new Player I use a PlayerFactory class that creates the PlayerModel, the PlayerView and the PlayerController and wires them together.
The problem is that after creating the Player I need the PlayerModel and PlayerView instances to create the Board.
My solution is to "wrap" the PlayerModel, PlayerView and PlayerController in a Player class that only has these 3 fields and 3 getters; pass the Player to the BoardFactory and inside the factory use the 3 getter to get the View and the Model needed by the Board.
I'm doing something like this :
PlayerFactory pFactory = new PlayerFactory();
Player player = pFactory.build("HUMAN");
BoardFactory bFactory = new BoardFactory();
Board board = bFactory.build(player);
My worries are about the "wrapper" Player class.
Does it make sense to have a class just to hold 3 objects ?
Is there a better way to pass the dependencies to the Board without using a IoC container?
Your overall approach looks good. Although, there are a couple of changes I would make :
PlayerController and Player seem to have the same responsibility. I would get rid of Player completely and just use a PlayerController instead
The pseudo-code would look like this :
public class PlayerController {
private PlayerView playerView;
private PlayerModel playerModel;
//constructor that intializes playerView and playerModel
public void render() { playerView.render() }
public void moveForward(int steps) {
if(playerModel.canMoveForward()) {
playerView.moveForward(steps);
}
}
}
Similarly, you can get rid of Board and just have a BoardController instead. BoardController can then depend on PlayerController instead of depending on Player. The pseudo-code for this would look something like :
public class BoardController {
private PlayerController playerController;
private BoardView boardView;
private BoardModel boardModel;
//constructor that intializes the dependencies
public void render() {
playerController.render();
boardView.render();
}
public void movePlayerForward(int steps) {
if(!boardModel.isGameOver()) {
playerController.moveForward(steps);
}
}
}
This way, you get rid of Player and Board classes that were really not doing much. Alternately, you can rename the above classes to Player and Board. Another advantage of the above pseudo-code is that you also end up making your code more readable by implementing the Tell Dont Ask principle.

adding on ground traps with libGDX

I am trying to look up how to add on ground traps in libGDX, but to no avail. I would like to find a trap example. It would be really nice if it uses object colisions, but I don't know if it is possible to do without making them impassable.
A use case would be like caltrops, where the player should be able to walk over them, but a collision still takes place.
A lot of information is lacking on your question. But it seems you are using boxd2, because if you were handling the collisions with your custom code you would easily solve your problem.
If you are using boxd2, you can make your trap body a sensor.
body.getFixtureList().get(0).setSensor(true); //assuming it has only one fixture
And set its UserData to something you can check when the collision occurs.
body.getFixtureList().get(0).setUserData("trap");
then, define a contact listener to check for collisions with bodies with that user data:
//define the Contact listener
public class MyContactListener implements ContactListener{
#Override
public void beginContact(Contact contact){
if ((String)contact.getFixtureA().getUserData()=="trap" || (String)contact.getFixtureB().getUserData()=="trap")
//hurt player
}
#Override public void endContact(Contact contact){}
#Override public void preSolve(Contact contact, Manifold oldManifold){}
#Override public void postSolve(Contact contact, ContactImpulse impulse){}
};
And create and set the contact listener in your ini code.
MyContactListener contactListener = new MyContactListener();
world.setContactListener(contactListener);

Looking for an appropriate design pattern

I have a game that tracks user stats after every match, such as how far they travelled, how many times they attacked, how far they fell, etc, and my current implementations looks somewhat as follows (simplified version):
Class Player{
int id;
public Player(){
int id = Math.random()*100000;
PlayerData.players.put(id,new PlayerData());
}
public void jump(){
//Logic to make the user jump
//...
//call the playerManager
PlayerManager.jump(this);
}
public void attack(Player target){
//logic to attack the player
//...
//call the player manager
PlayerManager.attack(this,target);
}
}
Class PlayerData{
public static HashMap<int, PlayerData> players = new HashMap<int,PlayerData>();
int id;
int timesJumped;
int timesAttacked;
}
public void incrementJumped(){
timesJumped++;
}
public void incrementAttacked(){
timesAttacked++;
}
}
Class PlayerManager{
public static void jump(Player player){
players.get(player.getId()).incrementJumped();
}
public void incrementAttacked(Player player, Player target){
players.get(player.getId()).incrementAttacked();
}
}
So I have a PlayerData class which holds all of the statistics, and brings it out of the player class because it isn't part of the player logic. Then I have PlayerManager, which would be on the server, and that controls the interactions between players (a lot of the logic that does that is excluded so I could keep this simple). I put the calls to the PlayerData class in the Manager class because sometimes you have to do certain checks between players, for instance if the attack actually hits, then you increment "attackHits".
The main problem (in my opinion, correct me if I'm wrong) is that this is not very extensible. I will have to touch the PlayerData class if I want to keep track of a new stat, by adding methods and fields, and then I have to potentially add more methods to my PlayerManager, so it isn't very modulized.
If there is an improvement to this that you would recommend, I would be very appreciative. Thanks.
I am not at all an expert in design patterns. But this is what I think might be useful:
To add actions to the player, you might wanna look at the Strategy Pattern. Just google for it and you will get lot of examples.
Here is an attempt by me:
For updating the player stats, I guess Observer Pattern will be helpful.
The Observer Pattern defines one-to-many dependency between objects so
that when one object changes state, all of its dependents are notified
and updated automatically.
It enforces loose coupling so that future changes are easy.
(You will have to read about Observer Pattern and also will have to see some examples. It is not as straight forward as Strategy.)
Due to the fact that you said you want to be able to add new stats and actions later, I would tend to make a stats object that doesn't need to know anything about the game it's recording. The advantage is that the Stats class would never need to change as you added new features.
public interface Stats {
void incrementStat(Object subject, String stat);
int getStat(Object subject, String stat);
}
You Player implementation would look something like:
public void jump() {
// Logic to make the player jump...
stats.incrementStat(this, "jump");
}
Of course, what you're trading for that flexibility is static type-checking on those increment methods. But in cases like this I tend to think the simplicity is worth it. In addition to removing tons of boiler plate from the PlayerData and PlayerManager classes, you also end up with a reusable component, and you can get rid of the cyclic dependency between PlayerManager and Player.

Testing Presenters in MVP GWT application

I have a simple application and want to make it testable. I m new in this area.
Here is a simple Presenter, taking in mind this code ,could you advice or give me some example how to test it.
public class SomePresenter extends Presenter<MainPanelPresenter.Display>
{
public interface Display extends WidgetDisplay
{
HasClickHandlers getAddButton();
HasClickHandlers getDeleteButton();
void setData(ArrayList<Person> data);
ArrayList<String> getSelectedRows();
Widget asWidget();
}
private final DispatchAsync dispatcher;
public static final Place PLACE = new Place("main");
#Inject
public SomePresenter(DispatchAsync dispatcher, EventBus eventBus, Display display)
{
super(display, eventBus);
this.dispatcher = dispatcher;
bind();
}
protected void onBind()
{
display.getAddButton().addClickHandler(new ClickHandler()
{
public void onClick(ClickEvent event)
{
eventBus.fireEvent(new AddButtonEvent());
}
});
display.getDeleteButton().addClickHandler(new ClickHandler()
{
public void onClick(ClickEvent event)
{
ArrayList<String> list = display.getSelectedRows();
deletePerson(list);
}
});
}
....
private void loadDbData()
{
..........
}
private void deletePerson(ArrayList<String> ids)
{
..........
}
}
Edit:
What does the Presenter is, load initial data from db, have 2 buttons add and delete.
When add is press then a new form is load and user is able to input data and save to the db,
delete button just delete person from db.
Thanks
The general idea of unit testing such a class would be, like for any other class :
create Mock version of the dependencies (Display, EventBus, etc...)
set expectations on what the depdencies should do when the Presenter works
exercice the Presenter and check the expectations
However there are a couple of issues with your version of the Presenter :
The loadDbData() method is not showed, but I assumed it means the Presenter also has access to some other component that does the fetching. Can this component be abtracted in a dependency, and mocked liked the rest ?
Then there is the testing of bind(). The only responsibility of your Presenter in this method is to set up callbacks on some buttons provided by the Display. What you want to test is both :
That the callbacks are set
That the set callbacks do the expected things
A few ideas to help with the later :
You can reduce the coupling between Presenter and Button. If possible, change the Display interface from :
Button getAddButton();
to
addAddButtonClickedHandler(ClickHandler);
This means your Presenter does not have to use a Display object that returns actual BUtton
You can reduce the callbacks content to calling a single method, that you can then test in isolation
protected void bind() {
display.addAddButtonClickHandler(new ClickHandler() {
public void onClick(ClickEvent) {
fireAdded();
}
});
}
// The fireAdded function can be tested independenty of the Display, potentially with
// a mock EventBus
protected void fireAdded() {
event.fireEvent(....)
}
If you really want to check that the callbacks are properly set, than you can use a 'Dummy' implementation of the Display class, that provides you a list of all the callbacks, and let you call them
private class DummyDisplay implements Display {
private List<ClickHandler> addButtonClickHandlers;
public void addAddButtonClickHandler(ClickHandler handler) {
addButtonClickHandlers.add(handler);
}
public void fireAddButtonClick() {
for (ClickHandler h in addButtonClickHandlers) {
h.onClick(new ClickEvent());
}
}
// ....
}
Then your test would :
create a presenter with such a dummy display
use bind to set the callbacks
use display.fireAddButtonClick() to simulate a user clicking
check that has the result of the click, the effects of fireAdded are seen
This type of class (that mostly glue other classes together) can tend to be hard to test ; at some point, it the other classes are thoroughly tested it can become slightly counter productive to concentrate on the gluers, rather than the glued.
Hoping this helps.

Categories