text:
Moving my sprite in XNA using classes
Hey, im a newbie at this programming lark and its really frustrating me. I'm trying to move a snake in all directions while using classes. Ive created a vector2 for speed and ive attempted creating a method which moves the snake within the snake class.
Now I'm confused and not sure what to do next.
Appreciate any help. Thanks :D
This is what i've done in terms of the method...
  public Vector2 direction()
        {
                Vector2 inputDirection = Vector2.Zero;

                if (Keyboard.GetState().IsKeyDown(Keys.Left)) inputDirection.X -= -1;
                if (Keyboard.GetState().IsKeyDown(Keys.Right)) inputDirection.X += 1;
                if (Keyboard.GetState().IsKeyDown(Keys.Up)) inputDirection.Y -= -1;
                if (Keyboard.GetState().IsKeyDown(Keys.Down)) inputDirection.Y += 1;

                return inputDirection * snakeSpeed;

        }

Appreciate any help. Thanks :D
EDIT:
Well let me make everything clear. Im making a small basic game for an assignment. The game is similar to the old snake game on the old Nokia phones. I've created a snake class (even though I'm not sure whether this is needed because im only going to be having one moving sprite within the game). After I written the code above (in the snake class), the game ran with no errors but I couldn't actually move the image :(
EDIT2:
Thanks so much for everyones responses!!

Appologies for the bad quote of my code :/

This seems like a workable approach, but I don't see an actual question here. Are you asking how to make use of the result of your "direction" function to actually move an object?

I think if you post the code that actually uses the output from this direction method, we might be able to help. I think the error is in how you are updating the position of the sprite.

Upvoting and accepting answers is another way, GD's way to thank your fellow developers who helped you achieve your goal. =)

Although I am also a newbie in game development, my bet would be that you are always reinitializing your inputDirection variable to Vector2.Zero.
I don't know much about game development, but as for object-oriented programming, that is another thing! Here what I have come with after having read your comment about classes.
public class Snake {
    private Texture2D _snake; // Represents your snake's sprite.
    private Vector2 _snakePos; // Field that determines your snake's position.
    private Vector2 _snakeSpeed = new Vector2(10.0f, 10.0f); // Field that determines the number of pixels your snake will move at once while moving.

    public Snake(Vector2 initialPosition) {
        _snakePos = initialPosition;
    }

    public void MoveDown() {
        _snakePos.Y += _snakeSpeed.Y;
    }

    public void MoveLeft() {
        _snakePos.X -= _snakeSpeed.X;
    }

    public void MoveRight() {
        _snakePos.X += _snakeSpeed.Y;
    }

    public void MoveUp() {
        _snakePos.Y -= _snakeSpeed.Y;
    }
}

public class Game Game1 {
    private Snake _snake = new Snake();

    protected override void Update(GameTime gameTime) {
        Keys[] keys = Keyboard.GetState().GetPressedKeys();

        if (keys != null && keys.Length > 0)
            switch (keys[0]) {
                case Keys.Escape:
                    Exit();
                    break;
                case Keys.Down:
                    _snake.MoveDown();
                    break;
                case Keys.Left:
                    _snake.MoveLeft();
                    break;
                case Keys.Right:
                    _snake.MoveRight();
                    break;
                case Keys.Up:
                    _snake.MoveUp();
                    break;
                default:
                    break;
            }
    }
}

I hope this helps, and to be on the right direction to a viable solution! =)

This seems a long winded way to use a few buttons.. but what do I know lol.
I actually have no idea what I'm doing in terms of classes :(.

In fact, this is your Snake class that should be aware of its speed and direction. Aside, this is the game that is getting the user inputs. So, in my understanding, you have to make the snake know what direction it shall head next, that is, I believe that you should have, within your Snake class, four methods: MoveDown(), MoveLeft(), MoveRight() and MoveUp(). It is the snake that knows what to do to move one way or another, and since it also knows its speed, it shall move accordingly. Then, in your Game class, instantiate your snake, and input the directions through its methods!

Please, see my edited answer as I have included a possible Snake class exposing four Move methods. The snake doesn't have to know what key has been pressed, rather your game shall get the keys. Then, it is your game that tells your snake where to go depending on the keys that have been pressed by the player. Then, your game tells your _snake instance to MoveLeft, MoveDown etc. depending on the keys that you pressed. Let me know if this helps! And feel free to comment about stuff you don't get working or so, I'll be glad to help the most I can.

Thank you so much, this is exactly what I was looking for in terms of an answer. You called yourself a newbie but showed otherwise :).
I'm literally awful at this coding jazz. My confusion is when using classes for everything (which is probably key).

I'm glad I could help! I'm a beginner in game development, but not in object-oriented programming or programming itself! You might as well upvote and accept my answer if this is the one that helped you solve your problem. =) Thanks!

Imo, Head First C# is a neat book for getting a good object-oriented primer while actually producing visible results all the way through.

I use code like this to move my sprites, it tends to work quite well for me, it also uses "GameTime" to ensure movement is consistent across frame-rates.
// Sprite Protecteds
Vector2 direction;
Vector2 position;
float speed;

// Sprite Code
void Update(GameTime time, KeyboardState kb)
{
    // reset to zero for no keys pressed
    direction = Vector2.Zero;

    if (Keyboard.GetState().IsKeyDown(Keys.Left)) direction.X = -1;
    if (Keyboard.GetState().IsKeyDown(Keys.Right)) direction.X = 1;
    if (Keyboard.GetState().IsKeyDown(Keys.Up)) direction.Y = -1;
    if (Keyboard.GetState().IsKeyDown(Keys.Down)) direction.Y = 1;

    position += direction * speed * time. Milliseconds;
}

// Game "Update" method (not sure of exact code here)
sprite.Update(gameTime, Keyboard.GetState());

Obviously you may want to provide more parameters to the sprite during its update process, so you may very the speed or other things as well.

There should be giant red stickers all over every XNA tutorial to inform people of the use of GameTime to modify all frame-by-frame events that you want to be updated at a constant real-time rate to provide a consistent player experience regardless of hardware.

@Bill: My sentiments exactly.

This question needs more lambdas.
Note this is from a WIP, so there's some unused and implied-but-unimplemented features. Where you see the () => add your inputDirection.X -= -1;. I realize this is for a Gamepad and you're using a keyboard, but the grouping principle, or at least the notion of the action map still applies.
This is probably overkill, but lots of fun!
Setup function that maps the controls:
public void SetController(MyGamePad controller)
{
    controller.ClearActions();

    controller.BindAction(Buttons.Start, ButtonGroup.FullyExclusive, () => sine.play());

    controller.BindAction(Buttons.A,
        ButtonGroup.FaceButtons, () => showText("A!"));
    controller.BindAction(Buttons.A | Buttons.B,
        ButtonGroup.FaceButtons, () => showText("A and B!"));
    controller.BindAction(Buttons.B,
        ButtonGroup.FaceButtons, () => showText("B"));
    controller.BindAction(Buttons.B | Buttons.Y,
        ButtonGroup.FaceButtons, () => showText("B and Y!"));
    controller.BindAction(Buttons.Y,
        ButtonGroup.FaceButtons, () => showText("Y!"));
    controller.BindAction(Buttons.Y | Buttons.X,
        ButtonGroup.FaceButtons, () => showText("Y and X!"));
    controller.BindAction(Buttons.X,
        ButtonGroup.FaceButtons, () => showText("X!"));
    controller.BindAction(Buttons.X | Buttons.A,
        ButtonGroup.FaceButtons, () => showText("X n A, I made a funny!"));
    controller.BindAction(0x0,
        ButtonGroup.FaceButtons, () => showText("Nothing on the face buttons."));

    controller.BindAction(0x0,
        ButtonGroup.ShoulderButtons, () => showText("No shoulder buttons"));
    controller.BindAction(Buttons.LeftShoulder,
        ButtonGroup.ShoulderButtons, () => showText("Left shoulder button!"));
    controller.BindAction(Buttons.RightShoulder,
        ButtonGroup.ShoulderButtons, () => showText("Right shoulder button!"));

    controller.BindAction(0x0,
        ButtonGroup.DirectionalPad, () => showText("Nothin' on the dpad!"));
    controller.BindAction(Buttons.DPadUp,
        ButtonGroup.DirectionalPad, () => showText("DPAD UP!"));
    controller.BindAction(Buttons.DPadDown,
        ButtonGroup.DirectionalPad, () => showText("DPAD DOWN!"));
}

The game component that makes it work (instantiate 1 per player):
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System.Collections.Generic;

namespace MyGame
{
    [Flags]
    public enum ButtonGroup
    {
        NonExclusive            = 0x00,
        FaceButtons             = 0x01,
        DirectionalPad          = 0x02,
        ShoulderButtons         = 0x04,
        LeftSide                = 0x08,
        RightSide               = 0x10,
        FullyExclusive          = 0xFF,
    }

    class MyGamePad : GameComponent
    {
        private Buttons FaceButtons;
        private Buttons DirectionalButtons;
        private Buttons ShoulderButtons;
        private Buttons LeftSideButtons;
        private Buttons RightSideButtons;
        private Buttons AllButtons;

        private PlayerIndex playerIndex;
        private Dictionary<KeyValuePair<Buttons, ButtonGroup>, Action> actionMap = new Dictionary<KeyValuePair<Buttons, ButtonGroup>, Action>();

        public InstrumentPad(Game game, PlayerIndex playerIndex) : base(game)
        {
            this.playerIndex = playerIndex;
        }

        public void ClearActions()
        {
            actionMap.Clear();
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            updateButtons();

            foreach (KeyValuePair<Buttons, ButtonGroup> pair in actionMap.Keys)
            {
                switch (pair.Value)
                {
                    case ButtonGroup.DirectionalPad:
                        if (DirectionalButtons == pair.Key)
                            actionMap[pair].Invoke();
                        break;
                    case ButtonGroup.FaceButtons:
                        if (FaceButtons == pair.Key)
                            actionMap[pair].Invoke();
                        break;
                    case ButtonGroup.ShoulderButtons:
                        if (ShoulderButtons == pair.Key)
                            actionMap[pair].Invoke();
                        break;
                    case ButtonGroup.LeftSide:
                        if (LeftSideButtons == pair.Key)
                            actionMap[pair].Invoke();
                        break;
                    case ButtonGroup.RightSide:
                        if (RightSideButtons == pair.Key)
                            actionMap[pair].Invoke();
                        break;
                    case ButtonGroup.FullyExclusive:
                        if (AllButtons == pair.Key)
                            actionMap[pair].Invoke();
                        break;
                    case ButtonGroup.NonExclusive:
                        if ((AllButtons & pair.Key) == pair.Key)
                            actionMap[pair].Invoke();
                        break;
                }
            }
        }

