Jump to content

  • Log In with Google      Sign In   
  • Create Account

menyo

Member Since 09 May 2010
Offline Last Active Today, 08:49 AM

#5267020 My A* Hierarchical pathfinding.

Posted by menyo on 19 December 2015 - 05:56 AM

(Issues solved) I did not multiple the heuristic by the correct cost. But... why would this have mattered in the way it could not find a path? It should visit each node anyway afaik. If I simply return 0 on the heuristic it should work like Dijkstra but it is not adding anything to the openList. Anyway, this obviously fixed the performance issue by a great deal since it was not sorting correctly and the closed list was getting huge.

 

Original post

 

I am trying to make my own Hierarchical pathfinding system and apart from the fact I still think it's slow I'm having a issue I cannot put my finger on. I want to solve this issue first before I continue. I will explain what I have and start with this picture to visualize it for you. It is the top right of the map, so no node connection on the far top and far right are needed since the map ends there.

 

laIvyDE.png

 

I have divided the map into "sectors" and connect these sectors by nodes (white circles). In the sector with the blue circles I have selected the single white one and painting all connected nodes blue, so afaik this is correctly implemented. The red ones are the path I generated from the bottom left to the bottom right.

 

When I request a path I create a node at the start and destination and add all reachable nodes in that sector as connections with corresponding costs. Then I add the start node to the open list and perform A* search.

 

The first time this always finds a path if there is a path. But somehow if I try to find a path between topleft-bottomright and then topright-bottomleft it won't find a path for the seconds one. If I start my program and do that in reversed order it won't find a path for topleft-bottomright. On a smaller scale, so not traversing the complete map but just a couple of sectors there does not seem to be a problem.

public List<Node> findNodePath(Coordinates start, Coordinates destination)
    {
        long time = System.nanoTime();
        List<Node> path = new ArrayList<Node>();
        boolean pathFound = false;

        //create startnode and connect it to sector exits.
        Node startNode = findExitNodes(start); //Find exit nodes for the sector start is in
        startNode.setH(manhattanHeuristic(start, destination));
        startNode.setG(0);
        Node destinationNode = findExitNodes(destination); //Find exit nodes for the sector destination is in.

        List<Node> openList = new ArrayList<Node>(); //Deciding what datastructure is best
        CostComparator comparator = new CostComparator();
        TreeSet<Node> closedList = new TreeSet<Node>(comparator); //Treemap since closeList is more for looking up then inserting

        openList.add(startNode);
        while (openList.size() > 0)
        {
            //sort openList
            Collections.sort(openList, comparator);
            //pop first
            Node currentNode = openList.remove(0);
            closedList.add(currentNode);

            //Check if connection with the destination node is made.
            //Todo: add a more efficient way of finding destination
            for (Connection c : destinationNode.getConnections())
            {
                if (c.getTo().equals(currentNode)) pathFound = true;
            }
            if (!pathFound) {
                //Find all connections and add them to the openlist
                for (Connection c : currentNode.getConnections()) {
                    if (!closedList.contains(c.getTo())) {
                        if (!openList.contains(c.getTo())) {
                            //If it's not on the openList add it
                            c.getTo().setH(manhattanHeuristic(c.getTo().getPosition(), destination));
                            c.getTo().setG(currentNode.getG() + c.getCost());
                            c.getTo().setParent(currentNode);
                            openList.add(c.getTo());

                        } else {
                            //If it's already on the openList check if this is closer to start point and update it.
                            if (c.getTo().getG() > currentNode.getG() + c.getCost()) {
                                c.getTo().setG(currentNode.getG() + c.getCost());
                                c.getTo().setParent(currentNode);
                                //Collections.sort(openList, comparator);
                            }
                        }
                    }
                }
            }
            else //currentNode is connected to destination
            {
                System.out.print("Path found! ");
                while (currentNode.getParent() != null)
                {
                    path.add(currentNode);
                    currentNode = currentNode.getParent();
                }
                //Break out of while loop
                break;
            }
        }
        System.out.println((System.nanoTime() - time) / 1000000 + "ms");
        return path;
    }

