text:
Random Movement for multiple entities
I have this code for a arraylist of entities.
All the entities use the same random and so all of them move in the same direction. How can I change it so it generates a new random number for each entity?
public void moveFemale() {
    for(int i = 0; i < 1000; i++){
        random = rand.nextInt(99);
    }

    if (random >= 0 && random <= 25) {
        posX -= enemyWalkSpeed; // right
    }

    if (random >= 26 && random <= 50) {
        posX += enemyWalkSpeed; // left
    }

    if (random >= 51 && random <= 75) {
        posY -= enemyWalkSpeed; // up
    }

    if (random >= 76 && random <= 100) {
        posY += enemyWalkSpeed; // down
    }
}

Is this correct?
public void moveFemale() {
    for (Female female: GameFrame.females){

        female.lastChangedDirectionTime += elapsedTime;

        if (female.lastChangedDirectionTime >= CHANGE_DIRECTION_TIME)
        {
            female.lastChangedDirectionTime = 0;

            random = rand.nextInt(100);

            if (random >= 0 && random <= 25) {
                posX -= enemyWalkSpeed; // right
            }

            if (random >= 26 && random <= 50) {
                posX += enemyWalkSpeed; // left
            }

            if (random >= 51 && random <= 75) {
                posY -= enemyWalkSpeed; // up
            }

            if (random >= 76 && random <= 100) {
                posY += enemyWalkSpeed; // down
            }
        }
        }
    }

Sorry -- what is the purpose of your for loop? I don't think you need that? What does the 1000 refer to?

its a crude timer that only allows random to generate a new number after 1000 has been hit. I know its bad but I can't figure out a timer.

Ouch, that's bound to cause issues. Let me think.. what are you trying to achieve with that, game-mechanics-wise? Is this to change direction only after some time has passed?

Yeah but anyway... How would I fix the random movement? All the entities move the same way. I honestly have no idea how to fix it.

Your entities ("females") need to have a public member on them, something like
public int lastChangedDirectionTime = 0; //milliseconds

You also need some time interval at which you want them to change direction, set up as a constant:
public final int CHANGE_DIRECTION_PERIOD = 1000; //milliseconds