        public void BindAction(Buttons buttonCombo, ButtonGroup buttonGrouping, Action action)
        {
            KeyValuePair<Buttons, ButtonGroup> pair = new KeyValuePair<Buttons, ButtonGroup>(buttonCombo, buttonGrouping);
            if (!actionMap.ContainsKey(pair))
                actionMap.Add(pair, action);
            else
                actionMap[pair] = action;
        }

        private void updateButtons()
        {
            GamePadState padState = GamePad.GetState(playerIndex);
            LeftSideButtons = 0x0;
            RightSideButtons = 0x0;

            FaceButtons = 0x0;
            if (padState.Buttons.A == ButtonState.Pressed)
                FaceButtons |= Buttons.A;
            if (padState.Buttons.B == ButtonState.Pressed)
                FaceButtons |= Buttons.B;
            if (padState.Buttons.X == ButtonState.Pressed)
                FaceButtons |= Buttons.X;
            if (padState.Buttons.Y == ButtonState.Pressed)
                FaceButtons |= Buttons.Y;

            RightSideButtons |= FaceButtons;

            DirectionalButtons = 0x0;
            if (padState.DPad.Up == ButtonState.Pressed)
                DirectionalButtons |= Buttons.DPadUp;
            if (padState.DPad.Down == ButtonState.Pressed)
                DirectionalButtons |= Buttons.DPadDown;
            if (padState.DPad.Left == ButtonState.Pressed)
                DirectionalButtons |= Buttons.DPadLeft;
            if (padState.DPad.Right == ButtonState.Pressed)
                DirectionalButtons |= Buttons.DPadRight;

            LeftSideButtons |= DirectionalButtons;

            ShoulderButtons = 0x0;
            if (padState.Buttons.LeftShoulder == ButtonState.Pressed)
            {
                ShoulderButtons |= Buttons.LeftShoulder;
                LeftSideButtons |= Buttons.LeftShoulder;
            }
            if (padState.Buttons.RightShoulder == ButtonState.Pressed)
            {
                ShoulderButtons |= Buttons.RightShoulder;
                RightSideButtons |= Buttons.RightShoulder;
            }

            AllButtons = LeftSideButtons | RightSideButtons;

            if (padState.Buttons.Start == ButtonState.Pressed)
                AllButtons |= Buttons.Start;
            if (padState.Buttons.Back == ButtonState.Pressed)
                AllButtons |= Buttons.Back;
        }
    }
}

Now I'm confused and not sure what to do next.

Does this mean your code isn't doing what you think it should be doing or do you have some feature that you need to implement that you don't know how or do you want advice on what feature to implement next?
Either way...
if (Keyboard.GetState().IsKeyDown(Keys.Left)) inputDirection.X -= -1;
if (Keyboard.GetState().IsKeyDown(Keys.Right)) inputDirection.X += 1;

You don't want to subtract a negative for one direction and add a positive in the other.  Those two evaluate to the same thing.

Well let me make everything clear. Im making a small basic game for an assignment. The game is similar to the old snake game on the old Nokia phones.
I've created a snake class (even though I'm not sure whether this is needed because im only going to be having one moving sprite within the game).
After I written the code above (in the snake class), the game ran with no errors but I couldn't actually move the image :(

@Tom, you should put the clarification in the question itself.

Here's how I'm doing this in one of my games on Windows Phone. Bear in mind that I have made some simplifications for the sake of example. In my game, enemies follow a set of waypoints along a path.
In the Update method inside my Enemy.cs class, I evaluate Enemy.Waypoints.Peek() - Enemy.Position (normalized) to determine which direction the enemy should be moving.
this.Direction = this.Waypoints.Peek() - this.Position;
this.Direction.Normalize();

Then, I calculate the velocity (direction + speed) for the current frame using the direction.
this.Velocity = Vector2.Multiply(this.Direction, Settings.Speed * this.Speed);

Finally, I adjust the actual position of the enemy.
// Adjust the position according to the velocity.
this.Position += this.Velocity;

It helps to understand the math involved, but this is how you can move an object.


text:
Software for game system design overview
Yes so this is a question more oriented towards the planning / project part of game development. What software do you use to plan your game, I am talking about visual stuff like a mindmap application for making some neat diagrams and so on, sort of like database design only it's for the game instead, is there any good ones?
Thanks

Freeplane is an awesome fork of Freemind, but you may also like VUE.
For me, the best tools for game design have always been a pencil and graph paper. Then Google Docs or a wiki to disseminate information throughout the team. Google Groups is useful as well.

VUE was exactly the thing I was looking for, thanks a bunch! I tried freemind but did not like how it arranges nodes, VUE is awesome!

When I was at EA, we used some mindmapping software especially during meetings. Design docs were mostly done in Word, although the company has moved to doing most of that in Mediawiki now. Personally, I think wikis are a great fit for game design:

They're non-linear and easily cross-linked.
They support images inline.
Content is easy to edit by many people (since designs change often).
Anyone can view the docs with just a browser.
A history of changes is stored with every page.

An additional wiki benefit is that they can also be easily cross-linked to future projects as well; this encourages creating reusable systems and content!

The most important element in game planning is a good design document. The typical example is Chris Taylor's game design document. Also check out this question: "Design Document Contents"
Also for the technology involved in storing and editing documents and team management, check out "What type of document for game design?"

That Chris Taylor example is great.

It is, there is also the design doc to Total Annihilation floating around somewhere I think. In fact this sample design doc might be based on that.

The poster is pretty clear about asking for visualization apps rather than a simple doc. Chris Taylor's has been floating around forever and it's a solid example of the basics of documenting your game design, but I don't think it properly addresses the question here.

Schematic diagram is to database design, as design doc is to game design. Nowhere in the question was it mentioned that sqa was looking for something more than a design doc; rather I got the impression that sqa was not aware of the concept of a design doc and was trying to find the equivalent of a database diagram for game design. If this question is not useful then he/she can accept a different one or even downvote it if I did something wrong.

Nothing too exciting:

Word Docs for initial outline
Powerpoint to flesh out the pitch and get people excited
Transition to Wiki once getting into actual prototyping. Wiki's are great for splitting up design tasks among several designers, showing how mechanics cross link and giving the rest of the team and easily sorted and searchable database of what should be in the game.
Continue with focused powerpoints for mechanics when needed. Lots of people are visual learners and I've found you can just communicate ideas more quickly this way.
Post-it notes and a big section of wall somewhere for doing scoping and auditing exercises.

NOTE
Wiki's don't police themselves and can get out of control or just die if you don't have at least one resident Nazi who keeps the whole look & quality consistent. Build out templates for content pages and stick to them. For information that changes regularly (like tuning numbers), put it in source control and just link to it from the page. Keep all other information in the Wiki.

My personal workflow is as follows:

A Google text document to
capture the initial set of ideas under a meaningful title.
Later, I'd move those ideas into a mind-map to start organising and
building upon them.
Then, I just keep
a To-Do list of tasks necessary
to complete the project.
I might draw out complicated systems as UML, although I've never been happy with any of the tools for that so I tend to use pencil and paper.

That works for me as a lone developer. When working in a team we had good results when working with a Wiki for the design (my preference was DokuWiki but there may be something better, eg. Confluence) and issue and task tracking software for tasks (again, we used JIRA but you can get by with Bugzilla, Trac, Redmine, etc)

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/2.5/

sort: votes


text:
What is a rim shader used for?
What does a rim shader do and what is it used for? In what cases would it make sense to utilize a rim shader?

In the context of graphics programming and shaders, a "rim" shader would be one that focuses on achieving a lighting effect related to the silhouette or other feature/contour edges of an object (crudely, "the outline" of the object). Typically this would be to simulate rim lighting (more examples), which comes about from back-lighting a subject.
I suppose if you wanted to stretch it, you could consider shaders employ other edge-related effects (such as drawing the outlines on cel shaded scenes) "rim shaders" as well, since they do have something to do with the feature edges of the object. More I think more traditionally the term is used to refer to the lighting effect.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/2.5/


text:
Java game design question (graphical objects)
I'm beginner in game development, in Java and here on this site too and I have a game design question. Please comment my idea:
I have a main loop which call update and draw method. I want to use an ArrayList which stores graphical objects, they have coordinate and image or text to draw and my game objects extends this class. In update, I can choose which objects should be put in the array and in draw method I'll display the elements of array on the screen. I'm using a buffer and draw first there.  Here is a simple (not full) code, only the logic:
public class GamePanel extends JPanel implements KeyListener
{
   ArrayList<graphicalObjects> graphArray = new ArrayList<graphicalObjects>();

   public void update()
   {
      //change the game scene, update the graphArray, process input etc.
   }

   public void draw()
   {
      //draws every element of graphArray to a JPanel
   }

   public static main(String[] args)
   {
      while(true)
      {
          update();
          draw();
      }
   }
}

My questions:

Should have I use interface or abstract class for graphicalObjects? graphicalObjects class and the ArrayList really needs or there is some better solution?
How to draw objects? They draw themself with their own method or in the draw method I have to draw manually based on graphicalObjects variables (x,y coordinates, image etc.)?
If this conception is wrong, please suggest another one!

Should have I use interface or abstract class for graphicalObjects? graphicalObjects class and the ArrayList really needs or there is some better solution?

I would go with an interface. If all graphical objects have lots of similar data, you may reconsider.

2.  How to draw objects? They draw themself with their own method or in the draw method I have to draw manually based on graphicalObjects variables (x,y coordinates, image etc.)?

I suggest you follow Javas pattern and pass on a Graphics object and let the object paint themselves. Just set clip and offset properly before you pass on the graphics object.

3. If this conception is wrong, please suggest another one!

