Thursday, December 15, 2011

Combat System Update

I've got a basic combat system implementation it just needs some cleaning up. I haven't really had much time with the Christmas shopping and work getting in the way. I am planning on getting back to it and finishing it up.  Hopefully you'll be able to gleam something useful from it.

I would like to apologize for the lack of updating. I am still dealing with the programmers version of writers block and the feeling of being overwhelmed with ideas. Probably due to not having large time blocks to dedicate to game making.

Happy Holidays everyone!

Friday, December 2, 2011

Days off

Having a 3 day weekend for me is like Christmas morning. It's a good chance to get coding work done and more snippets on here. Unfortunately the job comes first these days so progress is of course slow which makes any time I can get really precious. Though side-tracking really takes its toll as well. Today was a very good day of sidetracking looking at the Ludum Dare competition, very cool. Thinking about entering, I otherwise I would just use that weekend for projects. It would be a very good thing for me and force me to finish a project and work out some issues with how quickly I move through projects, content, and polish.

So taking a look at some of the games on there actually provided some fruitful results, plus it is always motivating to me to see other peoples finished projects. I am only just beginning to push myself to complete games and make fun mechanics. So lots to do and look forward to.

So something that might interest you game developers out there, if you already know him he's got some good videos and details into games development. Chevy Ray the videos I found interesting are here. One of the things I found most interesting is his use of colliders plus I was genuinely impressed with the attention to detail and how smooth the implementation appeared. Very good job and highly recommend watching the videos and checking out his development progress. It's a good example of making and using tools to save time and energy in content making.

Additionally a couple days ago I happen to take a look at Coke and Code the Slick engine was interesting. So check it out I gave it a quick try and it has enough value in it to make some decent games plus the support for webstart and applets made it appealing to me. Still looking for suggestions on the combat system if anyone feels so inclined to share, also interested in anybody's personal projects. Give yourself a little free advertising I'd be willing to put a link up to your project.

Cheers and happy holidays to all.

Links: Added Chevy's site, and Coke and Code to links.

Tuesday, November 29, 2011

Green Algae: Updates & Combat System

Health bar, obelisk,
summoning effect and monsters
Here are some recent screenshots of the Green Algae project. Progress so far is minimal as I was discovering how to use GLES20 for Android. Added a green health bar and summoning of enemies from the obelisks with a basic scaling circle for a summon effect so far. It's rudimentary but at least it is something. I used the same placeholder image for both the enemies and for the player avatar. So the avatar in the image is the one directly below the obelisk or the messed up wooden thing sticking out of the ground. I refined the map generation algorithm a little and put in sandy beach like outlines. Still have way too many trees there.


Accelerated Image Problem
I also fixed an issue with images not being accelerated, the problem being unknown but found when I got incredible choppy and low framerates after putting in the fullscreen switch. You can test if an image is accelerated like this
GraphicsConfiguration gc = GraphicsEnvironment
 .getLocalGraphicsEnvironment()
 .getDefaultScreenDevice()
 .getDefaultConfiguration();
boolean isAcclerated = 
 image.getCapabilities(gc).isAccelerated();
In order to get the images accelerated I simply switched them to being VolatileImages which did the trick but then it broke the fullscreen switching so I need to reload them when the switching to fullscreen exclusive mode, or use the fullscreen window and just scale everything to match the size without changing resolution.


Map Generation Changes
Map generation actively changes
as the map is being generated
Here is another screenshot, its the map generation preview which helped me debug a few oddities with the sand outlining piece and parameters. I have a bunch of primitive looking slide-bars that act as controls for how many islands and how large, long, and how much they vary when built. You can see my attempt at grass here and making it repeat well. Also my first attempt at an actual standing tree to align with the top-down style graphics, it needs work and a leafy version.


Combat System Snippet Work
So, after fiddling a little bit with trying to make the summoned monsters fight back I found that I am indeed in need of a combat system. So I started thinking about the design of it and what I wanted it to be able to handle. I have a few basic classes and interfaces put into a separate project so I can share it with all of you as a snippet. Currently the idea is to use the mediator design pattern having a CombatSystem class as the mediator to handle things like who swung first and what not, handle multiple Combatants (which are the Colleagues in the pattern). Asses damage and timing between attacks it seems like it will be a good way of handling combat and could potentially be used in a lot of different games. So hopefully have that working in a couple of days if I get time to work on it. Or it may have to wait till the weekend, my day job does get busy sometimes.

Other ideas
If anyone would like to share what types of systems they've used in the past for combat, I am sure people would find it very helpful. Thanks for reading, and if you have any suggestions for snippets or need help figuring out something that I may know how to do don't hesitate to ask in a comment.

Tuesday, November 22, 2011

A weekend with Android GLES20

So I spent most of the weekend porting my android game code from GL10 to GLES20 it's quite the endeavor especially if you've never worked with opengl shaders or matrices. Moving away from the matrix stack was about the hardest part. The shaders were easy to get a handle on all except for the texture passing bit since you don't actually bind the texture to a specific sampler it's done indirectly through the use of numbered textures and order of sampler definitions in the fragment shader.