As each game loop goes by, get the amount of time that has elapsed since the last game loop iteration (if you don't have this value, comment!), and do
for (Entity entity : entities) //every one!
{
    entity.lastChangeDirectionTime += timeElapsed; //presumably both in the same time unit eg. seconds

}

As soon as you've done the addition, do this:
if (entity.lastChangeDirectionTime >= CHANGE_DIRECTION_PERIOD)
{
    entity.lastChangeDirectionTime = 0;

    //do your directional change logic, here.
}

I'm not 100% sure of your structure so you'll need to figure out where to slot these into your code.

Thanks so much for the answer, but I get this error when try to to for(Females female : females): Can only iterate over an array or an instance of java.lang.Iterable                                          I have no idea what this means at all, I've never actually dealt with this particular for loop before.

Not to worry. First I see your typename is Females with an 'S', is that right? Secondly a for-each loop like I have there is just the same as saying for (int c = 0; c < entities.length; c++) { Entity entity == entities[i]; //etc. } No difference, for-each is just a bit quicker to type.

ok so if my arraylist is in my GameFrame class, the for loop would be like this?: for (GameFrame.Female female:females) Is that correct?

My arraylist in gameframe: static ArrayList<Female> females = new ArrayList<Female>();

Ah, you have an ArrayList. Yes, this is why I said, "Females with an 'S'" right? Because you had a typo, before. Try again with for (Female female : females) That should work fine, because ArrayList adheres to java.lang.Iterable as mentioned before. Read that colon as "in", in your mind, and it will make sense as you type it.

So what does timeElapsed equal then? Can I use do time++ inside a loop and use that for timeElasped? Thanks for all your help so far!

You're welcome. OK, timeElapsed: Do you know how many frames per second your game is running at? Yes / No? (And, you must never do timing like you suggest there. It will break everything.)

That's the thing, I have a basic timer set up in my GameFrame class : mainTimer = new Timer(10, this);   mainTimer.start(); However, I have no idea how to get this to return a variable.

No, that's absolutely great. OK, so that Timer(10, this) is just saying that you have a 10 millisecond fixed timestep. There are 1000 ms in a second, so your fps/update rate is 1000/10 = 100 frames per second, just for interest's sake. So you can use 10 as the value for timeElapsed; on every update, we know 10ms have passed since the last update, right? Take it away!

Very important: Are you using milliseconds everywhere? Just make sure you are. I've changed my code for that, too. Note, I'm off to bed. GLHF :)

Its a little buggy, as in some of the entities don't move at all, but you sir deserve a huge damn medal for all this! Thanks!

Could you take a quick look at my final code I put in the question please? Just to make sure I did everything right :P


text:
Moving the jBullet collision body to with the player object
I am trying to update the location of the rigid body for a player class, as my player moves around I would like the collision body to also move with the player object (currently represented as a cube).  Below is my current update method for when I want to update the xyz coords, but I am pretty sure I am not able to update the origin coords? :
    public void Update(float pX, float pY, float pZ) {
    posX = pX;
    posY = pY;
    posZ = pZ;

    //update the playerCube transform for the rigid body
    cubeTransform.origin.x = posX;
    cubeTransform.origin.y = posY;
    cubeTransform.origin.z = posZ;

    cubeRigidBody.getMotionState().setWorldTransform(cubeTransform);

    processTransformMatrix(cubeTransform);
    }

I do not have rotation updated, as I do not actually want/need the player body to rotate at all currently.  However, in the final game this will be put in place.

You need to make the physics object a kinematic object. See Bullet Physics Manual for more information. Bullet Physics ask every frame the current transformation from kinematic objects. You need your own MotionState implementation for that. Mine is as simple as this:
public class KinematicMotionState extends MotionState {
    private Transform worldTransform;

    public KinematicMotionState() {
        worldTransform = new Transform();
        worldTransform.setIdentity();
    }

    @Override
    public Transform getWorldTransform(Transform out) {
        out.set(worldTransform);
        return out;
    }

    @Override
    public void setWorldTransform(Transform worldTrans) {
        worldTransform.set(worldTrans);
    }
}

In addition you must tell the rigid body that it's a kinematic object:
rigidBody.setCollisionFlags(rigidBody.getCollisionFlags() | CollisionFlags.KINEMATIC_OBJECT);
rigidBody.setActivationState(CollisionObject.DISABLE_DEACTIVATION);

And then updating the transformation of the kinematic object:
Transform transform = new Transform();
transform.setIdentity();
transform.origin.set(x, y, z);
motionState.setWorldTransform(transform);

That is so simple!  I had looked through the Bullet Physics manual a bit before posting, but I guess I just didn't know what I was looking for!  This was super helpful thank you again msell!

Isn't this just setting the position? What happens when something collides?

source: Stack Exchange

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

sort: votes


text:
Java game object pool management
Currently I am using arrays to handle all of my game objects in the game I am making, and I know how terrible this is for performance.  My question is what is the best way to handle game objects and not hurt performance?
Here is how I am creating an array and then looping through it to update the objects in the array:
public static ArrayList<VboCube> game_objects =  new ArrayList<VboCube>();
/* add objects to the game */

while (!Display.isCloseRequested() && !Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {
        for (int i = 0; i < game_objects.size(); i++){
            // draw the object
            game_objects.get(i).Draw();
            game_objects.get(i).Update();
            //world.updatePhysics();
        }
}

I am not looking for someone to write me code for asset or object management, just point me into a better direction to get better performance. I appreciate the help you guys have provided me in the past, and I dont think I would be as far along with my project without the support on stack exchange!

In which part of your code do you have perfomance problems? Did you profile?

Are you sure your performance problems come from the way you store entities? You may want to look at the way the Artemis framework store entities. It uses what they call a Bag. From the doc: Collection type a bit like ArrayList but does not preserve the order of its entities, speedwise it is very good, especially suited for games. Maybe you should check it out :)

I will take a look at this Nathan, thank you for the recommendation.

As far as storing and retrieving game objects is concerned, you could use a native array but an ArrayList is already nearly as fast as it gets.
Now I'm making a guess, not knowing what your list of game objects contains nor how the objects are drawn and updated, but I'd venture that maybe you do not need to update and draw all objects on every frame. That or the draw or update code itself is inefficient.
HTH

All the update code does is update the location of the object, with that of the jBullet collision object.  The update code is so basic that it would not be the cause I dont think.  If an ArrayList is the best method I guess I need to look at other places I can improve on code wise.

In this regard, I strongly support Maik's suggestion that you use a profiler. It's the best way to avoid optimizing parts of your code that are already fast enough.

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


text:
Portal View/Projection Matrix near plane
For RenderToTexture/Camera based portal rendering, the basics seems simple enough.
However, with a free camera, most of the time it is going to be looking at such portals at an angle:

Now a regular near clipping plane will not always work here, it will either intersect with the wall the portal is sitting on, or possibly with objects in front of the wall.
The desired near clipping plane would be aligned like the portal, producing a view volume more like this:

or this in 3D:

So here is my question:
How does one construct or "truncate" a view/projection matrix to achieve such an off-camera-normal (near) clipping plane?

Would it work to simply contain the room in a bounding box and cull everything not in the box rather than mess with an angled near plane?

I don't think so, as the problem is with the near plane intersecting the wall of the room or objects inside it.

I don't understand that statement. None of your diagrams show the near plane intersecting a wall.

You want to use the following technique to modify the projection matrix. It moves the near plane to a given location (like the plane of the portal).
http://www.terathon.com/lengyel/Lengyel-Oblique.pdf

Can you please outline the most central parts directly in your answer, as link-only answers are not optimal. Thank you.

I have not implemented this myself, but I would imagine using the the stencil buffer would solve your problem. Render the portal to the stencil buffer and then render the objects in the portal's frustum. You will then get pixel-perfect culling of the object.
Here's a website with some details:
http://th0mas.nl/2013/05/rendering-recursive-portals-with-opengl/

Adapted from this page, which was linked in Eric Lengyel's paper. Given a view matrix, projection matrix, and a point and a normal for the desired plane, it produces the right projection matrix.
rplane plane;

D3DXPlaneFromPointNormal(&plane, &p, &normal);

D3DXMATRIX matClipProj, WorldToProjection;

WorldToProjection = matView * matProjection;

D3DXMatrixInverse(&WorldToProjection, NULL, &WorldToProjection);
D3DXMatrixTranspose(&WorldToProjection, &WorldToProjection);

D3DXVECTOR4 clipPlane(plane.a, plane.b, plane.c, plane.d);
D3DXVECTOR4 projClipPlane;

// transform clip plane into projection space
D3DXVec4Transform(&projClipPlane, &clipPlane, &WorldToProjection);
D3DXMatrixIdentity(&matClipProj);

if (projClipPlane.w == 0)  // or less than a really small value
{
    // plane is perpendicular to the near plane
    return;
}

if (projClipPlane.w > 0)
{
    // flip plane to point away from eye
    D3DXVECTOR4 clipPlane(-plane.a, -plane.b, -plane.c, -plane.d);

    // transform clip plane into projection space
    D3DXVec4Transform(&projClipPlane, &clipPlane, &WorldToProjection);

}

// put projection space clip plane in Z column
matClipProj(0, 2) = projClipPlane.x;
matClipProj(1, 2) = projClipPlane.y;
matClipProj(2, 2) = projClipPlane.z;
matClipProj(3, 2) = projClipPlane.w;

// multiply into projection matrix
D3DXMATRIX projClipMatrix = matProjection * matClipProj;

matProjection = projClipMatrix;


text:
Custom inventory items based on inheritance
So, here's the scenario:
I'm building an RPG. Like most of the other RPGs on the market, my game will feature an inventory and of course, inventory items. So far I've worked well with using a single class for all items, because I did not need anything else than character stat alteration on item usage (consumption). However, I'd like some items to have a more exotic effect. Think of something like when the user consumes a transformation potion, he automatically turns into a beast.
In order to achieve this I've thought about declaring a new class that inherits from BaseItem for each item. Each descendant would override some methods (like void OnConsume()), to change the base behavior.
This works fine, but when it comes to inventory management, I have some issues. The actual inventory will have to work with BaseItem components only (for obvious reasons, as it's an enumerable collection of objects of the same type); casting any descendant to the base class is possible, so no problems in adding items to the inventory. But how can I keep track of the descendant's type (class) for each item in the inventory? And how to perform the descendant's OnConsume from withint he inventory, for each item?
Let me know if you can think of a better solution than mine, or if you can think of a solution to my problem only.
Development is done in C#, inside Unity 3.5.
Thanks!

Gotta edit: apparently, casting back to the descendant isn't actually possible. So the problem is a bit more complicated.

Well inheritance should take care of basically all your problems. The game will be sure to call the proper "OnConsume" method of the child class so you don't really need to worry about it. If you want to cast the object to a subclass use something like "BeastPotion potion = item as BeastPotion; if (potion != null) { ... }"

Funny thing though: I have decided to not use inheritance at all. It's possible that I might have gotten around 900 custom classes in the end. I'm now using only the BaseItem class, paired with delegates to custom methods for item behavior. So basically, each item is a BaseItem instance, with an OnPickup/OnConsume field that uses the appropriate delegate to link the item to its custom behavior.

So it goes like this: BaseItem it = new BaseItem() ... it.OnConsume = TheAppropriateMethodForThisItem; I'm quite happy with the result, and it's a lot cleaner, in my opinion, than my first idea w/ inheritance usage.

ah, honestly I can't say I would recommend that, but it's not wrong. I personally just find things easier to use inheritance in the event I need to backtrack for mistakes (since I can just open the class with the item name rather than look for where I stored all my delegate methods.) Either way works and so long as you are consistent and have a way to easily find the code you need to work on. I just like subclassing because it extracts the shared code (like removing the item after it is used) and you only have write code for the effects.

It's fine so far, regarding usability; items use 3 callbacks only, for three events: on pickup, on consume and on drop. All methods are organized, so that I may get to the right one by searching the file for the item's ID.

To check whether an object is an instance of a class in C#, use the is keyword:
var item = inventory.getItem( ... );

if ( item is SpecialItem ) {
    var specialItem = (SpecialItem) item;
    // do something special...
}

or just cast it with as and see if it succeeds:
var specialItem = item as SpecialItem;
if ( specialItem != null ) {
    // do something special...
}

See also: How to: Safely Cast by Using as and is Operators (C# Programming Guide)

Edit: To keep track of your items, you should organize them into a reasonable class hierarchy instead of having all of them inherit directly from BaseItem.  So, for example, a helmet might be an instance of class Helmet, which extends Headgear, which extends Armor, which extends Wearable (armor, jewelry, etc.) which extends BaseItem.  (Of course, you don't have to do it exactly like this.  For example, if you have no use for a separate class for headgear, you can just have Helmet inherit directly from Armor.)
You'll probably also want to use interfaces to describe different aspects an item might have.  For example, imagine that you want to have a magic helmet.  Obviously, you could have a parent class MagicItem for all magic items, but C# won't let you inherit from both Helmet and MagicItem at the same time.  Instead, you can define an interface IMagicItem that any item class can implement to indicate that it's magic (and provide methods to invoke its magic effects), and declare your magic helmet class like this:
public class MagicHelmet: Helmet, IMagicItem {
    // Implement the IMagicItem interface here, and optionally override some
    // methods from Helmet.
}

You could also, for example, define an IWearable interface in addition to (or instead of) the Wearable class, so that when you decide to, say, implement a flower that can be worn on the head (or maybe a tame parrot that can be worn on the shoulder), you can do that even though neither Flower nor Parrot are subclasses of Wearable.
(Ps. I had to go AFK for a while as I was writing this edit, and I see from the comments that you managed to solve your real problem in the meanwhile.  I'll post this anyway, since it might still be helpful.)

Thanks! I had no idea about the "as" and "is" operators. This simplifies the problem by a lot! How would you suggest to keep track of the derived class of each item in the inventory? Suppose you have a simple list like List. Each entry in the list can be any of... 10 derived classes, cast back to BaseItem.

Further details: since there will be more than 100 items, there will be more than 100 separate classes (descendants of BaseItem). Trying to see if a BaseItem is actually one of the descendants by going through each one of the descendants and using "is" or "as" would be horribly slow.

Sorry for sounding so dumb :) I have refreshed my knowledge of inheritance. Apparently, overriding a virtual method in a descendant, casting back to the base class, and calling the virtual method again actually calls the descendant's overridden method. So basically any BaseItem.OnConsume() will actually call the descendant's OnConsume(). Problem solved, and I'll accept your answer as correct. Thanks!


text:
Fighting Game and input buffering
In fighting game, there is an important thing called input buffering. When your character is doing an action, you can input the next action that will activate as soon as possible (the buffer is 5-10 frames).
Has anyone already implemented, or knows the most efficient way to do this?
I thought of things like this:
Enum list moves (a list of all my moves)
if (moves = fireball)
{
    if (Mycharacterisidle)
    {
         Do the fireball
    }
    else if (MycharacterisMoving)
    {
         if (lastspriteisnotfinished)
         {
             InputBuffer++;
         }
         else if(spriteisfinished && InputBuffer < 5)
         {
             Do the fireball
         }
    }
}

Any better ideas?
Thx.

How about you use a Queue<T>?
There are 4 significant members of Queue<T> you can use:

Queue.Enqueue(T item) - put your item at the end of the queue.
T Queue.Peek() - look at the first item without removing it.
T Queue.Dequeue() - get and remove the first item.
Queue.Count - check how many items are in queue.

Sample usage
Here's what could be a class representing moves:
public enum MoveType
{
    Fireball, Jump, Block
}

public class Move
{
    public MoveType MoveType { get; private set; }
    public double Duration { get; private set; }
    //...

    public Move(MoveType moveType)
    {
        this.MoveType = moveType;
        switch (moveType)
        {
            case MoveType.Fireball:
                this.Duration = 1.0;
                break;
            case MoveType.Block:
                this.Duration = 0.5;
                break;
            case MoveType.Jump:
                this.Duration = 0.8;
                break;
        }
    }
}

Your update checks to see if moves are elapsed:
Queue<Move> _moveQueue = new Queue<Move>();
double _elapsedMoveTime = 0;

public override void Update(GameTime gameTime)
{
    if (_moveQueue.Count > 0)
    {
        _elapsedMoveTime += gameTime.ElapsedGameTime.TotalSeconds;
        Move current = _moveQueue.Peek();
        if (_elapsedMoveTime > current.Duration)
        {
            _elapsedMoveTime -= current.Duration;
            _moveQueue.Dequeue();
        }
    }
    else
    {
        _elapsedMoveTime = 0;
    }
}

To add a move to the queue, simply call
_moveQueue.Enqueue(new Move(MoveType.Fireball));

To get the current move, simply
Move currentMove = _moveQueue.Peek();
if(currentMove.MoveType == MoveType.Fireball)
   //...

Also - don't count the duration in frames, count it in seconds (or milliseconds if you must).

I'll try to use the queue system

I know this is old but, what is the issue with using frames? Is that not how it is typically done in fighting games? Not a lot of docs on this but, from what I've seen elsewhere frames are the norm.

I have a really simple method of detecting special move sequences for my game Fearless Night.
It just stores the last 60 frames of input, but you can make it any length.  I implemented a simple method for checking if a sequence has been executed.  It's written in Lua, but I'll do my best to write it in C# for you.
We use integer values to represent directions based on a keyboard's number pad, but you can use anything that's comparable as a replacement for the input state.  I simplified some things here, such as not accounting for a character's direction flipping when crossing over an opponent.  Normally this would flip the forward and back directions for a special move input.
The algorithm simply checks each input state from the CurrentTick offset inside the input buffer back until maxDuration.  This assumes that the buffer array is circular.
public class Input {
    int bufferSize = 60;
    int[] buffer = new int[60];

    // Offset for the current input in the buffer.
    int CurrentTick = 0;
    ...
    // maxDuration must be <= bufferSize
    public bool CheckSequence(int[] sequence, int maxDuration) {
        int w = sequence.Length-1;

        for(int i=0; i<maxDuration; ++i) {
            int direction = buffer[(CurrentTick-i+bufferSize) % bufferSize];

            if(direction == sequence[w])
                --w;
            if(w == -1)
                return true;
        }

        return false;
    }
}

You can use it like such
// Somewhere at the start of the "match"
Input input;
...
// 2=down, 3 = down-forward, 6=forward
int[] qcf = new array[] {2, 3, 6};

// Where you check for move transitions
if(input.CheckSequence(qcf, 16)) {
    ExecuteMove("Fireball");
}


text:
Gigantic 2d maps?
I've been thinking about a game idea for a week or two and the last few hours I was thinking of some technical stuff and came up with that the map would need to be 360,000x360,000 pixels in size. To me it sounds insane, but I've never done much in depth game development so I'm not sure if its reasonable or not to have a map that large.
Basicly my question is, would it work to have a map that large in a 2D game?

Have you considered using tiles?

You definitely need to split your map in to sections/segments/areas that are loaded on the fly the moment there is a proximity between the character and the area.

A 360,000x360,000 image has the same number of pixels in it no matter how it's split up.  Yes, you can save on RAM usage at runtime by splitting it and paging it in on demand, but that doesn't really solve the chief data storage problem; how big it is on disk and during distribution.

@TrevorPowell Well he isn't entirely clear on whether he is talking about map dimensions or a solid image. Next to that I made a comment, I didn't give it up as a solution/answer. I had the idea he was talking about the map boundaries, not so much 1 to 1 pixel data. I can't deduce from his question that he is talking about an image of that size.

Technically it's feasible, but does it make for good game play? What sort of game did you have in mind? Something that big will have to be filled with procedurally generated content.

First about the technical aspects:
The vast majority of 2d game engines are tile-based. That means that the game world is built from a pool of small sub-images of a fixed size. Here is an example. Note that many of the 32x32 tiles in this image are identical to others:

(Image source: http://www.codeproject.com/Articles/106884/Implementing-Auto-tiling-Functionality-in-a-Tile-M)
When your tilesize is 36x36, you could represent your game world with ((360,000 / 36) * (360,000 / 36)) 100 million tiles. The only data you need per tile is the id number of the tile image which is used for it. So when you have between 256 and 65536 different tiles, you will need two bytes per tile, so your world data is less than 200MB. When you have about 1000 different tiles, and each tile is 36 x 36 x 4 bytes, you have about 5 MB of graphic data.
Considering that modern PCs have gigabytes of RAM (assuming that's your target platform), you don't even have a reason yet to not load the whole map into RAM... yet. A good reason to do that will very likely come up in a later development stage.
Now about the gameplay aspects
Assuming that you have a 2d engine with a fixed zoom factor, it's usually not a good idea to have such large maps in a 2d game.
When you have a 3d game, the strong point of a large game world is the ability to present great vistas to the player. Send him to a peak of a mountain, and have him stare at the huge stretches of land beneath him. Then make him realize that everything he sees is playable content, and it blows his mind.
Being able to see into the distance is also a great navigation help. When you see a tower a mile away, you know you just have to keep moving in that direction, and eventually you will reach it.
But that doesn't work in a 2d engine. The player only sees a small window of the game world which is at most 1920x1080 pixels in size on a consumer-grade monitor. He can't make out any landmarks in the distance. That makes large 2d maps a lot harder to navigate. For that reason, large open spaces should be avoided in 2d maps. Every possible map location should have a well-defined set of paths the player can follow and must be recognizable and unique, otherwise it gets too easy for the player to get lost.
As a result from this, the map design in a 2d game must be pretty compact and made with a lot of care about detail. The larger the map, the harder it gets to keep up the quality.

Supreme Commander had a huge 2D map and it worked fine--you could simply zoom in and out.  (System performance was another matter, though...)

I've never played Supreme Commander, but all the screenshots I find on Google Images look very 3d to me. Are you sure you mean that game?

"at most 1920x1080 pixels in size" ... any 24" display made in the last 5+ years running at 1920x1200 begs to differ, not to mention the current generation 27" displays running at 2560x1440. Your point still stands though!

Terraria is a 2D game with a REALLY REALLY huge map and it is pretty good, so huge 2D maps can be made. Doesn't mean it's easy, though (-8

@ccxvii: I added the phrase "on a consumer-grade monitor", because very few average users have screens larger than 1920x1080.

@Philipp:  Are you thinking of Supreme Commander 2?  That is 3D--and has MUCH smaller maps also.

@Loren Pechtel: Maybe you are thinking of Total Annihilation, the inofficial precedessor?

360,000 * 360,000 == 129,600,000,000 pixels in total.
Let's be generous, and assume that you're only using a 16-color palette, so each pixel can specify its color using only four bits.
129,600,000,000 pixels * 4 bits per pixel == 518,400,000,000 bits.  Divide by 8 bits per byte gives us 64,800,000,000 bytes.  Divide by 1024 bytes per kilobyte (or kibibyte, if you go in for that sort of naming), and then by 1024 kilobytes per megabyte (mebibyte), and you get approximately 61,798 megabytes.  Let's round that off and call it an even 60 gigabytes (gibibytes).
Of course, if you want a 256-color palette (eight bits per pixel), then you'd need double that amount of space to store it.  And if you want a modern "full-color" palette, then you need at least 24 bits per pixel, so that's about 360 gigabytes.  Just for your map image.
Of course, if you have ways to compress your image (say, if you have large regions of a single color so you can run-length encode it, for example, or if you're happy to work with lossy compression), then you could bring that down a good deal.  But if you're starting from 360 gigabytes of data, I doubt that this sort of compression is going to bring it down to a size which many people would be eager to download.
Most 2D games work by defining larger "tile" images, and placing those tiles together to form a map, rather than using a single large image.

It would work but much better is to create a data structure that holds coordinates of all needed tiles on your screen as a branches of binary or r\b tree, for example.
So you need a structure that holds the indexes of those tiles and their positions on the screen, when you'll call a render function of your game, you'll read data from that structure and form a raster image using tiles and that data.  (So you will know where to place your tiles).
For a ready-made containers, that can hold map data, you can look at the different realizations of Map containers, like ones in the STL library for C++ or java.util.Collections if in Java, and other languages as well.


text:
Difficulties with rotation of a sprite

Possible Duplicate:
How do I make a jumping dolphin rotate realistically?

I want to program a dolphin that jumps and rotates like a real dolphin. Jumping is not the problem, but I don't know how to make the rotation. My dolphin always rests in the same angle while it jumps. But I want that it changes the rotation during the jump, like a real dolphin does.
How can I improve the rotation?
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    Texture2D image, water;
    float Gravity = 5.0F;
    float Acceleration = 20.0F;
    Vector2 Position = new Vector2(1200,720);
    Vector2 Velocity;
    float rotation = 0;
    SpriteEffects flip;
    Vector2 Speed = new Vector2(0, 0);

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        graphics.PreferredBackBufferWidth = 1280;
        graphics.PreferredBackBufferHeight = 720;
    }

    protected override void Initialize()
    {
        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        image = Content.Load<Texture2D>("cartoondolphin");
        water = Content.Load<Texture2D>("background");
        flip = SpriteEffects.None;
    }

    protected override void Update(GameTime gameTime)
    {
        float VelocityX = 0f;
        float VelocityY = 0f;

        float time = (float)gameTime.ElapsedGameTime.TotalSeconds;
        KeyboardState kbState = Keyboard.GetState();
        if(kbState.IsKeyDown(Keys.Left))
        {
            rotation = 0;
            flip = SpriteEffects.None;
            VelocityX += -5f;
        }

        if(kbState.IsKeyDown(Keys.Right))
        {
            rotation = 0;
            flip = SpriteEffects.FlipHorizontally;
            VelocityX += 5f;
        }

        // jump if the dolphin is under water
        if(Position.Y >= 670)
        {
            if (kbState.IsKeyDown(Keys.A))
            {
                if (flip == SpriteEffects.None)
                {
                  rotation = 45;
                  VelocityY += 40f;
                }
                else
                {
                  rotation = -45;
                  VelocityY += 40f;
                }
            }
        }
        else
        {
            VelocityY += -10f;
        }

        float deltaY = 0;
        float deltaX = 0;

        deltaY = Gravity * (float)gameTime.ElapsedGameTime.TotalSeconds;

        deltaX += VelocityX * (float)gameTime.ElapsedGameTime.TotalSeconds * Acceleration;
        deltaY += -VelocityY * (float)gameTime.ElapsedGameTime.TotalSeconds * Acceleration;

        Speed = new Vector2(Speed.X + deltaX, Speed.Y + deltaY);

        Position += Speed * (float)gameTime.ElapsedGameTime.TotalSeconds;

        Velocity.X = 0;

        if (Position.Y + image.Height/2 > graphics.PreferredBackBufferHeight)
            Position.Y = graphics.PreferredBackBufferHeight - image.Height/2;

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();
        spriteBatch.Draw(water, new Rectangle(0, graphics.PreferredBackBufferHeight -100, graphics.PreferredBackBufferWidth, 100), Color.White);
        spriteBatch.Draw(image, Position, null, Color.White, MathHelper.ToRadians(rotation), new Vector2(image.Width / 2, image.Height / 2), 1, flip, 1);
        spriteBatch.End();

        base.Draw(gameTime);
    }
}

Increase the rotation, don't set it.
rotation += 0.01f
Although as someone already mentioned, not the best place for this question.


text:
Scale a normalized 2D vector always to the same length
For any normalized 2D vector, except for ( 0, 0 ), how would I scale the vector to always be the same length?
For example:
int length = 10;

vector v = vector( 0.1, 0.5 );
vector v2 = vector( 0.3, 0.8 );

// Scale v to be length of 10
// Scale v2 to be length of 10

Homework question?

You seem to use the term normalized incorrectly. A normalized vector has unit length (1.0), while the ones you have in your example are definitely not of unit length.

Scaling a vector means multiplying it by a constant.

@JariKomppa Why homework? This is one of primary tasks you bump into when making 2D games. But I, as the OP, I'm here to do games, not math.

You mean like this?
length = sqrt(v.x * v.x + v.y * v.y);

// normalize vector
v.x /= length;
v.y /= length;

// increase vector size
v.x *= 10
v.y *= 10

Not really, please have a look at my edit.

@MichielPater is it ok?

@user23837 Yes that is what you want. That's the way to normalize a vector. You do it for all vectors in question and then multiply by a new length/magnitude

A normalized vector, by definition, has length 1.  To scale it to length 10, you need to multiply it by 10.
(To multiply a vector by a number, multiply every component of the vector by the number.  Depending on the language you use, just writing vector = vector * number may do that automatically, or there may at least be a library function or method to do that.)
By the way, the vectors in your example code are not normalized — their length is not 1.  To normalize them, do as Gajoo suggests, i.e. divide them by their length.  Again, your language or vector library may already provide a function to do that.

Normalised vectors have the same length by definition: one. If you want to scale them to an arbitrary length L instead, multiply them (or their components) by L. Note that the examples you have provided are not normalised vectors. To normalise, divide the vectors by their magnitude.
For example (component-wise, as I do not know the extent of vector algebra support in your environment):
int targetlength = 10;
vector v = vector( 0.1, 0.5 );
float vMagnitude = sqrt(v.x*v.x + v.y*v.y);
v.x = targetlength * v.x / vMagnitude;
v.y = targetlength * v.y / vMagnitude;

// v = ( 1.96, 9.81 )

Or with vector algebra:
int targetlength = 10;
vector v = vector( 0.1, 0.5 );
v = targetlength * v / v.length;


text:
OpenGL glMatrixMode rotation
I'm stuck on trying to figure out how to rotate the viewport(or camera). So far I've figured out I need to use the function glRotatef and glMatrixMode(GL_MODELVIEW). But I have no idea how to apply the rotations to the model view. I'm sorry I have no code to show because I have no idea how to get started. Any help would be greatly appreciated!

Instead of rotating the camera, you can rotate an object as well.
But for the reference, you can check out this project made by me.
Hope this will clear most of yor queries.
http://code.google.com/p/3dtouchmovingcube/

You should just read any tutorial.

What are you talking about. Most tutorials I find don't cover camera work...

glRotatef should apply to whatever matrix is currently selected by glMatrixMode. Just execute it after glMatrixMode.
It's worth nothing that glMatrixMode is a deprecated command. The new way of doing things involves using shaders, binding a matrix to them and multiplying them together with the vertex coordinates.


text:
OpenGL first person camera orientation issues
I have a "camera" in my opengl program that I recently finished. However, I've noticed that whenever I rotate and then move again, the x, y, and z angles change. For example, when I press the "w" key, I move forward along the "z" axis. If I then rotate the camera 90 degrees, when I push the "W" key, I will actually be moving right, seemingly along the "x" axis. It makes sense why this happens, I'm just wondering why its happening. Here's the rotation function:
private void camera() {
    glRotatef(xrot, 1.0f, 0.0f, 0.0f);
    glRotatef(yrot, 0.0f, 1.0f, 0.0f);
}

The keyboard function:
if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
        xpos -= 0.035 * delta;
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
        xpos += 0.035 * delta;
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_W)) {
        zpos += 0.03f * delta;
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_S)) {
        zpos -= 0.035 * delta;
    }
if (Keyboard.isKeyDown(Keyboard.KEY_UP)) {
        xrot += 0.035;
        if (xrot > 360) {
            xrot -= 360;
        }
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) {
        xrot -= 0.035;
        if (xrot > 360) {
            xrot += 360;
        }
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) {
        yrot += 0.035;
        if (xrot > 360) {
            xrot -= 360;
        }
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_LEFT)) {
        yrot -= 0.035;
        if (xrot > 360) {
            xrot += 360;
        }

    }

And my translate function:
        glTranslated(xpos, ypos, zpos - 30);

any ideas on how to solve this? I would be very grateful

possible duplicate of Creating an OpenGL FPS camera: I have the position and orientation vectors, now what?

That is possibly the most annoying thing you could say. ITS NOT.

That question includes explicit code examples to do what you want.  The only original bit of your question comes down to debugging your code for you, which is not what GDSE is for.  If I'm wrong, which is quite possible, that's fine as nobody else will give the other 4 required votes to close, and you're good.  No need to snip at me for it. :)

Yeah I'm sorry, I shouldn't have snapped at you!

Note that your code is also full of elementary coding bugs: if (xrot > 360) xrot += 360 doesn't make sense, you want if (xrot < 0) when you're subtracting from xrot. And later on in the left/right case you update yrot then you check xrot for overflow.

What you're not doing is rotating your x- and y-positions based on which direction your player is pointed.
(note that this depends solely on your z-angle, and not on the x and y axes)
You will need to perform your manipulations on a pair of variables that get rotated after all the keys are checked, which also means you'll need to calculate the rotation with good-old sines and cosines.
(note that you'll also need to handle things carefully if you have any slopes whatsoever. Having the player move smoothly up and down them is extremely important for a good user-experience)
The code is relatively simple:
// Process the motion commands as normal

// Now rotate the raw values:
final_dx = raw_dx*cos(rot_z) + raw_dy*sin(rot_z);
final_dy = raw_dx*sin(rot_z) + raw_dy*cos(rot_z);

Note that you may have to change a few signs around (ie, multiply by -1) to make sure that the rotations line things up properly.

Yeah I realized this as soon as I went to bed last night :/ raw_dy is the originaly variable right? Thanks for your help!

What I meant was raw_dy is my xpos variable, which is my position varibale.

And I don't have a rot_z variable variable, only a rot_x and rot_y. Is it ok if my rot_z is just set equal to 0?

Whoops. I forgot, you're probably using Y as your vertical axis, right? Then you'll need to swap the Ys and Zs in the code I gave.

Thanks! I actually figured it out using a different method, but your way is by far the most simple and easiest way to do it, thank you!


text:
What is the issue with my model rendering from .obj files?
Well I can clearly tell that what rendered is close to what I wanted, but there seems to be a few problems.
The .obj files contained values like "f", "v", "vt".
Image Of Problem:

As you can see it renders very close to what it's suppose to be, but there's a few problems. I can provide more examples/code if needed. The top two are what I'm rendering, the bottom two are while it's loaded in Blender.
Example below of each:
v 0.025487 1.194620 0.121091
v -0.025487 1.194620 0.121091
v 0.025487 1.143731 0.118145
v -0.025487 1.143731 0.118145

vt 0.032776 0.559649
vt 0.041251 0.559656
vt 0.041210 0.563958
vt 0.035813 0.563927

f 47/1 46/2 35/3 36/4
f 51/5 50/6 39/7 40/8
f 51/5 40/8 44/9 55/10
f 45/11 33/12 41/13 53/14

Going by simple things in Math Vertex,Edge,Face The "v" must be corners and "f" must be the quads or the jointed triangular faces. So then each of the "f"'s must build 6 indices?
So what I did was
Firstly I wrote the size of the vertices and quads.
content.writeInt(vertexs.size());
content.writeInt(quads.size());

I wrote to a separate file all the "v" values.
for (Vector3f vector : vertexs)
    content.writeVector(vector);

So they are in order that they were loaded out of the .obj file.
Then I figured every line for the faces would be 6 indexes. So from what I found in some tutorials you're suppose to do it clockwise so for a 1 side of a quad 1,2,3 then 2,4,3. So What I did was load the first part of each "f" so let's say we had "f 11/5 12/6 13/7 14/8" I'd store the values 11,12,13, and 14. Then I'll write them out like the following:
11,12,13,
12,14,13
So basically what I have below.
for (Quad qv : quads)
{
    content.writeShort(qv.indices[0] - 1);
    content.writeShort(qv.indices[1] - 1);
    content.writeShort(qv.indices[2] - 1);
    content.writeShort(qv.indices[1] - 1);
    content.writeShort(qv.indices[3] - 1);
    content.writeShort(qv.indices[2] - 1);
}

So now I can load these into DirectX like this:
LOAD MODEL METHOD
CacheReader::open("model.dat"); //For now it just files no indexing yet.
CacheReader *reader = CacheReader::readFully();

vert_size = reader->readUnsignedInt();

int faces = reader->readUnsignedInt();

int index_capacity = faces * 6;
index_size = faces * 2;

CUSTOMVERTEX *verts = new CUSTOMVERTEX[vert_size];
short *indices = new short[index_capacity];

for (int i = 0; i < vert_size; ++i)
{
    verts[i].X = reader->readFloat();
    verts[i].Y = reader->readFloat();
    verts[i].Z = reader->readFloat();
    verts[i].COLOR = D3DCOLOR_XRGB(255, 255, 255);
}

int n = 0;

for (int i = 0; i < faces; ++i)
{
    indices[n++] = reader->readUnsignedShort();
    indices[n++] = reader->readUnsignedShort();
    indices[n++] = reader->readUnsignedShort();
    indices[n++] = reader->readUnsignedShort();
    indices[n++] = reader->readUnsignedShort();
    indices[n++] = reader->readUnsignedShort();
}

VOID* pVoid;

d3ddev->CreateVertexBuffer(vert_size * sizeof(CUSTOMVERTEX),
    0, CUSTOMFVF, D3DPOOL_MANAGED, &v_buffer, NULL);
v_buffer->Lock(0, 0, (void**)&pVoid, 0);
memcpy(pVoid, verts, vert_size * sizeof(CUSTOMVERTEX));
v_buffer->Unlock();

d3ddev->CreateIndexBuffer(index_capacity * sizeof(short), 0,
    D3DFMT_INDEX16, D3DPOOL_MANAGED, &i_buffer, NULL);
i_buffer->Lock(0, 0, (void**)&pVoid, 0);
memcpy(pVoid, indices, index_capacity * sizeof(short));
i_buffer->Unlock();

D3DXMATRIX matView;
D3DXMatrixLookAtLH(&matView, &D3DXVECTOR3 (0.0f, 0.0f, -5.0f),
    &D3DXVECTOR3 (0.0f, 0.0f, 0.0f), &D3DXVECTOR3 (0.0f, 1.0f, 0.0f));
d3ddev->SetTransform(D3DTS_VIEW, &matView);

D3DXMATRIX matProjection;
D3DXMatrixPerspectiveFovLH(&matProjection, D3DXToRadian(45),
    (FLOAT)SCREEN_WIDTH / (FLOAT)SCREEN_HEIGHT, 1.0f, 100.0f);
d3ddev->SetTransform(D3DTS_PROJECTION, &matProjection);

RENDER METHOD:
d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);
d3ddev->Clear(0, NULL, D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);

d3ddev->BeginScene();
d3ddev->SetFVF(CUSTOMFVF);

D3DXMATRIX matRotateY;
static float index = 0.0f; index+=0.05f;
D3DXMatrixRotationY(&matRotateY, index);
d3ddev->SetTransform(D3DTS_WORLD, &matRotateY);

d3ddev->SetStreamSource(0, v_buffer, 0, sizeof(CUSTOMVERTEX));
d3ddev->SetIndices(i_buffer);
d3ddev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, vert_size, 0, index_size);

d3ddev->EndScene();
d3ddev->Present(NULL, NULL, NULL, NULL);

INITALIZE METHOD
d3d = Direct3DCreate9(D3D_SDK_VERSION);

D3DPRESENT_PARAMETERS d3dpp;

ZeroMemory(&d3dpp, sizeof(d3dpp));
d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.hDeviceWindow = hWnd;
d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
d3dpp.BackBufferWidth = SCREEN_WIDTH;
d3dpp.BackBufferHeight = SCREEN_HEIGHT;

d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
    D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &d3ddev);