I think it's okay, but here is a small remark:
Most Java UI's are event-driven. Since you seem to plan to implement a KeyListener, I would suggest you follow this convention. That is, throw out the update/draw loop, and repaint the panel after processing received events.

Agreed about the interface, especially if you follow the second rec and pass in the graphics object needed to draw themselves.

I agree with all the answers but offer caution on the last answer. If the game is itself event driven then this will work. If however, it is not, then the use of some kind of update loop will be needed.. To either render the new position an object has taken while you are watching it, or even to simply redraw a timer on the screen while you are trying to guess the answer to a trivia question. That's all, otherwise spot on answer! :)

I agree with @James, and I think that most games will require a update/render loop.

What needs an object to be drawn
Let's start with a basic class for an object which should do the following.

The coordinates Simple variables such as x_pos and y_pos
An Image The face of the object
a render() method To draw the object

The coordinates
Every object requires the coordinates to note it's position on the screen. They can be complex Vectors and also simple vars. Let's name them x_pos and y_pos. They need to set in the constructor for games (To have multiple instances).
The image
An image let's the user to identify the game objects. Loading images is extremely easy than sounds. Here's a loadImage() method.
public static Image loadImage(String name){
    Image img = null;
    if (cache.containsKey(name)) {
        img = cache.get(name);
    } else {
        try {
            img = new ImageIcon(this.getClass().getClassLoader().getResource(name)).getImage();
            cache.put(name, img);
        } catch (Exception e) {
            System.err.println("Error loading image : " + name
                    + "\nFatal error. The program is exiting.");
        }
    }
    return img;
}

Here the cache is a HashMap so that an image is only loaded once and all the instances use the same image.
A render() method
In this method you would draw the object to the game. See it and you may understand it without any explanation.
public void render(Graphics2D g){
    g.drawImage(img, x_pos, y_pos, null);
}

Where the null refers to ImageObserver class which we do not need. To draw the object, simply call this method from the paint method of the game. (Don't forget to cast the legacy Graphics class to the new Graphics2D class).
Reference
You may see this class as a reference. Just rename it to graphicalObjects and use it up.
GObject class
List of pre-created actions (useful for beginners) like bounce() etc.,
Pre-Created Actions (Inspired by Game Maker)

-1 Answers that are just a link to something and don't really explain anything aren't very useful. What if your link goes dead? Your answer becomes useless. Try to actually say something in your answer.

@JonathanHobbs The links will never be dead because they are from my game engine which is hosted on googlecode. And I've just given links because the class contains 774 lines of code.

Your answer is just a link to some code. It doesn't answer the question (how to implement graphical objects and draw things in the game) and the class itself doesn't count as an explanation - it's just a lot of code which you'd only be able to fully understand if you didn't have to ask this question. The list of pre-created actions itself has no apparent meaning. You're not answering anything or explaining anything.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Adding objects to the environment at timed intervals
I am using an ArrayList to handle objects and at each interval of 120 frames, I am adding a new object of the same type at a random location along the z-axis of 60. The problem is, it doesn't add just 1. It depends on how many are in the list. If I kill the Fox before the time interval when one is supposed to spawn comes, then no Fox will be spawned. If I don't kill any foxes, it grows exponentially. I only want one Fox to be added every 120 frames. This problem never happened before when I created new ones and added them to the environment. Any insights?
Here is my code:
/**** FOX CLASS ****/
import env3d.EnvObject;
import java.util.ArrayList;

public class Fox extends Creature
{
    private int frame = 0;
    public Fox(double x, double y, double z)
    {
        super(x, y, z);

        // Must use the mutator as the fields have private access
        // in the parent class
        setTexture("models/fox/fox.png");
        setModel("models/fox/fox.obj");

        setScale(1.4);
    }

    public void move(ArrayList<Creature> creatures, ArrayList<Creature> dead_creatures, ArrayList<Creature> new_creatures)
    {
        frame++;
        setX(getX()-0.2);
        setRotateY(270);

        if (frame > 120) {
            Fox f = new Fox(60, 1, (int)(Math.random()*28)+1);
            new_creatures.add(f);
            frame = 0;
        }

        for (Creature c : creatures) {
            if (this.distance(c) < this.getScale()+c.getScale() && c instanceof Tux) {
                    dead_creatures.add(c);
            }
        }

        for (Creature c : creatures) {
            if (c.getX() < 1 && c instanceof Fox) {
                dead_creatures.add(c);
            }
        }
    }
}

import env3d.Env;
import java.util.ArrayList;
import org.lwjgl.input.Keyboard;

/**
 * A predator and prey simulation.  Fox is the predator and Tux is the prey.
 */
public class Game
{
    private Env env;
    private boolean finished;
    private ArrayList<Creature> creatures;
    private KingTux king;
    private Snowball ball;
    private int tuxcounter;
    private int kills;

    /**
     * Constructor for the Game class. It sets up the foxes and tuxes.
     */
    public Game()
    {
        // we use a separate ArrayList to keep track of each animal.
        // our room is 50 x 50.
        creatures = new ArrayList<Creature>();

        for (int i = 0; i < 10; i++) {
            creatures.add(new Tux((int)(Math.random()*10)+1, 1, (int)(Math.random()*28)+1));
        }

        for (int i = 0; i < 1; i++) {
            creatures.add(new Fox(60, 1, (int)(Math.random()*28)+1));
        }

        king = new KingTux(25, 1, 35);

        ball = new Snowball(-400, -400, -400);
    }

    /**
     * Play the game
     */
    public void play()
    {

        finished = false;

        // Create the new environment.  Must be done in the same
        // method as the game loop
        env = new Env();

        // Make the room 50 x 50.
        env.setRoom(new Room());

        // Add all the animals into to the environment for display
        for (Creature c : creatures) {
            env.addObject(c);
        }

        for (Creature c : creatures) {
            if (c instanceof Tux) {
                tuxcounter++;
            }
        }

        env.addObject(king);
        env.addObject(ball);

        // Sets up the camera
        env.setCameraXYZ(30, 50, 55);
        env.setCameraPitch(-63);

        // Turn off the default controls
        env.setDefaultControl(false);

        // A list to keep track of dead tuxes.
        ArrayList<Creature> dead_creatures = new ArrayList<Creature>();
        ArrayList<Creature> new_creatures = new ArrayList<Creature>();

        // The main game loop
        while (!finished) {

            if (env.getKey() == 1 || tuxcounter == 0)  {
                finished = true;
            }

            env.setDisplayStr("Tuxes: " + tuxcounter, 15, 0);
            env.setDisplayStr("Kills: " + kills, 140, 0);

            processInput();

            ball.move();

            king.check();

            // Move each fox and tux.
            for (Creature c : creatures) {
                c.move(creatures, dead_creatures, new_creatures);
            }

            for (Creature c : creatures) {
                if (c.distance(ball) < c.getScale()+ball.getScale() && c instanceof Fox) {
                    dead_creatures.add(c);
                    ball.setX(-400);
                    ball.setY(-400);
                    ball.setZ(-400);
                    kills++;
                }
            }

            // Clean up of the dead tuxes.
            for (Creature c : dead_creatures) {
                if (c instanceof Tux) {
                    tuxcounter--;
                }
                env.removeObject(c);
                creatures.remove(c);
            }

            for (Creature c : new_creatures) {
                creatures.add(c);
                env.addObject(c);
            }

            // we clear the ArrayList for the next loop.  We could create a new one
            // every loop but that would be very inefficient.

            dead_creatures.clear();
            new_creatures.clear();

            // Update display
            env.advanceOneFrame();
        }

        // Just a little clean up
        env.exit();
    }

    private void processInput()
    {
        int keyDown = env.getKeyDown();
        int key = env.getKey();

        if (keyDown == 203) {
            king.setX(king.getX()-1);
        } else if (keyDown == 205) {
            king.setX(king.getX()+1);
        }

        if (ball.getX() <= -400 && key == Keyboard.KEY_S) {
            ball.setX(king.getX());
            ball.setY(king.getY());
            ball.setZ(king.getZ());
        }
    }

    /**
     * Main method to launch the program.
     */
    public static void main(String args[]) {
        (new Game()).play();
    }
}

/**** CREATURE CLASS ****/
/* (Parent class to Tux, Fox, and KingTux) */
import env3d.EnvObject;
import java.util.ArrayList;

abstract public class Creature extends EnvObject
{
    private int frame;
    private double rand;
    /**
     * Constructor for objects of class Creature
     */
    public Creature(double x, double y, double z)
    {
        setX(x);
        setY(y);
        setZ(z);
        setScale(1);
        rand = Math.random();
    }

    private void randomGenerator()
    {
        rand = Math.random();
    }

    public void move(ArrayList<Creature> creatures, ArrayList<Creature> dead_creatures, ArrayList<Creature> new_creatures)
    {
        frame++;
        if (frame > 12) {
            randomGenerator();
            frame = 0;
        }

//         if (rand < 0.25) {
//                 setX(getX()+0.3);
//                 setRotateY(90);
//         } else if (rand < 0.5) {
//                 setX(getX()-0.3);
//                 setRotateY(270);
//         } else if (rand < 0.75) {
//                 setZ(getZ()+0.3);
//                 setRotateY(0);
//         } else if (rand < 1) {
//                 setZ(getZ()-0.3);
//                 setRotateY(180);
//         }

        if (rand < 0.5) {
            setRotateY(getRotateY()-7);
        }   else if (rand < 1) {
            setRotateY(getRotateY()+7);
        }

        setX(getX()+Math.sin(Math.toRadians(getRotateY()))*0.5);
        setZ(getZ()+Math.cos(Math.toRadians(getRotateY()))*0.5);

        if (getX() < getScale()) setX(getScale());
        if (getX() > 50-getScale()) setX(50 - getScale());
        if (getZ() < getScale()) setZ(getScale());
        if (getZ() > 50-getScale()) setZ(50 - getScale());

        // The move method now handles collision detection
        if (this instanceof Fox) {
            for (Creature c : creatures) {
                if (c.distance(this) < c.getScale()+this.getScale() && c instanceof Tux) {
                    dead_creatures.add(c);
                }
            }
        }
    }
}

The rest of the classes are a bit trivial to this specific problem.

I removed the link to pastebin, as they tend to expire and this question would then be more difficult for others who stumble across it with a similar problem to read. Also, if one of the answers below helped you, you should mark it as the answer.

If I understand your code, your fox class is the one that spawns new fox objects inside the move method. By putting this logic in the move method, multiple fox instances are adding more foxes to the list. Also, if no foxes exist, this logic will never occur because the move method will not execute (no instances to call upon). Thus, if there are no more foxes (no fox objects are being updated) then foxes will not be spawned.
You should move this spawning code outside of the fox class. That way only one fox is added every 120 frames (no exponential growth) and a fox will always respawn, regardless of whether there are no more foxes.
Keep track of the frames and spawn foxes outside of this move method. Do not put it inside the fox class, make it independent of fox instances so that this logic is only at least and no more than once, regardless of the number of fox instances. That's the only reason why your seeing this erratic behavior. It's because you've got some game logic in the wrong place, making it dependent on whether there are fox instances being moved (updated) when this spawning logic should be independent and outside of the move method, and perhaps the fox class altogether.

That's very strange. We had a very similar situation to this in our earlier exercises. We would spawn a Fox randomly when it ate a Tux and add it into the list from there.

OOOH. I get it. The other situation we used a for loop to iterate the list and added a new Fox based on what a particular instance of Fox did. I should have read your first paragraph more carefully. THANK YOU.

Questions that heavily involve code like this might be more suitable for SO. Anyway, I'm glad you understand the problem now.

It may be my lack of understanding the underlying objects here, but I think the definition of 'frame' is the cause of the problems.
You are incrementing the counter once per creature so the more creatures you have the faster new ones will spawn. This likely should be incremented before the call to move() instead of inside the call that happens once per creature.
If this isn't the case, please clarify in comments and I'll try again. :)
EDIT: This is the line that is the culprit; you are ++frame PER FOX, not per update loop as mentioned in the comments section:
public void move(ArrayList<Creature> creatures, ArrayList<Creature> dead_creatures, ArrayList<Creature> new_creatures)
{
    frame++;

This should be done in the loop that is calling move() or the like, not by the move method, unless this frame variable is, as suggested, part of the fox object itself. In that case, every fox has its own unique frame counter to spawn off of; that also gives you your exponential growth.

Is the frame variable per instance or is it in the scope of all instances? (I'm not a java guy) I was wondering what he meant by exponential. (fast spawning or multiple spawning simultaneously)

the frame variable is updated every time ENV3D advances one frame. With the amount of objects I am using in this game it's about 20-40 FPS.
The reason it is growing exponentially is because the move() method is being called every frame for EVERY instance of Fox. The more Foxes in the ArrayList, the more will spawn when it comes time to spawn a Fox.
From a set theory point of view, there are n elements in the list. It will grow by n elements every time it is time to spawn. nxn = n^2.

Yes, but there is a frame field in the fox class that is updated in the move method. Anyway, I can see that you understand the problem with the code. Problem solved?


text:
Separating physics and game logic from UI code
I'm working on a simple block-based puzzle game.
The game play consists pretty much of moving blocks around in the game area, so it's a trivial physics simulation. My implementation, however, is in my opinion far from ideal and I'm wondering if you can give me any pointers on how to do it better.
I've split the code up into two areas: Game logic and UI, as I did with a lot of puzzle games:

The game logic is responsible for the general rules of the game (e.g. the formal rule system in chess)
The UI displays the game area and pieces (e.g. chess board and pieces) and is responsible for animations (e.g. animated movement of chess pieces)

The game logic represents the game state as a logical grid, where each unit is one cell's width/height on the grid. So for a grid of width 6, you can move a block of width 2 four times until it collides with the boundary.
The UI takes this grid, and draws it by converting logical sizes into pixel sizes (that is, multiplies it by a constant). However, since the game has hardly any game logic, my game logic layer [1] doesn't have much to do except collision detection. Here's how it works:

Player starts to drag a piece
UI asks game logic for the legal movement area of that piece and lets the player drag it within that area
Player lets go of a piece
UI snaps the piece to the grid (so that it is at a valid logical position)
UI tells game logic the new logical position (via mutator methods, which I'd rather avoid)

I'm not quite happy with that:

I'm writing unit tests for my game logic layer, but not the UI, and it turned out all the tricky code is in the UI: Stopping the piece from colliding with others or the boundary and snapping it to the grid.
I don't like the fact that the UI tells the game logic about the new state, I would rather have it call a movePieceLeft() method or something like that, as in my other games, but I didn't get far with that approach, because the game logic knows nothing about the dragging and snapping that's possible in the UI.

I think the best thing to do would be to get rid of my game logic layer and implement a physics layer instead. I've got a few questions regarding that:

Is such a physics layer common, or is it more typical to have the game logic layer do this?
Would the snapping to grid and piece dragging code belong to the UI or the physics layer?
Would such a physics layer typically work with pixel sizes or with some kind of logical unit, like my game logic layer?
I've seen event-based collision detection in a game's code base once, that is, the player would just drag the piece, the UI would render that obediently and notify the physics system, and the physics system would call a onCollision() method on the piece once a collision is detected. What is more common? This approach or asking for the legal movement area first?

[1] layer is probably not the right word for what I mean, but subsystem sounds overblown and class is misguiding, because each layer can consist of several classes.

Did my answer help, need any further information?

Please, either upvote and accept the answer if this has helped or tell about your problems implementing such an architecture or something, but keep us informed of your situation so that we may be of better assistance. =)

I'll try an attempt to answer this question as I can understand what you're asking, though I don't have much game development experience since I'm still only learning.
As I see it, you to to separate the GUI code from your game logic and domain objects, that is, the puzzle pieces. These are indeed three separate layers - and yes, layer is an appropriate term in my opinion. It is often used to explain the concepts of separating each objects level of a system into subsystems that are independent from each other.
In regards of object-oriented programming, each object shall be a class. So, each piece of your puzzle shall consist of a class per itself, and so the game board. The game board should contains X pieces of puzzle depending on its size and movement capacity that you want to give to the player.
So, here are my thoughts on the topic - I hope that it will help:

The GUI layer: This layer shall contain methods only to display the pieces on the game board to allow the interaction between the the game itself and the player;
The Game Controller layer: Is responsible for the player's inputs. That is the layer that should tell a piece to move in the different directions, and ask the game board whether there will be collisions upon movement and so on;
The Business layer: This layer shall contains all of your business classes, that is, the pieces of your game and the game board object that contains the puzzle pieces.

In this architecture, you would have the GUI layer show the player of the game state, the location of each pieces of puzzle. The GUI layer would then be responsible for getting the player inputs and pass it to an underlying Game Controller layer, which would then be responsible for collision detection. If there's none, then the piece can be ordered to move into that input direction. To do so, you would simply have to call this piece's MoveLeft, MoveRight, etc. methods to make the piece move. You might as well let the game board know what piece you want to move, and then it orders by itself the piece's movement, and piece then moves into the demanded direction. This architecture makes it easy for testing each piece of code into the different layers, and then allows you for unit testing, integration testing and functional testing.
I know this might seem a little confusing at for sight, and thank god if it isn't! Should you require further details and help, please feel free to ask, I'll be glad to help the best I can though I'm a beginner into game development.
Thanks for reading! =)

Which sounds very similar to Model View Controller.

To be honest, any description of abstracting interface from underlying implementation is going to sound like Model View Controller. But that's because the terminology and techniques used are the same (abstracting away from implementation details, and separating user interface from implementation). But it assumes a very simple environment. There are multiple layers here, and there are controllers in each layer. Separating the view from the model isn't enough here, you need to also separate the user interaction control from the game control.

I wonder what's so complex here, since we're moving pieces of a puzzle onto a delimited game board. The controls are gotten from the GUI, which is fact is a good way, and pass out to an abstraction layer, that is, the game controller. The game controller checks for collisions upon movement, then tells the piece to move if there no collision detected. The piece of puzzle then moves properly toward the requested direction and reveals its new position through its Position property getter function, so that the game controller now require the GUI to display this moved piece to that new position.

heh, I blogged about "MVC" in game development a few months ago. Yes, it's a good gateway concept for those uninitiated with game development: http://codecube.net/2010/08/xna-for-the-everyday-developer/

Thanks for your comment Joel Martinez! I shall take an eye out your article on my spare time so that I may learn more about it. =)