I've worked with shaders before in a similar way with XNA so some of the concepts were familiar to me. The new part for me was getting a basic post-processing bloom shader to work. I got it now but apparently there are some techniques I have to research before I use it efficiently. But about the one thing that opengl offers that Java2D is without is additive blending which is extremely useful for a lot of great effects, of course you can create your own custom composite in Java for doing additive blending though performance might be an issue there.

But some of the things I learned in getting this to work are as follows,
  • One you need to setIdentity before filling in the transforms
  • You can use the Matrix.translateM, Matrix.rotateM, and Matrix.scaleM in sequence
  • If you want to translate for example from the last position in the matrix you need to multiply the matrix by the new translation matrix (problems with order of operations)
  • A problem I am still having is that of textures still appearing mirror or flipped and other such non-sense due to orientation issues.
  • Oh and you have to manage your own matrix stack, if you want to change coordinate systems to use local coordinates for a particular object.
I'll post examples and more details after the holidays.

Aside from that just getting ready for Turkey Day. Hope everyone has a good and thankful Thanksgiving!

Wednesday, November 16, 2011

Green Algae Project

Yeah weird name I know. But it's good to have a non-restrictive name for a project that doesn't really make you think of anything specific. It helps you move in different directions without thinking about the title of the game. Although I have a work-in-progress game title, but I don't know if it will fit the game exactly after I change the game a bit.

So yes the game! The initial idea was centered around building bridges out to sea. Though one just can't build bridges for the hell of it (or can one, I wonder, hmmm) Any way it was decided that they cannot but the reason for building the bridges is indeed an odd one to be sure. And the reason would be, of course, sea monster hunting. Yeah well sea monsters are kind of cool. Think giant sun fish, man size and above, that can walk on land and rip your precious bridges and you to shreds.

You don't just build bridges, oh no, there's more to build like buildings a bunch of them. You can build well you can build yourself a hut to place your rare fish trophies in collect them all and get to the bottom of this nasty fish evil that's plaguing the island inhabitants. Oh yeah did I mention that there are islands yeah lots of them or as many as you like. The random map generation was of course on of the first things I got working. It's not bad, and by not bad I mean I wouldn't release a game with it but if it came down to it. It wouldn't be horrible. 

Currently only three types of tiles, you get sand, and um water, and of course grass. The terrain generation is random and controlled by a few parameters at the moment island count, size, length, and a extra variance value I used to vary some of the random chances and things. I will make an additional post about the generation method later so you can see one way of doing it.

So the project I figured is for my own personal enjoyment so it's more like a test bed I can work with to implement gameplay mechanics and test out effects and other things. So in order to get working on the combat system I thought I'd add in the ability to summon monsters. You place a wooden obelisk yeah weird but anyway this is of course after chopping down the tree and dragging the fallen log to where you want it. Then you start summon after a little while monsters will appear for you to fight. And right now it's pretty much you just go up to them attack them then they die, you get experience which you can't see atm, that's easily shown take me like 5 minutes.

So yeah that's The Green Algae project. A nice test project that could potentially have some interesting gameplay. Those green things are trees by the way. And that would be a boring old wood pile and a test avatar sprite placing wood in the pile.

So hang on to the edge of your seats for some spectacular updates.

Wednesday, November 2, 2011

Mouse Movement by Dragging

So I forgot to post this one type of movement piece. It's pretty simple if you know how to do the math which I will show you. Like the other snippets it's not entirely polished so there is definitely improvements that can be made to the movement style. This snippet will do a simple move towards the cursor when the mouse is dragged.

Other ways to do mouse movement is point-and-click movement. Point-and-click movement usually works along side a good pathfinding algorithm using either tiles or nodes. So here's the meat of this snippet.
  // only move if the user is dragging the mouse and we aren't already
  // at the mouse position
  if (dragging && !isMouseOverBlock()) {
   // the amount to move the character in x and y directions
   double dx = 0.0d;
   double dy = 0.0d;

   // relative mouse position from the character
   double relativeMouseX = mouseX - basicBlock.x;
   double relativeMouseY = mouseY - basicBlock.y;

   // determine the angle the mouse is from the current position
   double angle = Math.atan2(relativeMouseY, relativeMouseX);

   // now determine based on the angle what direction to move in
   dx = Math.cos(angle);
   dy = Math.sin(angle);

   /*
    * move the block by multiplying the amount of time in seconds that
    * has passed since the last update by the speed constant and by the
    * change in x or y directions which will either will result in += 0
    * or dt * speed negative or positive.
    */
   basicBlock.x += dt * speed * dx;
   basicBlock.y += dt * speed * dy;   
  }
So one of the tricks here is knowing how to use the atan2 method. It gives you the angle for the Cartesian points x,y passed to the function using the arctan trig function. Once we have the angle it's a simple matter to move in that direction based on speed and time. You can think of the dx and dy as percentages of the speed to apply and the dt as the amount of time applied.

Some ehancements that could be made to this snippet are things like using acceleration instead of pure speed. You could use this snippet to experiment with different styles of mouse movement such as the point and click and other variations as per your gameplay.

