# Question
Title: Dungeon Generation with no corridors and room dependencies
I'm making a game with a procedurally generated world created at the beginning of the game, consisting of several areas represented by grids (say, 8x8, 9x6, the sizes would ideally be arbitrary). These areas are supposed to be connected to each other through a dependency list.

A connection exists when at least 3 spaces of that grid are exposed between those two areas. In the middle cell of that 3 space connection area is the doorway between areas:

I've been trying to figure out a way to connect them, but it becomes increasingly complex the more areas you need to consider at the same time.

I've tried some paper prototyping and while it's a very simple process when doing it visually, I haven't found out a good set of mathematical expressions that allows me to place rooms with the same efficiency by code.

Here's a "simple" example I'm struggling with right now:

* Area 'a' needs to be connected to 'b' and 'c'
* Area 'b' needs to be connected to 'a' and 'd'
* Area 'c' needs to be connected to 'a' and 'd'
* Area 'd' needs to be connected to 'b' and 'c'

Consider, for simplicity, we're placing the rooms by their order of appearance on the list (I've tried others). So I'm approaching this as your standard procedural Dungeon Generation algorithm.

We place 'a' anywhere on the board, since it's the first area. Next, we pick a wall at random and, since nothing is connected to that wall, we can place 'b' there:

Now we need to place 'c', but 'a' is already on the board, and has an occupied wall, so we decide to put it on another wall. But not every placement will do, because 'd' is coming up and it needs to be connected to 'b' and 'c' too:

I tried a possible limitation that 2 rooms that have the same set of dependencies cannot be on opposite walls, but even that doesn't guarantee success:

And in other cases, where the areas have different sizes, being on opposite walls can work:

Also, not considering a used wall is a flawed assumption since it rules out valid solutions:

I've tried looking up research on other Procedural Generation algorithms or similar, such as Optimal Rectangle Packing and Graph Layout algorithms, but usually those algorithms don't take into account every constraint of this problem and are hard to mix together.

I thought about a bunch of approaches, including placing an area and backtrack until a suitable placement is found, but they seem very dependent on trial and error and costly in terms of computation. But, given the extensive research on the last two problems I mentioned, it might be the only/best solution?

I just wanted to see if someone has had similar problems in the past or is willing to help me figure this out and give me a few pointers on where I should start with the algorithm. Or, failing that, I'll have to look into loosening the constraints I've set.

# Answer
This is a cool problem. I believe it can be solved using action planning in the space of room placements.

Define the **State** of the world as follows:

```
//State:
//    A list of room states.
//    Room state:
//      - Does room exist?
//      - Where is room's location?
//      - What is the room's size?

```

Define a **Constraint** as:

```
 // Constraint(<1>, <2>):
 //  - If room <1> and <2> exist, Room <1> is adjacent to Room <2>

```

Where "adjacent" is as you described (sharing at least 3 neighbors)

A **Constraint** is said to be *invalidated* whenever the two rooms are *not* adjacent, and both rooms exist.

Define a **State** to be *valid* when:

```
// foreach Constraint:
//        The Constraint is "not invalidated".
// foreach Room:
//       The room does not intersect another room.

```

Define an **Action** as a placement of a room, given a current State. The **Action** is *valid* whenever the resulting state from the action is valid. Therefore, we can generate a list of actions for each state:

```
// Returns a list of valid actions from the current state
function List<Action> GetValidActions(State current, List<Constraint> constraints):
    List<Action> actions = new List<Action>();
    // For each non-existent room..
    foreach Room room in current.Rooms:
        if(!room.Exists)
            // Try to put it at every possible location
            foreach Position position in Dungeon:
                 State next = current.PlaceRoom(room, position)
                 // If the next state is valid, we add that action to the list.
                 if(next.IsValid(constraints))
                     actions.Add(new Action(room, position));

```

Now, what you're left with is a **graph**, where **States** are nodes, and **Actions** are links. The goal is to find a **State** which is *both* valid, *and* all of the rooms have been placed. We can find a valid placement by searching through the graph in an arbitrary way, perhaps using a depth-first search. The search will look something like this:

```
// Given a start state (with all rooms set to *not exist*), and a set of
// constraints, finds a valid end state where all the constraints are met,
// using a depth-first search.
// Notice that this gives you the power to pre-define the starting conditions
// of the search, to for instance define some key areas of your dungeon by hand.
function State GetFinalState(State start, List<Constraint> constraints)
    Stack<State> stateStack = new Stack<State>();
    State current = start;
    stateStack.push(start);
    while not stateStack.IsEmpty():
        current = stateStack.pop();
        // Consider a new state to expand from.
        if not current.checked:
            current.checked = true;
            // If the state meets all the constraints, we found a solution!
            if(current.IsValid(constraints) and current.AllRoomsExist()):
                return current;

            // Otherwise, get all the valid actions
            List<Action> actions = GetValidActions(current, constraints);

            // Add the resulting state to the stack.
            foreach Action action in actions:
                State next = current.PlaceRoom(action.room, action.position);
                stateStack.push(next);

    // If the stack is completely empty, there is no solution!
    return NO_SOLUTION;

```

Now the *quality* of the dungeon generated will depend on the order in which rooms and actions are considered. You can get interesting and different results probably by just randomly permuting the actions you take at each stage, thereby doing a *random walk* through the state-action graph. The search efficiency will greatly depend on how quickly you can reject invalid states. It may help to *generate* valid states from the constraints whenever you want to find valid actions.
> 6 votes

# Answer
Your generation priorities are in conflict. When generating levels, your first goal should be a web of planar (non-overlapping), connected *points*, irrespective of scale. Then proceed to create rooms from the points within that web. Creating room shapes first is a mistake, generally speaking. Create connectivity first, and then see what room forms can be accommodated within that.

**General Algorithm**

1. Create a quantised floor grid of sufficient size to support your level, using a 2D array or image.
2. Scatter points at random across this empty floor space. You can use a plain random check on each tile to see whether it gets a point, or use standard / Gaussian distribution to scatter points. Assign a unique colour / numeric value to each and every point. These are IDs. (P.S. If after this step you feel you need to scale your space up, by all means, do.)
3. For each such generated point, in sequence, incrementally grow a bounds circle or bounds rectangle out by a single step (typically a rate of 0.5-1.0 cells/pixels per step) in `x` and `y`. You can either grow all bounds in parallel, all starting from size zero at the same step, or you can start growing them at different times and at different rates, giving bias to the size of those that start earlier (imagine seedlings growing, where some start late). By "grow" I mean fill in the newly-incremented bounds with the colour / ID unique to the starting point for those bounds. A metaphor for this would be holding marker pens against the back of a piece of paper, and watching inkblots of different colours grow, until they meet.
4. At some point the bounds of some point and another point are going to collide, during the grow step. This is the point at which you should stop growing the bounds for those two points -- at least in the uniform sense described in step 3.
5. Once you've grown all points' bounds as far as possible and stopped all growth processes, you will have a map that should be largely, but not entirely filled. You may now want to pack up those empty space, which I will assume to be white, as if colouring in a sheet of paper.

**Post-process Space-filling**

A variety of techniques can be used to fill in the empty / white spaces that remain, per step 5:

* Have a single neighbouring, already-coloured area claim the space, by flood filling it that colour so it all joins up.
* Flood with new, as-yet-unused colours / numbers / IDs, such that they form entirely new areas.
* Round robin approach such that each already-filled neighbouring area "grows" a little bit into the empty space. Think of animals drinking around a watering hole: they all get some of the water.
* Don't totally fill the empty space, just cross it to link up existing areas using straight passages.

**Perturbation**

As a final step to make things look more organic, you could do edge-perturbation in varying degrees, on the edges cells of areas. Just be sure not to block crucial movement routes.

**Theory, for Interest's Sake**

This is similar to the approach taken in Voronoi Diagrams / Delaunay Triangulation, except that in the above you are not explicitly creating edges -- instead, when bounding areas collide, growth ceases. You will notice that Voronoi Diagrams are space-filling; this is because they do not cease growth merely on touching, but rather on some nominal degree of overlap. You could try similar.
> 7 votes

---
Tags: procedural-generation
---


# Question
Title: Affine transformation: rotate a plane parallel to another plane
I am writing a function that extrudes a 2D shape along a 3D spline, as found in 3D modeling software.

I need a way of translating a set of points P so that they all lie in a new plane L (preserving distances between points).

* P is all points where Z = 0;
* L is defined by (0,0,0), with the normal vector N.

I am using Processing, it has common matrix and vector functionality (but no quaternions) A conceptual or pseudo-code answer is OK.

# Answer
> 1 votes
> I need a way of translating a set of points P

I suppose you mean *rotating* here?

Let `Z = (0,0,1)`. If `cross(N,Z)` has length 0, it means that all your points already lie in the desired plane. Otherwise we can build a basis of the target plane:

* `U = normalize(cross(N,Z))`
* `V = cross(N,U)`

Now to transform a point `P = (x,y,0)` so that it lies in your target plane, simply do this:

```
P2 = x * U + y * V

```

---
Tags: mathematics, rotation
---


# Question
Title: Is 50KBs of bandwidth practical for players?
For my client-server lockstep 16-player RTS game, I've calculated the maximum bandwidth usage per second to be 50KBs for hosting a game (though this value is closer to 20KBs practically). ~90% of this bandwidth usage is due to sending out packets and the rest, incoming packets.

To cut down on costs, I'd like to have players host games and official servers function in the background as backups (in case the player host drops). Is it reasonable to expect 1 in every 16 players is able to handle this bandwidth demand?

Note: The game will be on PC.

# Answer
> 1 votes
It depends a lot on what minimum requirements you want to have for your game, the worst case scenario would be dial-up modems, unfortunately they can only handle 33.6 kbit/s or 4.2kB/s in upload speed (they could still probably play the game as a non-host however).

Looking at the state of internet report from Akami Technologies you can see that the average speed in the world is 3.9Mbit/s or 487kB/s. Keep in mind that upload is usually much lower than download though, 10% is a good rule of thumb, which would put the world average at just underneath 49kB/s. If your requirement is only 1/16 having high enough upload speed then you would on average have 7-8 players that can act as a host.

But most likely people who are interested in an online game will have higher than usual bandwidth and/or come from countries with better internet speeds, so in reality you will probably find that nearly all players will be able to act as hosts with those requirements.

# Answer
> 1 votes
50'000 bytes per second is absolutely reasonable for PC game.