d3ddev->SetRenderState(D3DRS_ZENABLE, TRUE);
d3ddev->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
d3ddev->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
d3ddev->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
d3ddev->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
d3ddev->SetRenderState(D3DRS_CULLMODE, D3DCULL_CW);
d3ddev->SetRenderState(D3DRS_LIGHTING, FALSE);

load_model();

Here's what the first quad shows in the .obj file.
These are the vertex's
47:  v 0.104867 0.547076 -0.142017
46:  v 0.113943 0.548103 -0.144205
35:  v 0.113968 0.543585 -0.146221
36:  v 0.108210 0.542732 -0.144383

This is the first face.
f 47/1 46/2 35/3 36/4

Yeah, the problem this whole time was that my method of storing floats in order to speed up load time had a few minor errors with some values. Thus only a couple floats or coordinates were screwed up. I've converted it to read as ASCII code, but this is horribly slow and I'll be trying to figure out a better alternative that's still fully portable.
Thank's for all the help guys. Sorry that the issue was something so simplistic when it felt like something much more. Seem's I've spent 3 days trying to figure out an error that was merely my own fault for trying to optimize the floats, but my tests showed it worked, which led me to think it was a good system.
I'll have to start verifying every class is working from the easiest to the hardest. So I don't run into a really easy glitch again.