There is also a little bug I noticed in this example, sometimes when moving the block if it is over the mouse cursor it will sometimes jump quickly back and forth around the cursor. I tried to fix it by using the isMouseOverBlock but it wasn't 100% successful. If you figure it out please let me know.
Here's the full snippet:



Thursday, October 27, 2011

Busy busy

It's been an extremely busy work... month for me. It sucks too since I have wanted to work on a game I've been building in Java. I promise to bring you up to speed soon with development progress and screenshots. And I hope to provide some insight into the process and code that you might find interesting.

Monster summoning
So I haven't had the time to create any new snippets for your game development needs. But to give you a glimpse into the mechanic I want to implement. It's a summoning circle, the requirements are going to be that you are near a summoning pillar or I guess an obelisk would be a more fitting name for the object.

So you can build one out of wood for now and place it where you want. Depending on where you place it and your summoning skill different quantities and kinds of enemies will be drawn toward it.

It's basically developed out of a necessity to develop and test a combat system for the game including the experience and rewards of combat. It opens up a whole range of interesting dynamics to the gameplay. For instance I could have the summoned monsters drop rare items our give the player unique skills he can use elsewhere in the game. Or eventually recruit the summoned monsters instead of just fighting them.

These would be just some of the ideas I have been toying with when I get a few precious moments to think.

Also I was thinking of having etchings on the obelisks each etching could provide a way of controlling what happens when you summon around that obelisk. So just thought I would throw in this little update to let you know I am still around and working on games.

Tuesday, September 6, 2011

Game Rhythm

Every game has a rhythm to it, whether it's noticed or not. The intensity builds up and things become more difficult. This can just happen naturally if the game copies current trends in games or common game design and level design principles. But there is a reason for it and that is creating rhythm and if you pay attention to the rhythm of a game you can create a greater and more intense play experience.

I need a break

Breaks are an important part of creating rhythm. One tends to focus on the fun parts those with more action intense aspects. But properly timing the breaks between intensity helps keep immersion. Leveling systems for example naturally create the opportunity for a break in action. After an intense point in a level there is usually a lull and it's a good place to save progress. Progress saving provides a weak reward and a marker for achievement in the players mind. It also is a weak goal for the player, "make it to the next checkpoint". I say a weak goal because it really has no intrinsic meaning to it. And doesn't always tie into the theme very well, and its a big risk for breaking the immersion unless it somehow helps define the game world in a unique way.


Failing

I find when I loose a level or fail to reach a checkpoint and have to start over I don't feel rewarded but punished and quickly forget about the events of the failure. The game usually does too not counting how many times I tried nor does it gauge my skill level based on attempts or alter difficulty.
The question for the designer is how to keep the player interested and coming back after a failure. Nine and three quarters times out of ten I will stop playing a game when I fail to reach a checkpoint a certain number of times dependent on how long it took and whether or not I am willing to put in as much time to try again or based on if I think I can beat it the next time I try.

So for a designer you have to make sure your checkpoints are reasonable if you are using such a system. Or you can try something different. Like tracking the number of failures and making it easier next time the player tries. This will help push them through parts their having trouble with. That might actually make the game less challenging however so you'd have to be careful. It'd be nice to see games try things like this but only if the game keeps trying to challenge me instead of just sticking difficulty on low because I am having trouble and leaving it there.

If your looking to design an action game focusing on creating an intense experience of combat then rhythm is important. You want to steadily but subtly increase the combat intensity. You don't just want a steady continuous steam of baddies bombarding the player. This will just lead to boredom because nothing changes so there is nothing new for the player to grok.

Enough is enough

While you want to control the intensity of the game part of creating a rhythm is the lulls, yes lulls not lols. after the culmination of build up you want to provide a sort of safe point and give the player reward. this can all be seen and came about in designs naturally. Now it seems like games do this more out of tradition than good design, in a level you fight continuously harder baddies until the end of the level where there is usually a boss, the gameplay is usually changed in boss fights creating almost a separate unique experience depending on implementation. Then comes the satisfaction of once again not anticipating dying, this is the lull.

Beat the game

The game is over when the player says it's game is over. The player doesn't have to and won't continue playing if there is no enjoyment left. 

Tuesday, August 30, 2011

Focus on Game Logic

The focus is what gives the game programmer his power.
It took me years to get to the point where I finally realized that most 2D games have a very simple set of code necessary from the graphics and collision ends. All you need is the ability to draw images and detect collisions, and maybe play sounds (qed eh), the rest is all game logic.

It binds the games together
The game logic is the truly unique and interesting pieces of code, had I known this long ago or listened to people when they told me to focus on making a game and not just the graphics and structural code, I would have had so much more experience programming game logic. Alas, it is what it is and I need to churn out game logic code like there's no tomorrow in order to catch-up on missed opportunities.

Use the focus Luke, let go your graphics!
So a word to the wise, frequently implement as many different types of game logic code as possible. This will help familiarize you with the implementation problems and challenges and help you flush out ideas much more quickly in the future. Believe me when I say I've spent enough time coding to realize the first time is always the hardest when implementing something you've never done. Each time afterwards becomes much easier, so much so that eventually you can implement it as fast you are able to type.