Sorry for the late accept, I was unfortunately distracted from the project for a while. I really like the controller approach, I'll adopt it!


text:
Game actions that take multiple frames to complete
I've never really done much game programming before, pretty straightforward question.
Imagine I'm building a Tetris game, with the main loop looking something like this.
for every frame
    handle input
    if it's time to make the current block move down a row
        if we can move the block
            move the block
        else
            remove all complete rows
            move rows down so there are no gaps
            if we can spawn a new block
                spawn a new current block
            else
                game over

Everything in the game so far happens instantly - things are spawned instantly, rows are removed instantly etc. But what if I don't want things to happen instantly (i.e animate things)?
for every frame
    handle input
    if it's time to make the current block move down a row
        if we can move the block
            move the block
        else
            ?? animate complete rows disappearing (somehow, wait over multiple frames until the animation is done)
            ?? animate rows moving downwards (and again, wait over multiple frames)
            if we can spawn a new block
                spawn a new current block
            else
                game over

In my Pong clone this wasn't an issue, as every frame I was just moving the ball and checking for collisions.
How can I wrap my head around this issue? Surely most games involves some action that takes more than a frame, and other things halt until the action is done.

The traditional solution to this is a finite state machine, which is being suggested in several comments.
I hate finite state machines.
Sure, they're simple, they're supported in every language, but they're such an amazing pain to work with. Every manipulation takes a ton of bugprone copy-and-paste code, and tweaking the effect in small ways can be a huge change to code.
If you can use a language that supports them, I recommend coroutines. They let you write code that looks like:
function TetrisPieceExplosion()
  for brightness = 0, 1, 0.2 do
    SetExplosionBrightness(brightness)
    coroutine.yield()
  end

  AllowNewBlockToFall()

  SpawnABunchOfParticles()

  RemoveBlockPhysics()

  for transparency = 0, 1, 0.5 do
    SetBlockTransparency(transparency)
    coroutine.yield()
  end

  RemoveBlockGraphics()