Why don't you read/write floats directly from the file? Something like this

Or better still this. I haven't tested those, but they shouldn't be too difficult to get working.

I don't think that's completely portable? I'd like it so I can have other computers use this. Worst case I can make separate downloads, but I'd rather not have to. Thank's for the suggestion I'll look more into it.

The issue is that indices in a .obj file start at 1, while when rendering, they start at 0. Pretty much everyone who writes a .obj parser will run into this issue at some point.
The solution is to subtract each index by 1 when loading it:
for (Quad qv : quads)
{
    content.writeShort(qv.indices[0] - 1);
    content.writeShort(qv.indices[1] - 1);
    content.writeShort(qv.indices[2] - 1);
    content.writeShort(qv.indices[1] - 1);
    content.writeShort(qv.indices[3] - 1);
    content.writeShort(qv.indices[2] - 1);
}

Additionally, the other answer is correct about index ordering, and you're going to run into another issue when you want to apply a texture. The order of the vertices (v) and vertex texture coordinates (vt) don't match up, which is why f defines two indices for every vertex. What you want to do is create a new vertex buffer and copy the vertices into it as the indices specify.
This is necessary because the .obj format does not guarantee unique sets of vertex data, so you'll run into issues if you try and sort the texture coordinates alone, because they are sometimes used with more than one vertex.
Link to obj specification