You might have issues with number of packets though, knowing RTS games design, you should wrap packets in bundles (as discussed in your previous questions).

---
Tags: multiplayer, server, hosting
---


title: unity destroy enemy when jumping on it

text:
# Question
Title: unity destroy enemy when jumping on it
I am creating a 2D platformer using Unity3D, I want to have the player destroy enemies when it jumps/falls over them (just from the top). But I have been having problems trying to implement this. I stripped everything and used two simple box colliders in order to make it easy. So, when `onCollisionEnter2D` is called I get the bounds of the objects colliding like this:

```
    Bounds playerBounds = new Bounds(transform.position, collider2D.bounds);
    Bounds collisionBounds = new Bounds(collision.transform.position, collision.collider.bounds);

```

Then I check if the object colliding is below by comparing it's bounds:

```
    //If the player's lowest point is greater than the
    //colliding object's highest, then it is above it
    bool isAbove = playerBounds.min.y >= collisionBounds.max.y;

```

Then I check if the object is actually an enemy, and if so, I destroy it:

```
    if(isAbove)
    {
        if(collision.gameObject.tag == "Enemy")
        {
            collsion.gameObject.getComponent<EnemyController>().die();
        }
    }

```

Now the thing is this never happens, `isAbove` is never true, so I tried checking the heights of each object so I use

```
    Debug.Log("player : "  + playerBounds.min.y + " enemy : " + collisionBounds.max.y)

```

It says the player bottom-most is below the enemy top-most. Since I use this same method to detect if the player is grounded in order to enable jumping I noticed it works beautifully with other things like platforms but not with enemies. Also y used `Debug.break` to stop the game and noticed that when colliding with platforms the player's collider was always above the platform's, but when it collided with enemies they overlap: so the player's bottom-most part is below the enemy's top-most part. I read somewhere that this is due to the `minPenetrationPenalty` property, I didn't like the results of messing with it so I just left it the same (If I lower it doesn't even work with platforms, and I increase it they don't even touch and the collision is detected). I tried to compensate for this penetration when checking the bounds so I said:

```
    bool isAbove = playerBounds.min.y >= collisionBounds.max.y - 0.01;

```

It sometimes fails and sometimes not depending on the angle and other stuff, I still don't get it because if this was the problem It shouldn't work with the platforms either but it does, it only fails with enemy. I even tried to check for the overlap and said:

```
    float overlap = playerBounds.min.y - collisionBounds.max.y;

    bool isAbove = overlap > -0.01;

```

this still works beautifully with platforms only reporting positive values (which means they are not overlapping), but with enemies it actually reports negative values (which confirms the previous: they do overlap), even more strange it actually reports overlaps greater than what should be allowed, the usually report a `-0.09` which means a 0.09 overlap which is greater than the 0.01 that the physics engine is supposed to allow.

If I apply this code in `OnCollisionStay2D` instead it works, I guess by this time the overlap is fixed, but this looks unnatural and I still don't understand why this works perfectly with platforms (they never even overlap!) and not my enemies.

# Answer
I haven't used unity, but most likely your terrain is using a different collision type, such as static terrain.

Unity is probably finding the correct contact point for these, whereas for two dynamic collision boxes (player, monster) it isn't trying so hard to keep them from overlapping since you're likely to implement some sort of damaging mechanic.

You would have to compare the player vs the monster with that in mind, by for instance adding a scaling factor `playerBounds.min.y >= collisionBounds.max.y * 0.8f`

A better option might be to calculate the normal between the player and the enemy and then calculate the angle from the up vector, in pseudo code:

```
normal = (playerBounds.center - collisionBounds.center).normalize();
if (normal.dot(UpVector) < cos(Pi/4))
  killEnemy();

```

Edit: A normal is simply a vector with a length of 1, to convert any arbitrary vector (except for 0,0,0 which is undefined) to a normal you simply divide it with it's length `(x,y,z) / sqrt(x*x + y*y + z*z)`

It's useful to us in this case because you can calculate the angle between two unit vectors using the dot product between two vectors, in the code example I gave I check if the angle is less than 45 degrees.

In your game you might want to change this slightly, for an enemy that is as wide as it is tall 45 degrees is good, but for a taller one you would need a smaller angle or it will accept if your characters legs hit the side of the head.

The accuracy of the normal will be more than enough for calculating the angle in this case.

However, since your colliding with boxes it can still happen that you get a detected collision without the characters visually touching, simply by having two corners of the boxes touching while neither head nor feet are near the corners.

You can fix this by making collision boxes for each bodypart and check with these after the initial boxes collide (in which case you can check if the feet of your character is colliding with the head/shoulders of the enemy instead of checking the angle).

Another, much more difficult option, is SAT or GJK algorithms to detect the point of impact, but for this you have to split your objects into concave subsections and if your doing that you could just as easily fix bounding boxes for each bodypart instead. You would only really need to use these algorithms if you need to calculate the exact point of impact (so that the objects can change their rotation in a space game for instance).
> 1 votes

# Answer
Another solution would be to add another collisionbox ontop of the enemy that is onTrigger, when it's triggered push the player up a bit and destroy the enemy.
> 1 votes

# Answer
Use Physics2D.Raycast http://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html on your enemies and then check if your player hits the enemies raycast that's on top of the enemy.

Cheers, Demetry :)
> 0 votes

---
Tags: unity, collision-detection, platformer
---


title: Question about where to put a method

text:
# Question
Title: Question about where to put a method
I'm working on a tower defense game as a class project and i got it to a kinda working level(creep spawns, towers can shoot etc), but i have a problem with my classes.

Currently the towers shoot but there's no bullets, i'm using an ArrayList to store bullets.

Where should the ArrayList be, on the Game class(manages all the logic) or on the tower class?

# Answer
I think you shouldn't put bullets into a tower class. If you store bullets in the tower class you'll not be able to destroy tower when some bullets in way to the target. For example, if you have rocket launcher with slow rockets, it would be hard to sell it, because in any moment of game some rocket will be on the way. So, ArrayList (or special class called like BulletsManager) is better. If you need to handle relationship between bullet and tower just save pointer to a tower in bullet's instance.
> 1 votes

# Answer
The tower class should probably inherit a bigger class that manages bullets, weapons and the sort. That being said, it's a fairly simple game, so from the limited information you've provided, I'd say put it in the tower class so you can do `Tower.Shoot()` -- neat and logical.
> 1 votes

---
Tags: c#, sdl
---


title: Rotating an object with quaternion

text:
# Question
Title: Rotating an object with quaternion
I have a question in regards to using quaternions for the rotation of my graphics object.

I have a `Transform` class which has the following constructor with default parameters:

```
Transform(const glm::vec3& pos = glm::vec3(0.0), const glm::quat& rot = glm::quat(1.0, 0.0, 0.0, 0.0),
    const glm::vec3& scale = glm::vec3(1.0))
{
    m_pos = pos;
    m_rot = rot;
    m_scale = scale;
}

```

In my `Transform` class calculate the `MVP` as follows:

```
glm::mat4 Transform::GetModelMatrix() const
{
    glm::mat4 translate = glm::translate(glm::mat4(1.0), m_pos);
    glm::mat4 rotate = glm::mat4_cast(m_rot);
    glm::mat4 scale = glm::scale(glm::mat4(1.0), m_scale);

    return translate * rotate * scale;
}

```

The issue I'm facing is that when I use `const glm::quat& rot = glm::quat(1.0, 0.0, 0.0, 0.0)` my object appears normal on screen. The following image shows it:

However if I try to use for example `const glm::quat& rot = glm::quat(glm::radians(90.0f), 0.0, 1.0, 0.0)` (rotating on y axis by 90 degrees) my object appears as if it has been scaled. The following image shows it:

I can't figure out what is causing it to become like this when I try to rotate it. Am I missing something important?

If it's of any relevance, the following is how I calculate my view matrix:

```
glm::mat4 Camera::GetView() const
{
    glm::mat4 view = glm::lookAt(m_pos, m_pos + m_forward, m_up);

    return view;
}

```

# Answer
the `glm::quat(float, float, float, float);` constructor doesn't do what you think it does. It sets the values directly.

The values of the quaternion `(w, x, y, z)` are in order: the cosine of half the angle, the sine of half the angle times the x coordinate of the normalized rotation axis, and the same for the y and z components.

So instead you want to use `glm::quat(cos(glm::radians(90.0f/2)),0,sin(glm::radians(90.0f/2))*1,0);` or after inlining the result of the trig: `glm::quat(sqrt(1/2),0,sqrt(1/2),0);`
> 4 votes

# Answer
You should probably use `glm::angleAxis()` (documentation here):

```
glm::quat rot = glm::angleAxis(glm::radians(90.f), glm::vec3(0.f, 1.f, 0.f));

```
> 14 votes

---
Tags: opengl, rotation, quaternion, glm
---


# Question
Title: Camera movement constrained to pixel boundaries
So a friend and me, we are currently making a game in C# using XNA. We are trying to get the camera to move in full pixel motion, but we just don't get it right. This concept is hard to explain, but i'll try to make it as clear as possible with this gif.

As you can see, on the left hand side the black pixel moving in full pixel motion, while the right pixel is moving in free motion. Full pixel motion is basic motion in native resolution, but when we scale things up, the second case occurs. We are trying to avoid this, while making the camera as smooth as possible, with acceleration, deceleration, etc. The Cave Story cameras is the perfect example for this. Any ideas? Thanks for the help in advance.

P.D: please forgive any spelling or gramatical errors, English is not my native language.

# Answer
> 1 votes
Did this image demonstrates your problem?

Left image not scaled, right have scalet by 2. Visual pixels become like a half of real pixels. *If I understand you correct* you can draw image without any scale to the render target and then it draw it to required scale, better to integer value to avoid any artifacts.

In other way if you mean that you want measure all values in independent units so do it. I'm using 1 unit = 8 pixels, couse 8 pixels im size of my tiles. If I want to draw something I just divide all values like position, offset and other to 8 (better use constant like PIXELS\_PER\_UNIT = 8 or whatever). No measures in pixels - only in units. My tile is 8x8 pixels, so it represents like 1x1 unit; hero (my avatar) is 16x16, so it will be 2x2. Just keep proportions to avoid distortions.

---
Tags: xna, camera
---