Now I really hope someone can spot what I am doing wrong. The only thing I am altering in the main graph is the G & H and the parent. But this should not matter since if it's not on the openList yet I am setting these to the correct values. The cost comparator  just sorts on highest F score (G + H).

@Override
    public int compare(Node n1, Node n2) {
        return n1.getF() < n2.getF() ? -1 : n1.getF() == n2.getF() ? 0 : 1;
    }

And the equals and hashcode of node are derived from just the coordinates.

 

Node.Java

@Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Node node = (Node) o;
        return position.equals(node.position);

    }

    @Override
    public int hashCode() {
        return position.hashCode();
    }

Coordinate.java

@Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Coordinates that = (Coordinates) o;
        if (x != that.x) return false;
        return y == that.y;
    }

    @Override
    public int hashCode() {
        int result = x;
        result = 31 * result + y;
        return result;
    }

Performance?

Now other then this I find this to be very slow and this is probably mostly because of the closedList lookups. I am aware that my map in it's current state pretty much represents a worse case of a map, it is generating a lot more nodes then a open/indoor/playerbuild type of map. Anyway, on smaller maps with regular A* I have been using a boolean[][] as the close list so I had direct access if a certain location was already closed. I was getting near the same lookup times as I have now with a hierarchical search. But for this project I want to have a much larger map and do not want a huge boolean[][] in memory. So can you see a major performance issue and how to speed it up?  Any other way to speed it up? I have a private HashMap<Coordinates, Node>[][] sectorGraph; which could be useful for much quicker lookups if I know which sector to look for.




#5266869 Better visualization of isometric layers

Posted by menyo on 18 December 2015 - 04:08 AM

 

Another option would be to increase the wall height so they do not line up what good

I agree the perfect alignment of the tiles at different levels is a problem. Instead of making the walls higher, did you consider making them lower?

 

 

Rollercoaster tycoon 1 & 2 have what you have now, and the result is that a down-slope facing away from the player is completely invisible. Transport Tycoon Deluxe (and OpenTTD) have a reduced height, and down-slopes are still visible.

 

As for solutions, rollercoaster tycoon has the problem of building mid-air, where you have absolutely no idea (in my experience) how high or low you are. They used height labels at tracks paths and land, so you could figure out height. They also have an underground mode, where tiles were mostly transparent, and like you they have an indicator of the xy position at the floor at all times.

It was probably all that you could do at the time, but I found it very complicated to build things in it. On the other hand, I have seen very big and complicated designs for this program, so it seems other people had less problems.

 