Actually I was editing the way I loaded them and forgot to add the -1 part again, but it still does the same thing as in the picture those were taken prior the the modifications. I've been trying different values for the 0,1,2,1,3,2, but it doesn't seem to get rid of those extra chunks. Thanks for the comment though.
I'm wondering if it's just the way I'm rendering them through DirectX because it seems like it's pretty much loaded just fine, but there's like an extra bulk of triangles around it.

If you're using counter-clockwise winding, try 0, 1, 2, 0, 2, 3. Otherwise, try 0, 2, 1, 0, 3, 2.

I'm thinking that stuff is working correctly, but it must be something else that I'm just not seeing. I'm a bit new to models in 3D, but when I tried rendering small objects they didn't seem to have any problems. I noticed I only got these issues when the "f" values had more than 1 type. E.g. if it was only "f 1 2 3 4" that works fine, but when it's "f 1/10 2/11 3/12 4/12" I'm parsing it correctly since I've tested it, but I haven't done anything with the texture or normals yet. I'm wondering if that's the cause? I also provided the first quads information at the end of the original post.

Make sure you aren't accidentally including texture coordinates or vertex normals in your vertex buffer. The model loading code isn't for the .obj format, so I'm assuming you're converting it to your own format first.

Hmm, It seems valid I had it print out everything and front what I was willing to compare it looked okay. There's a few extra thing I noticed.
At the very bottom of the .obj is the following which I ignored.
f 5570 10142
I'm not sure what the 5570 means, but 10142 is the total vertexs.
Then there's a few other things.
usemtl BlackCloth -> So that must be the texture.
Then right before the faces are read in this is there.
usemtl man
and
s 1

The last vertex doesn't necessarily have to be a part of the last face. The obj format doesn't specify totals at any point. You should be counting the number of v lines for the number of vertices. I added a link to the obj specification in my answer, it should clear up all your questions about which keywords mean what.

I think this has something to do with how I stored the vertex and indices, because I just tried a really simple sphere and it's showing a few extra triangles outside the sphere's shape. Which would mean it's using data that I didn't tell it to. So it must be that I'm not rendering it properly. I'll try to find some tutorials for rendering spheres and see if I can merge my data into that and find a possible reason. I'm pretty sure I stored everything correctly though, but that's the only other thing I could think of.Since it seems like it's rendering extra stuff.PIC: i49.tinypic.com/2qbayj8.jpg

Like I said in my last comment, it looks like you might accidentally be reading in texture coordinates as vertices, how do you actually parse the obj file?

Well the sphere has no "vt"'s. Only "v" and "f".
I'll edit the main post at the very bottom with all the files associated with this. One moment.

I don't know if you are triangulating your quads correctly.
for (Quad qv : quads)
{
    content.writeShort(qv.indices[0]);
    content.writeShort(qv.indices[1]);
    content.writeShort(qv.indices[2]);
    content.writeShort(qv.indices[1]);
    content.writeShort(qv.indices[3]);
    content.writeShort(qv.indices[2]);
}

Would make the triangles
-----|
\    |
 \   |
  \  |
   \ |
    \|

and
     /|
    / |
   /  |
  /___|

which dont represent the quad. You can change the second triangle to match the first one,
like so:
for (Quad qv : quads)
{
    content.writeShort(qv.indices[0]);
    content.writeShort(qv.indices[1]);
    content.writeShort(qv.indices[2]);
    content.writeShort(qv.indices[2]);
    content.writeShort(qv.indices[3]);
    content.writeShort(qv.indices[0]);
}

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


text:
At this point in time, avoid XNA?
XNA seemed like a valid option a few years ago, but XNA was never a real success, and now it seems like a footnote, even Microsoft seems to treat it that way.
Should I just go the DirectX route instead?
Ideally, eventually, I'd like my games to be playable on all major platforms (Windows, Linux, Mac + all consoles), but my primary focus is getting the games out the door on Windows XP, 7 and 8.
EDIT: This question and releated might already be answered here: What is the future of XNA in Windows 8 or how will managed games be developed in Windows 8?

did you ever work with UDK or Unity? How are your sure that they are not flexible enough for what your are trying to do? They offer a really big package to realize lots of different ideas on all kinds of platforms. And if the editors really lack something, there are ways around if really needed.

As per the [FAQ], "what technology to use" questions are considered off-topic for this site.

I'm going to focus on this:

Ideally, eventually, I'd like my games to be playable on all major platforms (Windows, Linux, Mac + all consoles), but my primary focus is getting the games out the door on Windows XP, 7 and 8.

Generally OpenGL and DirectX are the two most supported graphics libraries. Of course XNA is built over DirectX, however it was not adopted to the expected extent. Now if you are being smart in your development, you should be able to isolate your graphics handling in such a way that by changing only a select few of your files, you can completely migrate from one graphics library to another.
I can't remember which Sims game it was, (Medieval i think), but the game was developed with DirectX for PC and Xbox, but then they replaced it with OpenGL for the Mac, Linux builds.
I recommend sticking to the more commonly accepted libraries, as to have the largest amount of support. XNA is greatly accepted here at gamedev, however OpenGL and DirectX are both supported as well, both here and at overflow.
I was making the same decision around a year or two ago and concluded I would head into OpenGL (OpenTK for C#) grounds rather than staying with XNA for the following reasons:

OpenGL can be used on all platforms
XNA (in my opinion) was messy, which is one of the reasons i think it hasn't been adopted to a large extent.
A knowledge of OpenGL or DirectX is as good as you get. If you learn them, picking up XNA would be a piece of cake. The same cannot be said the other way round.

My final advice though, is to try it all out for yourself. Check out Reimers tutorials in XNA and DirectX (and just browse google for some OpenGL tuts), and work out which one you think would be better for your interests.

but XNA was never a real success

XNA is an amazing success. If you just look at this site as a measuring ground, you will notice that:

XNA is the top recent tag (it stays up there quite a lot)
XNA questions get quickly answered, often with multiple answers
Difficult XNA problems are addressed

This shows that there are a lot of people interested in, and actively using, XNA. I tried many, many different tools and platforms before eventually coming back to XNA.

I'd like my games to be playable on all major platforms

Me too. Since I love XNA so much, I ditched the Microsoft version, and went with an open-source implementation of XNA, aka MonoGame. Try it, and see for yourself.
And by the way, it supports Android and iOS via MonoTouch and MonoDroid. It also supports Windows (and Windows 8) out of the box.

XNA does not seem to be a success if we're talking general adoption, XNA might be popular among Stack Exchange users, though. But if you look at released games, even among Xbox Live games, very few are XNA developed, this worries me a bit...

@Erik XNA has an amazing community of active developers. Whether they actually finish games or not is not relevant though; they are there. Other game engines and platforms don't have that.

Also, there's actually a decent number (not a majority but sizable)  of XBLA using XNA as well as all WP7 and XBLIG games.

Compare XNA forums to gamedev.net
The only reason you see so many XNA questions here is (no offense) because if people want a fast OpenGL or DirectX answer, they go to StackOverflow.

Unity seems to be a good option to you, even if you are a beginner, since it welcomes new users easier than most engines and frameworks, like XNA.
It has a growing community and fast support. Also have options to export for almost all major platforms (including consoles).

Linux received support since Unity 4.

Unless I've misunderstood something, I'd need to shell out $4500 to  get all features Unity offers, and be able to deploy on Android and iOS? I'm not yet sure what exactly the free version offers, but it seemed to be pretty limited feature wise.

Yes, that is a bit true. Unity is pricey unless you want to stick with the PC. A license for consoles is even more expensive, but it's not shown on the site.

@Erik the free version of Unity may work for you depending on what you're after.

XNA would work wonders for you then, and I imagine XNA will build up again when they release the new Xbox.

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


text:
ScaleX and Y for stretching MovieClip
I'm developing a game, and the game has a shop.  In that shop there is an option for a house expansion.  This is a movieclip that I want the user to be able to spend their coins to increase their house in the following ways:
-> stretch house to right <- stretch house to left ^ stretch house upward v stretch house downward.
The thing is, I've been thinking of using ScaleX and ScaleY to accomplish this.  The only problem:  It stretches the left and right, I can't make it do one.  I'm sure there is a way to do this, but I haven't yet figured it out.  Any ideas?

I figured it out, and I'd like to hear your thoughts on my answer!

Set up the stage:
var num:Number = 10;

Change mc to your MovieClip
For up:
mc.height += num;
mc.y -= num/2;

For down:
mc.height += num;
mc.y += num/2;

For left:
mc.width+=num;
mc.x -= num/2;

For right:
mc.width+=num;
mc.x+=num/2;

At least give "num"  a proper name ;). Also changing scale depends on your center of origin in the coordinate space of your Movieclip. You should check your own answer so that this question isn't listed as not answered.