Not this crude matter!
By game logic, I am referring to things like scoring, inventory, turn based battles, tech trees, quest systems and puzzles etc... Also get into level design early, the hardcore performance heavy and resource intensive code doesn't matter as much as being a good content creator. Sadly these are things I never really got to implement, I was too busy focused on the structural OO design and making a complete engine package or more and more advanced graphics and 3D work. Recently I've been trying to undo years of focusing on the wrong thing. I was in the whole boat of the having a million small projects but none ever got finished.

You're my only hope
As many people will tell you one finished polished game is better than thousands of unfinished ones. This is due to the myriad things needed to polish off a game. Down to minute details that you don't anticipate like crouching and reloading at the same time. Things like balancing and making sure the game is fun and the shotgun isn't too powerful or too weak, the bfg is hard enough to get and you don't get it till later. All those things add up and sometimes are so specific to your game design that you would never think about it until you've implemented game X at least once.

Good Luck!

P.S. I'd love to hear of others experiences and advice when implementing game logic. And some good coding exercises to help refine your skills to make game making easier!

Thursday, August 18, 2011

Deceptively Simple Prototypes

I decided to work on some very simple types of snippets related to game mechanics. Small little almost but not quite games! Definitely not polished.

This one I came up with is insanely simple. It's only purpose is just to focus on a process for prototyping different game mechanics. This isn't really a mechanic you would directly use as-is in a game. The core mechanic here being "click" the moving re-sizing circle as close to the center as possible to get maximum points.

Evolution
I tend to like exercises to come up with ways to change a currently working game or in this case snippet to turn it into something else. To sort of evolve it into it's own thing. There are a number of things I could add or change to enhance this and eventually make it into a game. It would be a casual arcade style game. I am not sure how well this idea of taking a simple mechanic and expanding on the gameplay works to create a fully polished game, but in my opinion it's better than just trying to brainstorm and come up with a game even if you're a designer and are good at visualizing the end product.

Prototypes
From my perspective it's definitely worth it. The experience of coding any gameplay mechanics no matter how small is useful. It forces you to turn the ideas in your head into something tangible and to work out coding issues you WILL have later on in development. Almost every game development team I have been on has always focused on the graphics and architecture first. The successful teams either use an existing engine or separate the graphics and architectural code from the game logic such that they are independent.

Your real drive is to get to the good stuff, the fun aspects of game making, the actual design. Coming up with battle systems, interesting weapons, big explosions, and detailed adventure areas, using all your creative juices. I have been tap-dancing around writing any game logic code for years. But I have always found small simple examples to be the best way to explore new areas in coding. So I am pushing myself to create as many small examples of different types of mechanics as possible. And I will of course post them here.

The Snippet
This snippet wasn't hard to get setup and rendering, one of the reasons I enjoy using Java for game development. It's basically create a window and a thread that continuously renders to the screen capture input via mouse position and do stuff when the buttons released.