# Question
Title: OpenGL/GLSL/LWJGL return value from shader
I'm trying to do some bone animation. I don't want the whole skeleton to be loaded to the GLSL shader every time, even tough it's not needed, because one vertex is parented to one bone, not more. My question is simple: (How) can i return some value from the vertex shader back to my code? I'm using LWJGL/Java

# Answer
> 3 votes
You can use a Transform Feedback Buffer to output from your vertex shader, your question is not very specific though so I can't be sure if this is truly what you want to do.

---
Tags: shaders, glsl, lwjgl
---


# Question
Title: SFML - How do I create an OpenGL context before showing the window?
I want to create an OpenGL context to initialize some assets before actually showing the window with SFML. How can I do this?

# Answer
> 1 votes
```
sf::Context context;

```

creates a valid OpenGL context.

You can find more info in the official tutorial or the documentation.

---
Tags: opengl, windows, sfml, assets
---


title: Network tilebased game updates design

text:
# Question
Title: Network tilebased game updates design
I have a top/down grid based multi-player game. So I have a 2D array on the server that holds the entire map and a much smaller 2D array on the client that holds only what the client needs to see of the bigger server map. For now we'll say the client 2D is 5x5 but the server is 400x400.

When the player starts, the server see's what tile it's on and gets the 5x5 area around the player (with the player being at the center of that) and sends the tile info to them. The client then updates their 5x5 array and draws the objects in the tiles. This is all great and working.

Now, when the player moves I want to basically always keep the 5x5 array updating around them, loading and unloading the objects in those tiles from the server. Now in reality it'll be bigger than 5x5 but I'm using this for testing purposes only since it's smaller to manage.

I don't want to always send the 5x5 array (will be larger in final version) to the player because it's a waste of bandwidth to do so. If the player moves right 1 tile then the majority of the information in their 5x5 array is still the same. Really it's only the right most column that changed and needs to be updated while every other column gets shifted 1 to the left. The same happens if they move up, down, left, or any of the diagonals.

The question I'm after would be around how the server can track and easily send just the changes of tiles for clients. So on the server I send tile updates once a second, NOT when they tell me they changed tiles. When I send them data I store their current position as last position, so this means I can get the 5x5 array from their last position (which this is what their 5x5 array looks like) and I can get the new 5x5 array from their current position. I the need to know what changed from the last position 5x5 array to this new 5x5 array and only send them those changes along with how to shift their 5x5 array around to match this new 5x5 array. **Is there any neat tricks out there for comparing 2 2D arrays to find out such information? Does anyone have any other ideas on how to handle this situation? I'm open to new ideas around this.**

# Answer
> 1 votes
Correct me if I am wrong, but you have 2 issues here.

First issue is how to implement minimal update from server to client. When the player moves, you only want to send the new tile, and not the whole area.

Second is how to implement minimal update from client to server. It sounds like, while playing, the player can dirty up the play area, so the server needs to be aware of these changes. So, the question is, how do you send only the changes and not the whole play area.

Regarding the first issue, I would try using linked lists on the client side to store the map data. You can set up 2d linked lists to represent the play area. With linked list you can have tail and head insertions. This will allow you to add and remove whole rows at a time. So, you can set up 5 linked list to store each row, and have an outer linked list that holds all of the row lists. This will make vertical movement simple. The server sends only the new row and it gets inserted at either the head or the tail of the outer linked list, and the opposite end gets removed. Left and right movement will be a bit more tedious, but is done in much the same way. The server sends the new column data, and each row list will insert their tile at either the head or the tail, and the opposite end gets removed. The down side of using linked list vs arrays is the lose of random access. If traversing the map becomes to cumbersome, then I would consider adding a second "view" of the map data. Have the server update the linked list version of the play area. Every time that gets updated, recreate a 2d array view. At this point it should be business as usual for you.

In regards to the second issue, I would make each tile responsible for knowing when it changes. Keep track of all changed tiles, then only update those select tiles.

---
Tags: tilemap
---


# Question
Title: How can this kind of entity/component organization improve cache efficiency?
I've been reading up about entity component systems as a design pattern for an OpenGL engine. The style I'm trying to implement has entities only being integers, and components being long contiguous arrays of, for example `glm::vec3` for a world-position component.

The entity integers then work as indices into those arrays. All of this described best by this post.

As I understand, the main benefits of an ECS would include:

* Simplification and elimination of unnecessary dependencies and spaghetti code
* Performance boost: contiguous component arrays translate into fewer cache misses and an overall de-bloating of complex inheritance

While I do agree with the first point, I don't understand how the second could be true.

On a regular draw call, you'd need almost always the majority of components. You need position, scale, rotate for loading a MVP matrix into the shaders. You need the mesh and textures for rendering itself. You even need details like light color or whether or not it casts shadows. Everything! This means that you will inevitably encounter cache misses in some form, since you can't fit your component arrays in cache.

Add to that the fact that since the entity integers are indices into the component arrays, *all* of the component arrays need to grow in size whenever you add an entity - independent of it's type. This means that adding 30 entities with no mesh will inevitable generate 30 empty mesh allocations that will never be used.

How would you implement such a system to truly minimize cache misses without incurring in unnecessary memory waste?

# Answer
The benefit of organizing data in the fashion described (storing things that will be frequently used or accessed together next to each other in memory) is not *zero* cache misses. It is *fewer* cache misses. That's all.

You're not wrong: if you represent your entity as an index, and use that index to refer to separate arrays for each of position, texture coordinates, mesh or shader references, et cetera, then yes, that's not very cache-efficient at all.

Instead, *don't break your entity down into such pointless granular components*. If you need position/texture coordinate/resource references all at the same time when processing that component (such as during rendering) store them all in a single record:

```
struct RenderComponent {
  Vector3 position;
  Vector2 textureCoordinate;
  Texture * texture;
  Shader * shader;
};

```

Create a an array of *that* structure and use your entity index to refer to that.

Don't fall into the (unfortunately extremely common) trap of thinking that building a component-based entity system means breaking down everything into the smallest thing possible. You want to break things down into the smallest component such that a single component is still a useful thing on it's own.
> 2 votes

---
Tags: opengl, entity-system
---


title: If-clause in GLSL

text:
# Question
Title: If-clause in GLSL
I read a few thing about, that in GLSL both sides of the if-clause is executed, so do you have any idea for a workaround for this one:

```
uniform int uses_bones;
uniform mat4[] bone_transformations;

void main()
{

    vec4 worldPosition = transformationMatrix * vec4(position, 1);
    if(uses_bones == 1)
    worldPosition = transformationMatrix * vec4(position, 1) * (bone_transformations[bone_pointer] *  bone_intensity);
    vec4 pos =  projectionMatrix * worldPosition;

```

The int uses\_bones represents a bool, because LWJGL does not support loading booleans to the shader. 1 = true, 0 = false

# Answer
You can create two shaders and set the correct one from the application. Use a define to turn on/off features.

> GLSL both sides of the if-clause is executed

Partially true.

One core execute a lot of (64) with SIMD paradigms. Think about them as a vector of data and one instruction pointer (IP). In program with a branch the core can't use two IP for different data. So in this case both branch are executed and the registry from the "wrong" branch ignored.

But if the branch depend only on *uniform data* all the data in the SIMD vector will follow the same branch, and the compiler add a real branch instruction. Older shader compiler didn't support this feature, but modern compiler and hardware does. In HLSL you can enforce the branch with \[branch\] before the if. I don't know if GLSL have something similar.

In any case, use branch in shader only if you don't have other alternative.
> 5 votes

---
Tags: shaders, glsl, boolean
---


# Question
Title: Getting distance between point of an object and another object in Unity
First, I'd like to apologize because this is a very basic and repetitive question, but I am completely new to game development.

I understand that I can find a distance between two objects using:

```
float dist = Vector3.Distance(other.position, transform.position);

```

However, how can I find the distance between a point of one object to other object?

For instance let's say my object is this sphere

Now, how can I return an array that says that there are no objects to the left (null), in the front there is an object at 1, and to the right there is an object at 0.5?

Thank you for your patience and understanding

# Answer
> 1 votes
If it should only work with left, up, right, and down use Raycasts! Your code will look like this

```
public float[] CheckCollisions() {
    Raycast hit;
    float[] collisions = new float[4];
    if (Physics.Raycast(transform.position, transform.Vector3.Up, 100.0f, out hit))
        collisions[0] = hit.transform.position - transform.position;
    else
        collisions[0] = Float.NaN;
    //other directions
    return collisions;
}

```

It isn't the most beautiful way - make a Vector3 array with all directions you wanna check and then iterate through, and check current Vector for hit.

Sorry for any mistakes, wrote this with my cellphone.

---
Tags: unity, physics
---


# Question
Title: Is it a good idea to make most actions in a game driven by simple tiny threads (in Java)?
I'm thinking of for example making the jump action of a character, that takes ~1s, a distinct runnable, so then other threads can read its state, with additional control over the action itself by the "action thread". Are people doing this? What is there to consider when thinking about creating and destroying hundreds (or thousends) of threads a second in a bigger game or other application?

# Answer
> 6 votes
This is flawed. Some reasons here

The goals in game development:

1. Keep development costs down.
    * Developing with threads is more costly, it requires more developer hours. Indies can't afford it and big companies only use it when there is a proven benefit.
2. Do not complicate maintenance more than needs be.
    * Debugging and even sometimes reading code that uses threads, can be more complicated. For instance bugs can occur only when two specific threads do certain things which is very hard to reproduce and trace. Sometimes you may think your code does *something* but because it works simultaneously with multiple threads that may run in a variety of orders, it may do *something else completely*.
3. Keep the product performant.

* According to all the tests / benchmarks I and many other have done, running many threads on pc hurts performance. If you do use threads, you need to plan and use a number that is similar to the number of threads the intended architecture supports performantly (test).
    * Threads require context switching, they don't actually run in parallel and you (mostly) don't control when and how long they run. If you have many threads this would result in poor performance if the "wrong" thread gets too much cpu time.

There are more good reasons:

Read here.

tl;dr

You want to keep the focus on game design when you are developing a game. Threads are specifically used in game programming for two purposes:

1. Running the same "sub-process" multiple times inside the same program (like a game server that updates players).
2. Improving performance by splitting up sequential segments (intensive data computation) in your code and making them concurrent.

That 1s portion (jump code) you speak about isn't sequential in the first place. It is something that's supposed to happen in chunks between renderings to the game view.

You don't need a thread to create a `Jump` object and have it listen to the game clock.