end

Obviously rather pseudocodey, but it should be clear that not only is this a simple linear description of the special effect, but it easily lets us drop a new block while the animation is still finishing. Accomplishing this with a state machine will generally be ghastly.
To the best of my knowledge, this functionality isn't easily available in C, C++, C#, Objective C, or Java. This is one of the main reasons I use Lua for all my game logic :)

You could also implement something along these lines in other OOP languages. Imagine some sort of an Action class and a queue of actions to perform. When an action is complete, remove it from the queue and perform the next action etc. Way more flexible than a state-machine.

That works, but then you're looking at deriving from Action for every single unique action. It also assumes that your process fits into a queue nicely - if you want branching or loops with undefined end conditions, the queue solution breaks down quickly. It's certainly cleaner than the state machine approach, but I think coroutines still trump it on readability :)

True, but for the Tetris example it should be sufficient :)

Co-routines rock- but Lua as a language sucks in so many other ways, I just can't recommend it.

As long as you only need to yield at the top level (and not from a nested function call), you can accomplish the same thing in C#, but yes, Lua coroutines rock.

+1 for "I hate FSMs". By the way, there are coroutines in C#, they're just called generator blocks (-8

For sake of completeness - coroutines are in C++20 now.

I'm taking this from Game Coding Complete by Mike McShaffry.
He talks about a 'Process Manager', which boils down to a list of tasks that need to be done. For example, a process would control the animation for drawing a sword (AnimProcess), or opening a door, or in your case, make the row disappear.
The process would be added to the process manager's list, which would be iterated every frame and Update() called on each. So verymuchlike entities, but for actions. There would be a kill flag to remove from the list when it has finished.
The other neat thing about them is how they can link, by having a pointer to the next process. In this way, your animate row process may actually consist of:

An AnimationProcess for the row disappearing
A MovementProcess to remove the pieces
A ScoreProcess to add points to the score

(Since processes can be one-use things, conditionally there, or there for X amount of time)
If you want any more details, ask away.

You can use a priority queue of actions. You push in an action, and a time. Each frame, you get the time, and you pop off all actions that have a time specified as before that time and execute them. Bonus: Approach parallelises nicely, and you can actually implement almost all game logic this way.

You always need to know the time difference between the previous and the current frame, then you've got to do two things.
-Decide when to update your model: eg. in tetris when a row removal begins, you don't want stuff collide with the row anymore, so you remove the row from the 'model' of your application.
-You then have to handle the object that is in a transitioning state to a separate class that resolves the animation/event over a period of time. In the tetris example you would have the row fade out slowly (change the opaqueness each frame a little bit). After the opaqueness is 0 you transfer all blocks on top of the row one down.
This might seem a bit complicated at first, but you will get the hang of this, just make sure to abstract a lot in different classes, this will make it easier. Also make sure that events that take time, like the removing of a row in tetris, are of the kind "Fire and Forget", just create a new object that handles everything that needs to be done automatically and that, when everything is done, removes itself from your scenegraph.

Also, in some cases heavy calculations might exceed the allowed time for one physics time step(eg. collision detection and path planning). In these cases you can jump out of the calculations when the allotted time has been used and continue the calculation next frame.

You need to think of the game as a "finite state machine". The game can be in one of several states: in your case, "expecting input", "piece moving down", "row exploding".
You do different things depending on the state. For example, during "piece moving down" you ignore player input, and instead animate the piece from its current row to the next row. Something like this:
if state == ACCEPTING_INPUT:
    if player presses any key:
        handle input
    row_timer = row_timer - time_since_last_frame
    if row_timer < 0:
        state = MOVING_PIECE_DOWN
elif state == MOVING_PIECE_DOWN:
    piece.y = piece.y + piece.speed*time_since_last_frame
    if piece.y >= target_piece_y:
        piece.y = target_piece_y
        state = ACCEPTING_INPUT


text:
Creating an alphabet with numbers in 3d using opengl-es
How should I create an alphabet with numbers in 3d in opengl-es? I'm trying to create them with the existing primitives, but it's not looking good. Do we have any alternate way to get these things done? If so, please let me know! Thanks in advance.

What do you need them for? Why doesn't a bitmap font work for you? Are you drawing a lot of text? What character set do you need (western, cjk, or some small subset) ?

I understood you are trying to create numbers and alphabets from primitives manually. You can create them in some modeling program (like Blender, which is freeware), it should be easier and you could get good results.


text:
Should I start to use DX11

Possible Duplicate:
learning Direct3D 9, 10 or 11 ?

I have just started game dev and was wondering should I use DX11 or version 10?
I know AMD/nVidia now have DX11 cards but there are not many games using them now.
So should I wait untill they are mainstearm?

Possibly related: http://gamedev.stackexchange.com/questions/8076/learning-direct3d-9-10-or-11

Possible duplicate of this: http://gamedev.stackexchange.com/questions/8076/learning-direct3d-9-10-or-11

Depends what you want to use it for. If you just want to play with new features and learn stuff, go right ahead! Whatever you do will be useful in the future.
If you're aiming to sell software, and want to have a large target market, it might not be the best move right now. According to steam hardware survey, only about 5% of users have dx11-capable systems, while over 50% have dx10 now. Keep in mind though that this is survey of steam users, who more likely have gaming-capable PCs, so the total market situation is probably worse.

He "just started game dev", so by the time he's ready to ship a game/put it on the internet, DX11 is likely to be mainstream.

You know what's scary? If you look at the survey now only 4 months later, DX11 hardware has 41% share on Steam.

Well, that's 41% of vista or win7 users, but the increase is still rather massive.

Use DX11. You can target DX10 and DX9 feature levels from DX11 so when you're ready, you can use the additional DX11 features.


text:
Drawing large 2D sidescroller level terrain
I'm a relatively good programmer but now that it comes to add some basic levels to my 2D game I'm kinda stuck.
What I want to do: An acceptable, large (8000 * 1000 pixels) "green hills" test level for my game.

What is the best way for me to do this?

It doesn't have to look great, it just shouldn't look like it was made in MS paint with the line and paint bucket tool.
Basically it should just mud with grass on top of it, shaped in some form of hills.
But how should I draw it, I can't just take out the pencil tool and start drawing it pixel per pixel, can I?

2019, the question is still actual :)

Photoshop has layer-effects which can be used to draw good looking levels really fast. I don't know if that would work with GIMP, but here are some steps how to get something on screen fast using Photoshop:
Instructions

Get some dirt and grass textures. The one I'm using in my example are from this freetexture set.
Open a dirt texture in Photoshop. Select all Ctrl-A and copy Ctrl-C. Then select Edit > Define Pattern... from the Menu. Name your Pattern "Dirt".
Do the same for the Grass texture, name it "Grass".
Create a new Layer in Photoshop and apply the Pattern Overlay and Stroke Effect to your layer. Select the "Dirt" pattern for the overlay and the "Grass" pattern for your Stroke (see images below).
Paint with any brush on your layer... instead of having a boring single color, it should render as a landscape, thanks to the layer effects. The beauty of this is, that you can freely add/remove parts of your landscape by using regular drawing tools like the brush or eraser.
(optional) Draw a gradient from dark blue (top) to light blue (bottom) on the background layer for your sky (you could also use layer-effects for that).
(optional) Add some more layer-effects like a gradient and drop-shadow to your "landscape" layer in order to achieve a better look.

Images
Pattern Overlay settings

Stroke settings

Final result
With some more layer effects and a background.

You can also download the PSD file here to have a look at it.

and you just have one big image for the entire level?

Yes, you can store it for the entire level; I would separate background, objects, etc. from the actual hills. For collision detectioning, you can use the alpha layer. +1 for amazing technical art :)

Many platformers and games of all kinds use a tile-based level system, where each level is made up of a grid of tiles, sometimes in multiple layers.  You might have several "grass surface" tiles, several mud tiles, and so on.  Then, instead of drawing a huge image, you lay the tiles out into a map.  It tends to save on texture space, among other things.
More advanced 2D games take a similar approach, but with large "stamps" that can be freely moved, rotated, and/or scaled to make up a level and aren't stuck to a grid like in the tile-based technique.  Aquaria uses this method.

If you don't mind it looking a little boring, you could just draw a bunch of circles of varying sizes along a flat line (your ground plane) and flood fill them in. Then you can go back and draw a brown box covering the "underground" portion of the map, and then add in little touches of ground to meet the top curves of the circle. Then you could do a detail pass to add grass or whatever (very easy if you have Photoshop with the different brushes).
That help?

I would highly recommend you grab a copy of Paint.NET its free, and 100x better than MS Paint -- its got some basic tools to facilitate generating art in the sense you are looking for.
It will, for example, allow you to make a selection and fill the entire selection with a given color/gradient, this will save you from using the pen tool and drawing pixel by pixel.
Its not even close to photoshop, but its excellent for this type of use-case, where you are looking for basic style art.


text:
Are there any good html 5 mmo design tutorials?
Hey all. I got a rather inspired after playing gaia online's zOMG and wanted to revive an old project idea I've had laying around for a few years now.
I'm looking to work with html5 (ie canvas, svg based sprites, & WebGL) to build a graphical web based MUD/MMO. Obviously, this is a new take on an old idea and after searching google I haven't really turned up many good resources. But does anyone have any tutorials or other resources to point me in the right direction?

You'll find a lot of questions on here about HTML5 games, based on my observations, it seems the general consensus is to avoid it for now, since the compatibility across browsers is low.

The guy here in the video does not seem to like the current trend with HTML5 standards, "mimimalism is often underrated" -he said something like that. Perhaps, HTML5 is still under review because the costs of too ambitious standards may backfire later. He said also JS is a young-language-for-its-age and now some ES3.1 -- things seem to be still in draft boards...

Update: Because of some comments below I'll have to clearify something; the idea is not to create WOW or something overtly graphical "rich" in the browser that would have too much overhead from both the browser and the os. The idea is to create something fun and playable. FF7, Diablo, Starcraft, Runescape, and DooM still has a fan base to this day. Plus, runescape was the first graphical MUD(multi-user-dungeon) that started the MMO craze.