I have to wait 2 days for that, my friend ;)

Change the registration point of movieclip from "center" to  x=0 and y=0 . Keeping the registration point in the center, causes the movieclip to stretch on both the sides equally.

+1 Thanks, but I figured it out, until I realized this is also a good method, if I were only trying to do one side.


text:
Detecting Light Intensity Around Characters
Later Edit
Since there seemed to be a bit of confusion: I am asking this for purely didactic reasons, I'm not searching for the most efficient solution. Reformulated question: I'm working under Unity, and I'd like to know if it would be possible to somehow query the material + shader of each GameObject that has a Mesh Renderer attached to itself, in order to find out how much light has fallen on the 3D model. I'm not very experienced in computer graphics, so this may seem like a stupid question. I'm thinking of something along the line of pixel by pixel comparison of a texture's brightness at any given point in time.

It depends on how you've implementing lighting in your game. Frequently those calculations are done in the shader, so it'll be difficult to get the result. But it sounds like you're talking like the material somehow does all these calculations without a performance cost. It'll cost just as much to do it outside the context of the model.

Right, so it's the shader that calculates the thing. Good to know! @costs: maybe my question was ambiguous. I was thinking that instead of taking into consideration the distance between each model and the light source + the light's brightness I could somehow do... pixel by pixel comparisons on the  model's texture (to see how bright they are). Not sure how to put it differently.

I'm working under Unity, and I'd like to know if it would be possible to somehow query the material + shader of each GameObject that has a Mesh Renderer attached to itself, in order to find out how much light has fallen on the 3D model.

As per Unity's documentation, Unity does not provide such functionality, so it's not possible to achieve what you want.

Can you provide a link to this documentation? It would probably help later viewers.

A quick and dirty solution might be to get the position and intensity of nearby light sources and calculate intensity/distance for each, taking the greatest value to be the light level (if you're just after relative levels rather than pure accuracy, such as you might want when making a minecraft clone and deciding whether creatures spawn or not depending on darkness).

+1. Trying to read back lighting from the graphics system is likely to be fraught with difficulty. It's almost certainly easier and better to just use the logical position of light sources without considering the rendering side at all.

That's what I said too. I was just asking for didactic reasons, as I was curious if it would be possible to somehow decide how much light falls upon a character based on how bright the rendered materials are.

If you could mark the answer as correct that'd be great (need the points!) thank you very much :)

Well damn, I would, but your answer is basically the same as the 2nd and third paragraphs in my question.

Well there's gratitude. Nice.

You did not answer my question, it's that simple.

let us continue this discussion in chat


text:
D3D/DXGI handle fullscreen transition
I have a D3D11 application, and I want to add proper fullscreen suport.
Now I can let DXGI switch my window to fullscreen for me, and I'm under the impression that DXGI will take care of everything needed to make the swap chain flip front and backbuffer instead of blitting them.
However, letting DXGI perform the swich seems unreliable with a multi monitor setup - secondary screens stay entirely black after the switch a great deal of the time, with no apparent reason or pattern to it.
It can take a few times switching back and forth before I get the fullscreen window and the rest of the desktop being shown on the other screens.
Apparently I'm not alone with this, Battlefield 3 and WoW seem to have similar issues for a lot of people.
Now, the actual question: I guess since even those AAA game dev companies can't get this to work, my biggest hope would be to somehow perform the switch to fullscreen myself.
Is there anything I can do to elevate my window/swapchain into proper, buffer-flipping fullscreen mode?

At the time of this writing, the current version of World of Warcraft no longer has the display mode configuration issues/memory leaks you mentioned. They were certainly problematic but have been fixed as of 7.3.2

To my knowledge, the onlything that works is:
 DwmEnableComposition(DWM_EC_DISABLECOMPOSITION);

at the start of your application and:
DwmEnableComposition(DWM_EC_ENABLECOMPOSITION);

before quitting. For the transitions, proceed as usual. I have tried InvalidateRect(NULL, NULL, true) just after switching to fullscreen to no avail. Hope this helps.

After trying everything, it seems you are correct. Only disabling composition reliably prevents this from happening. Not the answer I had hoped for, but better than nothing I suppose.

Note that Windows 8.1 and later ignores this setting. You can't disable DWM.

You're indeed not the only one facing this issue. First thing to check: make sure you're using the latest/beta/top-notch drivers for the video card you're using.
Now, I'd say that there's only a small chance that you can get this working better than the automatic DXGI implementation. This kind of issue is highly dependent on the adapter vendor, driver version, and monitor configuration. So by fixing it on one machine you may end up breaking it on more.
I advise against returning to the dark ages of DirectX 9 where you had to do everything by hand. A better idea would be to try fixing the automatic switching. Some trails to follow:

Read the (sparse) documentation carefully.
If you're not doing it already, try to respond to the WM_SIZE event that you receive upon switching from/to full-screen, as described here. If you do so, make sure that you are properly releasing all references to the back buffer before calling ResizeBuffers, as described there. Failing to do so might cause this kind of weird semi-issues.
Try to start directly in full-screen, and to create your swap chain with one of the enumerated display modes. If this works all the time, this might mean that you're not using one of the enumerated display mode when handling WM_SIZE (or not entirely, things such as the refresh rate can be important).
Try mucking around with the swap effect and the buffer count of your swap chain description. You should probably be using DXGI_SWAP_EFFECT_SEQUENTIAL and a BufferCount >= 2. Maybe your driver has poor support for more "exotic" options.

Resizing the buffers works fine. I've also tried all the swap effects, they don't seem to make a difference, and I've always used 2 buffers. I would try the fullscreen thing, (even though I don't know what you mean by "using one of the enumerated display modes" - when responding to WM_SIZE all I do is ResizeBuffers, there is nowhere to pass a display mode as an argument) but I spontaneously installed windows 8 and guess what, I can't replicate the problem right now..

Went back to windows7, and tried creating the swapchain in fullscreen from the start, but the issue persists.


text:
Am I implimenting a sweep and prune broadphase correctly?
The code that I am using is:
    std::vector <PhysicsBody*> physicsChildren; //containing all objects

    ...

    std::sort(physicsChildren.begin(), physicsChildren.end(), sortByLeft);
    std::vector <PhysicsBody*> activeList;

    unsigned int one;
    unsigned int two;
    for(one = 0; one < physicsChildren.size(); ++one)
    {
        activeList.push_back(physicsChildren[one]);
        for(two = 0; two < activeList.size(); ++two)
        {
            if (physicsChildren[one]->m_position.x + physicsChildren[one]->m_radius > activeList[two]->m_position.x - activeList[two]->m_radius)
            {
                CheckIntersectionBetween(physicsChildren[one], activeList[two]);
            } else {
                activeList.pop_back();
            }
        }
    }

I think something is wrong because for 800 objects 309169 calls to CheckIntersectionBetween. A bruteforce would use 640000 calls, I didn't think this was much improvement (considering only objects close in the x-axis should test).
I wrote the code from reading Jitter-Physics article about SAP:

Create a new temporary list called “activeList”.
You begin on the left of your axisList, adding the first item to the activeList.

Now you have a look at the next item in the axisList and compare it with all items
 currently in the activeList (at the moment just one):
 - If the new item’s left is greater then the current activeList-item right, then remove
the activeList-item from the activeList
 - otherwise report a possible collision between the new axisList-item and the current
 activeList-item.

Add the new item itself to the activeList and continue with the next item in the axisList.

What have I done wrong?

I misinterpreted remove
the activeList-item from the activeList to mean pop_back the item just added(I had just been added an active item, it was logical! ;) ) when, because the activeList was being looped, meant remove that specific one. Hence:
activeList.erase(activeList.begin() + two);

has replaced that line. Now 11408 checks are being done for the 800 objects (55x less than brute) and this seams much more logical to me.

I was reading the exact same article, and am struggling to implement this. It seems that you did not add the "new item" to the active list when a potential overlap is found... Did you succeed in implementing this after this question ?

That is what activeList.push_back(physicsChildren[one]); is doing. When an overlap is found, CheckIntersectionBetween is called (as instructed by the 'otherwise report a possible collision' line)

About an hour ago, I took a look at the source code for Jitter Physics (Collision/CollisionSystemSAP.cs in particular, for future visitors) and got it right. Thanks for commenting me back even though this question is 2 years old :)


text:
Increasing height increases width
I have a game, where the user presses a button to spend money and increase the height of a Movie Clip. I use the following: height ++.
The problem:  When I test this out, it seems the width increases, too.  The actual thickness, you could say.  How can I solve this?

You might want to give us more about the implementation. Common objects you're using, how you're applying the change in size and so on.

The Movie Clip registration is the bottom.  It's called mc.  I call mc.height++  and it increases the height. It also increases(barely) the width.  The movieclip is a rectangle.

I fixed it by selecting the line in my movie clip and changing the scaling property to none.


text:
Storing items in external data files
My project, in its current state, keeps all of the info for each inventory item in script files. That means, inventory items and their properties are part of the codebase. This works well, but I'm advancing quickly through development and I fear that this system is going to pose some problems later on. Normally, data (item properties) are not stored in the code, but in some sort of database.
I was thinking about storing item properties in external (text for now) data files, that would get parsed when the game loads. I'd mark each item with a string ID (for easier referencing in other places - GetItemWithID("FOOD_FISH") makes more sense than GetItemWithID(5)). Then, I'd build some sort of class that would take care of item-driven events (such as what happens when an item is consumed). Then I'd map each function implemented by the manager to some interpretable string counterpart (in an item's data file I'd have the string "RestoreHealth(50)" - this would be mapped by the manager to the function RestoreHealth (the param would get passed too)).
Is this an even remotely good idea? How would you do it?
Another thing that I'm thinking of, since I'm building a tool to make inventory item creation easier, is to develop something that simply generates appropriate C# code for an underlying database of user-readable and editable item properties.
E.g. it takes in
FOOD_FISH
Name:Fish
Value:50
OnConsume:
RestoreHealth(40)

and generates
FoodFish = new InventoryItem();
//Properties set here.

LATER EDIT:
After Byte56's reply, I came up with a kind of format that's easy enough to parse.
[ID:IT_FO_TROUT]
[Name:Trout]
[Description:A raw trout.]
[Value:10]