Some ideas to consider (I haven't tried any of this), maybe it would be nice to cut away things that are in front of the cursor. Another idea I have is to have a kind of rotating laser light. Imagine that at your cursor you have a horizontal rotating laser, and it puts a (eg red) line at all surrounding walls at the same height.

That will fail in mid-air, but maybe add some kind of  land measurement pole? Imagine a thiny pole going up from some keypoints at the grid, and the laser highlights its height at the pole, so you can see how much higher you are than the ground below the pole. Obviously, nothing prevents you from adding poles below some floor too.

 

 

I do not want to make my walls lower because the height of the wall should represent the same height as a average living room. If I make them lower I have to shrink my character too much.

 

I have thought about the approach of TTD but I need cliffs (straight down) as well so this would not work anyway. But this is no issue anymore in the current version, I have added complete rotation in 90 degree steps. The tile picking only takes place on a single level, if the player want to select a "cube" of more levels it can go up and down levels while selecting. I do need to make see trough possible for convenience.

 

The laserlight is great, I have seen this work on several other games where you only work on a single height at a time.

 

I've tried to solve similar problem with cursor for my editor.

So far most clean version is to draw final outline (how terrain should look) with solid colored lines.

Green lines shows places where height will be added or not altered, red lines shows places where height will be lowered (material cut). Also there's dashed lines that show difference between new and current terrains - green dash is above current terrain, red dash is below current terrain.

 

attachicon.gifbrush.png

 

I still find the red lines very confusing. But if I see correctly you game works with a Tile[][] map and each tile (or corner) has a height. My game has a Tile[][][] map and each tile has a floor and a wall. It's really hard to come up with something that works and is user friendly for these types of games. But I should take advantage of the fact that each floor or wall in my game is the same height as any other.

 

 

The original X-Com solved some of this really well. It had a couple of display modes when looking at the map. The default view had a current height that you could set and the game would render everything at that height and lower. So if you were at level 2, and there was a three story building, it would show you level two of the building and any parts of level 1 that weren't covered up. Also, the cursor had a faded out version of itself that went all the way to the ground to give you a reference for its location. Here's a picture:

 

http://www.ibiblio.org/GameBytes/issue19/greviews/ufo2.gif

 

You might also want to check out Gnomoria first-hand or watch some videos on YouTube to see how they did it.

 

- Eck

 

Edit: Doh - I see you already stumbled across the x-com cursor trick. Ah well. smile.png

 

Love the fact you mention X-com, I used to play that the whole weekend without sleeping :D. My game works basically the same if the player is on level 20 it can only see from level 20 and down. Since most of my game is indoor it's not practical to have a "See all view" since it will obscure everything on the current layer with stuff on the top layer. I do need a see through toggle if there are important item or tiles obscured but I guess this is easily implemented.

 

----

 

Anyway, thanks all. I guess this is more of a experimenting thing to get right. I am currently very happy with the isometric engine I have. It only renders whats visible for each of the 4 angles and I currently have a 256 x 256 x 128 map loaded in. However this is eating the brain of my computer (just the map is almost 1gb of memory) so I have to cut that up in chunks eventually.

 

But then pathfinding is going to be a problem since not all of these chunks are available. So I will be keeping a higher hierarchical weighted graph in memory that creatures outside the player view can use for traveling. Say a enemy spawns on the edge of the map and needs to go to a player unit. It will just spawn on a designated node of the map then it looks up a path on this higher level graph and travels from node to node. If the player does move the camera to the chunk where the creature is at it will check on which tile the creature should be. A bit of a brain breaker for me but my prototype on a simple 2D map is looking good.

 

In the end this might be another of my too ambitious projects but I'm having a ton of fun with it.




#5265518 Better visualization of isometric layers

Posted by menyo on 08 December 2015 - 07:15 PM

By experimenting some more I have gotten better results. I now show the cursor by coloring the tile wall or floor. When there is no floor I currently show a transparent default block but I'm planning to show some form of grid with some form of visual element that goes down until there is a tile with a floor. It's already a lot more user friendly but I am still concerned where there is a change in z level. I like to pronounce that more.




#5265444 Better visualization of isometric layers

Posted by menyo on 08 December 2015 - 09:45 AM

I'm not sure where to post this but I guess it has all to do with design so I post it here.

 

I am creating a multilayered isometric map. Each tile has a floor and solid wall that can be removed. First I had a basic template image of the wall and floor and when a wall was removed it was impossible to see the difference at the SE and SW edge. With my new tiles it's a lot better but still not very clear. Are there special techniques for this? I have also made each layer below the current layer darker to create some sort of extra depth.

 

To improve this I am thinking about creating a outline only on the side where there is a height difference but this requires me to invest a lot of time in art and code and I'm not sure of the results. Another option would be to increase the wall height so they do not line up what good, this only works for X levels though but with the darkening this should not matter. However i do not want to make my walls to high since I want to add ramps that are not too steep.

 

Tile dimensions:

Width: 64.

Depth: 32.

Wall height: 32.

Floor height 8.

 

Same goes for my tile selector. It's not easy to see which tiles are actually picked. My selector image is the height of the floor and the wall together. Some sort of building grid would help but that has to go under the floor and walls and thus gets obscured.

 

I'm sure that with more different tiles things get easier to see but I'm very interested in common techniques used.

Attached Thumbnails

  • isometric.png



#5265081 Threaded pathfinding on dynamic tilemap

Posted by menyo on 05 December 2015 - 06:24 PM

Great read Rip-off!

 

The problem is I cannot queue up much tasks. Say a building requires 2 stones. If I would start queuing up these 2 tasks there is a risk the second task is pointing to the same stone.

 

Anyway, I already know I need the threading since I have potentially large maps 6.000.000 tiles and have a lot of experience with pathfinding on these tile maps. I could implement hierarchical pathfinding and that would help a ton on performance but I think it has it's charm when units do not react instantly anyway. I have also done tests on DataStructures and looking up or sorting 1.000.000 items just cannot be done in a couple of ms and these are the numbers I'm aiming for. Just a single battle with 20 units can leave hundreds of items behind. Even if I would cut up everything in chunks there still might be some items of interest all across the map and that would kill performance on the main thread. So to keep the UI responsive threading is afaik the only way.

 

Taking your advice I still have a lot to learn about threads especially about thread safety I guess. But I currently have a working prototype (console app) at the moment where I simulate the behavior I need. The path finding is just simulated by Sleep the thread but the lists of items are "real". It's not thread safe, I have to work on that but I am locking items so they cannot be accessed when being interacted with.

  • Unit 1 is idle and looks for an activity.
  • A building needs to be build that still requires 2 wood and 1 stone.
  • Request a Item lookup for the wood.
  • The thread is ready, the wood item gets flagged unavailable and Unit 1 is on it's way.
  • Unit 2 is idle and looks for an activity.
  • That same building still needs 1 wood and 2 stone.
  • Request a item lookup for wood.
  • The thread is busy so we request a lookup for stone.and get it.
  • Unit 3 is idle, he cant find a job so he goes to the pub to waste himself until a thread is ready.

This is where the looking up is being done, only activities access this. I have tried to work with the thread and task itself but eventually ended up having a boolean busy to mark the thread busy.

public boolean requestLookup(String type, Coordinates nearCoordinates)
    {
        if (busy) return false;
        //if (lookUpThread.isAlive()) return false;
        /*
        if (lookupTask != null)
            if (!lookupTask.isDone()) return false;
            */
        lookupTask = new FutureTask<Item>(new LookupTask(type, nearCoordinates, items));
        lookUpThread = new Thread(lookupTask, category + " lookup thread");
        lookUpThread.start();
        busy = true;
        return true;
    }

    public Item getItem()
    {
        if (!lookupTask.isDone()) return null;

        try {
            busy = false;
            return lookupTask.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println("Item lookup failed");
        return null;
    }

This is in the class ItemLookup and each item category will have such a class firstly to release the strain on the lookups since I will have a lot of items and when looking for stone I am not interested in weapons. Secondly, I can have more threads running simultaneously. I will implement a ExecutorService for the tasks with a thread pool to eliminate the overhead of creating threads.

 

While this seems to be working there is a lot more room for improvement and thinking. 

  • Whenever I place a building or a task that requires multiple items I could look those items up together and mark these for retrieval within the building.
  • Perhaps I could have the thread wait for a view seconds and lookup a lot more at once. For example to lookup an item I need a flood fill. Say 100 stones are needed I can potentially do this all in a single thread.



#5265006 Threaded pathfinding on dynamic tilemap

Posted by menyo on 05 December 2015 - 06:53 AM

I am playing with the idea and already did some tests on having pathfinding run on a separate thread. I am very new to threading and I want to explore the possibilities of this since in the game I have in mind I do not need immediate paths. The player does not control units directly but issues orders through the interface. Something like the game Settlers does :

  • The player places a building and a unit with the building job enabled can get a order from the building to construct it.
  • The player issues a stockpile to store weapons the stockpile looks for the nearest item and finds a Idle unit preferably nearby with the hauling job enabled.

Now as I understand dynamic and threading are conflicting with each other. I cannot issue all these order simultaneously since unit A might go for the same item as Unit B and things will obviously break. How can I deal with this in a proper way? This is what I am thinking off:

  • Stockpile needs item.
  • Stockpile issues a Thread to lookup the item.
  • Thread goes to work.
  • Stockpile needs another item.
  • The thread is still running so it cannot issue another order yet.
  • Thread has finished the job and marked the item as unavailable.
  • Stockpile notices that the Thread is finished and can proceed with the next item.

When an order is cancelled or perhaps the unit has died or the item cannot be reached anymore the item becomes available again. I will also have a list for each type of item so I can have a thread that looks for food and one for weapon run simultaneously. So basically I will have a single thread for each job that handles dynamic data running at a time.

 

Since I am new to Threading I have no idea what to use. In the passed I have dabbled a bit with FutureTask and custom Callables. Should I create a Thread for each of the needed tasks and wait for them to finish? Perhaps I can create a listener to notify when a Thread has done it's job? Is there already build in functionality for this in Java or a library that is compatible with LibGDX desktop? Is this even a good idea or should I drop this whole concept?




#5264872 Running a method in another thread and get result.

Posted by menyo on 04 December 2015 - 09:13 AM

The problem was lying in the following line:

TestMap.pathFinder.searchNodePath(location, destination, new HeuristicImplementation(), resultPath);

I was using this pathfinder for each thread and since this changes state I was getting errors. So I created a new pathfinder in the Runnable. Eventually when the map is dynamic I will probably need to do the same for the graph or make a deep copy of it's current state so when it the map alters during the pathfinding it will still find a (incorrect) path once the unit realizes the path is incorrect it requests a new path or cancels it's job.




#5261372 Breakout bonus drop ideas.

Posted by menyo on 10 November 2015 - 11:18 AM

 

A few ideas that I've seen elsewhere, I believe, are:

  • Explosive ball: when the ball collides with a brick, a small explosion occurs, causing damage to surrounding bricks.
  • Ball-lasers: as it travels, the ball itself periodically fires shots/lasers at nearby bricks.
  • Multi-ball: additional balls appear in the play-area, potentially producing additional collisions.
  • Sticky-paddle: when the ball collides with paddle it is held there until the player presses the "fire" button, at which point it is launched as though it had just bounced.
  • Rapid-ball: the ball moves extremely fast, and is no longer lost when it hits the bottom of the level.

A few ideas that I don't think that I've seen before:

  • Warp-walls: the ball "passes through" the walls of the level, wrapping around to re-emerge from the opposite side.
  • Paddle-cannon: the paddle is replaced by a cannon that oscillates its aim. When the ball hits the paddle-cannon, it is held there until the player presses the "fire" button, at which point it is launched in the direction in which the cannon is aiming at the time.

 

 

Ball lasers is a nice idea. The basic effect I have on my ball currently looks a bit like a lightning ball, I could sent lightning out to nearby blocks when this effect is obtained and use a more neutral effect for the default ball. I was already expirimenting with a fireball that does explosion damage to nearby blocks but it's a great addition!

 

Warp-walls is nice as a neutral effect since using the walls can be beneficial in some scenario's too. Thanks!

 

 

 

Multi-ball

 
This is my favorite. When the powerup is acquired, the ball (wherever it happens to be in the level) breaks up into three balls. Losing one or two of them doesn't cost a life, only when every ball on the screen is gone do you lose a life.

 

Additional powerups:

 - Multi-paddle / mirror-paddle: You have a second paddle, that moves opposite of your regular paddle.

 - Auto-paddle: You have a second paddle below your first paddle, that moves back and forth on its own.

 - Tracer: The ball's trajectory is visible, making it easier to predict where you need to move your paddle to.

 - Safety net: If you miss the ball and the ball hits the bottom of the screen, it bounces off the bottom like a normal wall. Only lasts for one bounce, but has no time-limit.

 

If you want negative powerups:

 - Clouds moving across the screen slightly obscuring vision.

 - The bricks move around.

 - The vertical screen space decreases, giving you less time to react.

 - The ball itself wobbles back and forth on its normal trajectory.

 

 

Yeah, multi-ball works great already.

 

Multi-paddle is a great idea and easy to implement. Having both of these pickup bonus effects could add some nice mechanics to the game.

 

The tracer might make things too easy since the player just has to touch at the predicted path. Also since I have a lot of moving objects, moving round objects that change the angle of the ball realistically cause the path to go crazy each frame.
 

The safety net is great too, I will implement it probably with a timer.

 

Most of my bricks already move around. I have to think about the clouds, it's nice but does not fit the "style" of the game. Have to come up with something else for it. Maybe some sort of distortion field but that requires me to delve into shaders.

 

Thanks.

 

 

Duplicate paddle - a second AI paddle appears temporarily which helps you

 

Block off bottom of screen - ball temporarily bounces off the bottom of the screen rather than costing lives

 

Catchers mitt - allows you to catch and hold the ball and launch it again where you want it

 

The duplicated paddle is nice, I could have some sort of semi safety field in the form of a laser at the bottom that moves left and right. The others have been suggested already but thanks.

 

Thanks all, with some deviations this should provide more then 30 powerups. I do need some more negatives, I was thinking about shielding bricks, re-spawning bricks and regenerating (re-energizing) bricks.




#5260504 Breakout bonus drop ideas.

Posted by menyo on 04 November 2015 - 09:09 AM

I'm making a breakout clone and want something extra. I have a cool spaceship paddle, moving bricks and an awesome particle effect ball. But to make the game really interesting I need to have as many power-ups/downs as possible. All the ideas are welcome and here is a list of mine.

 

The basics:

 

Speed ball > speeds up the ball

Slow ball > slows down the ball

Shrink ball > shrinks the ball and decreases damage

Grow ball > grows the ball and increases damage

Shrink paddle > shrinks the paddle of the spaceship

Grow paddle > grows the paddle of the spaceship

 

Extra's

Extra life > grants an extra life

Subtract life > subtracts a life

Invisible bricks > makes the bricks invisible for X amount of time

Ghost ball > makes the ball move through bricks doing no damage for X amount of time

Wrecking ball > the ball continues it's path when colliding with normal bricks.

Laser > Shoots X amount of lasers from the ship that damage bricks

Brick shield > grands X amount of bricks a shield for X amount of time.

Teleport > ball teleports X forward in a straight line only changing path on the level bounds except bottom.

Bounce > Increases speed of the ball after each hit for a short time.

 

Maybe some people have some more innovative ideas or twists to share. I will be very great full for it.

 

 




#5258836 Storing "additional versions" of objects in other objects?

Posted by menyo on 24 October 2015 - 09:29 AM


There is perhaps an issue if some tiles only occur at some levels, but it is probably too much work to make a special case for that.

 

But if those tiles are not referenced in the Array they will get disposed of right?

 

 

 


You should aim for the conceptually correct solution first, and only deviate from that if forced by other constraints, imho.
A public static variable says to me it never changes, and it doesn't depend on level-specific things. You can make the monster list static, but then you sort of should make the entire game level static. Personally, I don't have major problems with that, but you might.

 

A public static final variable sound to me it never changes. A static variable just says there is only one of it no matter how many objects are created from the class where the static variable belongs to.

 

Yes essentially everything where there is only one from can be static. Like I said, making things public static may very well save memory and performance but it isn't "good" design which is essential for larger projects.

 

Anyway, since there should only be about (Active Creatures * 2 AbilityActions) active at any one moment I would not foresee any problems. Just had to make sure it would not be a problem if eventually hundreds of Abilities would cause problems with having all these large objects in them.




#5258505 OOP inheritance structure

Posted by menyo on 22 October 2015 - 07:22 AM

Ahh yes I get what you mean. But what do you suggest? I am thinking of MeleeAttackState, RangedAttackState, SpellAttackState, etc now. So for example a spell like berserk can set a mage to a MeleeAttackState. Or should I have a MageAttackState and check in there if the mage has a Berserk flag? The latter creates a lot of statements again, so I guess I know the answer.

 

I like to thank you, along with your input and what I have been reading I learned a lot. I now have a class DrainableStat where I create a health, mana and energy object from. It handles everything like adding and subtracting as well as bonus modifiers to it. This is how I create a creature now:

CreatureData race = new CreatureData("Dwarf", 10, 10, 10, 10, 10, 10, 10);
CreatureData career = new CreatureData("Warrior", 2, 2, 0, -2, 0, 0, 0);
new Creature(race, career);

Deciding on how I want to implement abilities since these should be racial or career restricted. I guess I plug them in manually and provide options to the player based on there race and career.




#5258435 OOP inheritance structure

Posted by menyo on 21 October 2015 - 04:14 PM

I would still like to have a comment on the code I posted.

 

Then I guess I'm on the right pad by reading Avoiding the Blob since that is pretty much what I am creating, I document and structure it very well but it remains a blob.. Sometimes I am giving some code it's own place but it pretty much stays in the realm that many people call the blob. But the article about avoiding it stretches it far, I mean it has a separate component for health, this might be great for a asteroids clone but is it still common sense for "deeper" games?

 

Should I be creating a Interfaces / components for each and every stat or does it make more sense to combine it? I would say the latter but I still might be thinking in "blobs". Anyway while soaking up all the information regarding this I am presented with 4 options:

 

  1. Using Map<K, V> to store various data. This seems the most simplistic but is kinda error prone since I need to provide strings manually.
  2. Using a single interface Entity that holds a ton of things. This really seems wrong to me, yet the article uses it for the Asteroids game.
  3. Using a interface for each functionality. This could mean interface Health that implements the methods regenerate(int amount) and damage(int amount). But I still have to define these methods in the class it belongs too and thus generating a blob again. I could of course have these as normal classes instantiated within my creatures.
  4. A full component system like Unity uses. Where I use a component manager for each object and access these components by someObject.getComponent("componentX") but that seems like overkill for anything other then a engine to me.

So I guess I have to go with option 1, what was suggested earlier by Krohm. Or with 3 but make the "components" there own accessible classes from the entity holding it. I have been looking for examples but have not found any yet. If anyone can point me to some examples, preferably C# or Java, I would much appreciate it. For now I will prototype both options and play with the idea.




#5251312 Popular languages for networking for games

Posted by menyo on 09 September 2015 - 05:15 AM

I am no expert on the subject but I do not think there is a "most popular" language for networking. As long as you have access to sockets you will be fine. As with everything, the more control you have the better you can create something that fits and works best with what you are planning. Therefor I guess C++ would be the language of choice. However if you are here to make games rather then building a framework or engine keep reading.

 

You mentioned Java and LibGDX and I'm a great fan of LibGDX. Nathan, the top contributor to LibGDX also made a Networking framework called KryoNet designed for Java. KryoNet works perfectly with LibGDX Android, Desktop and HTML modules, I'm not sure about OS. You can setup a client to server connection in a matter of minutes.

 

Put this in your core dependencies of "build.gradle" and you are ready to go.

        compile "com.esotericsoftware:kryo:3.0.1"
        compile ("com.esotericsoftware:kryonet:2.22.0-RC1") {
            exclude module : 'kryo'
        }

I currently have a server running on a Raspberry Pi using a regular Java Application. You basically only need this as the server to connect a client.

    public static void main(String[] args) throws IOException
    {
        final Server server = new Server();
        server.start();
        server.bind(tcpPort, udpPort);
    }

Now for the client which could be your LibGDX game.

 

    private void connectToServer()
    {
        Client client = new Client();
        client.start();
        try {
            client.connect(5000, "mydomain.com or localhost/127.0.0.1", tcpPort, udpPort);
        } catch (IOException e) {
            Gdx.app.log("Main", "Failed connecting to server.");
        }
        if (client.isConnected())
        {
            Gdx.app.log("Main", "Connected to server.");
        }
    }

Run both and you will connect. If you run the server from your desktop and want connect from outside instead of local(host) you need something like noip.com which is a free service that links your dynamic IP to a DNS. Of course you need to forward your ports to make this work over internet. Otherwise you could pay for hosting the server elsewhere.

 

To sent data back and forth you need to register so called "packets" in both client and server. A packet could look like this:

public class MessagePacket {
String name;
String message;
}
Add and register that class in both client and server:
server.getKryo().register(MessagePacket.class); //in server program
client.getKryo().register(MessagePacket.class); //in client program
Now we can sent stuff back and forth between server and connected clients. Let's send a message from the client to the server:
MessagePacket message = new MessagePacket();
message.name = "Menyo"
message.message = "Hello everyone!"
client.sendTCP(message);
And off it goes to the server. Now let's intercept it at the server.
 
    server.addListener(new Listener() {
        @Override
        public void received (Connection connection, Object object) {
            if (object instanceof MessagetPacket) {
                 //cast object to correct packet.
                 MessagePacket message = (MessagePacket) object;

                 System.out.println("Received message from client: " + message.name + " with connection ID: " + connection.getID);

                 //Check the message for bad words if you want here :)

                 //Sent it back to other connected clients.
                 server.sendToAllExceptTCP(connection.getID(), message);

            }
        }
    }

The server has received the message and sends it to all other clients. The last step is to listen for the Message on the client side and show it to the user. To receive a message at the client side you do the same as the previous step. Just listen for "received", cast it to the proper class and do you magic on it.

 

Since you now know how to sent and receive data on both server and client side nothing can stop you to make some amazing networking games! Well that's only partly true, creating a client/server structure requires different thinking and things can get more complicated faster then a offline game. But luckily, practice makes perfect.




#5250538 Alternatives to Hit Points.

Posted by menyo on 04 September 2015 - 01:20 AM

You already kinda named it.


C) Independent limbs having health (Vagrant Story / Deus Ex)

But I love the way Dwarf Fortress is doing it. Limbs do not have health but there is a chance armor get pierced and a limb gets damaged in a certain way (bruced, muscle torn, bone broke, severed, etc). It all depends on the type of impact (slashing, piercing, bashing) and the quality of the material.




#5191920 Adding item modifiers

Posted by menyo on 09 November 2014 - 06:29 AM

I want to implement modifiers for special items. But I cannot figure out a good way to implement this. Let's say I have this item class structure:

public class Item
{
    String name;
    int strengthReq;
    int dexReq;
    int wisdomReq;
}

public class Weapon extends Item
{
    int maxDamage;
    int minDamage;
    int durability;
}

Now i want to add modifiers to this, the best way i can think of besides directly altering the item itself is a modifier class that uses a Enum to tell what has been modified. Adding a modifier object to an item and use statements every time a modifier might have been used and act accordingly. Currently my game uses a simple action system, for instance: when someone attacks source and target get passed to a static method and all the damage will be resolved according to the weapon damage/type.

public class Modifier
{
    enum ModifierType()
    {
         Strength,
         Dexterity,
         Wisdom,
         MaxDamage,
         MinDamage,
         PlayerHealth,
         lifeDrain,
         etc
    }
    ModifierType modifierType;
    int modifierValue;
}

Looking for pointers to make my item system more dynamic and fun with modifiers.






PARTNERS