Dwight - dive in and start building.  Start small, build your way up.  I.e., get a nice little sprite based game working that's talking to a back-end server first, then worry about the whole WebGL thing later.
And ignore the HTML5 doubters.  See links below for some nice HTML5 demos and info on what it can do.  Also, go check out Google's App store.  There are some pretty amazing web based apps people have built that should inspire you.
http://www.chromeexperiments.com - A collection of impressive tech demos from Google.  Requires Chrome, but as far as I know is written primarily to HTML5 standards.  If other browsers support the standard, they will work too.
http://www.html5rocks.com/ - More information on HTML5.  Includes an interactive slideshow going over features of HTML5.

Check out EA's Lord of Ultima game, which I believe is heavily HTML5.  www.lordofultima.com

No. There are not good tutorials to make MMOs for the languages and environments that MMOs have actually been written in. There are certainly not tutorials for languages and environments that barely work as is.

-1  That's a pretty negative take on things.  I hardly would classify HTML5 as a "language and environment[s] that barely work as is."

@TimHolt +1 to your comment.

@Joe If your thinking of souly a mmo like those designed by E3, Blizzard or Venditti then maybe I can understand where your coming from. But really, with WebGL now out and the dropped support for flash on tablet/Mobiles; there are several MMO apps out floating on the web and on android market. Plus, as I pointed out Gaia Online is one of those type of games. I'm even working on a port of DooM to webgl. So this "answer" is a -20 for not thinking beyond the console system.

@DwightSpencer: So now that it's a year and a half later, you're going to link to the tutorials, then? No, you didn't. There still aren't any. HTML5? Still kind of a big mess. But sure, port Doom. Doing so will prove WebGL is at least as capable a platform as 1993-era MS-DOS. Everyone sure loved that!

This is quite similar to this question:
Browser-based MMOs (WebGL, WebSocket)
 which had some helpful answers imho.

There is much room for exploration in this arena.  If you're dead set on canvas+websockets, you should consider a non-RPG MMO, something like a massive puzzle game or a simple, iconographic, RTS.
Check out "comet" servers such as cometd, or something that you might build with mochiweb or nodejs.  And for the client side you could look into limejs or the dojo.gfx utilities.
Thats as good a place as any to get started.  The technology just isn't mature, much experimentation and waiting will be required before the browser is a good place for 'professional' games.

Ok, this is an old question, but it does need an updated answer.
This is 2014, most modern browsers are very reliable in terms of HTML5 features, and Chrome is the most used browser right now.
Probably you won't be able to create a full 3d mmorpg with canvas/WebGL, but you can still create an interesting 2d game with very good performance across most devices.
There are plenty of frameworks out there, and you can even used websockets to allow a fluid multiplayer experience.
With HTML5 you can develop apps much faster than using other 'native' languages, but you will have to drop support to older browsers like IE8 or lesser versions.

This doesn't provide a very good answer to the question (which was about specific tutorials).

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
2D Game Physics: How to evaluate when an accelerating ray is close to a point?
Given a ray in a 2D world at position p with initial velocity u and acceleration a how can I tell when it's within a certain distance r from a certain point.

Uniform motion: s = ut + at^2/2
Or p(t) - p(0) = ut + at^2 / 2
You want the first t >= 0 for which (p(t) - C).(p(t) - C) = r^2.
If u and a could be non-perpendicular then I think you have to solve a quartic.

Thanks, yes the directions are arbitrary. I was fearing a quartic as I'm unfamiliar in solving them, but is it just a case of running the constants through some published quartic solution and using the least positive amount?

@Nick, I think it should be, yes, although there's no guarantee of a numerically stable solution - see http://www-staff.it.uts.edu.au/~don/pubs/solving.html


text:
C++ game-programming; What would be the "next step"?
I'm reading C++ Primer Plus 5th Edition. I'm over at Chapter 8 exercises, which is more than half of the book to go but I was wondering what would be the "next step" after I'm through with the book?
I want to use SDL/OpenGL and whatever cross-platform open source api's and libs there are available for other components of game development.

Quite simply you should put what you've learned to the test and start making a simple game.

So no more books?

I wouldn't say that, but at some point you have to just jump head first in to the code. More reading is always a good idea, there are lots of books recommended on this site, all you need to do is a little searching.

@Bob: Books are good for learning. Practice is good for integrating your learnings.

@Bob- I would definitely start coding. I'm in the same predicament as you, and really, theory only gets you so far. You should start creating a game, and then start looking back and see if you can apply the theory you learned from the book to make the game/game engine broader, more flexible, etc. Besides, theory is boring unless you apply it.

As a side note, I would highly recommend using SFML instead of SDL. Since you've been hitting on C++ books, how SFML is organized will make a lot more sense that SDL. SFML is very object oriented.
Although SDL has been around longer and has a CRAP LOAD of existing resources and tutorials, SFML is worth the investment. I've worked with both, and I can tell you SFML is just nicer. An added bonus is that 2D rendering is hardware accelerated in SFML. So it's faster too.
End of shameless SFML propaganda.

Books are often not the best of resources when it comes to learning programming. Especially in a language as complex as C++. If this is your first language I strongly suggest starting out with another language such as Java or C#/XNA which are both easy to learn and give you a good understanding of whats involved in building a game. Simply diving into SDL/OpenGL and expecting to build a game without having much understanding of how things work is a big mistake, one that many people make which results in them disliking programming.
The book should only be used as a reference. You need to personally think of problems which you can solve and then solve them. Then begin writing more complex programs such as, for example Battleships in a console environment. The more programming you do the better you get. Furthermore, books don't teach you how to design your code, you get that from experience. Designing a good structure for your program is a difficult task but the more your practice the better you will get.
Just as a side note. 3D programming is a lot more complicated than 2D programming (I'm assuming you want to build 3D games). Try building console games first then go to 2D. Once you learn more only then you will have the skills to attempt 3D and graphics programming.

Mucking around in a console environment is the best way to start programming C++ IMO.

Go build something, anything and then after two hours of trying to get it to compile go back and read the book again.
You will now understand why x was called before y and what the purpose was.
This will allow you to use the knowledge from the book instead of just copying the code.


text:
Atmospheric Scattering
I'm trying to implement atmospheric scattering based on Sean O`Neil algorithm that was published in GPU Gems 2. But I have some trouble getting the shader to work.
I've downloaded sample code of O`Neil from NVidia site. Made minor adjustments to the shader 'SkyFromAtmosphere' that would allow it to run in AMD RenderMonkey.
In the images it is see-able a form of banding occurs, getting an blueish tone. However it is only applied to one half of the sphere, the other half is completely black. Also the banding appears to occur at Zenith instead of Horizon, and for a reason I managed to get pac-man shape.
I would appreciate it if somebody could show me what I'm doing wrong.
Vertex Shader:
uniform mat4 matView;
uniform vec4 view_position;
uniform vec3 v3LightPos;

const int   nSamples = 3;
const float fSamples = 3.0;
const vec3  Wavelength = vec3(0.650,0.570,0.475);

const vec3  v3InvWavelength = 1.0f / vec3( Wavelength.x * Wavelength.x * Wavelength.x * Wavelength.x,
                                           Wavelength.y * Wavelength.y * Wavelength.y * Wavelength.y,
                                           Wavelength.z * Wavelength.z * Wavelength.z * Wavelength.z);

const float fInnerRadius = 10;
const float fOuterRadius = fInnerRadius * 1.025;
const float fInnerRadius2 = fInnerRadius * fInnerRadius;
const float fOuterRadius2 = fOuterRadius * fOuterRadius;
const float fScale = 1.0 / (fOuterRadius - fInnerRadius);
const float fScaleDepth = 0.25;
const float fScaleOverScaleDepth = fScale / fScaleDepth;
const vec3  v3CameraPos = vec3(0.0, fInnerRadius * 1.015, 0.0);
const float fCameraHeight = length(v3CameraPos);
const float fCameraHeight2 = fCameraHeight * fCameraHeight;

const float fm_ESun  = 150.0;
const float fm_Kr    = 0.0025;
const float fm_Km    = 0.0010;
const float fKrESun = fm_Kr * fm_ESun;
const float fKmESun = fm_Km * fm_ESun;
const float fKr4PI = fm_Kr * 4 * 3.141592653;
const float fKm4PI = fm_Km * 4 * 3.141592653;

varying vec3 v3Direction;
varying vec4 c0, c1;

float scale(float fCos)
{
   float x = 1.0 - fCos;
   return fScaleDepth * exp(-0.00287 + x*(0.459 + x*(3.83 + x*(-6.80 + x*5.25))));
}

void main( void )
{
   // Get the ray from the camera to the vertex, and its length (which is the far point of the ray passing through the atmosphere)
   vec3 v3FrontColor = vec3(0.0, 0.0, 0.0);
   vec3 v3Pos = normalize(gl_Vertex.xyz) * fOuterRadius;
   vec3 v3Ray = v3CameraPos - v3Pos;
   float fFar = length(v3Ray);
   v3Ray = normalize(v3Ray);

   // Calculate the ray's starting position, then calculate its scattering offset
   vec3 v3Start = v3CameraPos;
   float fHeight = length(v3Start);
   float fDepth = exp(fScaleOverScaleDepth * (fInnerRadius - fCameraHeight));
   float fStartAngle = dot(v3Ray, v3Start) / fHeight;
   float fStartOffset = fDepth*scale(fStartAngle);

   // Initialize the scattering loop variables
   float fSampleLength = fFar / fSamples;
   float fScaledLength = fSampleLength * fScale;
   vec3 v3SampleRay = v3Ray * fSampleLength;
   vec3 v3SamplePoint = v3Start + v3SampleRay * 0.5;

   // Now loop through the sample rays
   for(int i=0; i<nSamples; i++)
   {
      float fHeight = length(v3SamplePoint);
      float fDepth = exp(fScaleOverScaleDepth * (fInnerRadius - fHeight));
      float fLightAngle =  dot(normalize(v3LightPos), v3SamplePoint) / fHeight;
      float fCameraAngle = dot(normalize(v3Ray), v3SamplePoint) / fHeight;
      float fScatter = (-fStartOffset + fDepth*( scale(fLightAngle) - scale(fCameraAngle)))/* 0.25f*/;
      vec3 v3Attenuate = exp(-fScatter * (v3InvWavelength * fKr4PI + fKm4PI));

      v3FrontColor += v3Attenuate * (fDepth * fScaledLength);
      v3SamplePoint += v3SampleRay;
   }

   // Finally, scale the Mie and Rayleigh colors and set up the varying variables for the pixel shader

   vec4 newPos = vec4( (gl_Vertex.xyz + view_position.xyz), 1.0);
   gl_Position = gl_ModelViewProjectionMatrix * vec4(newPos.xyz, 1.0);
   gl_Position.z = gl_Position.w * 0.99999;
   c1 = vec4(v3FrontColor * fKmESun, 1.0);
   c0 = vec4(v3FrontColor * (v3InvWavelength * fKrESun), 1.0);
   v3Direction = v3CameraPos - v3Pos;
}

Fragment Shader:
uniform vec3 v3LightPos;
varying vec3 v3Direction;
varying vec4 c0;
varying vec4 c1;

const float g =-0.90f;
const float g2 = g * g;
const float Exposure =2;

void main(void){
   float fCos = dot(normalize(v3LightPos), v3Direction) / length(v3Direction);
   float fMiePhase = 1.5 * ((1.0 - g2) / (2.0 + g2)) * (1.0 + fCos*fCos) / pow(1.0 + g2 - 2.0*g*fCos, 1.5);
   gl_FragColor = c0 + fMiePhase * c1;
   gl_FragColor.a = 1.0;
}

It is difficult to help you since the problem is very specific and what you need is basically a debugger.

the sky from atmosphere shader is meant to be used when the camera is positioned inside the atmosphere, you should be using the ***fromSpace shaders in this scenario. The ***fromAtmosphere shaders might simply not work for this point of view. Check if these issues are apparent at low altitudes, if they aren't, I'd say the shader is working fine  EDIT: asked 1 year ago...guess I'm a bit late

You might want to take a look at this source code which does the same thing for osgEarth.

I've nicened a bit your link and added one to the osgEarth home page. You can have a look here to give your answers the look they deserve ;) Welcome to gamedev-SA!


text:
Inconsistent accessibility error in xna
Hey all, you may remember me asking a question regarding a snake game I was creating about two weeks ago.
Well I'm quite far now into making the game (thanks to a brilliant tutorial I found). But I've come across the error described named above.
So heres my problem;
I have a SnakeFood class that has a method called "Reposition". In the game1 class I have a method called "UpdateInGame" which calls the reposition method to load an orange that spawns in a random place every second.
My latest piece of code changed the reposition method to allow the snake I have on the screen to not be overlapped by the orange that randomly spawns.
Now I get the error (in full):
Error   1   Inconsistent accessibility: parameter type 'TheMathsSnakeGame.Snake' is less accessible than method 'TheMathsSnakeGame.SnakeFood.Reposition(TheMathsSnakeGame.Snake)'   C:\Users\Tom\Documents\Visual Studio 2008\Projects\TheMathsSnakeGame\TheMathsSnakeGame\SnakeFood.cs 33  21  TheMathsSnakeGame
I understand what the errors trying to tell me but having changed the accessiblity of the methods, I still can't get it to work.
Sorry about the longwinded question.
Thanks in advance :)
Edit: Code I'm using
 (Game1 Class)