# Answer
> 3 votes
You aren't really gaining much with multithreading such a simple algorithm, it won't run faster, you won't have fewer variables, and now you have to make sure to keep everything synchronized.

You could just as easily keep track of your characters jump velocity in a regular variable and in the update loop do what you would have done in the separate thread.

# Answer
> 1 votes
The general architecture for a game looks like this:

You have a main update loop. This loop runs once per frame. The loop consists of three or four different parts (depending on whether your game really needs all of them):

1. You have some logic that renders graphics onto the screen, depending on the game's current state.
2. You have some logic that updates the game's physics and logic.
3. Part of the loop listens for user input and updates the player-controlled elements' states accordingly.
4. And part of the loop gives artificial intelligence routines an opportunity to provide input for computer-controlled elements.

Notably, *all four of these components run on the same thread*. Game programming typically is the task of filling in the details for these components (no small task, of course) and keeping each piece performant enough that the entire loop can run dozens of times a second.

So, instead of creating a thread specifically to take care of a character's jump, you would provide logic for how the character's jump affects the character's physics in the character's logic. Then, in the physics/logic component of the loop, you would use this logic to update the character's state one frame at a time. In many cases, this would specifically be that when a character receives a jump input from the user or AI, you give the character a sudden upwards velocity on the next frame, then let the physics engine handle what happens on subsequent frames.

Again, at no point does this particular architecture require additional threads.

# Answer
> 1 votes
To answer your question more directly, you can't even afford to create and delete 100s and 1000s of threads per second.

In some languages there are constructs often referred to as "green threads" where a single thread doesn't map to an OS managed thread, but JVMs aren't based on those (in general, anymore). Creating OS managed threads is extremely expensive. Most machines with cave in at thousands of threads being created just for benchmark purposes.

