# Question
Title: Inventory Management concepts in XNA game
I am trying to code the inventory system in my first real game so I have very little experience in both c# and game engine development. Basically, I need some general guidance and tips with how to structure and organize these sorts of systems. Please tell me if I am on the right track or not before I get too deep into making some badly structured system. It's fine if you don't feel like looking through my code, suggestions about general structure would also be appreciated.

What I am aiming to end up with is some sort of system like Minecraft or Terraria. It must include:

* main inventory GUI (items can be dragged and placed in whatever slot desired
* Itembar outside of the main inventory which can be assigned to certain items
* the ability to use items from either location

So far, I have 4 main classes: **Inventory** holds the general info and methods, **inventoryslot** holds info for individual slots, **Itembar** holds all info and methods for itself, and finally, **ItemManager** to manage interactions between the two and hold a master list of items.

So far, my itembar works perfectly and interacts well with mousedragging items into and out of it as well as activating the item effect.

Here is the code I have so far: (there is a lot but I will try to keep it relevant)

This is the code for the itembar on the main screen:

```
class Itembar
    {
        public Texture2D itembarfull, iSelected;
        public static Rectangle itembar = new Rectangle(5, 218, 40, 391);
        public Rectangle box1 = new Rectangle(itembar.X, 218, 40, 40);
        //up to 10 Rectangles for each slot
        public int Selected = 0;
        private ItemManager manager;

        public Itembar(Texture2D texture, Texture2D texture3, ItemManager mann)
        {
            itembarfull = texture;
            iSelected = texture3;
            manager = mann;
        }

        public void Update(GameTime gametime)
        {

        }

        public void Draw(SpriteBatch spriteBatch)
        {
                spriteBatch.Draw(
                                itembarfull,
                                new Vector2 (itembar.X, itembar.Y),
                                null,
                                Color.White,
                                0.0f,
                                Vector2.Zero,
                                1.0f,
                                SpriteEffects.None,
                                1.0f);
                if (Selected == 1)
                spriteBatch.Draw(iSelected, new Rectangle(box1.X-3, box1.Y-3, box1.Width+6, box1.Height+6), Color.White);
               //goes up to 10 slots

        }

        public int Box1Query()
        {
            foreach (Item item in manager.items)
            {
                if(box1.Contains(item.BoundingBox))
                    return manager.items.IndexOf(item);
            }
            return 999;
        }
//10 different box queries

```

It is working fine right now. I just put an Item in there and the box will query things like the item's effects, stack number, consumable or not etc...This one is basically almost complete.

Here is the main inventory class:

```
 class Inventory
    {
        public bool isActive;
        public List<Rectangle> mainSlots = new List<Rectangle>(24);
        public List<InventorySlot> mainSlotscheck = new List<InventorySlot>(24);
        public static Rectangle inv = new Rectangle(841, 469, 156, 231);
        public Rectangle invfull = new Rectangle(inv.X, inv.Y, inv.Width, inv.Height);
        public Rectangle inv1 = new Rectangle(inv.X + 4, inv.Y +3, 32, 32);
        //goes up to inv24 resulting in a 6x4 grid of Rectangles
public Inventory()
        {
            mainSlots.Add(inv1); mainSlots.Add(inv2); mainSlots.Add(inv3); mainSlots.Add(inv4);
            //goes up to 24
            foreach (Rectangle slot in mainSlots)
                mainSlotscheck.Add(new InventorySlot(slot));
        }
//update and draw methods are empty because im not too sure what to put there
public int LookforfreeSlot()
    {
        int slotnumber = 999;
        for (int x = 0; x < mainSlots.Count; x++)
        {
            if (mainSlotscheck[x].isFree)
            {
                slotnumber = x;
                break;
            }
        }
        return slotnumber;
    }

    }
}

```

LookforFreeSlot() method is meant to be called when I do AddtoInventory(). I'm kinda stumped about what other things I need to put in this class.

Here is the inventorySlot class: (its main purpose is to check the bool "isFree" to see whether or not something already occupies the slot. But i guess it can also do other stuff like get item info.)

```
class InventorySlot
    {
        public int X, Y;
        public int Width = 32, Height = 32;
        public Vector2 Position;
        public int slotnumber;
        public bool free = true;
        public int? content = null;

        public bool isFree
        {
            get { return free; }
            set { free = value; }
        }

        public InventorySlot(Rectangle slot)
        {
            slot = new Rectangle(X, Y, Width, Height);
        }
    }
}

```

Finally, here is the ItemManager (I am omitting the master list because it is too long)

```
class ItemManager
    {
public List<Item> items = new List<Item>(20);
        public List<Item> inventory1 = new List<Item>(24);
        public List<Item> inventory2 = new List<Item>(24);
        public List<Item> inventory3 = new List<Item>(24);
        public List<Item> inventory4 = new List<Item>(24);
        public Texture2D icon, filta;
        private Rectangle msRect;
        MouseState mouseState;
        public int ISelectedIndex;
        Inventory inventory;
        SpriteFont font;
public void GenerateItems()
        {
            items.Add(new Item(new Rectangle(0, 0, 32, 32), icon, font));
            items[0].name = "Grass Chip";
            items[0].itemID = 0;
            items[0].consumable = true;
            items[0].stackable = true;
            items[0].maxStack = 99;
            items.Add(new Item(new Rectangle(32, 0, 32, 32), icon, font));
        //master list continues. it will generate all items in the game;

        }
public ItemManager(Inventory inv, Texture2D itemsheet, Rectangle mouseRectt, MouseState ms, Texture2D fil,
                            SpriteFont f)
        {
            icon = itemsheet;
            msRect = mouseRectt;
            filta = fil;
            mouseState = ms;
            inventory = inv;
            font = f;
        }
//once again, no update or draw
 public void mousedrag()
        {

                        items[0].DestinationRect = new Rectangle (msRect.X, msRect.Y, 32, 32);
                        items[0].dragging = true;

        }

        public void AddtoInventory(Item item)
        {
            int index = inventory.LookforfreeSlot();
            if (index == 999)
                return;
            item.DestinationRect = inventory.mainSlots[index];
            inventory.mainSlotscheck[index].content = item.itemID;
            inventory.mainSlotscheck[index].isFree = false;
            item.IsActive = true;
        }

    }
}

```

The mousedrag works pretty well. AddtoInventory doesn't work because LookforfreeSlot doesn't work.

Relevant code from the main program: When I want to add something to the main inventory, I do something like this:

```
 foreach (Particle ether in ether1.ethers)
                    {
                        if (ether.isCollected)
                            itemmanager.AddtoInventory(itemmanager.items[14]);
                    }

```

This turned out to be much longer than I had expected :(

But I hope someone is interested enough to comment.

# Answer
> 2 votes
I agree with Petr Abdulin that the question is too vague. Still, here are a couple of pointers that might help you to improve your design:

* ItemManager is not needed at all. Use the Active Record pattern: Store item data in a database or XML file and use statements like Item::findById(5) to create item objects.
* Separate your classes' business logic from presentation logic. For example, in InventorySlot, x, y, width, and height do not belong in the same class as free and content; checking whether a slot in Itembar is free should not be done via a comparison of some rectangle positions; etc.
* Get rid of unnecessary dependencies and redundancies. For example: InventorySlot-\>free can be calculated from its content; InventorySlot does not need to know its position; nothing needs to be coupled with ItemManager; etc.
* Use encapsulation to your advantage. For example: Inventory and ItemBar only need one class! (Or, if they need to be distinguished from one another for reasons you did not mention, they can be derived from the same base class.)

Here is what your classes might look like:

```
class Inventory {
    property slots (List of InventorySlots)
    property numberOfSlots (int)
    property numberOfColumns (int)
    NO OTHER PROPERTIES

    function Inventory(slots, numberOfSlots, numberOfColumns) {
        if(slots == null) {
            // create numberOfSlots empty InventorySlots
        }
        if(numberOfColumns == null) {
            this->numberOfColumns = numberOfSlots;
        }
    }
    function addItem(Item) {
        slot = this->getFreeSlot();
        if(!slot) { return false; }
        slot->setContent(Item);
        return true;
    }
    function getFreeSlot() {
        while(slot = slots->next()) {
            if(slot->isFree()) {
                return slot;
            }
        }
        return false;
    }
    // Let draw except a position for the inventory on the screen
    function draw(position, sprite) {
        // draw sprite
        for(row = 0; row < this->numberOfSlots / this->numberOfColumns; row++) {
            for(column = 0; column < this->numberOfColumns; column++) {
                slot = slots->getElement(row*6+column);
                // InventorySlot->draw also expects a position, so let's calculate that
                positionToSlotPosition = <column*InventorySlot::width, row*InentorySlot::height>
                slot.draw(position + positionToSlotPosition);
            }
        }
    }
}

class InventorySlot extends SomeUIClass which implements Draggable {
    property content (Item)
    const width=32
    const height=32
    NO OTHER PROPERTIES

    function InventorySlot() {}
    function setContent(Item) {...}
    function getContent() {
        if(this->isFree()) {
            // return something that does not throw errors when you call Item's interfaces without actually doing anything
            return new NullItem();
        }
        return this->content;
    }
    function isFree() {...}
    function draw(position) {
        // draw rectangle with self::width and self::height at position
        // Draw the item in the item slot; draws nothing if getContent() returns a NullItem
        this->getContent->draw(position);
    }
}

class SomeUIControlStuff {
    property Inventories (List of Inventories)
    property ItemBars (List of ItemBars)
    property activeInventory (Inventory)
    property activeItemBar (Inventory)
    property selectedSlot (InventorySlot)
    function setSelectedSlot(InventorySlot)
    function getSelectedSlot()

    function initialize() {
        // If you have some game state, use that data to fill Inventories and ItemBars accordingly.
        // If not, create empty Inventories and ItemBars:
        this->activeItemBar = new Inventory(null, 10);
        this->activeInventory = new Inventory(null, 24, 6);
    }
}

```

If you want to add an Item to the Inventory:

```
Inventory->addItem(Item);

```

If you want to draw an Inventory (i.e. an inventory in your sense or an itembar):

```
Inventory->draw(position, sprite);

```

---
Tags: c#, xna, game-design, asset-management
---


# Question
Title: Calculating a line's normal for the purposes of collision
Given a line defined as two points in screen coordinate space (which themselves are two 2D vector positions) how would I calculate a 2D Vector perpendicular in the "up" direction for determining a normal force?

# Answer
If you have a vector *v* = A - B (the direction is from B to A), then you need to find a vector *u* so that *dot(u,v) = 0*.

If *v=(x,y)*, there's no unique solution for this problem, but let's choose the normal pointing to the left side of the *v* vector. This one is *u=(-y,x)* and it is attained by rotating *v* by 90 degrees. Using complex numbers: *v = x + i y* and a rotation of 90 degrees means multiplying *v* by **i**. Hence *u*= *vi* = *i x - y* or in cartesian coordinates: *u=(-y,x)*.
> 2 votes

---
Tags: physics
---


# Question
Title: What are the factors that determine the default frequency of a shader call?
After i have been played for some days with various vertex and fragments shaders seems clear to me that this programs are called by the GPU at every and each rendering cycle, the problem is that I can't really quantify this frequency and I can't tell if is based on some default values or not because I don't have a big collection of hardware right now to do extensive tests.

For what i know the answer could be really trivial like *"it's the same of the refresh rate of your monitor"*, but i would like some good answers on that to be clear on this.

For instance looks really odd to me that all the techniques used to control the amount of FPS that i have seen until now uses a call for the OpenGL function `glutGet(GLUT_ELAPSED_TIME)` to retrieve a value in ms about when the rendering started but I have to relies on the CPU to do the math. Why I can't set an FPS value in OpenGL if OpenGL clearly has a counter and a timer/clock?

PS I'm referring to OpenGL 3.0+

# Answer
> 7 votes
> What are the factors that determine the default frequency of a shader call?

There's no such thing as a default frequency for a shader call. It depends of course on the game's frame rate, but not only.

Vertex shaders are called for each vertice of a primitive rendering. The call frequency will depend on how many primitives you render, on the current view frustum (culling), on the number of passes required by the rendering techniques...

Fragments shaders are called for each sample of each pixel of each rasterized primitive. The call frequency will depend on the same as above, plus the viewport or the render target sizes, how many post processes are run...

> Why I can't set an FPS value in OpenGL if OpenGL clearly has a counter and a timer/clock?

If by "in OpenGL" you mean in shader code, the reason is a consequence of what precedes: your shader programs can be executed a "random" number of times a second, so you can't infer the FPS from them.

Note that `glutGet(GLUT_ELAPSED_TIME)` is indeed an OpenGL-related function (actually, a GLUT function), but this doesn't mean that it's accessible by shaders. It isn't. Even if you could add a performance timer in shader code, you'd have no way to output your results, so this would be useless.

---
Tags: opengl, shaders, timer
---


# Question
Title: Basic procedural generated content works, but how could I do the same in reverse?
My 2D world is made up of blocks. At the moment, I create a block and assign it a number between 1 and 4. The number assigned to the nth block is always the same (i.e if the player walks backwards or restarts the game.) and is generated in the function below. (Image shows a small portion of the game, in practice there are much more blocks)

As shown here by this animation, the colours represent the number.

```
function generate_data(n)
    math.randomseed(n) -- resets the random so that the 'random' number for n is always the same
    math.random() -- fixes lua random bug
    local no = math.random(4)
    --print(no, n)
  return no
end

```

Now I want to limit the next block's number - a block of 1 will always have a block 2 after it, while block 2 will either have a block 1,2 or 3 after it, etc. The next block's number is taken at random from the `next` table:

```
{
   [1] = {next = {2}},
   [2] = {next = {1,2,3}},
   [3] = {next = {4}},
   [4] = {next = {1,3,4}},
}

```

Before, all the blocks data was randomly generated, initially, and then saved. This data was then loaded and used instead of being randomly called. While working this way, I could specify what the next block would be easily and it would be saved for consistency. I have now removed this saving/loading in favour of procedural generation as I realised that save whiles would get very big after travelling.

Back to the present. While travelling forward (to the right), it is easy to limit what the next blocks number will be. I can generate it at the same time as the other data.

The problem is when travelling backwards (to the left) I can not think of a way to load the previous block so that it is always the same.

Does anyone have any ideas on how I could sort this out?

# Answer
If I understand your question correctly you'd like that each block be random, but blocks beside each other are related. In terms of a game, the sequence of rooms is random, but neighbouring rooms have to be compatible in some way. Going right isn't a problem since you have the current room and can easily apply the contsraint to the next room. Going left is a problem since you can't be certain which room was there.

Instead of trying to generate a specific block number instead think about the transitions between the blocks. Your random generator will produce a transition delta between the rooms. The delta value for a given block will be random, but based on a fixed seed (thus constant for a particular game). You then apply this delta to the player's current room number to get the new block. If you are going right you add the delta, and if going left your subtract the delta.

That is, you are currently in Block `X` with a value of `V`. Let's say the left-delta of block `X` uses `X` as a seed and the right transitions uses `X+1`. To go right you calculate the transition of `X+1` and add it to `V`. To go left you calculate the delta at `X` and subtract it from `V`.

An example with values, say the delta values are \[ 0, 1, -1, 0 \].

1. You start at block 0, which we give value 4 (random number)
2. To walk right we get delta X+1 = 1
3. You are now at Block 1 with a value 4+1 = 5
4. Right again, Block 2 with a value 5-1 = 4
5. Right again, Block 3 with a value 4+0 = 4
6. Walk left, delta X = -1
7. You are now at Block 2 with a value 4-(-1) = 5
8. Left again, Block 1 with a value 5-1 = 4
9. Left again, Block 0 with a value 4-0 = 4

You can see that walking both left and right will result in the same value produced for each block.
> 3 votes

# Answer
The fixed seed idea is the way to go, but you can keep it very simple.

If you concern is the save game size, just save the seed for each level and re-generate it entirely at game startup, in you own fixed order (e.g. for a row of blocks, from -1000 to +1000).

Oh, and maybe this save game size isn't an issue after all. Think about how big the Minecraft world is, and I'm pretty sure at least a good part of it *is* saved:
> 0 votes

---
Tags: procedural-generation, lua, random
---


# Question
Title: How to draw Isometric game Back to front
What is the for loop or algorytm for a 2D array of tiles that I would render the tiles back to front like this:

# Answer
> 3 votes
It's the opposite of how you would draw them front to back.

---
Tags: java, rendering, isometric
---


# Question
Title: Fitting a rectangle into screen with XNA
I am drawing a rectangle with primitives in XNA. The width is:

```
width = GraphicsDevice.Viewport.Width

```

and the height is

```
height = GraphicsDevice.Viewport.Height

```

I am trying to fit this rectangle in the screen (using different screens and devices) but I am not sure where to put the camera on the Z-axis. Sometimes the camera is too close and sometimes to far.

This is what I am using to get the camera distance:

```
//Height of piramid
float alpha = 0;
float beta = 0;
float gamma = 0;

alpha = (float)Math.Sqrt((width / 2 * width/2) + (height / 2 * height / 2));
beta = height / ((float)Math.Cos(MathHelper.ToRadians(67.5f)) * 2);
gamma = (float)Math.Sqrt(beta*beta - alpha*alpha);

position = new Vector3(0, 0, gamma);

```

Any idea where to put the camera on the Z-axis?

# Answer
The trick to doing this is to **draw the rectangle directly in raster space**. This is the space that the GPU works in when actually rendering stuff.

Normally your model starts in its own model space, you apply a world transform to get it into world space. You then apply a view transform to move the points in the world around the camera (to get the effect of the camera moving around the world). Then you apply a projection matrix to get all those points into the space that the GPU uses for drawing.

It just so happens that this space is always - no matter the screen size - from **(-1,-1)** in the bottom left corner of the viewport, to **(1,1)** in the top right (and from 0 to 1 on the Z axis for depth).

So the trick is to set all your matrices (world, view, project) to `Matrix.Identity`, and then draw a rectangle from (-1,-1,0) to (1,1,0). You probably also want to set `DepthStencilState.None` so that it doesn't affect the depth buffer.

---

An alternative method is to just use `SpriteBatch` and draw to a rectangle that is the same size as the `Viewport`.
> 4 votes

---
Tags: xna, c#, xna-4.0
---


# Question
Title: Tweaking AStar to find closest location to unreachable destination
I've implemented AStar in Java and it works ok for an area with obstacles where the chosen destination is reachable.

However, when the destination is unreachable, the calculated "path" is in no way to the closest location (to the unreachable location) but is instead some random path.

Is there a feasible way to tweak AStar into finding the path to the closest location to an unreachable destination?

# Answer
Keep track of the node with the lowest `EstimatedDistanceToEnd` (ie. the lowest `h(x)`), and if no end-node is reachable to backtrack from, backtrack from that node instead.
> 23 votes

# Answer
This is not really an A\* question. A\* is all about finding a path from point A to point B. Even though it can be extended, the results could easily be messy and unpredictable. What you need instead is an algorithm that picks the closest reachable destination.

Here's one way to do this: If A\* returns a valid path (start/end nodes in path match input nodes), return the path. Otherwise...

* Start searching from the initial node
* Traverse all linked nodes (remember to flag the visited ones to avoid infinite recursion)
* Compare distances to destination to find the closest node
> 1 votes

---
Tags: path-finding
---


# Question
Title: What is a good pathfinding library for Java?
I'm an amateur game developer and somewhat amateur Java developer as well. I'm trying to find a way to have path finding for my game(s). I've first Googled for some existing Java libraries that have various path-finding implementations, but I've failed to find any. It seems to me that the only way to get pathfinding code is to use it via a game engine (like Unity). But I'd just like to have a library that I can use and make the game loop and other stuff on my own.

Failing to find such a library I've tried implementing some algorithms myself. I've managed to make a running A\* in Java, but for fancier stuff like D\* I find it hard to do it by hand.

So then, my question is, are there any Java libraries that contain at least some basic pathfinding algorithms implementations?

# Answer
> 9 votes
Path finding libraries are not too common for general use. This is because the algorithm interacts directly with your world. The algorithm can't know in advance how you'll lay out your data structures for holding your world data. The amount of user required implementation for these algorithms would likely override the usefulness of providing the algorithm in library form. The more complex the algorithm, the more work it would be to make a generalized version for a library form. So you're less likely to really get what you want, the harder-to-implement algorithms won't be in library form. There are some libraries available, though I haven't used them, so I can't say how much work they are to use. Personally I would rather implement them myself so I can learn how they work and ensure they're properly integrated.

It *may* be useful to look at the libraries to get some implementation tips, but I don't think these will be implemented in the same way you would implement them. Since they need to overcome the issues I mentioned earlier, they might have some strange implementations.

For 2D, Slick2D has some built-in path finding for tile based games.

---
Tags: java, path-finding
---


title: Sprite Body can not stop

text:
# Question
Title: Sprite Body can not stop
Hey i have issue regarding jump sprite body. In my code i am using moveLeft and moveRight Button and when i am press moveRight Button using following code

```
if (moveRight.active==YES)
    {
            b2Vec2 force=b2Vec2(4,0);
            ballBody->SetLinearVelocity(force);
    }

```

Its move perfectly and When i release this Button than sprite body stop using following code

```
else
{
      b2Vec2 force=b2Vec2(0,0);
      ballBody->SetLinearVelocity(force);
}

```

But when i put this else part then jump can not done. My jump code is following

```
if (jumpSprite.active==YES)
                {
                    NSLog(@"Jump Sprite");
                    b2Vec2 locationWorld;
                    locationWorld=b2Vec2(0.0f,4.0f);
                    double force=ballBody->GetMass();
                    ballBody->ApplyLinearImpulse(force*locationWorld, ballBody->GetWorldCenter());
                }

```

If i remove else part then jump will perform complete but sprite body can not stop after release button.

So what to do??

Thanks in advance

# Answer
> 1 votes
Have you tried something like:

```
if (moveRight.active==YES)
{
      b2Vec2 force=b2Vec2(4,ballBody.yForce);
      ballBody->SetLinearVelocity(force);
}

if(moveRight.active==NO)
{
      b2Vec2 force=b2Vec2(0,ballBody.yForce);
      ballBody->SetLinearVelocity(force);
}

```

Note, I haven't used cocos2D, so I don't know how to properly get the y force (so I use `ballBody.yForce`, replace that with the correct code). I do recommend using the existing y force there, unless you want your jump to stop from x movement (same goes for your jump). I also find it strange that applying a force of `0` stops the ball, but you said that works.

---
Tags: cocos2d-iphone, box2d
---


# Question
Title: Converting world space coordinate to screen space coordinate and getting incorrect range of values
I'm attempting to convert from world space coordinates to screen space coordinates.

I have the following code to transform my object position

`Vector3 screenSpacePoint = Vector3.Transform(object.WorldPosition, camera.ViewProjectionMatrix);`

The value does not appear to be in screen space coordinates and is not limited to a \[-1, 1\] range.

What step have I missed out in the conversion process?

EDIT:

Projection Matrix

---

```
Perspective(game.GraphicsDevice.Viewport.AspectRatio, nearClipPlaneZ, farClipPlaneZ);

    private void Perspective(float aspect_Ratio, float z_NearClipPlane, float z_FarClipPlane)
    {
        nearClipPlaneZ = z_NearClipPlane;
        farClipPlaneZ = z_FarClipPlane;

        float yZoom = 1f / (float)Math.Tan(fov * 0.5f);
        float xZoom = yZoom / aspect_Ratio;

        matrix_Projection.M11 = xZoom;
        matrix_Projection.M12 = 0f;
        matrix_Projection.M13 = 0f;
        matrix_Projection.M14 = 0f;

        matrix_Projection.M21 = 0f;
        matrix_Projection.M22 = yZoom;
        matrix_Projection.M23 = 0f;
        matrix_Projection.M24 = 0f;

        matrix_Projection.M31 = 0f;
        matrix_Projection.M32 = 0f;
        matrix_Projection.M33 = z_FarClipPlane / (nearClipPlaneZ - farClipPlaneZ);
        matrix_Projection.M34 = -1f;

        matrix_Projection.M41 = 0f;
        matrix_Projection.M42 = 0f;
        matrix_Projection.M43 = (nearClipPlaneZ * farClipPlaneZ) / (nearClipPlaneZ - farClipPlaneZ);
        matrix_Projection.M44 = 0f;
    }

```

View Matrix

---

```
        // Make our view matrix
        Matrix.CreateFromQuaternion(ref orientation, out matrix_View);

        matrix_View.M41 = -Vector3.Dot(Right, position);
        matrix_View.M42 = -Vector3.Dot(Up, position);
        matrix_View.M43 = Vector3.Dot(Forward, position);
        matrix_View.M44 = 1f;

        // Create the combined view-projection matrix
        Matrix.Multiply(ref matrix_View, ref matrix_Projection, out matrix_ViewProj);

        // Update the bounding frustum
        boundingFrustum.SetMatrix(matrix_ViewProj);

```

# Answer
XNA has a built-in function for calculating world-to-screen space coordinates called Viewport.Project. It also has the opposite function (Unproject) for turning screen coordinates back into world coordinates (minus the depth value).

As far as why your implementation isn't working, I'm not 100% sure but here's a few ideas:

* You're using Vector3.Transform, but your ViewProjectionMatrix is 4x4, so you may be missing the homogenous W divide. I'm not sure whether Vector3.Transform takes this into account.
* If your object's WorldPosition is outside of the view frustum, its post-projective position won't be in the -1 to 1 range. This is how the GPU knows how to clip polygons that lie partially or fully outside the view frustum.
* The range of -1 to 1 is for the unit cube conversion; it's not actually screen space coordinates in the sense of texturing (0.0 to 1.0) or resolution (0.0 to screen width or height).

EDIT: It definitely looks like you're missing the W divide. Vector3.Transform drops the W component in the value it returns. Transform it like this and see if it works:

```
Vector4 objectPos4 = new Vector4( object.WorldPosition, 1.0f );
Vector4 postProjectivePosition = Vector4.Transform(objectPos4, camera.ViewProjectionMatrix);
float clipSpaceX = postProjectivePosition.X / postProjectivePosition.W;
float clipSpaceY = postProjectivePosition.Y / postProjectivePosition.W;

```

That should get it into the -1 to 1 range you desire.
> 3 votes

---
Tags: xna, c#, coordinates
---


title: Create Levels using blender

text:
# Question
Title: Create Levels using blender
I am creating a game and I have a custom level format for levels in my game. I wanted to know if it is possible to create levels for that kinda format in Blender. My format is XML based and just declares the positions of certain objects. Online I have seen many people use Blender to create levels in their own custom format that blender can understand.

How do i get blender to understand my format and use blender to create levels for my game?

# Answer
You have two ways:

* use the Python API
* since Blender is free and open-source you can re-factor all the pieces of code that you want to but this is a crazy idea even if you think about the fact that Blender has a relatively clean and modular design.

By the way Collada is just XML, I would just remind you that, the default .blend format file is probably not so standard, but there are prepacked alternatives.
> 6 votes

# Answer
By "level", it sounds like you mean you don't want the geometry in your level file, only where objects are located. A more clear term for that is "placement editor" (ie. use Blender to place objects around the scene)

I've written a Python script to do just that; it saves custom properties in addition to regular position/rotation/etc, and you can save the data as either XML or JSON.

(and then just for kicks I ported the script to Maya)
> 3 votes

# Answer
From my experience with using Blender as a level editor, here's some tips:

* *None of the existing exporters will currently export custom properties of various objects*. They are vital in supplying metadata so if you want that, you will have to make your own exporter.
* #blenderpython IRC channel (which can be found in the same server as other channels: http://www.blender.org/community/chat) should be able to help you with most of your problems (please do consult the documentation first though, it will help you find most variable names).
* If you want to export more than position data (meshes, for example), Blender's data requires lots of preprocessing so I highly recommend using at least one intermediate output stage.
* You can use F8 to reload scripts instantly. You can enable the console to find out why your script isn't registering the necessary menu items.

On second thought, if all you need is positions, why Blender? Is there anything bad about just making a "position viewer" app based on your game code (you could even load the level and instantly see it) and writing the level files yourself?
> 3 votes

---
Tags: c++, game-design, level-design
---


# Question
Title: Rotating voxels in 3d space amongst the x axis
I have a very simple voxel engine and so far it works based on coordinates, e.g. x, y, z. I was wondering if there is a formula for rotating groups of voxels/coordinates from the x axis(e.g. \[0, 1, 0\]\[1, 0, 1\] rotates to \[1, 0, 0\]\[0, 0, 1\] when rotated 90 degrees anticlockwise along the x axis) from a certain point, but I hear it involves matrixes and quaternions which sound scary.

# Answer
1) The non-scary way to do 90-degree rotations is to swap a set of axes, and negate one of them:

```
Rotated along x-axis: swap Y/Z to Z/-Y
(a,b,c) -> (a,c,-b)

```
> 5 votes

# Answer
You can't get too far into any 3D programming without matrices or quaternions. It's not too scary though. There are plenty of resources available to you, since you can use some existing resources 3D model transformations. Just think of all your voxel positions as vertex positions.

With that in mind, you can apply a transformation matrix to the voxel positions. However, I imagine you'd want your voxel positions to still align to a grid afterwards, so you'd need to pick your transformations carefully.
> 2 votes

---
Tags: 3d, mathematics, matrix, voxels, quaternion
---


# Question
Title: Smooth drag scrolling of an Isometric map - Html5
I have implemented a basic Isometric tile engine that can be explored by dragging the map with the mouse. Please see the fiddle below and drag away:

http://jsfiddle.net/kHydg/14/

The code broken down is (CoffeeScript):

**The draw function**

```
draw = ->
  requestAnimFrame draw
  canvas.width = canvas.width

  for row in [0..width]
    for col in [0..height]
      xpos = (row - col) * tileHeight + width
      xpos += (canvas.width / 2) - (tileWidth / 2) + scrollPosition.x
      ypos = (row + col) * (tileHeight / 2) + height + scrollPosition.y
      context.drawImage(defaultTile, Math.round(xpos), Math.round(ypos), tileWidth, tileHeight)

```

**Mouse drag-scrolling control**

```
scrollPosition =
  x: 0
  y: 0

dragHelper =
  active: false
  x: 0
  y: 0

window.addEventListener 'mousedown', (e) =>
  handleMouseDown(e)
, false

window.addEventListener 'mousemove', (e) =>
  handleDrag(e)
, false

window.addEventListener 'mouseup', (e) =>
  handleMouseUp(e)
, false

handleDrag = (e) =>
  e.preventDefault()
  if dragHelper.active
    x = e.clientX
    y = e.clientY
    scrollPosition.x -= Math.round((dragHelper.x - x) / 28)
    scrollPosition.y -= Math.round((dragHelper.y - y) / 28)

handleMouseUp = (e) =>
  e.preventDefault()
  dragHelper.active = false

handleMouseDown = (e) =>
  e.preventDefault()
  x = e.clientX
  y = e.clientY
  dragHelper.active = true
  dragHelper.x = x
  dragHelper.y = y

```

**The Problem**

As you can see from the fiddle the dragging action is ok but not perfect. How would I change the code to make the dragging action more smooth? What I would like is the point of the map you click on to stay under the mouse point whilst you drag; the same as they have done here: http://craftyjs.com/demos/isometric/

# Answer
To move smoother, change

```
scrollPosition.x -= Math.round((dragHelper.x - x) / 28)
scrollPosition.y -= Math.round((dragHelper.y - y) / 28)

```

to

```
scrollPosition.x = Math.round((x - dragHelper.x))
scrollPosition.y = Math.round((y - dragHelper.y))

```

To prevent jumping when first clicking on it, change

```
 dragHelper.x = x
 dragHelper.y = y

```

to

```
 dragHelper.x = x - scrollPosition.x
 dragHelper.y = y - scrollPosition.y

```

And you should be fine.

Not sure why the / 28, did you want it snap to grid?
> 7 votes

---
Tags: html5, isometric, coffeescript
---


# Question
Title: Back to front drawing in an Unorginized array of tiles
I have an Array of tiles in no particular order. How would I do a isometric back to front rendering on it? Do I HAVE to order it?

# Answer
From your comments it seems that you are trying to handle chunks all at once when at any 1 time at most you would only need to handle 8.

```
PPP
PCP
PPP

```

Where C is the current chunk you are on and P is pre-loaded. Now when the user moves into one of the preloaded chunks you generate/reload the chunks the player is heading towards and write the chunks that are now out of range. By using this method your have pretty much unlimited size (I use the term loosely as there is always a hard drive capacity).

This could be expanded to have a varying pre-load range or maybe pre-loading multiple chunks at once.

Here is a step-by-step example of a implementation:

1. On game creation create chunks

(-1,1),(0,1),(1,1)

(-1,0),(0,0),(1,0)

(-1,-1),(0,-1),(1,-1)
2. as the user moves into chunk (0,1) from (0,0) we then store chunks (-1,-1), (0,-1), (1,-1) as files and then generate (-1,2),(0,2),(1,2).

this would go on and on but you get the idea you ensure you only keep a set number of chunks in memory and load/unload the others.

Hope this helps
> 1 votes

# Answer
Depends on what your tiles are.

If they are the tiles from your map (fixed objects or terrain elements) they should already be ordered in a 2D grid. In this case, just run through your array in a defined scheme depending on the orientation of your grid.

If you refer to a bunch of random floating sprites, you will have to sort them. But it might not be that expensive; keep a sorted array of the visible sprites, and simply add or remove sprites as they become visible/invisible. Re-insert sprites that have moved, perform the re-insertion from their current position in the sorted array.
> 3 votes

---
Tags: java, rendering, isometric
---


title: Tessellating to a curve?

text:
# Question
Title: Tessellating to a curve?
I'm creating a game engine, and I'm trying to define a 3D model format I want to use. I haven't come across a format that quite does what I want.

My game engine assumes a shader model 5+ environment. By the time I'm finished with it, that won't be a very unreasonable requirement. Because it assumes such a modern environment, I'm going to try and exploit tessellation.

The most popular way, it seems, to procedurally increase geometry through tessellation is to tessellate to a height map. This works for a lot of things, but has limitations in that height maps still use up VRAM and also only have finite scalability.

So I want to be able to use curves to define what a mesh should tessellate to. The thing is, I have no idea what definition of curves I should use, how I should store it, and how I should tessellate to it. Do I use NURBS curves? Bezier? Hermite?

And once I figure that out, is there an algorithm to determine how the tessellation shader should produce and move vertices to match the curve as closely as possible? Is the infinite scalability and lower memory usage when compared to height maps worth the added computational complexity?

I'm sorry I'm kind if ignorant as to these matters. I just don't know where to start.

# Answer
> 3 votes
One area you might want to look into is CAD programs. They mostly use modelling techniques based on some version of parametric surfaces, curves and solids. The one thing that could be useful is the fact that most CAD programs can export their parametric based models to some sort of mesh based format like STL. There is usually some sort of "resolution" setting for the export that governs how close the mesh approximation of the parametric model will be. I guess those exporters use some version of what you might want, albeit not necessarily suitable for realtime tessellation. Still, it might give you some ideas to start with.

# Answer
> 2 votes
You might want to look into Phong tessellation and PN triangles. The idea with both of these techniques is to start with an ordinary triangle mesh with vertex normals - just as you would build in a standard art pipeline. Smoothed vertex normals fake the appearance of a curved surface, and the goal of both of these techniques is to actually generate a curved surface that matches the normals. This is nice because you can just drop it in and apply it to existing assets, as long as they have entirely smoothed normals.

Of the two, Phong tessellation is simpler and faster; PN triangles use a higher-order interpolation method and might look better in some cases but are more complex and slower.

Both of these methods have problems with cracking along hard edges: the geometry gets displaced differently on either side of the edge. One way to solve this would be to include an additional "tessellation normal" field in the vertex data, which would be globally smoothed. There's some more discussion of this problem in My Tessellation Has Cracks by Bryan Dudash, and a bit more in Deus Ex is in the Details by Matthijs de Smedt.

# Answer
> 1 votes
If you use height map with bicubic filtering, you should get curved look even with a lower resolution bitmap. Besides using just a single-channel height map you can use three-channel displacement map to distort the vertices in any direction, not just along the normal.

---
Tags: beziers, curves, splines, tessellation
---


# Question
Title: Pass a single boolean from an Android App to a libgdx game
I'm writing an Android application that needs to pass a single boolean into an Android game that I am also writing. The idea is that the user does something in the App which will affect how the game operates.

This is tricky with LIBGDX since I need to get the bool value into the Java files of the game, but of course, you can't call Android specific things from within LIBGDX's main Java files. I tried using an intent but of course the same problem persists. I can get the boolean into the MainActivity.Java of the android output of the game, but can't pass it along any further since the android output and the main java files don't know about each other. I have seen a few tutorials that explain how to use set up an interface in the LIBGDX java files that can call android things. This seems like wild overkill for what I want to do.

I've been trying to use Android's Shared Preferences with LIBGDX's Gdx.app.getPreferences, but I can't make it work.

Anyhelp would be MUCH appreciated.

I've set up two hello world applications. One is a standard Android app, with a single button that is supposed to write "true" into the shared preferences. The other is a standard LIBGDX hello world that is supposed to do nothing but check that bool when launched and if true display one image to the screen, if false, display a different one.

Here's the relevant bit of the Android code:

```
import android.preference.PreferenceManager;

 public void onClick(View view) {
    if (view == this.boolButton){

        final String PREF_FILE_NAME = "myBool";
        SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_WORLD_WRITEABLE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("myBool", true);
        editor.commit();
    }
}

```

And here's the relevant bit of the code from the LIBGDX main file:

```
Preferences prefs = Gdx.app.getPreferences("myBool");
    boolean switcher = prefs.getBoolean("myBool");

    if(switcher == true){
        texture = new Texture(Gdx.files.internal("data/worked512.png"));
        prefs.putBoolean("myBool", false);
        }
        else
        {
        texture = new Texture(Gdx.files.internal("data/libgdx.png"));
        }

```

Everything compiles fine, it just doesn't work. I've spent HOURS googling trying to find a way to pass this single boolean from android into a LIBGDX main and I'm totally stumped.

Thanks for your help.

# Answer
Even if the interface thing sounds like overkill, it *will* solve your problem, and is not much work. However, here's another solution: Just pass the value to your game when you create it, no need for the interface.

Example:

```
public class MyLibgdxGame implements ApplicationListener {
    // Or extends Game

    boolean passedInFlag;

    public MyLibgdxGame(boolean flag) {
        this.passedInFlag = flag;
    }

    // rest of the methods
}

```

Then you can use that boolean in your game.

Then you will need to change your starters to pass in a boolean. For Android:

```
public class AndroidStarter extends AndroidApplication {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        boolean myBoolToPass = false;

        AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
        // config stuff

        initialize(new MyLibgdxGame(myBoolToPass), cfg);
  }
}

```

All you do is pass it through a normal constructor.
> 3 votes

# Answer
Try some read firstly: http://code.google.com/p/libgdx-users/wiki/IntegratingAndroidNativeUiElements3TierProjectSetup .
> 0 votes

# Answer
Have you tried using postRunnable?

http://code.google.com/p/libgdx/wiki/ApplicationThreading
> 0 votes

---
Tags: android, libgdx
---


title: C++ unmanaged inside winform

text:
# Question
Title: C++ unmanaged inside winform
First: I am using C# and C++ on windows 7.

I have created a basic rendering engine in c++ with directx 10. It works good as a stand alone application. But, when I sending the Form.Handle of a WinForm I want to render inside to the engine it crashes during D3D10CreateDeviceAndSwapChain with the following error:

```
HRESULT: 0x887a0001 (2289696769)
Name: DXGI_ERROR_INVALID_CALL

```

I get the handle from the winform during loading of the form.

```
unsafe {
  void *ptr=m_view.Handle.ToPointer();
  uint v = (uint)ptr;
  lhandle = v.ToString();
};

```

# Answer
One has to create a **CHILD** to the parent window, not use the parent window handle directly.
> 1 votes

---
Tags: c++, c#, directx10
---


title: PHP city-sim castle layout

text:
# Question
Title: PHP city-sim castle layout
I am currently contemplating the layout system for my php based game but i've run into a couple of worries. So my idea is a 9X9 grid where the center 3X3 are inner castle. The inner castle will be 6X6 if you enter it(click on it). and with the option to expand the inner castle converting one of the 9X9 tiles to a 4X4 inner castle tile. So here is my question: What is the best way to tackle this type of layout? my original idea was a 18X18 grid and saving it in the db as (idCastle, Y, X) where X is a string of 18 numbers long telling me if the tile is an inner/outer tile or a inner/outer building. but i am not really fond of this idea and would like to hear some other ideas on how to tackle this. Thanks in Advance,

Gert

# Answer
> 0 votes
It depends on whether or not information about the outer layer tiles can be deduced from information about the inner layer tiles. If they can, then database normalization suggests to treat information about the outer layer tiles as redundant and only store information about the inner layer tiles. This is how this might work:

```
table tile // only inner tiles are recorded
    id (or use [castleID, x, y] as a composite primary key])
    castleID (int)
    x (tinyint) // on a 18x18 grid
    y (tinyint) // on a 18x18 grid
    content (whatever) // content of the inner tile for castleID at position <x, y>

```

This will result in 18x18 entries for every castle, assuming that you save all non-castle tiles as well. You could also just store castle tiles and assume that if there isn't a record for a given position, the tile is unoccupied. In order to get information about the outer layer tiles, you have to fetch information about the respective inner layer tiles and deduce information about the outer layer from that.

If, on the other hand, information about the outer layer tiles cannot be deduced from their respective inner layer tiles, you have to add another table for the outer layer tiles:

```
table outertile
    id (or use [castleID, x, y] as a composite primary key])
    castleID
    x (tinyint) // on a 9x9 grid
    y (tinyint) // on a 9x9 grid
    content  (whatever) // content of the outer tile for castleID at position <x, y>

```

The content field is just a placeholder for whatever you want to store with respect to your tiles. In actuality, it might be an id of a record in your building table, or several fields like startedBuilding (timestamp), spriteFile (varchar), etc.

---
Tags: mmo, php, simulations
---


title: Animate on tap in XNA (Windows Phone)

text:
# Question
Title: Animate on tap in XNA (Windows Phone)
I'm trying to convert a AS3 game to C# / XNA and I'm looking for a way to animate a sprite.

More precisely, I want the sprite to rotate and scale a bit, then return to its starting position.

In AS3 I just use a tweening library and add a touch listener to the sprite, but I haven't been able to find something like this for XNA. How would you do something like that in C#?
Thanks in advance!

# Answer
I'm under the impression AS3 is a retained-mode API. You create a collection of objects - it draws and manages them for you. XNA, on the other hand, is an immediate-mode API. You are responsible for drawing things each frame, reading inputs each frame, keeping track of time, and so on.

Here is a complete game class to demonstrate what you want. Just paste it over the one in the default template, and add your own texture called "myTexture" to the content project.

```
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        IsMouseVisible = true;
    }

    Texture2D texture;

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        texture = Content.Load<Texture2D>("myTexture");
    }

    bool animating;
    const float totalTime = 1;
    float time;

    MouseState lastMouseState;

    protected override void Update(GameTime gameTime)
    {
        MouseState mouseState = Mouse.GetState();

        if(mouseState.LeftButton == ButtonState.Pressed && lastMouseState.LeftButton == ButtonState.Released)
        {
            time = 0;
            animating = true;
        }
        else if(animating)
        {
            time += (float)gameTime.ElapsedGameTime.TotalSeconds;
            if(time > totalTime)
            {
                time = 0;
                animating = false;
            }
        }

        lastMouseState = mouseState;
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();

        float alpha = time / totalTime; // from 0 to 1
        Vector2 position = new Vector2(GraphicsDevice.Viewport.Width / 2f, GraphicsDevice.Viewport.Height / 2f);
        Vector2 origin = new Vector2(texture.Width / 2f, texture.Height / 2f);
        float rotation = MathHelper.TwoPi* alpha;
        float scale = alpha < 0.5 ? MathHelper.SmoothStep(1, 2, alpha * 2f) : MathHelper.SmoothStep(2, 1, (alpha-0.5f) * 2f);

        spriteBatch.Draw(texture, position, null, Color.White, rotation, origin, scale, SpriteEffects.None, 0);

        spriteBatch.End();
    }
}

```

(I've used `Mouse` here, and tested on Windows, but the code should work on the phone too (where `Mouse` is emulated). It should be easy enough to convert it to use actual touch inputs.)

On the one hand - this is an awful lot more code than you're probably used to. On the other hand - you get a lot more control and performance. Also - if you structure your code nicely and reuse things (admittedly this may take some practice) you can significantly reduce the amount of code you need to write in real-world situations, at least compared to the above.

And you could even go so far as to implement your own retained-mode style classes (eg: your own `Sprite` class). You can do this on top of an immediate-mode API. Whereas it's practically impossible to do the inverse: an immediate-mode style code on a retained-mode API.

(Personally I recommend just embracing the immediate-mode API. Let your own game model retain things - eg: a `Player` object that can draw itself, rather than a `Player` object that owns a `Sprite` object.)
> 1 votes

# Answer
What you're trying to do is not a part of the Microsoft XNA Framework so you have to create this behavior yourself. Here's what I would recommend.

1. First create a `Sprite` class which exposes the properties you need to animate, or simply expose these properties on your game object model classes, such as the `Player`. This is related to the difference between immediate-mode and retained-mode that Andrew talked about, so just pick the way you'd like to work.

public class Sprite { public Vector2 Position { get; set; } public float Rotation { get; set; } public float Scale { get; set; } public Texture2D Texture { get; set; } public void Draw(SpriteBatch spriteBatch); }
2. Instead of managing the animations directly inside your game object model, create an external class that encapsulates and manages all types of animations. You could...

* Try an existing tweening library such as TinyTween and see if it works for you (never used it).
* I like to treat this concept at an even higher level. What I usually do is create a class that can manage *any* sequence of actions, instead of just tweening properties. Then I create specific types of actions for tweening properties if I need it. Check the following answer for such an implementation "How to chain actions/animations together and delay their execution?".

3. Finally, queue the animations on your manager! For example, with the `ProcessQueue` class I wrote about in the other answer, this would be done with something like:

```
 processQueue.Add(new Rotate(23f));
 processQueue.Add(new Scale(1.5f));
 processQueue.Add(new Move(new Vector2(400, 200));

```
> 0 votes

---
Tags: xna, c#, tweening
---


# Question
Title: Efficient way to render tile-based map in Java
Some time ago I posted here because I was having some memory issues with a game I'm working on. That has been pretty much solved thanks to some suggestions here, so I decided to come back with another problem I'm having.

Basically, I feel that too much of the CPU is being used when rendering the map. I have a Core i5-2500 processor and when running the game, the CPU usage is about 35% - and I can't accept that that's just how it has to be.

This is how I'm going about rendering the map:

* I have the X and Y coordinates of the player, so I'm not drawing the whole map, just the visible portion of it;
* The number of visible tiles on screen varies according to the resolution chosen by the player (the CPU usage is 35% here when playing at a resolution of 1440x900);
* If the tile is "empty", I just skip drawing it (this didn't visibly lower the CPU usage, but reduced the drawing time in about 20ms);
* The map is composed of 5 layers - for more details;
* The tiles are 32x32 pixels;

And just to be on the safe side, I'll post the code for drawing the game here, although it's as messy and unreadable as it can be T\_T (I'll try to make it a little readable)

```
private void drawGame(Graphics2D g2d){
    //Width and Height of the visible portion of the map (not of the screen)
    int visionWidht = visibleCols * TILE_SIZE;
    int visionHeight = visibleRows * TILE_SIZE;

    //Since the map can be smaller than the screen, I center it just to be sure
    int xAdjust = (getWidth() - visionWidht) / 2;
    int yAdjust = (getHeight() - visionHeight) / 2;

    //This "deducedX" thing is to move the map a few pixels horizontally, since the player moves by pixels and not full tiles
    int playerDrawX = listOfCharacters.get(0).getX();
    int deducedX = 0;
    if (listOfCharacters.get(0).currentCol() - visibleCols / 2 >= 0) {
        playerDrawX = visibleCols / 2 * TILE_SIZE;
        map_draw_col = listOfCharacters.get(0).currentCol() - visibleCols
                / 2;

        deducedX = listOfCharacters.get(0).getXCol();
    }

    //"deducedY" is the same deal as "deducedX", but vertically
    int playerDrawY = listOfCharacters.get(0).getY();
    int deducedY = 0;
    if (listOfCharacters.get(0).currentRow() - visibleRows / 2 >= 0) {
        playerDrawY = visibleRows / 2 * TILE_SIZE;
        map_draw_row = listOfCharacters.get(0).currentRow() - visibleRows
                / 2;

        deducedY = listOfCharacters.get(0).getYRow();
    }

    int max_cols = visibleCols + map_draw_col;
    if (max_cols >= map.getCols()) {
        max_cols = map.getCols() - 1;
        deducedX = 0;
        map_draw_col = max_cols - visibleCols + 1;
        playerDrawX = listOfCharacters.get(0).getX() - map_draw_col
                * TILE_SIZE;
    }

    int max_rows = visibleRows + map_draw_row;
    if (max_rows >= map.getRows()) {
        max_rows = map.getRows() - 1;
        deducedY = 0;
        map_draw_row = max_rows - visibleRows + 1;
        playerDrawY = listOfCharacters.get(0).getY() - map_draw_row
                * TILE_SIZE;
    }

    //map_draw_row and map_draw_col representes the coordinate of the upper left tile on the screen

    //iterate through all the tiles on screen and draw them - this is what consumes most of the CPU
    for (int col = map_draw_col; col <= max_cols; col++) {
        for (int row = map_draw_row; row <= max_rows; row++) {
            Tile[] tiles = map.getTiles(col, row);
            for(int layer = 0; layer < tiles.length; layer++){
                Tile currentTile = tiles[layer];
                boolean shouldDraw = true;

                //I only draw the tile if it exists and is not empty (id=-1)
                if(currentTile != null && currentTile.getId() >= 0){
                    //The layers above 1 can be draw behing or infront of the player according to where it's standing
                    if(layer > 1 && currentTile.getId() >= 0){
                        if(playerBehind(col, row, layer, listOfCharacters.get(0))){
                                behinds.get(0).add(new int[]{col, row});
                                //the tiles that are infront of the player wont be draw right now
                                shouldDraw = false;
                        }
                    }
                    if(shouldDraw){
                        g2d.drawImage(
                            tiles[layer].getImage(),
                            (col-map_draw_col)*TILE_SIZE - deducedX + xAdjust,
                            (row-map_draw_row)*TILE_SIZE - deducedY + yAdjust,
                            null);
                    }
                }
            }
        }
    }
}

```

There's some more code in this method but nothing relevant to this question.

Basically, the biggest problem is that I iterate over around 5000 tiles (in this specific resolution) 60 times each second.

I thought about rendering the visible portion of the map once and storing it into a BufferedImage and when the player moved move the whole image the same amount but to the opposite side and then drawn the tiles that appeared on the screen, but if I do it like that, I wont be able to have animated tiles (at least I think).

That being said, any suggestions?

# Answer
I'm afraid my answer is to reply with a question: What is slow?

* Is the rendering itself slow (g2d.drawImage)?
* Is playerBehind slow?
* Is iterating over the tiles slow?

Use a profiler like YourKit or (quicker & easier) snip sections of code and re-run.

BTW using "35% of CPU" isn't a useful statistic, especially. Stick to milliseconds so that you can compare optimisations accurately.
> 1 votes

# Answer
You've got an idea to go on with rendering to a single image. If every tile has to be animated, it may not be the best idea, but with just a few you could have large areas using a single in-memory image.

Another way to get some frames is to only render the top tile (which you may already be doing).

Perhaps you could break up tiles into larger sections or "chunks", and only check the ones in chunks that are visible to the player.

I certainly hope you're already drawing tiles of the same type all at once, there's a huge amount of performance to be gained in sprite batching.

EDIT Only draw changes to the screen, for instance only when the player moves over a tile.
> 0 votes

---
Tags: java, rendering, tiles, tilemap, efficiency
---


# Question
Title: Direction of the bullet - how to have something else than left, right, top, bottom
I'm making a simple shooter game using canvas and javascript. The current code can be seen here.

To know which way I want the bullet to be shot, I simply have a `direction` property that can have 4 values (left, right, bottom, top), and I can then calculate the next position of the bullet easily.

However, I'd like to move the bullet to the mouse position, but I don't really see how to do this. How do I calculate the next position? I'm guessing there is some formula to calculate the line between two positions (the player's and the mouse's), but I don't have much idea yet.

So there is no obstacle, but I don't see how to calculate this, and be able have the next position of the bullet at each frame.

# Answer
Your problem doesn't need any path-finding. This is where vectors come in handy. For your example, you would calculate a direction vector (which is the normalized vector pointing from your player to the mouse). Then you increase the position of your sprite by `direction * speed * deltaTime` or (with a fixed timestep) by `direction * distanceToCoverEachUpdate`.

It's also a good idea to perform a check of the remaining distance, so if your sprite is closer to the target node than the current speed, just move the sprite by the remaining distance instead (otherwise the sprite would overshoot the target).

**Update:**

If your libaray/game-engine doesn't come with a vector implementation, you could use something existing, or just work with `x` and `y` values separately.

This would then look like this:

```
// Set the target position
var targetX = mouse.x;
var targetY = mouse.y;

// Get the direction in x and y (delta)
var directionX = targetX - player.x;
var directionY = targetY - player.y;

// Normalize the direction
var len = Math.sqrt(directionX * directionX + directionY * directionY);
directionX /= len;
directionY /= len;

// Set the speed (move 100 pixels per second)
var speed = 100;

// Flag to check if we reached the target
var targetReached = false;

// Your update method with a delta time
// (time passed since last update in seconds)
function update(deltaTime){
    // if we have reached the target, we can exit here
    if(targetReached){
        return;
    }

    // calculate remaining distance
    var dx = targetX - player.x;
    var dy = targetY - player.y;
    var lenSquared = dx * dx + dy * dy;

    // distance to cover in this update
    var distToCover = deltaTime * speed;

    // Check if the remaining distance is smaller than the
    // distance to cover. If yes, set location to target location.
    // Also set the "targetReached" flag to true
    if(lenSquared < distToCover * distToCover){
        player.x = targetX;
        player.y = targetY;
        targetReached = true;
    } else {
        player.x += distToCover * directionX;
        player.y += distToCover * directionY;
    }
};

```
> 3 votes

---
Tags: javascript, path-finding, html-canvas
---


title: How to use music in a simple game?

text:
# Question
Title: How to use music in a simple game?
It's like this: I've got this very simple game in mind, and I happen to be lucky enough to know this guy at my college who is the best musician I've ever met in person who wasn't already on a stage. He writes these beautiful songs on piano, just meandering and mysterious. They'd add so much as background music.

But here's my dilemma: say I record a 5 minute long song from him. How do I use it? Do I set it playing, and then make it start over as soon as it ends? Do I leave a 5 minute period of silence and then start it over again? Or do I find other music and just have continuous music playing? What do other people usually do for this sort of thing?

# Answer
Ideally for a good game, the music changes as the game atmosphere changes. For instance the music becomes more 'intense' during a boss battle or when the last and most powerful wave of enemy units is attacking your base..

Sine you are looking to make a 'very simple game', I'm guessing the music you are aiming for is simple BG music. With simple BG music, you normally wants something that loops forver without the player noticing where the loops ends/starts. Here are some questions:

1.Is that guy the right person for making simple BG game music vs. making cool instrumental music that doesn't necessarily suit your game?

2.Is the music track's ending and or start unobtrusive enough? Will the player notice it if it suddenly ends and or starts over?(taking the player's mind off the game)

3.Did the guy play your game already? Does he have a feel for the game? I think it is more fair towards the musician if he / she could play the game before making the track.

\*You will notice a lot of free games have a very simple, bland music just to avoid awkward silence sort of speak.
> 6 votes

---
Tags: music
---


title: Game Asset Size Over Time

text:
# Question
Title: Game Asset Size Over Time
The size (in bytes) of games have been growing over time. There are probably many factors contributing to this: trailer/cut scene videos being bundled with the game, more and higher-quality audio, multiple levels of detail being used, etc.

What I'd really like to know is how the size of 3D models and textures that games ship with have changed over time. For example, if one were to look at the size of meshes and textures for Quake I (1996), Quake II (1997), Quake III: Arena (1999), Quake 4 (2005), and Enemy Territory: Quake Wars (2007), I'd imagine a steady increase in file size. Does anyone know of a data source for numbers like this?

# Answer
Wasn't able to find any actual study on this so I'll offer my thoughts.

I believe any answer you could get would be kinda relative because model formats and compression have changed a lot over time. Because of that, one 200 poly model in 1996 could be a totally different size than another 200 poly model in that time. Also, you need to take the texture size into consideration. I believe that the texture size over time has grown more than the size of the model itself.

But on top of that, there have been numerous improvements to compression as well. Both, for the models file format and the overall packaging for the models. For my companies work, some of our high poly models, uncompressed, can reach 30 or more meg but once we save it as our preferred compressed format, they drop down to maybe 2-3 meg. You weren't asking for compression but I figured I would still throw it in.

As a test of current model file sizes, I took a 16k poly model (no bones, animation data or texture data) of mine and saved it as various formats that are currently used. However, keep in mind that these formats also save different amounts of information. And for most game companies, they have different standards of what info they want to keep in models so the sizes could be different. This makes it kind of difficult to actually know what the actual models size is without being there for development.

* .fbx = 2.3 Mb
* .dae = 1.7 Mb
* .3ds = 445 kb
* .obj = 856 kb
* .X = 6.2 Mb

As you can see, the same file has drastically different file sizes based on format. I'm not all too sure what standard formats devs were using back in the 90's but I'm fairly sure that they were usually different between companies
> 2 votes

---
Tags: textures, 3d-meshes, assets
---


# Question
Title: How to design the scenarios in a platform game?
I am developing a 3D platform game like Metroid Fusion with XNA. I have many classes for different elements as models, game screens, post-processing and so on. Now I want to start designing the scenarios but I think that the scenarios needed in a platform game are not as conventional.

I am very lost and do not know where to start and how to structure it.

# Answer
Most levels in 3D platformer games are built on a 3D grid. The old Tomb Raider games are very obvious about this. (Press forward and the character moves one square every time, you know you can jump 3 squares if you are running but only 2 if you are standing, etc.)

Even more recent examples, such as Darksiders 2 follow the same idea. The character has a defined set of abilities with regards to how far they can jump and run. The environment is built out of pieces that are relative to those measurements. Fluid animations will hide them.

Another thing to consider is that for the most part, you can simplify the movement paths in your game down to 2D when you are designing it. Consider the ball sections of Metroid Prime, or how most of the time you are moving along a corridor or climbing the side of a wall. You rarely need to turn 90 degrees in the jumping sections of those games. Usually that is reserved for the arena fights.

To make it easier to restrict the player from going off the expected path, newer games often severely restrict movement-enhancing items and abilities. Today, a grappling hook is only useful on specific points deliberately placed in the world. Contrast that to the hookshot in Zelda 64, which can be used on any wooden surface in the game. Other examples include only being able to wall-run or place portals on specific wall textures.

Some tips for designing a platformer/adventure game that can be applied to 2D or 3D:

* Make a list of all the item and movement abiltiy combinations in the game. For each item on the list, brainstorm interesting combinations. Examples: Double-jump + Hookshot, can be used to grapple something extra far away. Hookshot + Glide, grapple up high and glide in any direction.
* When you go to design a room, list all of the items a player is expected to have. Choose a subset of these. You don't want to use everything the player has in every room. Refer to your item combinations list for a set of interesting interactions to use in the room.
* Sketch out how the player is expected to move through the environment in 2D on graph paper. You can add some twists and turns when you build it in 3D later if you need to. For example, if you are climbing around on the walls of a room the 3D version could turn at a corner and keep going.
* Creating a 'theme' for each room can keep things interesting for the player. One room could use a certain item in every possible way. Another could demand a certain item to be used the same way in rapid succession.
* Translate the sketch to your level editor and build the room.
* Play test it. Hand someone else the controls and fraps their play session. Leave the room and then watch the video. It is important to see what they try without you there to provide hints.

Building modular rooms will make it easier for you to replace/cut/rearrange things based on play testing.
> 4 votes

---
Tags: xna, scene-graph, scene
---


title: Explaining Asteroids Movement code

text:
# Question
Title: Explaining Asteroids Movement code
I'm writing an Asteroids Atari clone, and I want to figure out how the AI for the asteroids is done.

I have came across that piece of code, but I can't get what it does 100%

```
if ((float)rand()/(float)RAND_MAX < 0.5) {
        m_Pos.x = -app::getWindowWidth() / 2;
        if ((float)rand()/(float)RAND_MAX < 0.5)
            m_Pos.x = app::getWindowWidth() / 2;
        m_Pos.y = (int) ((float)rand()/(float)RAND_MAX * app::getWindowWidth());
    } else {
        m_Pos.x = (int) ((float)rand()/(float)RAND_MAX * app::getWindowWidth());
        m_Pos.y = -app::getWindowHeight() / 2;
        if (rand() < 0.5)
            m_Pos.y = app::getWindowHeight() / 2;
    }

    m_Vel.x = (float)rand()/(float)RAND_MAX * 2;
    if ((float)rand()/(float)RAND_MAX < 0.5)
    {
        m_Vel.x = -m_Vel.x;
        }

    m_Vel.y =(float)rand()/(float)RAND_MAX * 2;

    if ((float)rand()/(float)RAND_MAX < 0.5)
        m_Vel.y = -m_Vel.y;

```

# Answer
> 6 votes
This looks like code to spawn a new asteroid at the border of a screen. Here's the outline of the code:

```
// returns a random float between 0 and 1
float randFloat() { return rand() / (float)RAND_MAX; }

// set position to a random position on the border of the screen.
if (randFloat() < 0.5)  {
    // SpawnOnLeftOrRightSide
    if (randFloat() < 0.5)
        SpawnOnLeft();
    else
        SpawnOnRight();
}
else {
    // SpawnOnTopOrBottomSide
    if (randFloat() < 0.5)
        SpawnOnTop();
    else
        SpawnOnBottom();
}
// I fixed what I assume is a copy-paste error here. In the original code, 50% of the time velocity.Y will be unchanged.
velocity.X = randFloat() * 4 - 2; // velocity.X ranges from [-2 to 2)
velocity.Y = randFloat() * 4 - 2; // velocity.Y ranges from [-2 to 2)

```

The key point to the SpawnOn\_**_** lines is that the coordinate system is 1-to-1 mapped to the X and Y pixels on the screen, but shifted so that (0,0) is at the center of the screen. This means that (in the case we chose to spawn on either the left or right edge of the screen, if `m_Pos.X` is `-screenWidth/2`, then the asteroid is on the left edge of the screen, and if `m_Pos.X` is `screenWidth/2` then the asteroid is on the right edge. The Y-position is then chosen to be a random distance on that edge.

# Answer
> 2 votes
Well, it's interesting and really bad code. I would not emulate this if that's your intention.

All in all, this code is trying to randomly set the position of `m_Pos` and randomly setting it's velocity `m_Vel`. I assume this would be used for spawning asteroids or other enemies. The only relation it has to movement (as you mention in your title) is the velocities set. There's nothing here that updates position based on velocity or anything like that, so I wouldn't call it movement code.

I'll go through the code line by line.

```
float r = (float)rand()/(float)RAND_MAX;

```

Is not used in the code you provided. However, the equation `(float)rand()/(float)RAND_MAX` is used a lot, and you should know that this produces a float between 0 and 1. References rand() and RAND\_MAX.

```
if ((float)rand()/(float)RAND_MAX < 0.5) {
    m_Pos.x = -app::getWindowWidth() / 2;

```

We'll call this case A. If `(float)rand()/(float)RAND_MAX` is less than `.5` set the `x` position to negative half the window width (off screen I guess?)

```
if ((float)rand()/(float)RAND_MAX < 0.5)
        m_Pos.x = app::getWindowWidth() / 2;

```

Unless a second take on random is less than `.5`, then set the `x` position to the center of the screen.

```
m_Pos.y = (int) ((float)rand()/(float)RAND_MAX * app::getWindowWidth());

```

Set the `y` position to some random position using the window width. Odd.

```
else {
    m_Pos.x = (int) ((float)rand()/(float)RAND_MAX * app::getWindowWidth());
    m_Pos.y = -app::getWindowHeight() / 2;
    if (rand() < 0.5)
        m_Pos.y = app::getWindowHeight() / 2;
}

```

The else for case A. Set the `x` position randomly in the width of the window. Then set the `y` to half way off screen or half way on screen depending on `(rand() < 0.5)` (Which no longer divides by `RAND_MAX` like everywhere else, for an unknown reason. Meaning this is unlikely to result in a value less than `.5`.)

```
m_Vel.x = (float)rand()/(float)RAND_MAX * 2;

```

Set the `x` velocity randomly.

```
if ((float)rand()/(float)RAND_MAX < 0.5)
{
    m_Vel.x = -m_Vel.x;
    m_Vel.y =(float)rand()/(float)RAND_MAX * 2;
}

```

Again, if `(float)rand()/(float)RAND_MAX` is less than `.5`, here negate the x velocity you were using before and set the `y` velocity to some positive random value.

```
if ((float)rand()/(float)RAND_MAX < 0.5)
    m_Vel.y = -m_Vel.y;

```

Finally, negate the `y` velocity if our random value is less than `.5`.

---
Tags: c++, mathematics, ai, game-loop
---


# Question
Title: Getting Center and Radius of Irregural Object
I have drawn an asteroid object manually , and would like to get its center/radius by a specific equation. I think I can get them by calculated and hard-coded values.

The code to draw the asteroid:

```
float ratio = (float)app::getWindowWidth()/app::getWindowHeight();
gl::pushMatrices();

gl::translate(m_Pos*ratio);

gl::scale(m_size*ratio,m_size*ratio);
gl::color(ci::Color(1,1,1));

    gl::drawLine(Vec2f(20,0),Vec2f(80,0));
    gl::drawLine(Vec2f(80,0),Vec2f(100,20));
    gl::drawLine(Vec2f(100,20),Vec2f(100,50));
    gl::drawLine(Vec2f(100,50),Vec2f(60,100));
    gl::drawLine(Vec2f(60,100),Vec2f(40,100));
    gl::drawLine(Vec2f(40,100),Vec2f(50,70));
    gl::drawLine(Vec2f(50,70),Vec2f(25,90));
    gl::drawLine(Vec2f(25,90),Vec2f(0,70));
    gl::drawLine(Vec2f(0,70),Vec2f(20,40));
    gl::drawLine(Vec2f(20,40),Vec2f(0,20));
    gl::drawLine(Vec2f(0,20),Vec2f(20,0));

gl::popMatrices();

gl::pushMatrices();

float radius = getRadius();

Vec2f center = Vec2f(m_Pos.x+50, m_Pos.y+50);

gl::drawStrokedCircle(center*ratio, 10);
gl::popMatrices();

```

}

According to the answer I have written that code to calculate the radius, is it correct or not ?

```
cinder::Vec2f Asteroid::getCenter()
{
    return ci::Vec2f(m_Pos.x, m_Pos.y);
}

double Asteroid::getRadius()
{
    ci::Vec2f  _vec = (getCenter()- Vec2f(15,5));
    return _vec.length()*0.3f;
}

```

# Answer
> 2 votes
To get the center of the extents, take the max and min of both the x and y values, add them together and divide by two.

In your trivial example:

```
XMin = -15
XMax = 15
YMin = -5
YMax = 5

-15 + 15 = 0, 0/2 = 0
-5 + 5 = = 0, 0/2 = 0

```

So obviously the center is at (0,0)

The radius of the bounding circle is the largest distance from the center to a point that makes up the shape.

---
Tags: c++, mathematics
---


# Question
Title: My game engine is done, how can I get ideas of a game to make with it?
I read at many places how people have this GREAT ideas but are not able to program themselves. I have quite the opposite problem. I have developed game engine, level editor, embedded Lua scripting language, I have even made wrapper for Android and it all works well. But I have no good idea about how to proceed with actual levels; I have no good ideas. The engine itself is very generic and can be used in many game concepts, but I just cannot think of anything useful. Do you have any thoughts on how to proceed? Where should I seek ideas? Who should I ask? I am sorry if this question is a duplicate.

EDIT: Thank you all for your responses. I see now in FAQ that indeed my question was misplaced. I just saw this thread and people were advising that ideas are worthless and execution is what counts. So I wondered where all the "worthless" ideas are, because I cannot seem to find any when I need it.

Yes, the engine was targeted at one particular game, but I always envisioned it like "based on game X with additional features". So I added additional features but now I don't know how to use them in a funny and entertaining way. I could still finish the original game X, but it would only be unoriginal copy of the game X, which is just pointless.

Anyway, thanks again for your responses, wish you happy coding.

# Answer
> 7 votes
Go to LudumDare and see games that got a lot of positive attention in previous competitions. Play them and see which ones you like and simply develop on those ideas. Taking ideas from one game is stealing, taking from two or more is research.

# Answer
> 11 votes
Make a snake game with it. Make a shooter game with it. Make some simple well known games to start off. Once you've done this, you should be more confident with your engine, and making these games will give you ideas on where to keep going.

# Answer
> 3 votes
This is one of the classic problems of game engine development - your engine most probably is too generic.

Pick your favorite genre, perhaps even your favorite game - and look at how things work there. Try to copy a thing or two. Make something good, make something bad. Create experiments and problems. Experiments are useful for finding a good direction to take, an unexplored path. Problems have a tendency to keep developers interested for a long time. Pick something you've never done before to make space for both.

# Answer
> 0 votes
Proceeding with levels seems like a good next step, it can teach you how to create data structures to fit your game, and file input/output.

Also, I would just have tried to build the engine with a set target game in mind. You don't have to be very specific, but say just make the engine for a specific genre that you like. When you know what to make with your engine, you have a better idea of what actually works in your engine and what doesn't. A good engine would have been "battle-tested" already, and usable in real-world cases. I have been making a game around sample framework code- as I added more features to it that the game would definitely use, it became clearer which parts can be re-used for future games.

# Answer
> 0 votes
I disagree with @William 'MindWorX' Mariager regarding the nature of the question. It's game design and game programming related and belong here.

@Tomas, you created the egg before the chicken. You want your coding to have a purpose first. This is how project and business works. Most game development team will create the game design (most of it)(like a Game Design Document) before starting the programming of the game.

My studio has the inverse problem. We got a large amount of viable ideas, largely documented, and no game engine, modules or programmers to run/code it. I am even considering learning coding myself instead of waiting for the arrival of a miraculous coder.

I remember my first game idea. I was playing a Zynga game on Facebook and I thought: "The game is okay, but it could be more fun" and then: "I could easily create a better game than this". Shortly after, I started creating it. I suggest you think about what game you could improve (without copying or breaching copyrights) and start focusing on this with your game engine.

Also, try using brainstorm technics to stimulate and generate ideas and innovation.

---
Tags: game-design
---


# Question
Title: Checking collision of bullets and Asteroids
I'm trying to detect collision between two list of bullets and asteroids. The code works fine, but when the bullet intersects with an asteroid, and that bullet passes through another asteroid, the code gives an assertion, and it says about it can't increment the iterator. I'm sure there is a small bug in that code, but I can't find it.

```
for (list<Bullet>::iterator itr_bullet = ship.m_Bullets.begin();
     itr_bullet!=ship.m_Bullets.end();)
{
    for (list<Asteroid>::iterator itr_astroid = asteroids.begin();
         itr_astroid!=asteroids.end();
         itr_astroid++)
    {
        if(checkCollision(itr_bullet->getCenter(),itr_astroid->getCenter(),
           itr_bullet->getRadius(), itr_astroid->getRadius()))
        {
            itr_astroid = asteroids.erase(itr_astroid);
        }
    }
    itr_bullet++;
}

```

# Answer
> 1 votes
The problem is that you're removing an asteroid from the list, and then incrementing the iterator without first checking whether you're already at the end of the list.

The usual approach, when iterating over a container, is to remove the 'increment' step from the for clause, and instead to either do the erase (which implicitly does a safe increment), or else increment inside the code inside the for loop:

```
for (list<Asteroid>::iterator itr_astroid = asteroids.begin(); itr_astroid!=asteroids.end();)
{
    if(checkCollision(itr_bullet->getCenter(),itr_astroid->getCenter(), itr_bullet->getRadius(), itr_astroid->getRadius()))
    {
        itr_astroid = asteroids.erase(itr_astroid);
    }
    else
    {
        itr_asteroid++;
    }
}

```

---
Tags: c++, collision-detection
---


# Question
Title: Wheel rotation, to change velocity of vehicle
I update the velocity of my vehicle like so:

```
[v setVelocity:  ((2 * 3.14 * 100 * (wheel.getRotationValue / 360) / 30)) * gameSpeed]; // update on 60 fps this gets velocity on all frames divide by 60 for 1 frame.

```

This is done in my update method in my world class.

Now `wheel.getRotationValue` returns the rotation value which is worked out like this:

```
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:[touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];

    if (CGRectContainsPoint(wheel.boundingBox, location))
    {
        CGPoint firstLocation = [touch previousLocationInView:[touch view]];
        CGPoint location = [touch locationInView:[touch view]];

        CGPoint touchingPoint = [[CCDirector sharedDirector] convertToGL:location];
        CGPoint firstTouchingPoint = [[CCDirector sharedDirector] convertToGL:firstLocation];

        CGPoint firstVector = ccpSub(firstTouchingPoint, wheel.position);
        CGFloat firstRotateAngle = -ccpToAngle(firstVector);
        CGFloat previousTouch = CC_RADIANS_TO_DEGREES(firstRotateAngle);

        CGPoint vector = ccpSub(touchingPoint, wheel.position);
        CGFloat rotateAngle = -ccpToAngle(vector);
        CGFloat currentTouch = CC_RADIANS_TO_DEGREES(rotateAngle);

        float limit = 0.5;
        rotationValue += (currentTouch - previousTouch) * limit;
    }

    touching = YES;
}

```

Say I steer the vehicle to the far right of the screen, and want to move it to the far left, It wont start moving to the left of the screen until the rotationValue is past 0 degrees again (the wheel is in its center posistion) and is dragged past this value.

Is there anyway to change the code I have above, so that movement on the wheel is recognised instantly and updates the velocity of v instantly too?

# Answer
> 3 votes
When you detect the absence of a touch (I'll leave that to you), reset your rotation value to 0. Then any further change left will go left, etc.

If you want to do this when the user is continuously touching the interface, I think your question represents bad control design. If the user, even for an instant, moves their finger in a direction away from the direction they are currently turning, they begin turning in the opposite direction? That would be a horrible way to drive the car. If you could somehow prevent it from being erratic (which I think you could not), it would still be highly counterintuitive. Don't do that.

---
Tags: iphone, cocos2d-iphone, cocos2d, objective-c
---


# Question
Title: How would I create an HLSL effect like an animated "working" image?
I want to create the effect in the image in HLSL specifically get a block of pixels to move from a specified start point to an end point, so that it can go across the entire screen, but I don't have a clue where to start. Could someone please point me in the general direction ?

This is the effect I want to replicate

This is the image I will be working with

# Answer
You can create that effect by changing the texture coords you use to draw a special image. No need for special shaders (but you can use them too if you want) or even render targets. You will need to change that image though because it's not good for the effect you want to achieve.

Example (bad ASCII art):

```
Full image: |-----***$***----|
Initial drawing of texture with coords (0;0) to (0.5;1): |-----***|
Add 1/16 to texcoord X values: |----***$|
Add 1/16 again: |--***$*|
...

```

Remember that you must use the "wrap" texture repeat mode for this to work (the other option is to stitch sprites together and move them, but that's a lot harder to do).
> 2 votes

# Answer
First off, I think a pixel shader is overkill for what you have described. Using an animated sprite and drawing that on top of your scene is probably the way to go.

However, if you need to apply a full-screen pixel shader effect to your scene, this is the basic series of steps that you can research and perform:

1. Create a `RenderTarget2D`.
2. Set the `GraphicsDevice` to your new render target.
3. Render your existing scene as normal, which will put it on the render target instead of the back buffer.
4. Set the `GraphicsDevice` render target to the back buffer by setting it to `null`.
5. Create a custom pixel shader.
6. Using the `RenderTarget2D` as your source texture, and the pixel shader as your effect and `SpriteBatch.Draw` the render target to your back buffer.

Now, as for the pixel shader itself, you will need to pass in a parameter that is controlled by your update method. This will control where you are highlighting the texture. You could also pass in another texture to multiply your scene by, etc.

Example code:

http://create.msdn.com/en-US/education/catalog/sample/sprite\_effects
> 1 votes

---
Tags: xna, hlsl
---


title: Create a Texture2D from larger image

text:
# Question
Title: Create a Texture2D from larger image
I am having trouble with the basic logic of this solution: Xna: Splitting one large texture into an array of smaller textures in respect to my specific problem (specifically, I'm looking at the second answer.)

**How can I use my source rectangle that I already use for drawing to create a new Texture2D?**

```
spriteBatch.Draw(CurrentMap.CollisionSet, currentMap.CellScreenRectangle(x, y),
      CurrentMap.TileSourceRectangle(currentMap.MapCells[x, y].TileDepths[4]),
      Color.FromNonPremultiplied(0,0,0, 45), 0.0f, Vector2.Zero, SpriteEffects.None, 0.91f);

```

I know I want a method that I started so:

```
//In Update Method of say the player's character.

Texture2D CollisionTexture = ExtractTexture(MapManager.CurrentMap.CollisionSet, MapManager.TileWidth, MapManager.TileHeight);

// In MapManager Class who knows everything about tiles that make up a level.
    public Texture2D ExtractTexture(Texture2D original, int partWidth, int partheight, MapTile mapCell)
            {
                var dataPerPart = partWidth * partheight;
                Color[] originalPixelData = new Color[original.Width * original.Height];
                original.GetData<Color>(originalPixelData);
                Color[] newTextureData = new Color[dataPerPart];
                original.GetData<Color>(0, CurrentMap.TileSourceRectangle(mapCell.TileDepths[4]), originalPixelData,  0, originalPixelData.Count());
                Texture2D outTexture = new Texture2D(original.GraphicsDevice, partWidth, partheight);
            }

```

I think the problem is I'm just not understanding the overload of Texture2D.GetData\<\>

Part of my concern is creating an array of the whole texture in the first place. Can I target the original texture and create an array of colors for copying based on what I already get from the method TileSourceRecatangle(int)?

# Answer
Here's the code you need:

```
Texture2D originalTexture = Content.Load<Texture2D>("myTexture");
Rectangle sourceRectangle = new Rectangle(10, 10, originalTexture.Width - 20, originalTexture.Height - 20);

Texture2D cropTexture = new Texture2D(GraphicsDevice, sourceRectangle.Width, sourceRectangle.Height);
Color[] data = new Color[sourceRectangle.Width * sourceRectangle.Height];
originalTexture.GetData(0, sourceRectangle, data, 0, data.Length);
cropTexture.SetData(data);

```
> 7 votes

# Answer
You'll want to use RenderTarget2D, which are convertible with Texture2Ds (that's probably not the proper way of saying it). This uses the graphics device to create your new texture instead of the more expensive pixel copy, and is quite simple.

You'll want to

1. Create

```
RenderTarget2D newTarget = new RenderTarget2D(GraphicsDevice, partWidth, partHeight)

```
2. Set

```
GraphicsDevice.SetRenderTarget(newTarget);

```
3. Draw

```
SpriteBatch.Draw(original, Vector2.Zero, partSourceRectangle, <... other options you want ...>);

```
4. Reset

```
GraphicsDevice.SetRenderTarget(null);

```

(this gets you back to drawing to the backbuffer instead of your temporary target)
5. Convert

```
Texture2D newTexture = (Texture2D)newTarget;

```

(I believe the conversion is necessary so that the target is not automatically disposed of; render targets are meant to be temporary)

To summarize what I did: I set the draw target of the GraphicsDevice to a custom target which I created with the dimensions of the new texture. I then drew the new texture onto that target. Then I reset the GraphicsDevice so we are back to drawing to the screen. I then converted the render target into a more permanent texture.

Note that this will interrupt any drawing you are in the process of doing, so I wouldn't call this in the middle of a SpriteBatch run.

Also, I don't have VS open so I can't verify any of this, I'm going by memory. If anyone else has comments on the technique or syntax, feel free to edit or correct in comments.
> 0 votes

---
Tags: xna, c#
---


title: Creating multiple fixtures in one body

text:
# Question
Title: Creating multiple fixtures in one body
I want to create this type of fixture in one body. Here square and circle both are different fixtures but attach to one body. How do I do this?

# Answer
> 1 votes
I'm not sure how this is done specifically in Objective-C, but in normal C++ Box2D you just need to call the method createFixture("Fixture") on the body two times, one with the characteristics of the square, and another with the circle. See the manual in http://www.box2d.org/manual.html#\_Toc258082972.

---
Tags: cocos2d-iphone, box2d
---