[3DModel:null]
[InventoryIcon:trout]

[Tag:Consumable]
[Tag:Food]
[Tag:Stackable]

[OnConsume:RestoreHealth(15)]
[OnConsume:RestoreFatigue(15)]

Since on the project there will be people with no programming experience working remotely, using external files + custom item generators seems to be the best way to go. Should've figured it out earlier.

I prefer XML files myself, but whatever is easiest for you to parse should work just fine.

I find that parsing using simple string functions is much nicer. At least during development :)

Yes, storing the items in external files is a good idea. I created something very close to what you're talking about. It's an item/entity lexicon. Items, materials and entities are all stored in this "database". The script files get read on load and store every item available in game.
You can see kind of an example of what the entity files look like here.
The format of the script is up to you. You may want to use XML or some other common script, or you can make your own like I did or what it looks like you've started to do.
When the items are read in, they go into an item blueprint class. This class has all the required information for generating a new item. It also allows each item some variation. As you can see in my other answer, I define ranges of acceptable values. When the item is created it will choose a random value from within the range defined, giving each item a slightly different quality/value/whatever.
All those blueprints are stored in a HashMap, a Dictionary for C#. The ID is the key and the value is the blueprint. I also have the keys in a HashMap that's referenced by the item name. This makes it easier for me if I want to create a specific item, and I don't remember the name. For example I have an apple defined:
MATERIAL:"Apple" {
        description="An apple, a tasty fruit"
        commonName="Apple"
        pluralCommonName="Apples"
        tags=Fruit,Edible
        basetype=CulinaryFruit
        qualityrange=0.2:1.0
        itemtextureindex=10
        value=15
        density=20.0
        entityBaseAttributes="Small Physics Item","Slow Decay"

        HarvestItems{
                HarvestItem{
                        material="Apple seed"
                        TimeToCollect=200:500
                        WeightedChance=1
                        MinConditionToProduce=0.3
                        OverrideQuality=1.0:1.0
                }
                HarvestItem{
                        material="Apple core"
                        TimeToCollect=200:500
                        WeightedChance=1
                        MinConditionToProduce=0.3
                }
        }
}

Where Apple seed and Apple core are also items defined in the script. So if I want to create an apple somewhere, I have a method that takes the information above and generates the properties of an entity. Including some predefined standards like "Small Physics Item" and "Slow Decay" which add attributes to the entity being generated.
It's a pretty flexible system that allows me to quickly generate new items. And it's easy to use, because I don't actually even need to know the IDs of anything, I can reference them by name. I also have an entity named "Apple Tree" that has a ProduceItems attribute that generates Apple.
All in all, yes, it's a good idea to put your items in scripts. And with a little work, you can create some very complex behaviors and items with your item scripts.

This gives me some ideas! Especially the one about making the same item available via name as well as ID. Yeah, I guess storing them in files is a better idea, even though I have to do some parsing. Your entity reply also gave me some ideas on how to store NPCs and dialogues. That's the next step. I'll come with an edit to my original post and accept the answer.

Nice I'm glad that's useful. I'm still developing the format as I go, but it's nice to have a solid base. Your new format looks nice, and I think it'll work well for you.

Just one more question: you can notice I also entered identifiers for functions that must be called when the item is consumed. How would you approach this: every time the item is consumed, parse the string identifiers for the funcs and call their counterparts, or just use a list of pointers to functions (delegates) per each item, and call each function in the list when the item gets consumed? The 2nd way is more efficient, since you only do the parsing once, but passing parameters will be a pain that way (when parsing strings this problem is not present, since the params are there).

e.g: 1st way - foreach string s in (string identifiers for functions in OnConsume): func = Parser.GetFunc(s), params = Parser.GetParams(s); call func(params).

2nd way with delegates: foreach delegate func in (OnConsume functions): call func(paramsForFunc(func)); //a bit more difficult since you have to keep track of the parameters for each delegate

That's a tricky one. I would ask it as a new question so we can get others inputs and have an answer that's more fleshed out than an answer in a comment can be.

would like to add here that if you create an interface and allow your data loaders implement it that way if you wish to change your format only have to create a new loader.

Sorry to necro this but, how do you parse a file like this? Would you read it line by line and just check what gets read to know where to store it? Or is there some more magic to it?

@MennoGouw I've adapted a compiler I wrote. At least the parsing part of it. Check out lexical analysis to learn more. You're basically defining your own grammar and writing a parser for it. It's pretty quick once you get the hang of it, and extending it is really simple once the framework is in place.


text:
How do I calculate how an object will move from one point to another?
Here's the problem: A player starts the game in the 0 coordinate (x=0,y=0).
When the user clicks on the screen, it returns the coordinates of the destination.
Now the player has to move from its current position A(0.0) to B(x,y).
Take into account that B is in the first Quadrant so x>0 and y>0.
How will the player move?
I know that I will have to use this:
atan2(positionY-destinationY, positionX-destinationX)
to get the angle.
Now what? How will the player move with a fixed velocity (which by the way will be a variable, so a player may move faster while using some "items")?
Whose answer is better? What is more accurate? Trigonometry or Linear Algebra?

http://en.wikipedia.org/wiki/Euclidean_vector

what @Sidar said and also look into steering behaviors particularly seek and flee

Basic trigonometry example
cosine for x axis
sine for y axis
speed is whatever you would like the movement each time to increment by... Obviously the higher the number the more pixels it will move at any given time so the quicker it will be.
dx = (double) (Math.cos(angle) * speed);
dy = (double) (Math.sin(angle) * speed);

A.x += dx;
A.y += dy;

Linear algebra example
Check Sidar's answer :).. Explains it way better than I could.
This is in java... You can easily convert it to C++ though.

where speed is defined by...

whatever you would like the movement each time to increment by...
Obviously the higher the number the more pixels it will move at any given time so the quicker it will be.

To add to Savlons answer:
There are two ways of doing this
Vector2D objects(Assuming your positions are vectors):
Vector2D diffVec(B.posVec-A.posVec);
diffVec.normlize(); //Assuming it's applied on the vector itself
// and does not return a new one.
//This vector is now a unit vector which represents the heading/Direction
//without the "speed" (Well its speed is 1, more precisely its MAGNITUDE is 1).

diffVec.multiply(speed);

camera.velocity = diffVec;

The normalize function would probably look something like this:
void Vector2D::normalize(){
     float len = length();
     this.x /= len;
     this.y /= len;
};

 float Vector2D::length(){
    return sqrt(x*x+y*y);
 };

Now if you're not using vectors this could be translated to:
float dx = destinationX-positionX;
float dy = destinationY-positionY;

Let's pretend dx and dy are the components of an imaginary vector. ( And by components I mean the x and y properties ).
We can perform the same calculations as we have in our Vector2D class:
First we need to "normalize" our imaginary vector by dividing it by its length. Pythagoras theorem, remember that one?
float length = sqrtf(dx*dx+dy*dy);

Now we use this to normalize our imaginary vector:
dx/=length;
dy/=length;

Now if we were to apply the Pythagoras theorem on our new dx and dy value you will notice that the length is 1. Meaning that we have a direction, and a magnitude of 1. To change it to our speed simply multiply each component by it.
dx *= speed;
dy *= speed;

cam.velocityX = dx;
cam.velocityY = dy;

Imagine a vector to be an arrow with a specific length. When you normalize it you bring the length to one.

So if you multiply it ( by a scalar ), the speed in this case, the x and y components adjust accordingly that the length of the vector is the speed it's multiplied with.

Forget atan2.  You don't need angles.  Think in terms of linear algebra approaches.
You have a source and a destination.  Subtract source from destination to get a vector representing the change.  Normalize this.  You now have a unit vector pointing from source to destination.  Multiply by speed.  You now have the offset to apply each update. It's that easy.

you might want to help him out with some code mate. I'm guessing if he knew what you were talking about he probably wouldn't be asking this question yeh? Lol... I agree though +1 for your answer if you give him an example :)

actually, indeed I dont get it. It sounds interesting though

@jimmis98 http://en.wikipedia.org/wiki/Euclidean_vector

I don't know how to teach linear algebra while on my phone, sorry.  All I've got these days, been in the hospital for a few weeks due to an accident.

Feel free to write another answer with all the details you think I missed, though.

@SeanMiddleditch I hope you get well soon, and thank you for your time! :)

@Casey Study time!

@jimmis98 I have updated my answer to include a linear algebra method as stated by Sean.

@jimmis98 If you subtract vector A from vector B, you get a new vector that's  "going" from tip of A to the tip of B. It works for points just as well, because points and vectors are represented in the same way, where the tail is always the origin and the tip is represented by a point. It's indeed the best way to tackle the issue, the angle approach is unnecessarily convoluted and much more expensive. If you want to represent this with an equation, then if A + C = B, then B - A = C. Where A and B are your points/vectors and C is a vector "going" from A to B.


text:
How can I have parent-child transform in a component system?
Before when using inheritance, I could draw all my objects using this recursive function:
void Object::innerDraw(sf::RenderTarget& target, sf::RenderStates states)
{
    states.transform *= Object::getTransform(); //translate by this object's position
    this->Draw(target, states); //draw this object
    for (Object *child : m_children)
    {
        if(child->isVisible)
            child->innerDraw(target, states); //draw all children
    }
}

However, I am now looking at a component design where the graphics component pushes it's sprite to the renderer   Renderer::toDraw.push_back(&sprite);
The renderer then draws all the sprites in it's container
for (sf::Drawable *Entity : toDraw)
{
    target.draw(*Entity, state); // (state isn't doing any transforming here)
}

How can I be able to draw things relative to parents position?

Can't you just reference parent components using an interface (e.g. ITransformParent) to keep coupling low?

@Den, if the code/concept doesn't work, coupling is really the last thing to worry about.

I dont know what you are doing in that second piece of code but. Transform component in Unity, can have parent Transform on it. So when you go through sprite components, you get transform component, that can have absolute position in it.

Component-based entity systems are often about removing inheritance of type (and providing a nice means to drive things from data, although that aspect of things is not particularly relevant to this question).
That is, not having a very deep class hierarchy where everything in your game (tanks, bullets, space ships, whatever) exist in one large "family tree" of classes. It does not mean you need to remove logical parent/child relationships from your game.
In this case, you can implement the kind of hierarchical transformation approach in exactly the same way, either by having the renderable components have a transformation hierarchy themselves or simply having the renderable components contain a reference to a sprite which uses the existing transform hierarchy you outlined in your question -- this, in fact, would let you keep the bulk processing logic for those components in your renderer itself, where is could be in general more localized/cache-coherent and potentially better for parallelization (unlikely with rendering, but usually true for other subsystems or the subsystems themselves). See also the outboard component architectural approach.