private void UpdateInGame(GameTime gameTime)
    {
        //Calls the oranges "reposition" method every second
        if (gameTime.TotalGameTime.Milliseconds % 1000 == 0)
            orange.Reposition(sidney);
        sidney.Update(gameTime);
    }

(SnakeFood Class)
 public void Reposition(Snake snake)
    {
        do
        {
            position = new Point(rand.Next(Grid.maxHeight),     rand.Next(Grid.maxWidth));
        } while (snake.IsBodyOnPoint(position));
    }

Some example code will help.

Theres too much code to copy and paste, would you like me to copy and paste the code spoken of above?

You don't have to copy and paste everything, just the appropriate code that you're having issues with.

The accessibility levels of C# are public > protected > internal > protected internal > private. Your class' accessibility must by >= to the accessibility of the methods it contains.

+1. meaning you have a variable: TheMathsSnakeGame.Snake. This is an instantiation of some class. Make that class a public class so it's ok to pass any instantiated objects of that class as params to other class' public methods (i.e. .Reposition())

Thank you Steve, I've just made the Snake class public instead of its default (which is private?) and it has worked :D
Thank you! :)

internal is the default access modifier, when none is specified (http://msdn.microsoft.com/en-us/library/ms173121.aspx)


text:
2D non-tile based map editor
I am currently developing a relatively simple 2D, topdown oriented adventure game for the iPhone and was wondering what would be the easiest way to create the maps for my game. I figured I would need some kind of visual editor that would give me immediate feedback and would allow me to place all objects in the world exactly where I want them. I could then load the saved representation of the world I create in the editor in my game.
So, I am looking for a simple map editor that allows me to do this. All the objects in my game are simply textured rectangles build up from two triangles. All I need to be able to do is position different rectangles/objects in the map, and give them a texture. I am using texture atlases, so it would be useful to be able to assign portions of textures to the objects. I then need to be able to extract all the objects from the saved representation of my maps, together with the name/identifier of the texture(atlas) they use, and the area of the texture atlas.
I have looked at some tile-based map editors like Tiled and Ogmo, but they don't seem to be able to do what I want.
Any suggestions?
EDIT: a more concrete example: something like the GameMaker level editor, but then with added export functionality in a handy format.

Why non-tiled? What advantage does this bring?

Technically I guess it doesn't matter as long as the editor can do the things I mentioned. The tile-based editors I tried focus on other functionality than I want, however.

http://gamedev.stackexchange.com/questions/1886/tile-based-2d-level-editor and http://gamedev.stackexchange.com/questions/225/tools-for-creating-2d-tile-based-maps might help?

I looked at some of those before asking this question, and they did not have the features I need.

'Why non-tiled?' - to get rid of the grid-based look, allow arbitrary rotation/scaling of objects, and seamless blending of objects into each other using feathered alpha channels.

Have you seen my answer below? It sounds like what you're looking for.

Try Gleed. From its site:

GLEED2D (Generic LEvel EDitor 2D) is a general purpose, non tile-based Level Editor for 2D games of any genre that allows arbitrary placement of textures and other items in 2D space. Levels are saved in XML format. Custom Properties can be added to the items in order to represent game-specific data/events/associations between items etc.
  Check the video tutorials under the Documentation tab to get an idea of its powerful features.

This looks like exactly the sort of thing I need. The only downside is that it's windows only, and as I need this editor for my iPhone projects I would like something that works under mac osx. I guess I could run it in a virtual machine though, but if someone knows an editor like this for mac it would be perfect.

I'm sure you could run this under Parallels without a hitch.

There is an updated version of Gleed on Github: https://github.com/SteveDunn/Gleed2D/wiki -- the linked version on codeplex hasn't been updated since September 2010.

Thanks for the update. Funny I just came across the Github project today, too. It's great to see the tool being updated.

If you haven't already read it, I'd recommend reading this, gives some ideas of how non-tile-based 2D can be done very effectively:
http://www.davidhellman.net/blog/the-art-of-braid-index/
You could also take a look at the Aquaria source code, and see if its editor is adaptable to your needs (that used a mix of tiles and arbitrary object placement)
I've been working on a non-tile-based editor myself (screenshots: http://www.bluescrn.net/projects/twodee6.png , http://www.bluescrn.net/projects/twodee4.png), but it's still very much a work-in-progress.

Offhand, I don't know of any game-agnostic editors aimed at this task. However, you could consider using any existing paint program (Photoshop, GIMP, Paint.net, Acorn, Pixelmator, et cetera) that supports layers, build each level sprite in its own layer, then simply saving each layer individually to some directory, and then writing a tool to post-process that directory to isolate the position and bounds of each image within the layer file, save out that position and bounds information, and slice up the layer and re-composite all of them back on to a texture atlas.
Fundamentally that algorithm isn't any different than what a dedicated tool would be doing, and if you can do it on a bunch of distinct image files you can do it on images in memory -- in other words, it might not be terribly complex to write your own simple tool that does this after you get the basics of the process down using a paint program.
One problem might be if your levels are huge, editing them in a paint program might not be pleasant depending on the power of your machine. But for iPhone-game style levels I suspect you'd be fine.

I guess this will become unhandy if you want to re-use the same asset multiple times in a level. E.g. a Tree.

Yea, you'd have to copy-paste a lot. Maybe some painting tools have ways of doing reference layers, I'm not sure. It's certainly a think you could implement in a custom editor. On the other hand, it does allow for extreme variation in the "tileset" of the level, which can look pretty awesome if you're willing to put the effort in.

What you are suggesting sounds terribly cumbersome when creating a lot of levels. I am sure there must be lots of editors out there already? Isn't this a very common task when developing a 2d game? I just thought of a more concrete example of what I am looking for: something like the GameMaker level editor, but then with added save functionality

It will be cumbersome -- you have to decide if it's more cumbersome than writing your own editor or writing an importer for somebody else's file format. There are likely plenty of editors out there that act like what you want, but they're likely tied to the format of a specific game, and/or aren't available to the public. "Game-agnostic" editors are relatively rare.

I don't care writing an importer for any file format, as long as the editor does what I want. Any concrete examples?

I've recently released a non tile based level editor for iPhone and Android. It has in built physics simulation for testing and can load game elements from SVG or by tracing PNG images. For your game you could just import rectangular PNGs and position them where you wanted. The level designer produces a config file and a packed sprite sheet (optional) which can be exported straight to XCode (code is supplied to read the config file). It's pretty simple but very flexible. The program's called Shape Workshop and can be downloaded here.


text:
Multiple Sprites using foreach Collison Detection in XNA (C#)
Back again from my last question.  Now I was curious I use a foreach statement to use the same shot class.  How would I go about doing collison detection.
I used the tutorial here on how to shoot a fireball
XNA Development: Game Development for the masses.
I tried to put in several places a foreach to look at all of them to see if they have reached the borders of my sprite hero but doesn't seem to do anything.  If again some one might know of a good site that has tutorials to explain collision detection a little bit better that would be appriecated.

The fireball is a 'box' of width and height 200. And it's at a given position. Add a rectangle
Rectangle boundingRect = new Rectangle(position.X, position.Y, 200, 200);

to your fireball class.
Make sure to update the rectangle with the new position of the fireball every frame (so in the fireball's update or draw method)
Do the same thing for your player class.
Now you can check if the fireball has hit the player like this in your game's update method:
if(fireball.boundingRect.Intersects(player.boundingRect)) {
    //hit
}

I have tried that before with no results.  Where would I put the rectangle portion and where would I put the if statement.

add the rectangle portion to your fireball class (now you fireball has a rectangle, which will follow the position of your fireball image)
You can add the if statement wherever in the update statement though i do mine towards the end

I mean in which function of the class and do I also add a rectangle for my hero?  Also which function for the update cause i have a hereo, enemy, spirte, and fireball calss along wiht the game1 class.

Hey Bradley, I explicitly told you to make a rectangle in both your hero class and fireball class, however you could also add one in your enemey class.  If your hero, enemey and fireball all derive from the same class, then you could add it in that base class instead, make sure that you update the position of the rectangle every frame (you have todo this in the update or draw method of the entity that has the rectangle). Now the collision checking part needs to be done somewhere where you have access to all the items, usually in the game1.Update(..) method.

Thank you again for the help.  Finally got it after thinking aobut it yet again.  I had to add a rectangle for the player that was for his fireball and him, then I added a rectangle for the enemy and his fireball.  Of course every update I had if jumping or moving and for the firball being shot.  Then in the game update of game1.cs I just added an if statement to test it and then it would close the game if it ever became true.

Hey Bradley, no problem. If my answer helped you, then please mark it as the answer to this question (so it wont clutter the un-answered list, and it gives me some points :P).

No problem sorry new to using this site.


text:
Setting up OpenGL camera with off-center perspective
I'm using OpenGL ES (in iOS) and am struggling with setting up a viewport with an off-center distance point.
Consider a game where you have a character in the left hand side of the screen, and some controls alpha'd over the left-hand side.  The "main" part of the screen is on the right, but you still want to show whats in the view on the left.  However when the character moves "forward" you want the character to appear to be going "straight", or "up" on the device, and not heading on an angle to the point that is geographically at the mid-x position in the screen.
Here's the jist of how i set my viewport up where it is centered in the middle:
// setup the camera
    //

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    const GLfloat zNear = 0.1;
    const GLfloat zFar = 1000.0;
    const GLfloat fieldOfView = 90.0; // can definitely adjust this to see more/less of the scene

    GLfloat size = zNear * tanf(DEGREES_TO_RADIANS(fieldOfView) / 2.0);
    CGRect rect;
    rect.origin = CGPointMake(0.0, 0.0);
    rect.size = CGSizeMake(backingWidth, backingHeight);
    glFrustumf(-size, size, -size / (rect.size.width / rect.size.height), size / (rect.size.width / rect.size.height), zNear, zFar);

    glMatrixMode(GL_MODELVIEW);

    // rotate the whole scene by the tilt to face down on the dude
    const float tilt = 0.3f;
    const float yscale = 0.8f;
    const float zscale = -4.0f;
    glTranslatef(0.0, yscale, zscale);
    const int rotationMinDegree = 0;
    const int rotationMaxDegree = 180;

        glRotatef(tilt * (rotationMaxDegree - rotationMinDegree) / 2, 1.0f, 0.0f, 0.0f);

    glTranslatef(0, -yscale, -zscale);

    static float b = -25; //0;
    static float c = 0;

    // rotate by to face in the direction of the dude
    float a = RADIANS_TO_DEGREES(-atan2f(-gCamera.orientation.x, -gCamera.orientation.z));
    glRotatef(a, 0.0, 1.0, 0.0);

    // and move to where it is
    glTranslatef(-gCamera.pos.x, -gCamera.pos.y, -gCamera.pos.z);

    // draw the rest of the scene
    ...

I've tried a variety of things to make it appear as though "the dude" is off to the right:
- do a translate after the frustum to the x direction
- do a rotation after the frustum about the up/y-axis
- move the camera with a biased lean to the left of the dude
Nothing i do seems to produce good results, the dude will either look like he's stuck on an angle, or the whole scene will appear tilted.  I'm no OpenGL expert, so i'm hoping someone can suggest some ideas or tricks on how to "off-center" these model views in OpenGL.  Thanks!

Have you tried drawing a picture of what you want?  You could then try and figure out whether it's even physically possible or if you're stuck in some MCEscher world that can't ever be emulated with camera mathematics in a physical world.

Typically when working with a camera system, in addition to the frustum, you need three other pieces of information: where the camera is (eye), what it's pointed at (at), and its orientation (up). When trying to solve your shoulder-view problem, it is not typical to be modifying the frustum. You should set the camera at that shoulder view by modifying "eye." To get it to look like he is walking in a straight line, I would try making the camera look along a vector that is parallel to "the dude's" vector of movement in order to make it look like he is moving in a straight line, and that is done by modifying "at." If you need to make your scene look wonky by twisting the camera (so it has a sideways orientation or such), that is when you would modify "up."

This seems to make sense in theory, but it doesn't work for me.  Naively speaking, the "eye" is always going to be in the middle of screen...  so if its pointed in the direction of the dude's heading (at) then it will appear as though the dude is headed towards the center of the screen in the distance, even though both the dude and the camera are orientated with the same heading...  i could be wrong, but without some sort of twist, which "almost" works, i can't get the over the should view working (that is the perfect name for it btw).  Perhaps i'm wrong about where the eye is positioned?

In perspective view, two parallel vectors will appear to be moving towards each other in the distance. Think of the typical example of railroad tracks. The rails are parallel, but they meet at one point in the distance. You can't really help that. I expect that isn't your problem, however, because at distances so close to the camera you should not be able to notice that effect that perspective has. Have you tried making them point in the same direction (as opposed to at the same point), or are these just your thoughts on it?

Ah ok - this "point in the distance" issue IS my problem!  The point in the distance always seems to be in the center of the device, whereas my dude is at the 3/4 position.  I want the point in the distance to be 3/4 of the view as well, so that objects IN FRONT of the dude, are just "up" from it, as opposed to "up and a bit to the right".  I'm not sure what you mean by "tried making THEM point in the same direction"...  i think i do that now, and it doesn't help.  Its only when o tilt the camera to point somewhat in the dudes direction that i can get this to almost work, but never looks good.

What i really want to do is the following - lets say my device is 480x320.  If i actually were to fake render 720x320, so that the mid point is at the 360 position, but then only show the first 480 x, THAT would give me what i want!  But i don't know how to do that either ;)

Actually that sort of worked - when i change the backingwidth above to 720 it works perfectly!  However, i fear i'm rendering way too much...  any comments on this would be appreciated.

Old question, but well. It appears that instead of:
glFrustumf(-size, size,
           -size / (rect.size.width / rect.size.height),
           size / (rect.size.width / rect.size.height), zNear, zFar);

You want the frustum to be slightly off, for instance by a quarter of the screen size:
glFrustumf(-size - size / 2, size - size / 2,
           -size / (rect.size.width / rect.size.height),
           size / (rect.size.width / rect.size.height), zNear, zFar);

I think this will not achieve the desired result since it distorts the projection matrix (I'm trying to do the same as requested here and had already tried your approach).

I'm trying to do the same and found two ways of doing it:
One way is to render as if the screen is bigger, so that part of the viewport goes out of the screen and the viewport center align with the screen point you want (from a comment I can see that you've done this and it works), but it makes you draw more of the scene.
Another option (if you are using a version of OpenGL ES that supports vertex shaders) is to translate the resulting vertices (of the vertex shader, which should already be in projection space). This is something like:
gl_Position = u_model_view_proj_matrix * a_vertex_position;
gl_Position.xy = gl_Position.xy + u_viewcenter * gl_Position.w;

Where u_viewcenter is a vec2 (from -1 to 1) that defines where you want the view center to be.
This approach has some problems if you use the projection matrix in your code to do things such as picking or frustum clipping, since applying the projection matrix to the scene will no longer match the output of the vertex shader.

You should be able to apply a 2D offset/scale after the projection.
Just multiply the projection matrix by a suitable translation/scale matrix (where the translations are in the -1..1 range of viewport coordinates)

I tried this...  it didn't help.  I'm not sure what the scale is supposed to do.  I definitely do something like the translation now, but the "point in the distance" issue still exists.


text:
How to calculate vertex normals for a mesh in Java in OpenGL ES?
Can some one point me to Java code ( in Java not C or C++) that calculates all the normals for all the vertices of a mesh for OpenGL ES application. I need this for lighting. Lets say I have a cube with following vertices and indices:
float vertices[] = { -width, -height, -depth, // 0
                      width, -height, -depth, // 1
                      width,  height, -depth, // 2
                     -width,  height, -depth, // 3
                     -width, -height,  depth, // 4
                      width, -height,  depth, // 5
                      width,  height,  depth, // 6
                     -width,  height,  depth  // 7
        };
short indices[] = { 0, 2, 1,
                    0, 3, 2,
                    1,2,6,
                    6,5,1,
                    4,5,6,
                    6,7,4,
                    2,3,6,
                    6,3,7,
                    0,7,3,
                    0,4,7,
                    0,1,5,
                    0,5,4
                  };

In above specific example how many normals we need?

You need one normal per triangle. Calculating normals is covered here: http://gamedev.stackexchange.com/questions/8191/any-reliable-polygon-normal-calculation-code

@bummzack Is there a way in OpenGL-ES to only specify one normal per triangle? I thought you could only pass them in as a vertex attribute to your Vertex Shader (and do per vertex lighting). Right?

Yeah, you'll have to set the normal per vertex. For a cube, all vertices of one side share the same normal though. Therefore you can calculate the normal once per side and then pass that to all vertices belonging to that side.

You can calculate normals by taking two edges, and cross product for each vertex. A cube actually has 24 vertices not 8, the reason is that each corner vertex is shared with different faces, because openGL takes per vertex attributes, you need to duplicate a vertex if you find that it has 2 different normals, assuming you want hard edges.
http://www.devmaster.net/forums/showthread.php?t=1783
this is a C++ code but its self explanatory.