Once you factor in the fact that you're actually using the threads, and that you're not creating these threads once, but rather creating them, destroying them, and creating new ones every second you'll find that most machines simply can't handle the workload. With the default settings of the JVM just creating 500 threads will use over 256mb of memory (and that's not considering what kind of havoc this will all wreak on the scheduler). That memory won't be returned instantly when you delete the threads, and within seconds you'd find the JVM starved for memory.

My point isn't that the JVM is doing something wrong by not using "green threads". The name "green thread" might imply that they're somehow better than OS managed threads, but they have their own limitations especially related to taking advantage of multiple cores (and Java has it's own constructs for dealing with the cost of thread creation). Rather my point is the approach you're considering is actually impossible from a hardware standpoint (amongst other issues).

I think you could look at using an event based system if you want to have shared states like this. Your jump can be implemented to call invoke certain events when various parts of the action occur, such as at the start of a jump, the highest point etc. That being said, as the other answers have mentioned you really should consider if you actually require that level of complexity for your game-play, or it's all solely for the sake of your code's design.

---
Tags: java, multithreading
---


title: Realistically drivable car

text:
# Question
Title: Realistically drivable car
I want my car to be realistically drivable (like in real life...)

Unfortunately all I did so far is `Rotate` the whole vehicle using A and D; and `AddForce` in forward-backward direction using W and S (which didn't prevent it from moving sideways and yes, I am using `Rigidbody`)

I'm assuming I'd have to let front wheels rotate independently from the rest of the car, but how do I use them to move the car? And how do I force the car to move only in the direction of the wheels while still making drifting at high speeds possible?

# Answer
You probably don't want to use `AddForce`, and definitely don't use `Rotate` for physics since it completely overrides the physics engine (and collisions).

Use WheelColliders. They're specifically made for this purpose. I've used AddForce in conjunction with WheelColliders with extremely low friction to simulate arcade style hovering vehicles, but anything remotely realistic is going to need a lot more than that. WheelColliders expose properties that handle the suspension, tires, braking, acceleration and steering. Unity's implementation isn't perfect, but if you make sure that you're using the correct scale for your objects, with a few tweaks it can be used for a rather realistic setup.

This tutorial, by the creator of one of the biggest 3rd party vehicle plugins for Unity goes over a few tips you can use to get the most out of WheelColliders. To sum it up, it's goes over using the right units, "fudging" the center of gravity to help with roll, and most importantly, how to simulate an anti-roll bar (it's very easy to underestimate how incredibly important an anti-roll bar is in keeping a vehicle upright, and this carries over to Unity as well)

Using the physics engine joints for the suspension won't be particularly worth the trouble. Instead use the WheelCollider suspension in conjunction with procedural animation to get the best blend of realistic behavior, and a robust implementation.

WheelColliders are an extremely well explored area in Unity so do some searching in addition to looking at that tutorial, you'll find various implementations of features like gearboxes and simulated drivetrains. WheelColliders are really a good base that you can build on. Even more advanced realism features such as tire wear and temperature can all be simulated if you're willing to experiment with the various parameters they expose.
> 1 votes

# Answer
If you want realism, follow the physics of a real car. 4 tires on the ground. Only front two can rotate.

For front wheel drive, on each of the two front wheels, I believe rigidbody.addTorque(Vector3) is what you are looking for.

But there is a lot more to it. And I am not a mechanical engineer, so you may need an expert in the field to know where the vehicle weight needs to be and such. Tread on the tires help keep it sticking to the ground, but you can probably just mess with friction or something there.
> 1 votes

---
Tags: unity, physics, racing
---


title: Chess Game WPF MouseDown Event

text:
# Question
Title: Chess Game WPF MouseDown Event
I'm making a chess game with wpf and I have never used wpf before. I've used windows forms, so besides the xaml, it's pretty familiar. Usually when I want to create a mousedown event I look at what I have on window design screen-\>click the object-\>go to properties-\>events-\>MouseDown event-\>double click the event-\>it creates a method that executes when the mouse is pressed on that element. Looks like this...

```
private void Pawn_1__MouseDown(object sender, MouseButtonEventArgs e)
{

}

```

But for my chess game in my C# code in the mainwindow constructor I put some initialization code to place a bunch of rectangles all over the screen representing the grid I'd be using for my chess game. How can I create a MouseDown event for these rectangles since they aren't in the designer?

# Answer
I am guessing you are using System.Draw methods to draw the rectangles (I hope you are not drawing labels or something cause that would kill performance). I would make a mouse down event on the form, and then use the mouse position value to get the rectangle that was clicked depending on the width/height of them.

So say the user clicks at 250,250 and the rectangles are 100x100, then he clicked the rectangle\[(int) mouse.X / 100, (int) mouse.Y / 100\], which is rectangle\[2,2\] (third row third column). That way you can access the clicked rectangle and handle it the way you are supposed to.
> 1 votes

---
Tags: c#, wpf
---


title: Drawing the same model multiple times

text:
# Question
Title: Drawing the same model multiple times
I am looking ways to improve the efficiency of my draw method in XNA/Monogame and understand how things work. I have just a group of 4 models (bricks), (red, green, blue, yellow) I am drawing multiple times on the screen (100-120 total models, so drawing each model 25-30 times) on the current frame.

Here is how i am drawing 1 of the 4 types of models (the red ones) right now:

```
Matrix[] transforms = new Matrix[Brick.Red.Bones.Count];
Brick.Red.CopyAbsoluteBoneTransformsTo(transforms);
ModelMesh mesh = Brick.Red.Meshes[0];
BasicEffect effect = (BasicEffect)mesh.Effects[0];
effect.EnableDefaultLighting();
effect.View = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);
effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f),
   aspectRatio, 1.0f, 10000.0f);
foreach (Brick brick in Bricks)
{
    int i = brick.Index / Columns;
    int j = brick.Index % Columns;
    modelPosition = new Vector3(-HalfWidth + j * BrickWidth,
        HalfHeight - i * BrickHeight, 0.0f);
    effect.World = transforms[mesh.ParentBone.Index] * Matrix.CreateScale(scale) *
        Matrix.CreateTranslation(modelPosition);
    mesh.Draw();
}

```

This code seems to not perform as well as I expected (since its just 4 models drawn many times on different locations) when I timed it with a `StopWatch`. Is there something silly in my code that could be done better and i'm missing it ? I can't tell because so far I have only worked with sprites and 2D.

Edit: From other codes I saw that they used `effect.Parameters["World"].SetValue(...);` to set the `BasicEffect` values, but that gave me a null exception, and I am not sure what is the difference of that function since in my mind it seems the same with `effect.World = ...;`

# Answer
It looks like hardware instancing isn't supported by MonoGame yet, which is ideal. That leaves us with the answer to MonoGame: Draw thousands of quads without hardware instancing. Still, I've included an explanation of how it would be done if they get around to it.

## Hardware Instancing (pure XNA HiDef only for now)

It's been a while since I've done this, so most of my explanation will be taken from Shawn Hargreaves Blog: DrawInstancedPrimitives in XNA Game Studio 4.0 and the MSDN Instanced Model code sample. Moreover, this is just an explanation of how the method works. The way you'll need to do it in practice is far too complicated to explain here, so you'll probably need to refer to additional resources online if you run into any problems.

This form of instancing uses a shader to render the same thing in many places with various parameters. An example of such a *shader* can be found in the above code sample, but a simple instancing shader would be

```
float4x4 WorldViewProj;

void InstancingVertexShader(inout float4 position : POSITION0,
                            in float4x4 world : TEXCOORD0)
{
    position = mul(mul(position, transpose(world)), WorldViewProj);
}

```

...which we use to create an Effect that accepts, in this example, the many ways the model will be drawn. Of course, it's possible to use additional parameters like color, texture, etc., but to keep things simple I will stick to position.

To get that information into the shader we need a special vertex buffer:

```
var instanceVertexDeclaration = new VertexDeclaration
(
    new VertexElement(0,  VertexElementFormat.Vector4, VertexElementUsage.BlendWeight, 0),
    new VertexElement(16, VertexElementFormat.Vector4, VertexElementUsage.BlendWeight, 1),
    new VertexElement(32, VertexElementFormat.Vector4, VertexElementUsage.BlendWeight, 2),
    new VertexElement(48, VertexElementFormat.Vector4, VertexElementUsage.BlendWeight, 3)
);

// You can hang onto this between draw calls:
var instanceVertexBuffer = new DynamicVertexBuffer(GraphicsDevice,
                                                   instanceVertexDeclaration,
                                                   instances.Length,
                                                   BufferUsage.WriteOnly);
// Will need to call this if something has moved.
//     See DynamicVertexBuffer.SetData for more details.
instanceVertexBuffer.SetData(instances, 0, instances.Length, SetDataOptions.Discard);

```

And finally we can pass our mesh and instance information to the hardware for rendering:

```
foreach (ModelMesh mesh in model.Meshes)
{
    foreach (ModelMeshPart meshPart in mesh.MeshParts)
    {
        // Tell the GPU to read from both the model vertex buffer
        //     plus our instanceVertexBuffer
        GraphicsDevice.SetVertexBuffers(
            new VertexBufferBinding(meshPart.VertexBuffer, meshPart.VertexOffset, 0),
            new VertexBufferBinding(instanceVertexBuffer, 0, 1)
        );

        GraphicsDevice.Indices = meshPart.IndexBuffer;

        // Set up the instance rendering effect.
        Effect effect = meshPart.Effect;

        effect.CurrentTechnique = effect.Techniques["HardwareInstancing"];

        // (Set view/world/projection matrices on effect. See sample.)

        // Draw all the instance copies in a single call.
        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            pass.Apply();

            GraphicsDevice.DrawInstancedPrimitives(PrimitiveType.TriangleList,
                                                   0,
                                                   0,
                                                   meshPart.NumVertices,
                                                   meshPart.StartIndex,
                                                   meshPart.PrimitiveCount,
                                                   instances.Length);

        }
    }
}

```
> 2 votes

---
Tags: xna, c#, performance, monogame
---


title: Point sprites in particle system?

text:
# Question
Title: Point sprites in particle system?
I don't understand this passage from *Real-Time 3D Rendering with DirectX and HLSL by Paul Varcholik*:

> In the geometry shader, you can create quads around those central points, to which you can map textures. Such objects are commonly known as point sprites.

What are point sprites? How do they work in a particle system?

# Answer
> 4 votes
As the book says, a geometry shader can create new geometry in the pipeline. In this case, quads - which are just four vertices, or triangle pairs, that make up a 3D square. We often use quads to render sprites, which are just images with a position either in 2D or 3D coordinates. In fact, most 2D game engines are actually rendering everything with three dimensions, but using quads facing an orthographic camera.

Put another way, since every particle in a system is more or less identical, we just need to feed our image, its size in the world, and all the particle's positions into the shader effect, and it can tell the hardware to come up with all the little billboards with the image properly mapped onto each one.

---
Tags: particles
---


# Question
Title: Can I display text in SFML without setting a font?
I'm trying to render text without setting a font.

```
#include <SFML/Graphics.hpp>
#include <iostream>
using namespace std;
string culoare;
int main()
{

    sf::RenderWindow window(sf::VideoMode(800, 600), "Window");
    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }
        sf::Text text;
            //atext.setFont();
            text.setString("HelloWorld");
            text.setCharacterSize(20);
            text.setStyle(sf::Text::Bold);
            text.setColor(sf::Color::White);
            text.setPosition(0,0);
            window.draw(text);
            window.clear(sf::Color::Green);
            window.display();
    }

    return 0;
}

```

This just make a green window, but doesn't display text.

# Answer
What's happening is you're clearing the screen after drawing the text. So this

```
        window.draw(text);
        window.clear(sf::Color::Green);

```

should be this

```
        window.clear(sf::Color::Green);
        window.draw(text);

```

If it still doesn't display anything, you definitely need to set a font!
> 3 votes

---
Tags: c++, sfml, text
---


# Question
Title: How do I center the view around specific coordinates in SFML
I want to use sf::View in SFML in order to change the position of the view, such that the player sprite is always in the center of the screen. Thus I want to write a function which allows me to input a set of coordinates and thus center the screen around those coordinates. In addition I want to be able to set a limit to this, such that when the player reaches the side of the map, that axis of the camera stops following the player, as it has reached a "limit". How do I achieve this?

Thank you in advance.

# Answer
> 0 votes
You have to check if the player is too close to a side and move the view accordingly. If he is too much on one side then you don't center the view on him anymore.

Here is an example of how I would do it. (I haven't tested it)

```
//View is your current view.
//Position is the position you want to center the view on.
//Size is the size of your "area".

void move_view(View &view, sf::Vector2f size ,sf::Vector2f position)
{
    if (position.x > size.x-view.getSize().x/2)//on the right side
    {
        position.x  = size.x-view.getSize().x/2;
    }
    if  (position.x < view.getSize().x/2)//on the left side
    {
        position.x  = view.getSize().x/2;
    }
    //same for up and down
    //...
    view.setCenter(position);
}

```

---
Tags: c++, sfml, side-scroller, view
---


# Question
Title: Animator Panel in Unity - Where is "Entry"?
I am following a tutorial on Unity, and I saw a screenshot like the following:

When I reproduced the steps of the tutorial, I realized that the green "Entry" box was not present on my screen. I have been thinking why this could be and the only reasons that I could think of are:

1. The tutorial skipped a step
2. I have something misconfigured
3. In the latest version of Unity that box has been erased or replaced

Which one is it? Did I forget a 4th option?

PS: If it is option #3, could someone explain me what was this feature for, and what has it been replaced with?

**UPDATE** I am using Unity 4.6.2f1

# Answer
This is a new feature of Unity 5.0.

> In Unity 5, we’ve added **Entry** and **Exit** nodes to StateMachines. There are used during State Machine Transitions.
>
> **Entry**: When you transition to a StateMachine, the animation system will evaluate the Entry node and branch to the destination that its conditions meet.
>
> **Exit**: When going to the Exit node, the animation system will look at the outgoing StateMachine transitions and branch to the proper destination.

If you are using the latest version of Unity as you say, then that leaves options one or two.
> 1 votes

---
Tags: unity
---


# Question
Title: How to find all the possible places to go on a grid?
Given the amount of steps you can take in a grid, how could I implement a way to get all the possible places a unit can go to, in a game like Advanced Wars?

I have currently got A\* path finding working, but it would be nice to have an indicator of the possible places to go to. I have linked to an image to make things more clear.

I was thinking of computing the path of every single tile on the grid to the unit tile, then working it out from there, but I can imagine that will take crazy amounts of resources.

Notice how the other units 'block' the path of the selected unit. So unfortunately its not a trivial 'draw a circle with radius X'

# Answer
> 4 votes
Breadth First Search can calculate every location reachable from a start position, and it can also count how many steps to that location. (If some steps take more "moves" then use Dijkstra's Algorithm instead). See the fourth demo on this page. You would tell the algorithm to stop after some number of moves, so that it doesn't keep exploring the rest of the map. In this image I stopped it after 5 steps:

# Answer
> -1 votes
You just need to modify your A\* implementation to exit when there are no acceptable tiles left and save all tiles meeting the condition.

Start as usual and set a MaxCost value (that is max distance unit can walk). Then iterate possible tiles to go and add ones that are passable and whose cost is less than or equal than MaxCost to a list. Algorithm ends when there are no neighbor tiles left with walk cost less or equal to MaxCost.

---
Tags: tiles, path-finding, grid
---


# Question
Title: How to reference the right object in Unity
So, I'm developing this small 2D project where I have a sphere that detects if objects get close to it from three different directions.

I have successfully found a way to detect if an object touches my line if the object is referenced to a certain `LayerMask`, in this case the walls.

So, basically I'm doing this:

```
var layerMask = 1 << 10; //wall layer
float left = 0f, middle = 0f, right = 0f;

Debug.DrawLine (leftStart.position, leftEnd.position, Color.green);
Debug.DrawLine (middleStart.position, middleEnd.position, Color.green);
Debug.DrawLine (rightStart.position, rightEnd.position, Color.green);

leftSpot = Physics2D.Linecast(leftStart.position, leftEnd.position, layerMask);
middleSpot = Physics2D.Linecast(middleStart.position, middleEnd.position, layerMask);
rightSpot = Physics2D.Linecast(rightStart.position, rightEnd.position, layerMask);

```

Now, what I would like to do is reference the right wall (Horizontal or vertical) and calculate the distance between the wall and my sphere with:

```
Vector2.Distance(transform.position, wall1.position);

```

How can I get the reference to the correct wall to do this?

Thank you

# Answer
> 1 votes
You should be getting a `RaycastHit2D` object back from your test. You can access the hit info from that to get the distance and other information about the object you hit. Something like the following:

```
RaycastHit2D leftHitInfo = Physics2D.Linecast(leftStart.position,
           leftEnd.position, layerMask);

if(leftHitInfo.collider != null) {
   Debug.Log("Left hit! Distance: " + leftHitInfo.distance.ToString());
}

```

If you're performing this test regularly, I suggest you use the non-alloc version of this method:

```
int maxReturnedIntersections = 5;
RaycastHit2D[] hitResults = new RaycastHit2D[maxReturnedIntersections];

int hitCount = Physics2D.LinecastNonAlloc(leftStart.position, leftEnd.position, hitResults, layerMask);

if(hitCount > 0) {
    Debug.Log("Left hit! First distance: " + hitResults[0].distance.ToString());
}

```

Ideally, you'd create the array of hit results outside of your method so you're not creating a new one over and over.

---
Tags: unity, physics, raycasting
---


# Question
Title: Lists of concrete types show up in inspector, but not lists of interfaces
In one of my custom C# classes in Unity, I need to expose a `List` of objects in the inspector, and they need to conform to a specific interface.

Below are two lines from my class definition. `Card` is a concrete type in my game, and `CellObserver` is an interface. Multiple classes may implement this interface, so I'd like to define it this way if possible.

```
public List<Card> currentCards;
public List<CellObserver> observers;

```

The list of `Card` objects shows up in the inspector just fine, but lists based on `CellObserver` don't. It's not unique to this interface either - I also have one on another class that behaves the same way.

The code builds just fine, and as far as I can tell, this is valid in C#. Is there something else I need to do in Unity to implement this list? Or is this simply not an option in Unity?

# Answer
You'll probably have to look into PropertyDrawers to get what you want. These are custom property drawers for Unity. The Unity inspector doesn't know how to render a lot of things by default (and some things it's not very good at rendering, like arrays).

With a custom property drawer you can tell the Unity Inspector how to display your interfaces. Property drawers also allow you to change the way other types are displayed.
> 1 votes

---
Tags: c#, unity
---


# Question
Title: Set an scaled image rectangle coordinates
I have used the Origin parameter to draw the image (the image is also scaled) in center of the screen, and created a rectangle to detect whether user tapped on that image. The problem is that if I tap on left part of the image it doesn't happen anything but at the right part, it executes what it has to.

How can i fix this? I have tried something but any result...

```
ItemRectangle[ItemID] = new Rectangle((int)Position.X + (int)(Position.X * Scales), (int)Position.Y + (int)(Position.Y * Scales), ItemTexture[ItemID].Width, ItemTexture[ItemID].Height);

spriteBatch.Draw(ItemTexture[i], ItemPosition[i], null, Color.White, 0, new Vector2(ItemTexture[i].Width / 2, ItemTexture[i].Height / 2), Scale, SpriteEffects.None, 0);

```

# Answer
If you just want to draw a rectangle in the middle of the screen and scale it you could do it this way:

```
Texture2D rectTexture;
Rectangle rect = new Rectangle(x, y, width, height);
Vector2 scaleVector = new Vector2(0.5f, 0.5f);
Vector2 screenSizeVector = new Vector2(screenWidth, screenHeight);

spriteBatch.Draw(rectTexture, new Vector2(rect.X, rect.Y) +
     new Vector2(rect.width/2, rect.height/2) + screenSizeVector/2, null, Color.White,
     0f, Vector2.Zero, scaleVector , SpriteEffects.None, 0f);

```

And then you would have to scale the width and height of the rect when you are checking the user's inputs like this

```
Rectangle tempRect = new Rectangle(x, y, width*ScaleVector.X, height*ScaleVector.Y);

```
> 0 votes

---
Tags: monogame, windows-phone-8
---


# Question
Title: Project rotated matrix to isometric coordinate
I have a group of soldiers, and each has a vector describing their position in the squad. When the group rotates, I do this math to calculate the desired position of each soldier.

```
var unitPositions : Array<CGPoint> = []

let cosRadian = cos(rotation)
let sinRadian = sin(rotation)

for var index = 0; index < self.positions.count; ++index {

    // Find the vector for this unit, translate it, then store it
    let targetVector = self.getVectorAtPosition(index) - translate
    let newX  = targetVector.dx * cosRadian - targetVector.dy * sinRadian
    let newY = targetVector.dx * sinRadian + targetVector.dy * cosRadian

    unitPositions.append(CGPoint(x:newX, y:newY))
}

```

This produces the following result:

The problem with this is that units in an isometric world facing south east should match up with the reference grid. So the next step was to add a multiplier. In the loop above, I changed it to:

```
    let isoX = newX * 1.414213562373095;
    let isoY = newY

    unitPositions.append(CGPoint(x:isoX, y:isoY))

```

This produced closer results:

But, it's still not 100% accurate. So, right now I'm going through and trying to get my fundamentals of math, matrices, vectors, etc all figured out in hopes of producing this desired result:

I would love any pointers on what I should be searching for, as right now it is all a bit overwhelming. Thanks much!

**UPDATE**

Due to the awesome comment by @DMGregory, here are my findings:

If I want to "hack" this and continue to use screen coordinates, I can do so using 1.414213 (the magic number found here) combined with your true isometric projection.

```
let isoX = newX * 1.414213562373095
let isoY = newY * (1.414213562373095 * 1/sqrt(3))

```

That will produce:

That approach will work, but won’t solve everything else you mentioned (i.e: units will move faster when going certain directions). To handle that, creating the original formation with isometric vectors, and then just rotating that matrix will produce the same results. So, it looks like I have a lot of work converting my game calculations and coords to default as isometric coordinates. Thanks again!

# Answer
The trick here is conversion between **world space** and **screen space**.

**World space** is the coordinate system you use for your game logic - calculations of pathing, movement, formations, etc. Your original formation code is correct *for world space*.

**Screen space** is the coordinate system in which items are displayed. Because you're using an axonometric projection here, your vertical/depth axis is foreshortened. So a distance of "one meter" forward spans fewer pixels on screen than "one meter" to the right. This also means that right angles in world space can become acute or obtuse on screen - which is why your right-angled unit formation (which is correct for world space) doesn't match your isometric grid.

You generally won't want to do game calculations in screen space - otherwise units moving "North" will have a higher effective speed relative to your isometric grid than units moving "East" (and units will be able to shoot further if they attack from North/South etc.)

3D games typically store only the world coordinates of each entity. They generate a "View-Projection" matrix, based on the position/orientation/FoV of a virtual camera, which converts world coordinates into screen coordinates on the GPU as the content is being rendered. A lot of "2D" games do this too, just with an orthographic matrix or constrained camera angle.

Judging by your example though, it looks like you're manually positioning your units with a formula, so I'll demonstrate that style.

The details will vary based on your coordinate setup, so I'll make some assumptions you might need to modify.

Let's say your world axes run like this, to align nicely with your isometric grid:

Here's some pseudocode (uv is just a temporary label for notational convenience)

```
// First, we recenter our worldspace position
// By changing center.xy, you can pan the "camera" around the map
uv.xy = worldPosition.xy - center.xy

// Then we convert to pixel offsets from the center of the screen
screenPosition.x = (uv.x - uv.y) * TileWidth * 0.5
screenPosition.y = (uv.x + uv.y) * TileHeight * 0.5

// Depending on your drawing environment, you might need to apply an offset to this
// eg. if your pixel coordinates are measured from bottom-left rather than from the center

```

Where TileWidth is the number of pixels across one grid square from left to right.

If you're using a true isometric projection,

```
TileHeight = TileWidth * 1/sqrt(3)

```

But note that many games use an "almost isometric" ratio of 1:2 to avoid irrationals, in which case

```
TileHeight = TileWidth * 0.5

```
> 2 votes

---
Tags: rotation, matrix, isometric
---


title: Pathfinding: Tile-Based Navigation Mesh

text:
# Question
Title: Pathfinding: Tile-Based Navigation Mesh
I'm developing a real time, tile-based RTS. This is an example map:

This map consists of 4 regions with 256 tiles each. Blue tiles represent obstacles. Units can move in the standard eight directions. Units are bound to tiles; one tile can hold one unit.

These are some examples of the ideal paths I'm looking for. Typical A\* stuff:

My question is: Is a navigation mesh applicable to a tile-based RTS? I've only seen navigation maps used in games where units are free-moving and not bound to a grid of tiles. What would the navigation mesh look like on this particular map? An example image would be excellent.

# Answer
Yes, navigation meshes are still applicable to tile based games. Although, they would primarily be used as a optimization. For example, I've converted the lower left of your image to use a navigation mesh:

In this case, each green square would be a navigation node. As you can see, this drastically reduces the number of nodes that A\* needs to process. Units can then simply path to the center of each of these nodes.

The generation of these nodes is a different issue. It can be complex deciding how to form the nodes. There's a few questions on the site where you might find some ideas on how you'd like to implement that:

Subdividing a polygon into boxes of varying size

Identifying quad patterns in a two-dimensional array

https://stackoverflow.com/questions/20220215/minimum-number-of-rectangles-in-shape-made-from-rectangles

This navigation mesh can also essentially be used as a "first pass" path finding. If a path is found through the navigation mesh, you know that a path exists. This is a faster test to see if two points are connected.
> 12 votes

---
Tags: path-finding, rts, navmesh
---


# Question
Title: How to prevent fish eye effect when using CCOrbitCamera in Cocos2D?
Note: I'm using CocosSharp, a Xamarin C# version but the question is valid for all Cocos2D versions I presume. I'm also fine with answers in any Cocos2D dialect (there is no tag yet for CocosSharp here).

I'm trying to create a card flip animation using `CCOrbitCamera`. This works pretty well with the code below - unless the sprite ist not in the center of the screen.

```
var animateInFirstHalf = new CCOrbitCamera(animDurationSeconds, 1, 0, 0, 90f, 0, 0);

```

My idea is to flip the card 90 degrees, then exchange the texture, and flip further. At 90 degrees the only thing that's visible is a thin line if the sprite is centered. If it is out of the center, it looks something like this:

The picture is from a blog post where the issue was solved by faking the animation with skew and scale. However I wonder if it is possible to somehow run the animation as if the sprite was centered? Something like virtually translating it to the center.

# Answer
I don't know how to prevent eye effect, but for the problem you mentioned in question body ( `to create a card flip` ), you can use `x-scaling` technique as:

`[ ] => [] => | => change texture => | => [] => [ ]`

As I used this technique, I promise you that it will be what you want even if cards are out of the screen center.
> 1 votes

# Answer
Like you said, the card is just a thin line when centered on the screen in the x-axis at 90 degrees, at any other position (including the above case) the card will be a thin line when it aligns with the normal from the camera to the card's centre.

Using the dot product between two angles you can figure out the angle between them, so from the cameras position you want the angle between the direction straight forward and the direction to the card.

Here's some pseudocode (I don't use cocos2d so the function names might be different):

```
toCard = (card.centre - camera.position).normalize
angle = inverseCos( toCard.dot(camera.facingNormal) )

```

This is the difference in angle from the 90 degree rotation you used before, now you just have to figure out if the card is to the right or the left of the centre of the screen.

```
if (card.x <= screen.width / 2)
  90 - angle   or   Pi/2 - angle
else
  90 + angle   or   Pi/2 + angle

```

One little caveat though, if your card is above or below the centre of the screen the difference in y coordinates will make the angle come out wrong, in that case just use 0 as y coordinate for both the card's centre and the cameras position.

Now you rotate to this new calculated angle, once the card reaches that point, swap the texture, then rotate from that point to fully flipped over. Hope it was clear enough and useful to you
> 0 votes

---
Tags: animation, cocos2d
---


title: ASP.NET Browser game Timers

text:
# Question
Title: ASP.NET Browser game Timers
I am developing a simple browser game, using ASP.NET, C# and SQL Server 2012. I need to implement build time of some unit or building. One way would be storing finish date to database and just fetch remaining time on refresh, but there is one problem. If user doesn't refresh in a long time and building finished days before, the dependent records in database won't get updated (e.g. I have finished building Iron Mine 3 days ago, but the production per hour wont get updated until user refreshes). How would you approach this problem ? Is there some sort of timed event in database, that will not ruin database server performance when there will be a lot of timers ?

# Answer
> 0 votes
While it is *possible* to use a stored procedure and have it be called from the database itself, I would recommend you deal with this from the application layer instead.

You have two basic options, the first is to have a background process that handle unit/building completion and makes the changes in the database. This is fairly straightforward and if your game is multiplayer it might be your best bet. The downside is that if your paying for a shared server your process might get shut down when there aren't any visitors to your site, resulting in that time stops occasionally (and from the players point of view, randomly).

A second option is to make it so your game logic receives the current time instead of looking at the system time `Building.update(currentTime)`, this way you can look up if any buildings/units completed their orders at a time in the past, then update said units at that point in time.

```
void OnVisit(...) {
  var now = Date.Now;
  for (var event = DataBase.GetFirstUnprocessedEvent();
       event != null && event.DueTime <= now;
       event = DataBase.GetFirstUnprocessedEvent()) {

    event.Process(event.DueTime);
    event.Processed = now; // It's a good idea to mark when it actually happened
    DataBase.Update(event);

  }

```

Now time will keep on ticking normally even if the server gets rebooted, things just happen all at once when the player visits instead of over time like it normally would. By reading the first event until you can't find any more or they are in the future you allow the code to add new events in the past and things still work.

If you read all events that are due you need to make sure you process any newly added event (for instance, if the building will create a new unit after 3 hours you will want to make sure the unit gets created and their upkeep reduced before events that happen later).

Saving the current time is useful so you can find bugs or tweak algorithms, even if the game itself doesn't care about it. The downside with this approach is that a player who hasn't visited for a long time might cause a noticeable delay or lag when they suddenly remembers your game and comes back for a visit.

Of course, you can combine both options if you wish, by having a daily/weekly/monthly task update any outstanding build orders simply by acting like the player accessing the game.

---
Tags: timer, sql, browser
---


# Question
Title: Can Java be used for developing games for Android in Unity3D
I only know Java Programming Language and no other. Can I develop games for Android in Unity3D using Java?

# Answer
Unity does not natively support Java. There is scripting support for JavaScript, C# and Boo though. If you know Java the jump to C# is not that big.

Also see this SO.SE answer.

There however, seems to be a trick via a manual IKVM conversion from JAR to DLL that can work: http://answers.unity3d.com/questions/15308/can-i-access-java-code-from-unity.html#
> 2 votes

---
Tags: unity, java, android, game-design, unityscript
---


# Question
Title: How do I change a shape without affecting the rest of the screen?
I have drawn a shape like this in OpenGL:

```
 glColor4f(red,green,blue);
        glBegin(GL_QUADS);
            glVertex2f(x1,y1);
            glVertex2f(x2,y2);
            glVertex2f(x3,y3);
            glVertex2f(x4,y4);
        glEnd();
glFlush();

```

and I want change one the vertices like

```
glVertex2f(x_delta,y_delta);

```

But how do I redraw the shape without altering the other components of the screen?

# Answer
> 2 votes
You can't(\*). That's not how OpenGL works.

The API is designed around a model where every frame you clear the entire screen and redraw the complete scene, from scratch. Thus, in your `redraw` function you should call `glClear` and then redraw *everything*, including your updated quad.

---

(\*) Well, specifically, you *can* in certain limited circumstances get away with not clearing the color or depth buffer and doing some additional rendering to alter only small portions of the screen. However, the practical utility for this is limited and it is not the typical way in which you use the API.

# Answer
> 0 votes
You have to clear the screen and redraw everything from scratch on every frame.

---
Tags: opengl
---


# Question
Title: Working out velocity/time based on physical pixels moved
In my game I integrate like so: (Please assume all variables to be declared)

```
sprite.xTimeInSeconds = 5.0; //Time in seconds it should take this object to cross screen
sprite.xVelocity = 1f/xTimeInSeconds;

```

And then I move it like so:

```
sprite.gridX+=sprite.xVelocity*dt;
sprite.x=sprite.gridX*screenWidth;

```

Then I simply render the sprite at those coordinates:

```
sprite.draw();  //Uses sprite's internal 'x' which was set above

```

So, everything within the game itself works fine - ie. all movement is correctly scaled regardless of device, but now I'm trying to write my own swipe/fling touch control system for a menu.

The menu does work - the user can place finger on screen, move up and down and when they release their finger, the menu keeps scrolling(\* see below). If they then press their finger down again, the scrolling stops immediately, as one would expect.

The only thing I'm having problems with is how to 'decelerate' the scrolling when the user releases their finger. At the moment, it keeps scrolling at the same speed until it reaches it's limits or the user taps the screen to stop it.

Within my touch-scroll method, I'm simply detemining how much the users finger has moved by and then moving my objects by the same amount. What I need to know (and can't figure out), is how can I - from knowing only the amount of pixels moved, work out the 'time' variable above? (once I have this I can then decelerate at a scaled amount on all devices).

# Answer
> 1 votes
I may have misunderstood what do you want to do. However, if you know the initial velocity, you can set an acceleration with inverse direction. For example, if velocity is 10 you can set an acceleration -1. Continue to decelerate until the minimum velocity is reached, which is 0. Your velocity will be unlikely to equal 0, so you have to check a change of the signs. If you have acceleration, using Euler method, you can find the velocity. Example:

```
Velocity = 0.2;

if (........) // Check if the finger is released
{
    Acceleration = -Velocity;
    Acceleration /= abs(Acceleration); // abs returns the absolute value

    Acceleration *= 0.5; // 0.5 is the final magnitude.
}

Position += Velocity * dt;
PrevVelocity = Velocity; // PrevVelocity is needed to check changes in signs
Velocity += Acceleration * dt;

if (PrevVelocity*Velocity <= 0) // if their products are negative, then they
    // have opposite signs
{
    Acceleration = 0;
    Velocity = 0;
}

```

If you want to calculate the acceleration accurately, you may have to substitute:

```
Acceleration *= 0.5; // Some random number

```

with:

```
Acceleration *= 2/xTimeInSeconds*(distance/xTimeInSeconds-Velocity);

```

I didn't try this code. I'm not 100% sure that this will work.

---
Tags: movement, touch, scale, menu, integration
---


# Question
Title: How do I determine wall direction, with information of normal and incoming direction?
What is formula and theorys used to determine wall direction, with only knowing the normal of the wall and the direction of the incoming object?

This answer has already stated a formula, but I don't know where it came from, and I am in need of understanding.

# Answer
> 3 votes
If you already know the normal of the wall, then you already knows the direction of the wall. Perhaps you are unclear on what is the normal of something? See this wiki page: http://en.wikipedia.org/wiki/Normal\_(geometry).

---
Tags: collision-detection, vector
---


# Question
Title: How can I create an extending chain like the hookshot in Zelda in Unity?
In the Zelda games, there is an item called the hookshot. It is a small mechanical apparatus held in one hand that acts similar to, but not the same as the gun. When it is triggered, the hook at the tip of the item springs forward and an extending chain follows behind it. This chain is spawned when the hookshot is triggered and disappears when the hook is retracted. The chain is not visible beforehand, i.e, it is not spooled around any kind of cylinder and unspooled when shot.There are also other games where characters use grappling apparatus that can be made shorter or longer when a character is hanging from a specific point or pivot. Similarly, this grappling tether is created or hidden as needed to support whether the player wants to shorten or lengthen it.

My question is, how could one create an extending chain whose links are only visible when triggered and when retracted disappear from view? This chain does not need to necessarily interact with physics. I've thought of a couple of ways someone could create an effect like this, but I would rather see if there is a better known solution or implementation of this or a similiar effect before I dive in. Potential solutions could include:

1. A particle effect between the base of the hook and the tip of the gun. This might be far better suited for displaying a non-physical, energy tether, but I am not as familiar with the particle system in Unity and I am curious to see if a chain link could be faked with a particle.
2. Creating a chain link by link or section by section procedurally based upon the direction the hook was firing in and the distance between the positions of the gun tip and hook base. This seems like a more direct solution, but could have higher processing cost as the links are created on the fly and in rapid succession.
3. Creating a chain that is hidden when not fired and is made to slowly appear when fired as the hook leaves the hookshot apparatus. This seems like the most likely solution, but I have little to no idea as to how it could be implemented.

I would not be surprised at all if there is a better solution that I didn't mention. I look forward to seeing what people suggest. Thank you.

# Answer
I recommend your second option, adding/removing links.

If option 1, using a particle system, is even possible, it is highly likely to be essentially reimplementing option 2 by twiddling the particle system from outside. You'll also likely have issues at the ends due to the particles being obviously different from the neighboring geometry. I've never seen a particle system trying to represent a solid object do a decent job of it.

Your option 3, a partially-hidden chain, is possible — I don't know if Unity can do it by default, but it's certainly something a GPU can support. Think of a "half-invisible texture" slid along the length of the chain and controlling the visibility of the chain surface (or an equivalent directly programmed in the shader).

However, I think your option 2, creating objects on the fly, is likely to be the way to go. Creating new objects isn't as unreasonable as you might think. Think about a shooting game with non-hitscan projectiles (rockets, grenades, strangely slow laser pulses, etc.): in a big fight you would have lots of temporary objects flying around. In fact, you could keep around a fixed set of chain link objects up to the maximum length and merely hide/show and position each one as needed — that should be very cheap.

Since you mention Zelda games, I'd like to point out the example of the pull-chains in the Arbiter's Grounds in *The Legend of Zelda: Twilight Princess*. There are several places where (due to sloppy positioning), you can *see* new chain links popping into existence at the wall when you pull a chain out or when it retracts. That is, they chose option 2, though specifically for a *flexible* chain.

All you need to do to avoid the visible glitch is to make sure the addition/removal is buried inside other geometry (in the case of a hookshot, inside the hand grip's model). Also, you can make a single model of several chain links to add/remove at once as long as it's short enough to fit inside.

Using individual links also means that you can add bending effects if you want. I wouldn't recommend trying to add simulated physics (very hard to get right) unless you want to focus on that, but you could have it *appear* to curve in flight, slacken when the hook hits something, or vibrate under tension — whatever looks good for its role in the game.
> 3 votes

# Answer
One option is to create a tiled "chain" texture and use a dynamically sized plane. Stretch the plane over the period of the shot while modifying the texture scale (tiling) to match. For 2D this should work pretty well. For 3D it would depend on how you rotate the plane and the angle between the plane and the camera and may not be suitable.

Otherwise, I'd probably go with #2. One way to mitigate the overhead of creating the links on the fly is to create them up front and disable them. Store them in an array and then they can be placed, enabled, and moved at will.
> 1 votes

---
Tags: unity, software-engineering, procedural-generation, particles, gameobject
---


# Question
Title: How can I optimize these GLSL bitwise operations?
I need the following part of my vertex shader simplified.

```
 Sb=Sb|((gl_VertexID&(128+1))<<9);
 Sb=Sb|((gl_VertexID&(512+4))<<6);
 Sb=Sb|((gl_VertexID&(2048+16))<<3);
 Sb=Sb|(gl_VertexID&(8192+64));
 Sb=Sb|((gl_VertexID&(256+32768))>>3);
 Sb=Sb|((gl_VertexID&(1024+131072))>>6);
 Sb=Sb|((gl_VertexID&(4096+524288))>>9);
 Sb=Sb|((gl_VertexID&2)<<18);
 Sb=Sb|((gl_VertexID&8)<<15);
 Sb=Sb|((gl_VertexID&32)<<12);
 Sb=Sb|((gl_VertexID&16384)>>12);
 Sb=Sb|((gl_VertexID&65536)>>15);
 Sb=Sb|((gl_VertexID&262144)>>18);

```

I have considered using a lookup table in which case it would be at least 2 MB for the best case I can imagine.

What this code needs to do is to reference in to an array. From Sb I use the last 20 bits. the first 10 of them reference the row and the last 10 them the column. I need these to progress as if they were integral numbers counting up from zero, but read backwards.

The output would look like this:

```
0000000000 0000000000
1000000000 0000000000
0000000000 1000000000
1000000000 1000000000
0100000000 0000000000
1100000000 0000000000
0100000000 1000000000
1100000000 1000000000
0000000000 0100000000

```

Edit: Speed is key. This needs to happen very fast... ..but should not use up valuable memory.

# Answer
You can use two small tables of 16 entries to lookup 4 bits at a time

```
const int table1[16] = {
    0x0,
    0x2,
    0x0,
    0x2,
    0x1,
    0x3,
    0x1,
    0x3,
    0x0,
    ...
};

const int table2[16] = {
    0x0
    0x0
    0x2
    0x2
    0x0
    0x0
    0x2
    0x2
    0x1
    ...
};

x = table1[gl_VertexID & 0xf] << 8;
y = table2[gl_VertexID & 0xf] << 8;
x |= table1[(gl_VertexID >> 4) & 0xf] << 6;
y |= table2[(gl_VertexID >> 4) & 0xf] << 6;
x |= table1[(gl_VertexID >> 8) & 0xf] << 4;
y |= table2[(gl_VertexID >> 8) & 0xf] << 4;
// and so on

Sb = x + (y << 10);

```
> 0 votes

# Answer
So it turns out that, the solution is to use a TBO for storing the lookup table. The uniform buffer could be faster, but because the uniform buffer can not hold the entire lookup table the added computational cost of the necessary bitwise operations would diminish this advantage. Therefor to my knowledge this would be the fastest solution.
> 0 votes

---
Tags: opengl, glsl, optimization
---


# Question
Title: LibGDX - Executing 2 different touchDown events in the same method
On the bottom left of my screen is a circle with an Arrow and on the bottom right is a circle with a gun. If the player is in jetpack mode and the Arrow "button" is clicked he flies like flappy bird (touch down = push him upwards, touch up = he falls down) - if the player is in jump mode he simply jumps.

My problem is I can't seem to fly the jetpack upwards AND shoot a bullet at the same time (i.e. the case where I'm tapping both the Arrow and the Gun). Is there some sort of trick I can use here?

My touchDown() method is in a class **Controller** looks like this:

```
@Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        int tapY = Gdx.graphics.getHeight() - screenY;
        //true if the arrow (bottom left) is tapped
        arrowClicked = inRange(upArrowSprite, screenX, tapY);
        //true if the gun (bottom right) is tapped
        gunClicked = inRange(gunSprite, screenX, tapY);

        // if arrow is pressed and player isn't in jetpack mode, make him jump
        if (arrowClicked) {
            if (!(player.getState() == ObjectState.JETPACK_MODE)) {
                player.setState(ObjectState.JUMPING);
                player.jump();
            // if the player is in jetpack mode, accelerate him upwards every time arrow is tapped
            } else {
            player.setTouchedDownFlying(true); // set boolean to be true
            player.setState(ObjectState.JETPACK_MODE);
        }
        }
        //if the gun is tapped (bot right), shoot a bullet
        if (gunClicked) {
            player.shoot();
            }
        return true;
    }

```

these are the relevant methods in **Player**:

```
public void update() {
    moveBy(xSpeed, -gravity);
    ...
    if(touchedDownFlying) {
        jetPackFly();
    }
    ...
}

public void setTouchedDownFlying(boolean bool) {
    touchedDownFlying = bool;
}

public void jetpackFly() {
        setySpeed(getySpeed() + flyAcceleration);
}

public void shoot() {
        Bullet i = new Bullet(this);
        bullets.add(i);
}

```

Any help is highly appreciated, thank you :)

# Answer
It doesnt work, because you dont count fingers on screen, so no matter how many fingers will be on screen, touchDown always returns first touched coodrinates, next touches are ignored. If you want to use multitouch, then you have to make use of pointer variable in touchDown method. Actually i answered very similar question once in stackoverflow, and im sure it works, so i will just shamelessly copy and paste my answer ;)

I encoutered similar problem once,trying to set up 3 buttons on screen. Those buttons can be pressed separately (then there is no problem, you always use just one finger and one pointer - therefore pointer ID can be ignored), but they should also react properly, if any two of them are pressed, or player presses all at once. You have to make use of pointer ID, given by InputProcessor. Pointer ID is an int from 0 to 9 range (for 10 fingers). I did it that way:

first declared three variables for three pointers:

```
int forwardPointer, leftPointer, rightPointer;

```

then in TouchDown method i checked, which finger pressed which button (was it first, second or third press?), and stored this information in my variables for future use.

```
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    if (game.forwardButton.contains(screenX, screenY)) {
        game.forwardButton.isPressed=true;
        forwardPointer=pointer;
    }
    if (game.leftButton.contains(screenX, screenY)) {
        game.leftButton.isPressed=true;
        leftPointer=pointer;
    }
    if (game.rightButton.contains(screenX, screenY)) {
        game.rightButton.isPressed=true;
        rightPointer=pointer;
    }}

```

and then, in TouchUp method i checked, which finger was lifted up (by comparing pointer ID from TouchUp method with stored pointer variable value), and according to this, i "relased" proper button.

```
    @Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
    if (pointer==forwardPointer) {
        game.forwardButton.isPressed=false;
    }
    if (pointer==leftPointer) {
        game.leftButton.isPressed=false;
    }
    if (pointer==rightPointer) {
        game.rightButton.isPressed=false;
    }}

```

https://stackoverflow.com/questions/28130461/libgdx-multitouch-handling-using-inputprocessor/28131934#28131934
> 1 votes

---
Tags: java, 2d, libgdx, physics
---


title: Datastructure for infinite 2D map

text:
# Question
Title: Datastructure for infinite 2D map
I started a 2D Tilegame programmed with libgdx which needs potentially infinite tiles. That means when the player arrives the border of the map it should be possible to generate even more tiles. So a simple 2D Array is not the best datastructure for that purpose. A better solution I found here in the comments from dlras2: A way to store potentially infinite 2D map data?

it seems like he put 2D arrays in 2D arrays and that again and again, that reduces a lot of memory compared to one array for all tiles:

The problem is that I dont know before how many times the arrays will be encapsulated so it should be easily possible to wrap a new Array around if it is needed.

dlras2 also posted his code in C#, but I dont understand anything from it. Do you have an idea how to implement such a datastructure of recursive Arrays in Java? Or how to translate the whole C# code into Java? I hope the other stuff like putting tiles in the right array I'll solve by my selve.

# Answer
Here is a possible solution.

Let us define a segment of map as a fixed size 2D array; 10 by 10 in this example.

Then let us use a hashmap (or whatever the equivalent is in Java) that keep track of the right segment to use. For example,

```
function getTile(x,y):
     segmentI = int(x/10);
     segmentJ = int(y/10);
     segmentToUse = hashmap[segmentI+segmentJ];
     if (segmentToUse doesnt exist) create new map segment, put into hashmap
     return segmentToUse[x%10][y%10];

```
> 0 votes

---
Tags: java, tilemap, tiled
---


# Question
Title: XNA C# Adding objects to List in another class
Hi all i started creating this XNA/C# version of Space invaders to get better at xna since i've only been using it for about 4 days.

I've managed fine till now..

So my problem is adding my Bullets to a List in another class. So i've tried working out the solution for about 3 hours now and i hope you guys can help me.

In the Player.cs class i've got a method FireBullet() wich should create a new Bullet.cs class and add it to the list in Game1.cs (it does not do this when you debug) in theory this should work(i think).

```
Linking all the corresponding classes will take too much room so i've uploaded it to github

```

https://github.com/Breinss/Space-Invaders-XNA-C-

says C in title ran out of character ment to be C# ^^

Thanks in advanced!

# Answer
> 0 votes
In class `Player` you are wrongly creating a new Game1 `theGame1 = new Game1();` instance. That means you are trying to run 2 games at once. This is not what you are trying to do. Your Game should only have 1 instance and that is in your `Program.cs` file in the main method which starts running your game:

```
static void Main(string[] args)
{
    using (Game1 game = new Game1())
    {
        //this is where you game begins, and the Game1() constructor
        //then initialize is called, and [ Update() , Draw() ] functions keep looping
        game.Run();
    }
}

```

Remove `Game1 theGame1` completely from your classes and use `XNAInvaders.Game1.VariableName` instead (or you could add `using XNAInvaders;` and then use `Game1.VariableName`, but since you have all classes under the same namespace (XNAInvaders), you can simply use `Game1.VariableName` without having to add the `using` statement).

So do

```
void FireBullet()
{
   Bullet newBullet = new Bullet(position);
   newBullet.Init();
   Game1.bullets.Add(newBullet);
}

```

So basically, every variable you have in the Game1 class can be accessed by using Game1.VariableName in any other class.

However are you sure you need a `Bullet` list in your `Game1` class ? You should keep your `Game1.cs` as simple as possible. You could design it a bit better, using more classes(?) so that the `Game1.cs` isn't that messy, it really makes a difference when your game becomes more complicated (Perhaps with using something along the lines of `Level.cs` to keep the variables there)

Edit: I forgot to mention something important, you have to make your Game1 Variables **static and public** if you want to access them from other classes (because you will obviously have a single `Game1` instance right ? So why would the variables not be static)

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