You most probably need a complex transform state tree/cache system. You can start by adding a "parent" member to the transform object. Implementation pretty much depends on what you already have there so there's not much I can help with.
OR
You could go back to a system where you know how it's done (at least to that part of it). Why did you move away from it?

I moved away because I wanted to try a component system - just wanted to learn how to use it.

It's generally better to try and evaluate things in very small projects before moving them into bigger ones. If this already is a small project, you'll just have to find a way to fix it or get back to the real thing.

The easiest and most obvious way will work well enough:
Make a "parent relationship" component and attach it to your entities. Then in the transform calculation step, recursively calculate the parent transform.
If you want to improve efficiency, save a time stamp or frame counter with the parent entity so that you don't need to compute the parent transform more than once per frame.

I've got the feeling you might be misinterpreting what a component-system is about.
Here is an excellent article about this.
An ECM-system is meant to avoid the child-parent spaghetti between code-objects that inherit from each other, not between game-objects.
This has nothing to do with transforms. If you have a character and you want to move his head in relation to the body, you still need some form of parent/child relationship between them and a scene-graph or transform-stack that couples their position and orientation together.
For your example you could rewrite your renderer to apply the transforms itself and call *push_back* like this
void Object::innerDraw(sf::RenderTarget& target, Transform & parentTransform)
{
    Transform myTransform = parentTransform * Object::getTransform();
    Renderer::toDraw.push_back(&sprite, myTransform);
    for (Object *child : m_children)
    {
        if(child->isVisible)
            child->innerDraw(target, myTransform); //draw all children
    }
}

But I would probably prefer to keep it as it is and not.
(Note, that Transform is just a guess, I don't know how they're actually called in SFML)

You're misinterpreting the point of E/CS - it is meant for data-driven game object behavior composition. If being data-driven isn't necessary (and it usually isn't), simple composition is more than enough.

I'm not saying anything about EC being necessary here or not. I'm saying, EC doesn't absolve you from having to relate in-game objects if you want to draw them in their right position. (obviously I might still be wrong about the inheritance-spaghetti thing, in which case: sorry)

Yeah, I was just taking about that "inheritance vs. ECS" part. You're right about transforms being a different/another problem.


text:
Making a player move to my mouse when clicked?
How can I get my player to move to the mouse when it is clicked (like in Warcraft)?
So far I have tried:
if (Mouse.isButtonDown(0)) {

    if (X < Mouse.getX()) {
        X += Speed;
    }
    if (X > Mouse.getX()) {
        X -= Speed;
    }
    if (Y < Mouse.getY()) {
        Y += Speed;
    }
    if (Y > Mouse.getY()) {
        Y -= Speed;
    }
}

But that only does what I want if I hold the mouse down.

What I'd do is create 2 new variables that will hold the Mouse.Y() and Mouse.X() and set them when you click. Say we call them previousMouseX and previousMouseY.
Now, in your update method, we need to get the distance between your coördinates. That'll be Mouse.Y() - Y, same thing for the X distance.
After this we will get the angle of the movement so it moves in a straight line to the previousMouse X and Y. We will use sinus and cosinus for this. Then we multiply this by the speed so the object moves at the speed you want.
Example:
previousMouseX;
previousMouseY;

differenceX = previousMouseX - X;
differenceY = previousMouseY - Y;

angle = (float)Math.Atan2(differenceY, differenceX) * 180 / Math.PI;

X += Math.cos(angle * Math.PI/180) * Speed;
Y += Math.sin(angle * Math.PI/180) * Speed;

Good point. Let me edit.

That should do it!

You can omit the whole cos and sin call if you divide differenceX/Y with it's length and multiply that with your speed. See my answer to a different post : http://gamedev.stackexchange.com/questions/48119/how-do-i-calculate-how-an-object-will-move-from-one-point-to-another/48191#48191

Right, so you can't move at a set speed on both the X and Y axis. What you're doing now will mean that objects move faster moving diagonally then in the X or Y direction.
What you're better off doing is finding the angle between your player location and mouse location and then moving the player with a certain speed in that direction.


text:
How are old games levels made?
Take a look at Super Mario, or even PacMan, or Arkanoid.
How are their levels made, do they created a simple level editors to visualize them, or they designed them by hand (directly with code)?

All those old games didn't have the good fortune of level editors, with the exception of some of the super marios. Being mostly written in assembly with limited resources(memory, cpu speed, etc...) a lot of them would have just been hard coded points. Array's do well for this. But at the end of the day there isn't much difference as a level editor will have to load in or create the necessary data structures. This question is fairly generic and without more information like the type of game the possibilities are limitless.

Using arrays to define some more detailed levels would require a lot of imagination and work.

Writing an entire video game in assembly already requires a lot of imagination and work ;)

With pen/pencil and paper

@dennmat Don't underestimate paint.exe or similar programs as level editors. For example, all levels of the original Lemmings have been created in a simple paint program.

@Hackworth, however at the end of the day the "edges" and "points" were either hand inserted or detected by the colors of neighbouring pixels, and stored in some sort of point array or collision table.

@dennmat So? Obviously the engine has to know what to do with the data it gets. The question was about editors, all I'm saying is that even pretty old games had editors. BTW I was not quite correct about Lemmings. They did create their own level editor, but made its UI like everyone's familiar paint program.

Even if most of these games were written in assembly and that lots of data was the result of 'trial and error' method, for some other stuff (sprites, levels, ...) they use tools. Tools also allow non programmers to create some stuff in the game. look at that picture : http://s9.postimage.org/uebv3q00f/019.jpg (especially the guy at bottom left, editing mario sprite). Good old paper and pencil for prototyping is useful too !

@dennmat I'd like to see an example of one of the "super marios" that used a level editor. I was under the impression that the levels were detailed on paper like in the picture tigrou showed us and then a programmer coded it up (I believe I read this in an "Iwata Asks")

@Jeff how about Super Mario 64, Super Mario Sunshine, Super Mario Galaxy. He never specified which one, but seeing as he was comparing it to pacman I assume the first, which TIGROU was fairly toolless. I can't find it now at work but you should look into the post the creator of the original prince of persia guy made about making games like that in pure assembly and how he had some thousands(may have been hundreds don't remember the count) of pages of assembly and how he managed it.

By old I had thought OP meant "NES and older", I hadn't even considered the 3D Super Marios! :P I'd still love to see one of those level editors (doubt there's anything public)

@dennmap : Prince of Persia (for which source is now available after being recovered by the author) was made using a level editor. See the video : http://vimeo.com/2280934 (1987)


text:
OpenGL: Resizing Display and glOrtho/glViewport
I have researched this question from several sources and have yet to find a firm answer saying that "yes that is correct thinking" or "no, here is how it's done."
I am trying to ensure resolution independence with OpenGL rendering. The way I think I should go about it, is to create a projection using glOrtho with whatever I want the world coordinates to be. For example, glOrtho(-50.0, 50.0, -50.0, 50.0, 1.0, -1.0).  Next, set the viewport to the screen resolution, i.e. - glViewport(0, 0, 800, 600). Finally, whenever the window is re-sized, make a call to glViewport with the updated screen resolution. This will scale your figures.
Is this the correct way to ensure that models take the same proportion of screen-space on different resolutions? Should I be using a projection equal to the resolution as well? I found some answers saying glOrtho should use the resolution of your window while others said it should/can be different.
Thoughts?

What you have described is entirely adequate and appropriate to provide resolution independence. Anything you draw will indeed always take up the same proportion of your window.
However, if you do nothing more than this, you will have aspect ratio problems. For example, given the numbers you wrote, if you draw a circle, it will be squashed — wider than it is tall, because your horizontal scale is 800/(50+50) = 8 and your vertical scale is 600/(50+50) = 6.
There cannot be any automatic solution to this problem; you will have to choose what graphical result you want, and consider its effect on the gameplay. Some common examples:

In a perspective-projection 3D game with no HUD, the usual simple solution (available in OpenGL as part of gluPerspective) is to fix the projection's field of view relative to the vertical dimension. This means that in such a game, if you resize the window horizontally, you will see more or less of the scene and the middle part of the image will not change at all.
The same idea can be applied to a 2D/2.5D view as well.
(Note that this allows the player to enlarge their field of view horizontally by making a wide but not tall window. This could be unwanted in a competitive multiplayer game.)
If you have viewport-filling graphics with a fixed aspect ratio (for example, a non-scrolling 2D map, or a decorative border), or if you otherwise cannot change the layout, then you have to do something like having black bars on two sides to fill the unused space.
Or you can make graphics which have thematically consistent filler material around the edges that they can be cropped to fit the display without harming gameplay.
If you have a HUD on top of other graphics, you can decide that each HUD element is fixed to a part of the window (top left, bottom center, etc.) and compute its coordinates; the 'stretching' of varying the aspect ratios gets absorbed by the 'white space' between HUD elements.

As to the specific mathematics of the matter, given that you are doing resolution independence, all you need to start out with is the aspect ratio, a single number: width  / height. For example, if the window is square it will be 1; if it is 800 by 600 it will be 800/600 = 4/3 = 1.333̅.
For example, suppose you want the orthographic projection you have written to gain additional space on the left and right sides if the window is widened. You can do that like this:
float aspect = width / height;
glViewport(0, 0, width, height);
glOrtho(-50.0 * aspect, 50.0 * aspect, -50.0, 50.0, 1.0, -1.0);

This guarantees that, for windows at least as wide as they are tall, anything you draw with x and y coordinates within -50 to 50 will be visible.
On the other hand, if the window is narrower than it is tall, the -50-to-50 range will be cut off. Let's say you wanted to make sure that it is always visible (so that your content is at its maximum size if the window is square, but smaller otherwise); in that case, you simply do the same thing to the height instead of the width.
float aspect = width / height;
glViewport(0, 0, width, height);
if (aspect >= 1.0)
  glOrtho(-50.0 * aspect, 50.0 * aspect, -50.0, 50.0, 1.0, -1.0);
else
  glOrtho(-50.0, 50.0, -50.0 / aspect, 50.0 / aspect, 1.0, -1.0);

Note that in the second case we divide rather than multiply. This is simply because we computed the aspect ratio as width / height rather than height / width; take the reciprocal if you find it easier to understand that way.
Again, this is not the only way to manage aspect ratio; this is just a very simple one for making sure that your content is neither squished nor cut off. Figure out what you want to happen when your window is wide, tall, or whatever; then work out the mathematics of it.

Thank you for the VERY insightful response.  Answered my question beyond sufficiently.