Here's the 200+ line snippet.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.HashSet;
import java.util.Set;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class SimpleGame extends JComponent {

    public static class ScoreEffect {

        private static final double MAX_TIME  = 300;

        private final long          starttime = System.currentTimeMillis();

        private final int           score;

        private final int           x;

        private final int           y;

        protected ScoreEffect(int score, int x, int y) {
            this.score = score;
            this.x = x;
            this.y = y;
        }

        public void draw(Graphics2D init) {
            Graphics2D g = (Graphics2D) init.create();
            long cur = System.currentTimeMillis();
            double scale = ((cur - starttime) / MAX_TIME) + 1;
            g.translate(x, y);
            g.scale(1.5 * scale, 1.5 * scale);
            g.drawString(String.format("+%d", score), 0, 0);
            g.dispose();
        }

        public boolean isMax() {
            return System.currentTimeMillis() - starttime > MAX_TIME;
        }

        public static ScoreEffect valueOf(int score, int x, int y) {
            return new ScoreEffect(score, x, y);
        }
    }

    private static final int       MAX_HIT_COUNT = 20;
    private double                 direction     = 1;
    private double                 x             = 0;
    private double                 y             = 0;

    private double                 rsize;
    private int                    mouseX        = 0;
    private int                    mouseY        = 0;

    protected int                  score;

    private int                    hitCount      = MAX_HIT_COUNT;

    private boolean                isGameOn;

    private final Set<ScoreEffect> scores;

    public SimpleGame() {
        this.setPreferredSize(new Dimension(300, 200));
        this.setDoubleBuffered(true);

        scores = new HashSet<ScoreEffect>();

        (new Thread() {
            Object lock = new Object();

            @Override
            public void run() {
                synchronized (lock) {
                    while(true) {
                        repaint();

                        checkLooseCondition();

                        try {
                            lock.wait(10);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();

        Dimension size = getPreferredSize();
        if(x == 0) {
            x = size.width / 2;
        }

        if(y == 0) {
            y = size.height / 2;
        }

        addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseMoved(MouseEvent e) {
                mouseX = e.getX();
                mouseY = e.getY();
            }
        });

        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                if(!isGameOn) {
                    isGameOn = true;
                } else {
                    double distance = Math.pow(mouseX - (x + rsize / 2), 2)
                            + Math.pow(mouseY - (y - rsize / 2), 2);
                    if(distance <= 400) {
                        int addPoints = (int) (10 * (distance / 400.0d)) + 1;
                        scores.add(ScoreEffect.valueOf(addPoints,
                                e.getX(),
                                e.getY()));
                        score += addPoints;
                        x = 0;
                        direction = 1;
                    }
                }
            }
        });
    }

    protected void checkLooseCondition() {
        if(hitCount <= 0) {
            isGameOn = false;
        }
    }

    @Override
    public void paintComponent(Graphics init) {
        Graphics2D g = (Graphics2D) init.create();

        if(isGameOn) {
            rsize = Math.abs(getWidth() / 2 - x);

            rsize /= getWidth() / 2;

            rsize = 1 - rsize;

            rsize *= 20;

            if(x <= 0) {
                direction = 1;
            }

            if(x >= getWidth() - rsize) {
                --hitCount;
                direction = -1;
            }

            x += direction * 2;
            g.setColor(Color.black);
            g.drawOval((int) x, (int) (y - rsize / 2), (int) rsize, (int) rsize);

            g.drawString(String.format("Score: %d", score), 10, 25);
            String hits = String.format("Hits Left: %d/%d",
                    hitCount,
                    MAX_HIT_COUNT);
            g.drawString(hits, getWidth() - 10
                    - g.getFontMetrics().stringWidth(hits), 25);

            Set<ScoreEffect> remove = new HashSet<ScoreEffect>();
            for(ScoreEffect e : scores) {
                e.draw(g);
                if(e.isMax()) {
                    remove.add(e);
                }
            }

            scores.removeAll(remove);
        } else {
            String gameon = "Game Over - click to restart!";
            g.drawString(gameon, getWidth() / 2
                    - g.getFontMetrics().stringWidth(gameon) / 2, getHeight()
                    / 2 - g.getFontMetrics().getDescent());

            String lastScore = String.format("Last Score: %d", score);
            g.drawString(lastScore,
                    getWidth() / 2 - g.getFontMetrics().stringWidth(lastScore)
                            / 2,
                    getHeight() / 2 - g.getFontMetrics().getDescent() + 30);

        }
        g.dispose();
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame frame = new JFrame("Hit Me");
                SimpleGame g = new SimpleGame();
                frame.add(g);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}

Wednesday, August 10, 2011

Current snippets update

Still working on getting some useful mechanics snippets out. I want to focus on posting snippets that are the most helpful and insightful into some of the problems in coding game mechanics and game logic. I am working on the jump mechanic and others for platformers. What I am finding more and more is that most platformers have very specific code for handling their basic mechanics, since this is the first time I've actually attempted to write platformer movement code it's taking a while to get right. So today I will am posting my current progress it works in the sense that you can add platforms and jump from platform to platform but there are a number of subtle issues that you wouldn't want in the end.

To Fall or not to Fall
All I really wanted to show was a jump mechanic then I decided to add gravity since it is needed in order to do jumping, and then I figured we need platform collisions to stop the player and provide a base for jumping. The problem I am facing as of this writing is that of gravity as a constant acceleration in a direction (at this point it's mainly in the positive y direction or down but it's not hard and set in code) I am thinking I am trying to do too much at once perhaps it's better to do some daily progress. I don't expect the progress to be that great as it is I don't have much time to spend on doing these snippets and often second guess posting some times to hold out for a better idea or a more critiqued snippet and post.

Why I never tried coding a platformer before?
I've been programming games for a long time now 10+ years and while I did originally start a project similar to a platformer at that time I did not know the necessary physics to code the movement. The main reason though is that I've never been that much of a platformer player or enthusiast. I traditionally like strategy games and action-adventure's and as a game designer am enthralled with the design of arcade and puzzle games mainly due to a history of diverse and interesting mechanics and design.

Small Simple Prototypes
As a game programmer I often find it very helpful to iron out small simple snippets to test drive certain game code such as creating a specific effect or as previous posts suggest, framework code (e.g Resource Manager, Game State Machine, and things like Timed Animation etc.). I am confident in my knowledge base for graphics and API code plus the core framework coding to move on to the more important code which is the actual interactive elements of game code. I think small self contained example code lends itself well to solving buggy mechanics or smoothing out small issues. It helps you experiment with an idea and I believe it allows you to evolve mechanics easily. At the very least it is the exercise of taking your ideas for a specific piece of code in a game and presenting you with actual syntactical and logic problems.

Once you've mastered the basic logic structure of something like, "obtaining gold coins to use in a store to buy better weapons to kill more enemies to get more gold". You can most likely implement it much better in the future. If you've never coded something before you can't predict how long it will take to get right, but once you have that and similar codes become easier and easier.

Progress

Monday, August 8, 2011

Enhancement: Smoother Movement

A while ago I found an article while searching for reasons why some of my movement code was a bit choppy and had some jitter problems. I found this article Fix Your Timestep! it's a bit abrupt but it has helped. While I wasn't able to completely fix the propagation errors since I haven't mastered the interpolation concept completely or how exactly to work it into my designs.


The Concept

Make sure that your game updates only in discrete blocks as to not cause erroneous errors in movement and to account for time missed or wait until time has accumulated.

The interpolation

Used to compensate for formula errors in translational movement which add up overtime eventually causing objects to be positioned unrealistically. Though I haven't figured out how different it makes things using interpolation versus without it.

The Code

I took the Character 8 directional-movement snippet and changed the updating thread code, check it out, not perfect but much better than it was before works pretty well at least on my PC.

// our main task for handling the rendering and for updating and
  // handling input and movement events.
  renderTask = new Thread() {
   // no local variables in a constant loop.
   long lasttime = -1;
   long msDelta  = 0;
   double dt   = 0.01;
   long time;
   double deltaTime = 0;
   double accumulator = 0;

   @Override
   public void run() {
    final Object sync = new Object();
    while (true) {
     synchronized (sync) {
      // use nano time, for more accuracy
      time = System.nanoTime();

      // record the initial last time
      if (lasttime == -1) {
       lasttime = time;
      }

      // delta in milliseconds
      msDelta = (long) ((time - lasttime) * 0.000001d);
      
      // delta in seconds
      deltaTime = (time - lasttime) * 0.000000001d;

      // cap the number of update loops needed to keep up with
      // high frame-rates.
      if (deltaTime > 0.25) {
       deltaTime = 0.25;
      }

      lasttime = time;

      accumulator += deltaTime;

      // accurate update rates, loop for each fixed 
      while (accumulator > deltaTime) {
       update(dt);
       accumulator -= dt;
      }

      //check to make sure that the renderstrategy is valid
      if(SmoothMovement.this.isShowing()) {
       render();
      }

      // if there is any time left due to quick updating and
      // rendering then the thread can sleep
      long timeLeft = (10 - msDelta);
      if (timeLeft > 0) {
       try {
        sync.wait(timeLeft);
       } catch (InterruptedException e) {
       }
      }
     }
    }

   }
  };

Give it a Try

Test it out for yourself and let me know if you still find jitter or notice any places for improvement. I try to always look for ways to improve code and will go back to code I've done previously and see a lot of new optimization's I can make.

Full Source

Here's the whole file for you to take a look at.

Monday, July 25, 2011

Platform Jumping needs vector-ing

I was, on my way to showing a simple jump mechanic for a platformer when things just got way to complex for my liking especially the different physics variables, gravity, player speeds, jumping states etc... I had a speed constant and an velocity for jumping and for gravity and for the player. I had this messed up sense of the direction the player was moving, which was a radian angle. It didn't lend itself well to player movement in a platformer. I was flip flopping sin/cos and rotating the angles all over the place. It was a mess, then I just gave in and started using vectors.

Without vectors I had the player falling through the platforms even when it detected hits. I had a bug where I could only move in the air, then I was able to only move on the platform. Had the player repeatedly flying straight up like a rocket. And some double jump code didn't work right either, I kept increasing the velocity applied for the jumping to the point where you wouldn't just smoothly jump up. You'd immediately reach your apex and slowly come back down due to gravity. So yeah there is a lot of stuff to figure out.

So here is the vector class in all it's wondrous glory, I've used it to good effect so far without needing many changes. The most important functions are the normalize, magnitude, dot, and cross product functions. Those are necessary to perform many physics calculations.

Caveats: Originally I made this an immutable type but later added mutation methods (set(x,y)). There's probably a few hundred ways to do these calculations, for instance you could just use stand-a-lone static functions, or maybe a class that uses all Point2D.Double's for the vector data, etc... The ZERO static is not usable in calculations if you use the mutator methods, it will mutate the global instance. (oops!!! yeah I found it out because I was using it, should make a subclass for ZERO as a completely immutable type.)

/**
 * File: Vector.java
 *
 * This file is free to use and modify as it is for educational use.
 * brought to you by Game Programming Snippets (http://gpsnippets.blogspot.com/)
 *
 * Revisions:
 * 1.1 Initial Revision
 *
 */
package snippets.math;

/**
 * Mathematical vector class implementation. Provides the necessary methods to
 * use vector in physics calculations, ray tracing operations, and other types
 * of directional vectoring math applications. 
 *
 * @author Nick
 */
public class Vector {

 public static Vector ZERO = new Vector(0, 0);

 private double x = 0.0d;
 private double y = 0.0d;

 public Vector(double x, double y) {
  this.x = x;
  this.y = y;
 }

 public Vector add( double c ) {
  return new Vector(this.x+c,this.y+c);
 }

 public Vector add( double x, double y ) {
  return new Vector(this.x+x,this.y+y);
 }

 public Vector add( Vector v ) {
  return new Vector(this.x+v.x,this.y+v.y);
 }

 public Vector cross( Vector v ) {
  return new Vector(this.y - v.y, this.x - v.x );
 }

 public Vector divide( double c ) {
  return new Vector(this.x/c,this.y/c);
 }

 public Vector divide( double x, double y ) {
  return new Vector(this.x/x,this.y/y);
 }

 public Vector divide( Vector v ) {
  return new Vector(this.x/v.x,this.y/v.y);
 }

 public double dot( Vector v ) {
  return this.x * v.x  + this.y * v.y;
 }

 @Override
 public boolean equals(Object o) {
  if(o instanceof Vector) {
   Vector v = (Vector)o;
   return x == v.x && y == v.y;
  }
  return false;
 }

 public double getX() {
  return x;
 }

 public double getY() {
  return y;
 }

 public double magnitude() {
  return Math.sqrt(this.x * this.x + this.y * this.y);
 }

 public Vector multiply( double c ) {
  return new Vector(this.x*c,this.y*c);
 }

 public Vector multiply( double x, double y ) {
  return new Vector(this.x*x,this.y*y);
 }

 public Vector multiply( Vector v ) {
  return new Vector(this.x*v.x,this.y*v.y);
 }

 public Vector negative() {
  return this.multiply(-1);
 }

 public Vector normalize() {
  double mag = magnitude();
  if(mag != 0) {
   return new Vector(x/mag, y/mag);
  }else {
   return new Vector(x,y);
  }
 }

 public void set(int i, int j) {
  this.x = i;
  this.y = j;
 }
 
 public void set(double x, double y) {
  this.x = x;
  this.y = y;
 }

 public void set(Vector v) {
  x = v.x;
  y = v.y;
 }

 public void setX( double x ) {
  this.x = x;
 }

 public void setY( double y ) {
  this.y = y;
 }

 public Vector subtract( double c ) {
  return new Vector(this.x-c,this.y-c);
 }

 public Vector subtract( double x, double y ) {
  return new Vector(this.x-x,this.y-y);
 }

 public Vector subtract( Vector v ) {
  return new Vector(this.x-v.x,this.y-v.y);
 }

 @Override
 public String toString() {
  return String.format("(%f,%f)", x, y);
 }

 public static Vector valueOf(float x, float y) {
  return new Vector(x, y);
 }

 public static Vector valueOf(double x, double y) {
  return new Vector(x, y);
 }
}

Thursday, July 21, 2011

I hate stagnant blogs don't you!

I want to just apologize for not having posted in a while, especially to those who frequent this blog, if anyone does yet I want to say thanks for your patience.

Excuses, Excuses
Well guys, I've been busy as usual, this economy man it's a killer! Though that seems to be a common excuse these days. And since I have a regular job it isn't really true. Let's just put it this way, things just got busy. You know life stuff hard to keep a good blogging habit with lots of ya know that "stuff".

I've also been putting more time into the Android platform, as well as trying to figure out what the hell I should post next so many ideas and nothing seems to fit. Oh and I have to fight with my lackluster to code lately, yeah I am sorry I am one of those guys. Hey, look man I'm trying!

Blog Stuff
So every now and then I like to just randomly rearrange the blog and adjust settings, I noticed with the poll that it was creating scroll-bars, I hate when it does that, so annoying, though i don't think it did it on all browsers. But it did it in chrome which is the one I like to use on a regular basis, migrated from firefox though all three IE, firefox, and chrome have lodged themselves on my computer.

So I was going through the gadgets looking for something interesting and I dunno how does one choose from the pictures of hot chicks, puppy's, and style tips. Such tough decisions, yeah don't need to put any of those here, I doubt you want to be distracted by cute puppy's while reading or do you? So I decided on showing the Total pageviews thing, it's not terribly exciting only 12,188 at the time of this post. About 10-20 average visits a day. Not enough to make a living on, maybe someday. It'd be nice to be able to work on games all day as I do most of this in my little free time. So while I wait for that to happen I will just keep working on more snippets. Also removed some extra clutter with the external links, didn't really see a need for them but if someone liked using them please let me know. Added rss feed to gamasutra which I find an extremely good source for game design articles and other industry news as well as a couple of blog writers who share insights into how studios handle particular issues.

I really hope they are useful and anything you can think of that would help you out don't hesitate to ask me to try and figure out. Still need to figure out how to make the toggle screen-mode more professional.

Friday, April 29, 2011

Regarding Poll

I just realized something about the poll I put up, trying to see what people are interested in so I can focus on those snippets first. Whether it be collision detection, effects (particle system, animational effects etc.), game mechanics (scoring, acheivement systems, quests, stat systems, etc.), content tools would be like map editors, file format converters, asset building tools, particle engine editors, model viewers etc. And of course it isn't hard to guess what I meant with full game tutorials.

Anyways, what I realized is that I could probably use more of all of them, so I just wanted to see which ones I should work on first. Life being busy doesn't really leave me much time to work up solid snippets to help other developers.

Enough lamenting, on to more important issues, achievements, saw a good article for those of you who are interested and don't watch gamasutra, like I do, here it is:
The Cake Is Not a Lie: How to Design Effective Achievements

Some things to keep in mind if you are considering adding achievements to a game, some thought provoking analysis of games as always from the articles at gamasutra.

Thursday, April 21, 2011

Status & Poll

Been kind of busy lately with life, attempting to get into the android market but still have a lot of knowledge to share on making games in Java, I've been wanting to do more jogl and step up to some of the changes in jogl 2.0. I thought I would create a poll to help give me a little direction on what I should post here that would be the most useful for readers.

One of the big issues I have been wrestling with is making games vs. engines it's a tough thing. Especially since my engine is 90% there and almost ready to start being used to make complete games, I have had a few setbacks with select pieces of the design. Aside from that, my day job has been cutting into the amount of energy and desire I have to code when I get home.

This is probably the first actual blog post I've written, weird but it's the truth. Mainly I started this blog to post snippets I wanted to save and to help other developers to see how I solve some of the problems in making Java games. So I figured what the hell I'll actually start blogging instead of letting this blog just sit around idling in the blog'o'sphere.

So please take a second to vote on the poll for the things you are looking for and I will do what I can to help.

Friday, April 8, 2011

TapMania: First Android Test App

I have been getting into Android application development and wrote a small application to get my feet wet. This application just tests some OpenGL render capabilities, touch screen functionality, displays some text output for debugging purposes, and gives some basic menu options.

If you wanna try it out and test your phones touch screen and also help me determine how well it runs on other devices, I would greatly appreciate it. This will also help me to create some snippets for android and let you know what issues I find and things about performance for android games. So far the OpenGL-ES on android is working great on my phone I would love to know how it works on others.

I am still going through the process of setting the application up for publication to the android market as a demo to get more feedback and to grow the application into a game.

Let me know what you think!

Link to apk:
  • TapMania.apk (link now removed, app available on the android market)
Note: After realizing that the link to my google sites did not successfully allow you to install from your phone I finished the publishing process and got it up on the android market. I have a few small updates that I will publish this weekend.

Saturday, April 2, 2011

Response: Debugging High CPU Usage

Answer to: a comment posted on Double Buffering and Timed Rendering and on Game State Machine about 100% CPU usage with those samples.

Disclaimer: If you modified the examples, I can't help you, lol just kidding, it's a silly thing to have to say but try just redownloading and running the examples without any modifications.

The answer is a bit complicated, high CPU usage might be due to a few things.

Note: One thing I did not do that might make a difference is to use the createCompatibleImage method, this might make all the difference but I've never seen it have any effect. Or you could try using a VolatileImage it has it's own issues though, and I've never seen it have any effect either. If that doesn't work turn on java2D logging using the system properties see link below and look to see how long drawing operations are taking.

Another Note: If not on windows, try turning on opengl rendering and make sure it's actually on, you can verify it by using the "True" string for turning it on, with the capital "T" it will output whether opengl or directx rendering are being used.


Java Version Issues
Using your own buffer and repaint should work decently in Java versions on windows greater than 1.4.1 update 2, when directx support was added and turned on by default. Opengl support was added as of 1.5 but is not turned on by default on any platform, so you'd want to try fiddling with some of these properties. See System Properties docs

Problem with Repaint
In earlier versions of Java using repaint would result in tearing issues, because old swing versions would be not be double buffered. Thus the example with their own double buffering.

Hardware Acceleration Issues
No hardware acceleration will be available if you don't have some type of graphics card or if java has issues with the drivers, so it will only go as fast as the underlining computers CPU can handle in that case. Another issue using BufferedImages is the hardware acceleration can be lost if the bufferedimage raster is modified. Another choice is to use the Canvas approach with BufferStrategy which I have seen much much better performance than either creating a buffer myself .

I haven't seen 100% constant CPU usage with this example myself. If repaint works I do suggest going with what you know works well until you find something better. In the end if looks good and feels good for your game then it doesn't matter which method you use.

Things I tried
Trying to duplicate the 100% CPU usage with the Double Buffering and the Game State Machine examples was unsuccessful. I tried turning off hardware acceleration -Dsun.java2d.noddraw=True still performed as expected. I didn't change any of the code so it was left as is, still no 100% CPU usage, on an old 2.66 GHZ pentium 4 with a NVIDIA GeForce 8400 GS graphics card and tested with Java versions 1.5, 1.6, and 1.7ea without issue.

The only thing I could think of that would cause 100% CPU usage with these examples in their unmodified state is if the TimerTask run method takes more than 16 milliseconds. That would bog down the timer with continuous tasks needing to be fired since the java.awt.Timer is a single threaded queue based task scheduler. I was able to bog down the Timer and see high cpu usage. Haven't tried forcibly making the bufferedimage non-hardware accelerated yet. You could implement your own timer and see if that makes a difference.

I am meaning to work up a new snippet with better rendering methods, and updated code. The BufferStrategy approach link above is a good alternative and much better frame rates. Give that a try if your having trouble, I would also like to know if that works better for most systems. It's been a long time since I did those snippets back in 2007 I have learned a lot since then, still there is much much more to learn.

One Last Thing
I do remember that there was some issues I had on windows with a graphics card installed that slowed my rendering significantly, those were the options in the Display Properties -> Settings (tab) -> Advanced -> Troubleshoot (tab) the Hardware Acceleration, I have seen it have interesting effects at different levels with some of my Java games projects.

For further help just ask and you shall receive, of course more details next time would help tremendously.

Good Luck!