# Question
Title: How to calculate max region/area of 2d circles?
I have some 2d circles on a plane, each has its own minRadius and maxRadius. When two circles collides, both of them will shrink their radius, so the actual radius of a circle is in range \[minRadius, maxRadius\].

I need to calculate the max possible radius of each circle. See below image for an example.

Currently, I use the following algorithm to calculate the radius of each circle. I try to increase each circle's radius a little each steps, then check and solve if there is any collisions.

```
foreach c in circles: c.radius = c.minRadius;

for (int i = 0; i < 10000; ++i)
{
  foreach c in circles: c.radius = c.radius + 1
  foreach c in circles: calculate_radius(c)
}

function calculate_radius(c)
  collides = find_all_circles_which_radius_is_overlap_with_c()

  foreach x in collides {
    x.radius -= somevalue;
    c.radius -= somevalue;
  }
end

```

For now, the result looks fine, but the algorithm costs too much time.

So I wonder if there exists other ways to solve it?

=======================================================

@wondra counterexample(maybe)

The image below illustrates the problem.

From my understanding of your algorithm, the final radius of circle A is 1.6, the calculation sequence is (BC, AB, AD)

But if using my algorithm(increase radius by a small amount each step), the final radius of circle A is 1.5.

I don't think recalculate the dist matrix after each selection will solve the problem, as stated in my question, each circle may have its own minRadius and max Radius.

# Answer
> 3 votes
Lets put together some greedy algorithm. If we had two circles(circle centers), the solution is trivial, right? Just calculate the distance(pythagoras) between them and divide it by two.
But what if we had more? As you might agree, at least good solution, if not optimal, is always draw the smallest possible circles such as its radius is maximal possible.

```
while(hasCirclesToDraw)
draw(circles.GetSmallestCircle());

```

this information might not be helpful on its own, but if coupled with *how* to find such circle it will be working algorithm. If we had no circles drawn, which one will it be? The one\* with center closest to other center (\*actually this is pair of circles).
What about the second one? It can be harder because you must consider the circle is already drawn and had closer neighbour. Well... it is not, just subtract its radius from the distance. Also you might cache the distances calculated.

```
int[][] distMatrix;
for(int i = 0; i < circles.count; i++)
{
    Pair<int,int> edge = findShortest(distMatrix); // ignore -1 edges
    if(!circles[edge.first].hasRadius())
    {
    if(circles[edge.second].hasRadius())
        circles[edge.first].radus = distMatrix[edge.first, edge.second] - circles[edge.second].radius;
    else
        circles[edge.first].radus  = distMatrix[edge.first, edge.second] / 2;
    }
else if(){
    //i believe you can finish it for second circle of pair
}
    distMatrix[edge.first, edge.second] = -1; //"remove edge"
}

```

You can also optimize this by drawing any circles that doesnt have any other nearby (within double max radius) and removing them from the list before begining. Or ignore all big distances right away. You could also use priority queue instead of calculating distance/distance array - sort once and then only pop.
obviously, this will not work for extreme numbers of circles, because it requires n^2 space and the whole algorithm is n^3.
To illustrate the algorithm first steps (for ilustration purposes, the longes edges are not drawn at all):

1. find shortest edge, add two new circles(because on both ends there was nothing drawn). Remove edge (=mark -1)
2. find shortest edge, add only one new circle, because it already had circle drawn on one end. Remove edge (=mark -1)
3. step would be: find shortest edge(now the left most), do nothing, because on both end there is a circle. Remove edge (=mark -1)

---
Tags: collision-detection, collision-resolution
---


# Question
Title: How can I author objects with perspective that fit into a tile-based map but span multiple tiles?
I'm creating a tilemap city and trying to figure out the most efficient way to create unique building scenes. The trick is, I need to maintain a sort of 2D, almost-top-down perspective, which is hard to do with buildings or large objects that span multiple tiles.

I've tried doing three buildings at a time, and mixing and matching the base layer and colors, like this:

This creates a weird overlapping effect, and also doesn't seem that efficient from a production standpoint. But it was the best way to have shadows appear correctly on the neighboring buildings.

I'm wondering if modular buildings would be the way to go? That way I can mix and match any set of buildings together as tiles:

I guess I would have to risk some perspective and shadowing to get the buildings to align correctly.

What sort of authoring process could I use to allow me to create a variety of buildings (or other objects) that maintain this perspective while spanning multiple tiles worth of screen space? Would you recommend creating blank buildings, and then affixing art overlays as necessary to make the buildings unique? Or should they be directly part of the building tile (for example, create a separate tileset of buildings signs and colorings)?

# Answer
> 5 votes
I found an efficient way to build a city fast (or whatever you're trying to build) is definitely to go modular, and make indexed fittings for your buildings. For example:

Single buildings, referenced as A, B, C, etc...

Signs, skins, etc. associated to each:

Now you can mix and match to create a dynamic city quickly

Of the approaches I've tried, this works best.

# Answer
> 1 votes
I think what you are looking for is a form of parallel projection.

.

# Answer
> 0 votes
I think I found the best way to do it with the least amount of tiles...

All you need is 6 distinct tiles, composed of polygons:

Then you can create whichever building sizes you want from just these tiles:

And to resolve issue of fitting signs, textures, etc... just take the same approach! :)

---
Tags: tiles, tilemap, rpg, art
---


# Question
Title: Technique suggestion to render corroded pipes in 3D
We currently have a lot of data relating to cracks/corrosion/deformations in metal pipes which at present, can be viewed in a crude flat/2D application which makes the metal anomalies hard to spot.

What I would like to create is a virtual 3D pipe viewer that displays the pipe and then models all of the dents in it.

I have limited knowledge of graphics programming from University however, what I was thinking of doing is creating a height-map from the data given and then use tessellation to push/pull the vertices of the pipes mesh, similar to terrain generation techniques.

My Question(s):

* Can a tessellated square/plane be wrapped around to form a pipe (and would this approach loose accuracy)? (I've only ever manipulated vertices in the y-direction on a flat plane).
* Some of the dents are extremely small (1-5mm across/deep), would my approach be accurate enough to model these anomalies?
* Is this tessellated/terrain generation style the correct way to proceed or is there a simpler solution.

Any advise is welcome

# Answer
> 2 votes
Unless the 3D structure of the pipe is important to your application, I would strongly recommend against visualizing things in 3D. This requires turning the pipe to see all sides, and requires developing a UI for interacting with the pipe (rotate, zoom, change focus). These interfaces are difficult to learn, even for technical people. I have enough experience with poor interfaces to recommend that you stick to 2D whenever possible: it is much harder to screw up, and much easier to learn.

For linear pipe segments, you can easily display the whole pipe "rolled out" on the display. Highlighting corrosion/dents etc. can easily be done using lighting (i.e. normal mapping) or coloring the first/second derivative. Because a tubular pipe is very similar to a 2D plane as far as deformations go, you can simply pretend a cylindrical height map is 2D, and perform all calculations there.

If you do want to go 3D, then a plane can be mapped cylindrically, with the vertices being pushed/pulled towards the pipes axis rather than up/down. You should not lose accuracy doing this, as long as your source data is high enough resolution. Tessellation is almost certainly unnecessary, as it is unlikely that you have enough data to overwhelm a modern PC rendering just with a vertex buffer.

# Answer
> 0 votes
A straightforward cylindrical mapping should suit your purposes readily, if you look into the equation of a circle then you can come up with a 3D vector for any point on the pipe surface using all the data you have already, and your heightfield variation simply becomes variation of the radius parameter of the function.

If visualisation is your goal, then most likely what you actually want is a shader which highlights deviations from the 'normal' plane of the pipe. Whether you do that in 2D or 3D isn't really relevant, but I can imagine a simple shader that colours in a heatmap style based on the normal of the surface at any given point would quickly let you pick out deviations in the surface. Basically you would calculate the 'ideal' normal of the surface at any given point (i.e. point directly out from the centre of the pipe). Then pick your output colour based on how much the actual normal deviates from that ideal normal. If it doesn't deviate at all, then colour it black, if it deviates along the horizontal axis then raise the R component of the output colour, if it deviates along the vertical axis then raise the B component. Scale that appropriately, and you should see dents picked out as red/blue areas on the surface, with brighter colours indicating larger / more severe dents.

# Answer
> 0 votes
> Can a tessellated square/plane be wrapped around to form a pipe (and would this approach loose accuracy)? (I've only ever manipulated vertices in the y-direction on a flat plane).

It would be easiest to model a segment of a pipe as a cylinder and making an abstraction in your code so that you can think of the surface of the cylinder as a flat plane while mapping out the bumps and dents. I would be happy to give a more detailed explanation if you make this into a seperate question. Its an interesting problem that I think can be solved nicely.

> Some of the dents are extremely small (1-5mm across/deep), would my approach be accurate enough to model these anomalies?

Yes if you use enough vertices and do not visualize too much of the pipe at the same time (since there is a maximum to the number of vertices a GPU render at interactive rates). You can also use shading techniques to make it more clear where these little bumps are.

> Is this tessellated/terrain generation style the correct way to proceed or is there a simpler solution

I have seen this type of problem solved using these technique so I'm inclinded to say yes. However I'm not an expert.

*Small note: you see these are three questions, with three answers which is not really a good fit for this Q&A platform. If you seperate your questions and ask them again you will get better responses. Be sure to read the FAQ first!*

---
Tags: opengl, graphics, graphics-programming, tessellation, visualization
---


title: Rotating a GUI.Label relatively

text:
# Question
Title: Rotating a GUI.Label relatively
Learning Unity for 2D development, I want to create a text label.

So far, I have been using `GUI.Label` to write the text. It is above my sprite:

I would like to **rotate** the label relatively to the monster. In other words:

How can I achieve this? I have a feeling that `OnGUI()` is probably the wrong solution.

# Answer
You could get the rotation of the monster and then pass it into RotateAroundPivot before drawing the text. Alternatively if it's an option you could use the world space UI in Unity 4.6 beta to child the text to the monsters transform.
> 4 votes

---
Tags: unity
---


# Question
Title: How can I optimize a collision engine where order is significant and collision is conditional based on object group?
**If this is your first time on this question, I suggest reading the pre-update part below first, then this part.** Here's a synthesis of the problem, though:

> Basically, I have a collision detection and resolution engine with a grid spatial partitioning system where order-of-collision and collision groups matter. One body at a time must move, then detect collision, then resolve collisions. If I move all the bodies at once, then generate possible collision pairs, it is obviously faster, but resolution breaks because order-of-collision isn't respected. If I move one body a time, I'm forced to get bodies to check collisions, and it becomes a n^2 problem. Put groups in the mix, and you can imagine why it gets very slow very fast with a lot of bodies.

---

**Update:** I've worked really hard on this, but couldn't manage to optimize anything.

I successfully implemented the "painting" described by Will and changed groups into bitsets, but it is a very very minor speedup.

I also discovered a **big** issue: *my engine is order-of-collision dependent.*

I tried an implementation of unique collision pair generation, which definitely speed up everything by a lot, but broke the *order-of-collision*.

Let me explain:

* in my original design (not generating pairs), this happens:

1. a single body moves
    2. after it has moved, it refreshes its cells and gets the bodies it collides against
    3. if it overlaps a body it needs to resolve against, resolve the collision

this means that if a body moves, and hits a wall (or any other body), only the body that has moved will resolve its collision and the other body will be unaffected.

**This is the behavior I desire**.

I understand it's not common for physics engines, but it has a lot of advantages for *retro-style* games.
* in the usual grid design (generating unique pairs), this happens:

1. **all** bodies move
    2. after **all** bodies have moved, refresh all cells
    3. generate unique collision pairs
    4. for each pair, handle collision detection and resolution

in this case a simultaneous move could have resulted in two bodies overlapping, and they will resolve at the same time - this effectively makes the bodies "push one another around", and breaks collision stability with multiple bodies

This behavior is common for physics engines, **but it is not acceptable in my case**.

I also found another issue, which is major (even if it's not likely to happen in a real-world situation):

* consider bodies of group A, B and W
* A collides and resolves against W and A
* B collides and resolves against W and B
* A does nothing against B
* B does nothing against A

there can be a situation where a lot of A bodies and B bodies occupy the same cell - in that case, there is a lot of unnecessary iteration between bodies that mustn't react to one another (or only detect collision but not resolve them).

For 100 bodies occupying the same cell, it's **100^100** iterations! This happens because unique pairs aren't being generated - but **I can't generate unique pairs**, otherwise I would get a behavior I do not desire.

**Is there a way to optimize this kind of collision engine?**

These are the guidelines that must be respected:

* Order of collision is **extremely important!**

+ Bodies must move **one at a time**, then check for collisions **one at a time**, and resolve after movement **one at a time**.
* Bodies must have 3 group bitsets

+ **Groups**: groups the body belongs to
    + **GroupsToCheck**: groups the body must **detect** collision against
    + **GroupsNoResolve**: groups the body must **not resolve** collision against
    + There can be situations where I only want a collision to be detected but not resolved

---

---

---

**Pre-update:**

***Foreword****: I'm aware that optimizing this bottleneck is not a necessity - the engine is already very fast. I, however, for fun and educational purposes, would love to find a way to make the engine even faster.*

---

I'm creating a general-purpose C++ 2D collision detection/response engine, with an emphasis on flexibility and speed.

Here's a very basic diagram of its architecture:

Basically, the main class is `World`, which owns (manages memory) of a `ResolverBase*`, a `SpatialBase*` and a `vector<Body*>`.

`SpatialBase` is a pure virtual class which deals with broad-phase collision detection.

`ResolverBase` is a pure virtual class which deals with collision resolution.

The bodies communicate to the `World::SpatialBase*` with `SpatialInfo` objects, owned by the bodies themselves.

---

There currenly is one spatial class: `Grid : SpatialBase`, which is a basic fixed 2D grid. It has it's own info class, `GridInfo : SpatialInfo`.

Here's how its architecture looks:

The `Grid` class owns a 2D array of `Cell*`. The `Cell` class contains a collection of (not owned) `Body*`: a `vector<Body*>` which contains all the bodies that are in the cell.

`GridInfo` objects also contain non-owning pointers to the cells the body is in.

---

As I previously said, the engine is based on groups.

* `Body::getGroups()` returns a `std::bitset` of all the groups the body is part of.
* `Body::getGroupsToCheck()` returns a `std::bitset` of all the groups the body has to check collision against.

Bodies can occupy more than a single cell. GridInfo always stores non-owning pointers to the occupied cells.

---

After a single body moves, collision detection happens. I assume that all bodies are axis-aligned bounding boxes.

How broad-phase collision detection works:

**Part 1: spatial info update**

For each `Body` `body`:

1. * Top-leftmost occupied cell and bottom-rightmost occupied cells are calculated.
    * If they differ from the previous cells, `body.gridInfo.cells` is cleared, and filled with all the cells the body occupies (2D for loop from the top-leftmost cell to the bottom-rightmost cell).
2. `body` is now guaranteed to know what cells it occupies.

**Part 2: actual collision checks**

For each `Body` `body`:

* `body.gridInfo.handleCollisions` is called:

---

```
void GridInfo::handleCollisions(float mFrameTime)
{
    static int paint{-1};
    ++paint;

    for(const auto& c : cells)
        for(const auto& b : c->getBodies())
        {
            if(b->paint == paint) continue;
            base.handleCollision(mFrameTime, b);
            b->paint = paint;
        }
}

```

---

```
void Body::handleCollision(float mFrameTime, Body* mBody)
    {
        if(mBody == this || !mustCheck(*mBody) || !shape.isOverlapping(mBody->getShape())) return;

        auto intersection(getMinIntersection(shape, mBody->getShape()));

        onDetection({*mBody, mFrameTime, mBody->getUserData(), intersection});
        mBody->onDetection({*this, mFrameTime, userData, -intersection});

        if(!resolve || mustIgnoreResolution(*mBody)) return;
        bodiesToResolve.push_back(mBody);
    }

```

---

* Collision is then resolved for every body in `bodiesToResolve`.
* That's it.

---

So, I've been trying to optimize this broad-phase collision detection for quite a while now. Every time I try something else than the current architecture/setup, something doesn't go as planned or I make assumption about the simulation that later are proven to be false.

My question is: ***how can I optimize the broad-phase of my collision engine***?

Is there some kind of magic C++ optimization that can be applied here?

Can the architecture be redesigned in order to allow for more performance?

---

Callgrind output for latest version: http://txtup.co/rLJgz

# Answer
> 13 votes
***`getBodiesToCheck()`***

There could be two problems with the `getBodiesToCheck()` function; first:

```
if(!contains(bodiesToCheck, b)) bodiesToCheck.push_back(b);

```

This part is O(n2) isn't it?

Rather than checking to see if the body is already in the list, use *painting* instead.

```
loop_count++;
if(!loop_count) { // if loop_count can wrap,
    // you just need to iterate all bodies to reset it here
}
bodiesToCheck.clear();
for(const auto& q : queries)
    for(const auto& b : *q)
        if(b->paint != loop_count) {
            bodiesToCheck.push_back(b);
            b->paint = loop_count;
        }
return bodiesToCheck;

```

You are dereferencing the pointer in the gather phase, but you'd be dereferencing it in the test phase anyway so if you have enough L1 its no big deal. You can improve performance by adding pre-fetch hints to the compiler too e.g. `__builtin_prefetch`, although that is easier with classic `for(int i=q->length; i-->0; )` loops and such.

That's a simple tweak, but my second thought is that there could be a faster way to organise this:

You can move to using **bitmaps** instead, though, and avoiding the whole `bodiesToCheck` vector. Here's an approach:

You are using integer keys for bodies already, but then looking them up in maps and things and keeping around lists of them. You can move to a slot allocator, which is basically just an array or vector. E.g.:

```
class TBodyImpl {
   public:
       virtual ~TBodyImpl() {}
       virtual void onHit(int other) {}
       virtual ....
       const int slot;
   protected:
      TBodyImpl(int slot): slot(slot_) {}
};

struct TBodyBase {
    enum ... type;
    ...
    rect_t rect;
    TQuadTreeNode *quadTreeNode; // see below
    TBodyImpl* imp; // often null
};

std::vector<TBodyBase> bodies; // not pointers to them

```

What this means is that all the stuff needed to do the actual collisions is in linear cache-friendly memory, and you only go out to the implementation-specific bit and attach it to one of these slots if there's some need to.

To track the allocations in this vector of bodies you can use an array of integers as a bitmap and use bit twiddling or `__builtin_ffs` etc. This is super efficient to move to slots that are currently occupied, or find an unoccupied slot in the array. You can even compact the array sometimes if it grows unreasonably large and then lots are marked deleted, by moving those on the end to fill in the gaps.

***only check for each collision once***

If you've checked if *a* collides with *b*, you don't need to check if *b* collides with *a* too.

It follows from using integer ids that you avoid these checks with a simple if-statement. If the id of a potential collision is less-than-or-equal to the current id being checked for, it can be skipped! This way, you'll only ever check each possible pairing once; that'll more than half the number of collision checks.

```
unsigned * bitmap;
int bitmap_len;
...

for(int i=0; i<bitmap_len; i++) {
  unsigned mask = bitmap[i];
  while(mask) {
      const int j = __builtin_ffs(mask);
      const int slot = i*sizeof(unsigned)*8+j;
      for(int neighbour: get_neighbours(slot))
          if(neighbour > slot)
              check_for_collision(slot,neighbour);
      mask >>= j;
  }

```

***respect the order of collisions***

Rather than evaluating a collision as soon as a pair is found, compute the distance to hit and store that in a binary heap. These heaps are how you typically do priority queues in path-finding, so is very useful utility code.

Mark each node with a sequence number, so you can say:

* A10 hits B12 at 6
* A10 hits C12 at 3

Obviously after you've gathered all the collisions, you start popping them from the priority queue, soonest first. So the first you get is A10 hits C12 at 3. You increment each object's sequence number (the 10 bit), evaluate the collision, and compute their new paths, and store their new collisions in the same queue. The new collision is A11 hits B12 at 7. The queue now has:

* A10 hits B12 at 6
* A11 hits B12 at 7

Then you pop from the priority queue and its A10 hits B12 at 6. But you see that A10 is *stale*; A is currently at 11. So you can discard this collision.

Its important not to bother trying to delete all stale collisions from the tree; removing from a heap is expensive. Simply discard them when you pop them.

***the grid***

You should consider using a quadtree instead. Its a very straightforward data-structure to implement. Often you see implementations that store points but I prefer to store rects, and store the element in the node that contains it. This means that to check collisions you only have to iterate over all bodies, and, for each, check it against those bodies in the same quad-tree node (using the sorting trick outlined above) and all those in parent quad-tree nodes. The quad-tree is itself the possible-collision list.

Here's a simple Quadtree:

```
struct Object {
    Rect bounds;
    Point pos;
    Object * prev, * next;
    QuadTreeNode * parent;
};

struct QuadTreeNode {
    Rect bounds;
    Point centre;
    Object * staticObjects;
    Object * movableObjects;
    QuadTreeNode * parent; // null if root
    QuadTreeNode * children[4]; // null for unallocated children
};

```

We store the movable objects separately because we don't have to check if the static objects are going to collide with anything.

We are modeling all objects as axis-aligned bounding boxes (AABB) and we put them in the smallest QuadTreeNode that contains them. When a QuadTreeNode a lot of children, you can subdivide it further (if those objects distribute themselves into the children nicely).

Each game tick, you need to recurse into the quadtree and compute the move - and collisions - of each movable object. It has to be checked for collisions with:

* every static object in its node
* every movable object in its node that is before it (or after it; just pick a direction) in the movableObjects list
* every movable and static object in all parent nodes

This will generate all possible collisions, unordered. You then do the moves. You have to prioritise these moves by distance and 'who moves first' (which is your special requirement), and execute them in that order. Use a heap for this.

You can optimise this quadtree template; you don't need to actually store the bounds and centre-point; that's entirely derivable when you walk the tree. You don't need to check if a model is within the bounds, only check which side it is of the centre-point (a "axis of separation" test).

To model fast flying things like projectiles, rather than moving them each step or having a separate 'bullets' list that you always check, simply put them in the quadtree with the rect of their flight for some number of game steps. This means that they move in the quadtree much more rarely, but you aren't checking bullets against far off walls, so its a good tradeoff.

Large static objects should be split into component parts; a large cube should have each face separately stored, for example.

# Answer
> 3 votes
I bet you just have a ton of cache misses when iterating over the bodies. Are you pooling all your bodies together using some data oriented design scheme? With an N^2 broadphase I can simulate hundreds and hundreds, while recording with fraps, of bodies without any framerate drops into the nether regions (less than 60), and this is all without a custom allocator. Just imagine what can be done with proper cache usage.

The clue is here:

```
const std::vector<Body *>

```

This immediately raises a huge red flag. Are you allocating these bodies with raw new calls? Is there a custom allocator in use? It's most important that you have all your bodies in a huge array in which you traverse linearly. If traversing the memory linearly isn't something you feel you can implement consider using an intrusively linked list instead.

Additionally you seem to be using std::map. Do you know how the memory within std::map is allocated? You'll have an O( lg( N ) ) complexity for each map query, and this can likely be increased to O( 1 ) with a hash table. On top of this the memory allocated by std::map is going to thrash your cache horribly as well.

My solution is to use an intrusive hash table in place of std::map. A good example of both intrusively linked lists and intrusive hash tables is in Patrick Wyatt's base within his coho project: https://github.com/webcoyote/coho

So in short you'll probably need to create some custom tools for yourself, namely an allocator and some intrusive containers. This is the best I can do without profiling the code for myself.

# Answer
> 1 votes
Reduce the the count of bodies to check each frame:

Only check bodies that can actually move. Static objects only need to be assigned to your collision cells once after being created. Now only check collisions for groups which do contain at least one dynamic object. This should reduce the number of checks each frame.

Use a quadtree. See my detailed answer here

Remove all allocations from your physics code. You may wanna use a profiler for this. But I have only analysed memory allocation in C#, so I can't help with C++.

Good luck!

# Answer
> 0 votes
I see two problem candidates in your bottleneck function:

First is "contains" part - this is probably the main reason of bottleneck. It's iterating through already found bodies for every body. Maybe you should rather use some kind of hash\_table / hash\_map instead of vector. Then inserting should be faster (with searching of duplicities). But I don't know any specific numbers - I have no idea how many bodies are iterated here.

Second problem could be vector::clear and push\_back. Clear may or may not evoke reallocation. But you may want to avoid it. Solution could be some flags array. But you may probably have a lot of objects, so it's memory ineffective to have list of all objects for every object. Some other approach could be nice, but I don't know what approach :/

# Answer
> 0 votes
Note: I know nothing of C++, only Java, but you should be able to figure out the code. Physics is universal language right? I also realize this is a year old post, yet I just wanted to share this with everyone.

I have an observer pattern that basically, after the entity moves, it returns the object it has collided with, including a NULL object. Simply put:

(*I am remaking minecraft*)

```
public Block collided(){
   return World.getBlock(getLocation());
}

```

So say you are wandering around in your world. whenever you call `move(1)` you then call `collided()`. if you get the block you want, then perhaps particles fly and you can move left right and back but not forward.

Using this more generically than just minecraft as an example:

```
public Object collided(){
   return threeDarray[3][2][3];
}

```

Simply, have an array to point out the coordinates which, literally how Java does it, uses pointers.

Using this method still requires something other than a *priori* method of collision detection. You could loop this, but that defeats the purpose. You can apply this to Broad-, mid-, and narrow-collision techniques, but alone, its a beast especially when it works for 3D and 2D games quite well.

Now taking one more look, this means that, according to my minecraft collide() method, I will end up inside the block, so I will have to move the player outside of it. Instead of checking the player, I need to add a bounding box which checks which block is hitting each side of the box. Problem fixed.

the above paragraph may not be so easy with polygons if you want accuracy. For accuracy I would suggest defining a polygon bounding box that isn't a square, but not tesselated. if not, then a rectangle is just fine.

---
Tags: c++, collision-detection, performance, optimization, grid
---


# Question
Title: Matrix rotation wrong orientation LibGDX
I'm having a problem with matrix rotation in libgdx. I rotate it using the method matrix.rotate(Vector3 axis, float angle) but the rotation happens in the model orientation and I need it happens in the world orientation.

For example:

on create() method:

matrix.rotate(new Vector3(0,0,1), 45);

That is ok, but after:

on render() method:

matrix.rotate(new Vector3(0,1,0), 1);

I need it rotate in world axis.

# Answer
> 1 votes
You need to transform the world space rotation vector to model space before applying the rotation. Vectors are transformed with inverse transpose of the matrix, i.e. v'=transpose(inverse(M))\*v

Because models generally define model-\>world matrix you need to invert this to get world-\>model matrix. So you need to calculate v' = transpose(inverse(inverse(model\_to\_world)))\*v = transpose(model\_to\_view)\*v before applying the rotation. Also note that the w-component of the vector must be 0

# Answer
> 0 votes
You need to transform the world axis to your model's coordinate system first. You can do this by applying the model's current transformation matrix to the axis vector through multiplication; like so:

```
matrix.rotate(axis.mul(matrix), angle);

```

---
Tags: java, 3d, libgdx, rotation, matrix
---


# Question
Title: Working with retina graphics on Unity 2D
I begun trying Unity for iOS 2D development.

I am curious about how to work with retina devices. The first thing I did was create a 1136x640 solid rectangle sprite and throw it into my scene, then run the game on my iPhone 5.

My expectation was that this image would perfectly fill the screen - that is, the retina would "kick in". Alas, this was not the case: my sprite was much smaller than the iPhone's screen.

Then I saw the main camera game object, and played around with the size property. By default is was like 5, but I determined that the number I needed for my sprite was somewhere around 3.2.

This works and looks fine in my phone. But I am unsure if this is how I am suppose to do things: what is the correct way of supporting retina images? I feel like guessing the size property of the main camera is a bit hackish. Actually, how do I know if Unity is indeed using retina?

# Answer
Unity provides the `Screen` class which provides the current resolution and the screen's current DPI.

Unity won't have a concept of "kicking in Retina" though.

The game will simply run at a higher resolution if Retina technology is present on the device, and in fact, a common "hack" (that I would discourage the use of) to detect Retina is to simply check if the game is running on an Apple device that supports it.

Now there are Android devices and PC displays that have even higher DPIs so you should use a device-agnostic method to detect high-DPI screens.

And a small note, I'm not sure if you were just testing the DPI, but your example sounds like what you wanted was a "pixel perfect" camera, where 1 pixel directly corresponds to 1 unit in Unity. The formula I've used to get the correct size to do this is:

`screenWidth / ((( screenWidth / screenHeight ) * 2 )`

This provides a value that can be used with the `size` variable of an orthographic camera.
> 3 votes

---
Tags: unity
---


# Question
Title: How relevant is the ability to move/rotate buildings post construction in city builders?
I am playing with the concept of a city builder and I have seen many around, but I am still fresh in the area of game design.

I have seen city builders where, once you build a building, you have to demolish it to free the space in order to redesign your city. Once you start with a mistake, you have to work around it and in the end you get...ugliness. Improvisation. But its realistic. You have to plan ahead. Maybe restart the game without making that mistake. But this is discouraging to do. I often get frustrated with punishing games and feel no obligation to take the negative impact of my actions.

On other hand you have games that let you reposition / rotate the buildings after you construct them. While this is obviously unrealistic, you don't get punished for your earlier mistakes and have the freedom to aesthetically reshape your city to your liking. Still, you don't require foresight and I feel you are almost robbed of the reward of the foresight. Also, it breaks the immersion somewhat, you feel like "playing a game".

I can't touch on the relevancy of this. It seems such a trivial matter but I can't put my finger on it.

# Answer
> 1 votes
I agree with your sentiment that the "punishment" in games are sometimes a bit harsh, especially when having to restart a game in order to fix one or two simple mistakes.

Even in games that aim for realism, they are still a form of **entertainment** and as such I think they should avoid frustration as much as possible.

To that end, some ways to solve your particular problem would be:

* Allow an **undo** function, which would allow the last building placed to be removed without penalty. This can have a cooldown timer to prevent the player from overusing it (if needed). You can also limit the number of uses per game, to further prevent abuse.
* Allow buildings to be rotated/moved (or whatever) at a **very high cost**. This idea has been used in many different styles of games to prevent having to restart on account of a single (or very few) mistake, but still allow the player to continue by fixing these problems. RPGs use this by allowing characters to be re-spec'd at later stages in the game.
* If you want to keep it more tied to the game (i.e. avoid breaking immersion) you could (for example) have a "fund" that is specifically tailored to building maintenance or retro-fitting (or whatver you want to call it in-game). This fund can then be built up by the player (in whatver way seems fitting) and can then be used to alter buildings. To make it more "real" you could limit this "maintenance" to a single building at a time and make it take some amount of time (relative to how much money is spent) to complete before subsequent buildings can be altered. Using this method, it would be much more realistic, and it would actually add an extra layer to your gameplay.

Just some ideas for you. Obviously, whatever you implement will depend greatly on what your specific goals are and how the game plays in testing.

# Answer
> 2 votes
This is simply a design decision that you, as the developer, will need to make on your own terms. There isn't a correct answer to the question. Some paths you could consider:

* Poll the users on an established game's forums and determine what their communities prefer.
* Implement different difficulty levels in your game: Easy lets you rotate, Hard does not.
* Implement the rotation as a feature and let the player decide if they want to utilize the function or test their design skills themselves.

---
Tags: game-design, game-mechanics
---


title: Command Interface design for RTS

text:
# Question
Title: Command Interface design for RTS
Commands may have different target type; like NONE, COORD, UNIT.
Some example commands may be: Attack (target UNIT), Move (target COORD), AttackMove (target COORD), Stop (target NONE), UseAbility (target ability.getTargetType).
Commands will be executed by UI or AI.
So in an OOP approach here, what methods should my Command interface have?
For the command execution has access to the target the command wants.

# Answer
> 1 votes
There are not so many combinations when you write them all down.

We just have a bunch of overloaded methods alike:

```
CmdArmy(cmdType)
CmdArmy(cmdType, Unit)
CmdArmy(cmdType, Coord)
CmdArmy(cmdType, Param)
CmdArmy(cmdType, Coord, Param)

```

Where `cmdType` is a key alike:

```
ctAttack, ctMove, ctStop, ctAbility, ctEtc ...

```

It's not OOP, but it's going along the lines of KISS quite well.

# Answer
> 0 votes
I'd use a simple base class. That allows you to write commands like this (You didn't specify a language so I'll write something C#-like, using some concepts from Unity):

```
abstract class Command
{
    abstract string Description {get;} //Maybe you want all commands to have a description in your UI
    abstract string Name {get;}//This is also for the UI. Neither of these affect your logic
    //...More things you want all commands to have

    abstract void Apply(UnitController unitController, Action onCompletedCallback);

}

class MoveCommand : Command
{
    override string Description
    {
       return "This moves a Unit" //You'd probably have some logic here for localized strings instead of a literal
    }

    override string Name
    {
        return "Move" //See above
    }

    private readonly Vector3 TargetLocation;

    //...More command specific members

    MoveCommand(Vector3 targetLocation)
    {
        TargetLocation = targetLocation;
    }

    override void Apply(UnitController unitController,Action onCompletedCallback)
    {

        //Something along the lines of:
        unitController.MoveTo(TargetLocation) //Unit controller owns the logic for movement

        // --------------------Or---------------
        var pathFinder = unitController.GetComponent<Pathfinder>();
        if(pathFinder == null)
             //Throw some exception
        pathFinder.Move(TargetLocation,onCompletedCallback); //Path finder owns the logic for movement

        //---------------------Or---------------
        var movementMangager = GlobalManagers.Resolve<IUnitMovementManager>();
        movementManager.MoveUnit(unitController,TargetLocation); //Some class owns the logic for movement.
    }
}

```

---
Tags: rts, oop
---


# Question
Title: Using multiple strings within the path to Write to Text File
In Unity3D, How would I use something like this: `path = "C:\Users\Jonathan\Documents\FileData" + fileName + ".txt";` so I can make a for loop and create several text files under desired path?

The loop looks like this currently:

```
named = namesAsset.text.Split ('\n');
sliced = statAsset.text.Split ('\n');
for (int i = 0; i < named.Length; i++) {
    fileName = named[i].ToLower();
    path = "C:\Users\Jonathan\Documents\FileData" + fileName.Substring(1) + ".txt";
    File.WriteAllText(path, sliced[i]);
    Debug.Log (named[i]+".txt");
}

```

But there is a problem: They won't accept this! It spits out the error that the name has an invalid char.

Full script:

```
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Text;
using System;

public class SplitPage : ScriptableWizard {

    public TextAsset statAsset;
    public TextAsset names;

    public string[] named = new string[151];
    public string[] sliced = new string[151];
    public string path;

    public string fileName;

    [MenuItem("GameObject/SlicePage")]
    static void CreateWizard() {
        ScriptableWizard.DisplayWizard<SplitPage>("Split Text File", "Create");
    }

    void OnWizardCreate() {
        named = names.text.Split ('\n');
        sliced = statAsset.text.Split ('\n');
        for (int i = 0; i < named.Length; i++) {
            fileName = named[i].ToLower();
            path = "C:\Users\Jonathan\Documents\FileData" + fileName.Substring(1) + ".txt";
            File.WriteAllText(path, sliced[i]);
            Debug.Log (named[i]+".txt");
        }

    }
}

```

# Answer
> 1 votes
It is impossible to know for certain from the given code what the issue is, but a reasonable guess is that you `namesAsset` string contain DOS/Windows style line endings, and therefore when you split by `'\n'` you leave an `'\r'` at the end of strings.

I of course assume that the path you use is only a placeholder for code that reference the user folder properly.

---
Tags: c#, file-format, text
---


# Question
Title: How do I properly import an fbx 3D model into Unity3D?
I am trying to properly import a 3D model that was made for my game in Unity3D. I was able to import the model, and I put the texture on it, but there are several other files that go unused. I think I'm not importing the files properly, or I'm not using the files properly.

The files provided for me are as followed: (You can see these in this link as well)

* Cheese.FBX
* Cheese.obj
* Cheese.png
* Cheese\_D.png (What does the "\_D" indicate?)
* Cheese\_N.png (What does the "\_N" indicate?)

Perhaps I am overthinking it, but i feel like I should be attaching cheese\_d and cheese\_n to the prefab I'm making somehow, but I don't understand their function. I am fairly new to 3D modeling, so I think I'm missing some conventions.

# Answer
You probably don't need .obj if you want to use .fbx.

\_D usually indicates a diffuse texture, \_N is a normal map. You must create a new material and assign those textures into it.
> 2 votes

---
Tags: unity, models, fbx
---


title: Refresh rate in PSM apps

text:
# Question
Title: Refresh rate in PSM apps
In main loop of PSM app:

```
public static void Main(string[] args)
{
    Initialize();
    while (true)
    {
        SystemEvents.CheckEvents();
        Update();
        Render();
    }
}

```

we are not actually controlling cycle length. I guess the delay is implemented internally in

```
SystemEvents.CheckEvents()

```

function since it's the only one that is no defined by us. My questions are:

1. Is my assumption right about how refresh rate controlled in app?
2. Is there any function (or app setting) in SDK that allows to set refresh rate to any other than 60 fps?

# Answer
The PSM documentation for `CheckEvents()` says:

> Checks for system events and updates the system state.

This is not related to framerate, but for handling application minimizes and maximizes via the PS button.

Now, for `Update` and `Render`, you will notice that you are implementing both those functions. In the sample PSM application, `Render` will eventually call `GraphicsContext.SwapBuffers()`. `SwapBuffers` will wait for a retrace to actually swap the buffers, so it is the one that is actually capping your framerate.

I think the Vita goes at 60fps, but it's probably better if you don't take any guarantees, and update your frame logic at whatever framerate makes the most sense for your game, calling 0, 1 or more logic updates per graphics frame.

That's how I make my games, regardless of the platform.

And no, you can't change the display framerate on the vita.
> 2 votes

---
Tags: psm
---


title: Fullscreen transition time

text:
# Question
Title: Fullscreen transition time
I'm not sure whether this is the correct site to ask this question, but why does it sometimes (game-specific, usually) take really long to enter / exit a fullscreen game (black screen for ~1-5s)? And why don't we have these problems for example when entering a Windows 8 fullscreen app?

# Answer
> 5 votes
There are multiple points that come into play:

1. Switching from windowed to full-screen mode often involves recreating some rendering / drawing contexts which simply needs some time to do some "administrative" tasks, such as allocating memory. This may also involve finding a matching resolution that works (e. g. see the documentation for this D3D9 method) plus the time the monitor itself needs to adjust internally to this new set resolution.
2. As a result of #2, some assets may need to be reloaded which takes time.
3. Finally, based on the new rendering contexts and the assets, the scene needs to be rendered again. The rendering itself should not take long **\[\*\]** but the setup might, for example if a complete scene-graph systems needs to be repopulated from the previous state.

**\[\*\]** On the one hand, full screen mode usually involves more pixels to be rendered on. On the other hand, an application running in full-screen mode has a more exclusive/direct access to the rendering devices, which should speed up things again. See also this answer on Arcade.SE. All depends on the application and the chosen screen resolution, but in the end should play no major role for the actual switching time between the two states.

# Answer
> 2 votes
I would say that the most time-consuming task that needs to happen in most games is recreating video memory resources (textures, render targets, meshes) in response to a "device lost" event (note that this is specific to Direct3D 9 and earlier).

Taken from MSDN: http://msdn.microsoft.com/en-us/library/windows/desktop/bb174714%28v=vs.85%29.aspx#Resources

> The device makes a transition to the lost state when an event, such as the loss of keyboard focus in a full-screen application, causes rendering to become impossible. *(...)* A lost device must re-create resources (including video memory resources) after it has been reset. *(...)* If the device can be restored, the application prepares the device by destroying all video-memory resources and any swap chains.

Direct3D 10+ applications don't have this concept of a lost device state, and avoid most of this bookkeeping work in the process, I believe by virtue of the fact that the WDDM implements "virtual memory" for video RAM. That might explain why you wouldn't see this behavior in Metro applications.

# Answer
> -1 votes
In a game it needs to re-render all the things on screen, it also needs to recalculate the position on screen... Stuff like that. In a "simple" app, it just re-draws some stuff (buttons, text-fields...), and it's done. I think that may answer your question.

---
Tags: screen, screen-management
---


# Question
Title: How should I texture objects in Blender to use in Unity?
I need to model some things to use in Unity. How should I texture objects (road, tree, etc.) in Blender? I almost lost all textures when I exported and loaded them into Unity.

# Answer
> 1 votes
1. Model your 3D art in Blender.
2. UV-map textures to your models in Blender.
3. Import the .blend files into Unity.
4. Import the textures into Unity (unless you prefer to include them in the .blend file).
5. Set the appropriate textures on the auto-imported materials.

That's about it.

# Answer
> 0 votes
When you import a model from Blender(as .fbx or .obj ..etc), the textures will not be imported, but vertex colours will.

Textures and models are not linked when performing an import from certain file types. Save the textures separately and then import these textures into Unity. After you have your model and textures in Unity you can create a prefab with the model and texture by dragging the model into the scene and dragging the texture onto the model.

If the model is complex and comprised of several parts you can save several textures and apply them to individual parts of the model too.

---
Tags: unity, blender
---


# Question
Title: How do I generate solar systems for a 2d universe map, but still look random
I need to generate 64 systems separated into 16 sectors, each with 4 systems. Each system must have another system within 10 units in it's own sector, but no closer than 3. One system in a sector must have a non-sector system within 20 units, but no closer than 8. When I made a formula that satisfies these requirements, I end up with a very visible grouping of 16 sectors in a box formation with very little variety. Probably because I want it output into an array so I can track distances, etc.

I'd do a random generation, where it just places a system on a grid and then makes sure it doesn't conflict with a rule, and then find a way to group them, but it just seems beyond me right now. I wouldn't be sure how to check for inability to place another system... I'm probably looking at the problem from the wrong angle.

Any help?

Each dot is a system, the grey background is just a box to make it temporarily easier to see.

# Answer
Okay, my two cents:

In your problem, I would try with a heavily modified Poisson-Disk-Sampling.
This method will first Poisson-Sample a **Sector**, and, after sampling enough **Sectors**, will sample a universe. This means the algorithm runs in two phases. *This may be costintensive!*

Some thoughts to it. Consider a **Sector** being a disk with radius `sec`, and a **System** a disk with radius `sys`.

---

---

## How big have the radii to be too fullfill your criterias?

`sys` has to be at least `1.5`. This way, if two disks are placed next to each other, the center-points of the two disks are `3.0` appart, your minimum distance. Additionally, `sys` may not be larger than `5.0`, otherwise **Systems** would be more than `10.0` apart.
So when generating your disks, you can evenly give them a `sys` of `1.5` and allow gaps, or assign a randomvalue in the range of `1.5` to `5.0` to the discs. In the second case a newly placed disc should always touch at least one already existing disc to keep the **Sector** small.

---

`sec` is a bit more difficult to compute. What is the (approximate) minimal radius? Well, the minimal radius is achieved when all for systems in the sector are placed in a square with `sys` being `1.5` for each **System**. This means that the minimal `sec` is the diagonale between two **Systems** \+ a safety margin around the outermost **Systems**.
I happenend to draw a picture of this in paint:
I rounded a bit and came to the conclusion that the smallest possible `sec` is `≈6.0`. This is because the light-blue-lines count full, the diagonale (dark red) only counts half (as it goes through the center).
The computation of the *maximum* `sec` proved to be very difficult, so I will only make assumptions here (though detailed ones in my opinion).

First: When we leave your second rule out, the maximum `sec` is 4 + 10 + 10 + 10 + 4 = 38 This is your solution when you place all four **Systems** in one line. **THIS IS OBVIOUSLY NOT THE DESIRED SOLUTION**, as you could not guarantee that if you placed a similar **Sector** next to it, any **System** would have a non-**Sector**-**System** in range. We can however make an assumption (which is just that, it does not have to be true). We can assume that the **Systems** are more or less evenly distributed. This means that if a **System** covers `50%` of anothers **Sectors** Area, it will most likely have also a **System** from the other **Sector** in Range. Time to Math!

```
a*a + b*b = c*c
a = sec
b = sec + sec + (sec-4)
c = 20

sec^2 + (3*sec - 4)^2 = 20^2    ==>    sec ≈ 7.5

```

As you can see, to nearly guarantee all conditions your `sec` has to be in the range of `6.0` and `7.5`. Pretty small **Sectors**, huh? If you weaken the conditions, your sectors will grow in size, but so will the average spacing between Non-**Sector**-**Systems**. Your call.

One note. This also limits the distance of a **System** from the **Sector**-Midpoint. Satisfying all conditions, a **System** is between `2.0` and `3.5` units away from the Midpoint. *Use this in your calculations!*

---

---

To recap:

> `sys` is in the range of `2.0` and `3.5`
> `sec` is in the range of `6.0` and `7.5`

I must admit, I actually never generated a star field with this method, only draw a lot of circles on a lot of paper and it looked nice and stuff. The actual result can *(and probably will)* be ... **interesting**. You will have to play alot with `sys` and `sec` to produce nice looking results, but I hope I could help you.
> 3 votes

# Answer
I think the main problem is that you are generating your sectors too closely together, so that according to your criteria, sectors too close will be discarded, thus leaving those sectors that are *just* far enough apart. This results in a tight packing, which would be a hexagonal grid if you use Euclidean distance, or a square grid if you use Manhattan. Is that what's happening here?

Instead, try generating your sectors really far apart, and pulling them together until they are close enough together. Note that if you overdo this, you'll end up with long chains or very sparse tree-like structures. If the results are too sparse to your liking, you can try adding a criterion for maximum universe size, so that you keep pulling the farther ones together.

Iterative algorithms are great for such problems; I recommend trying a force-directed algorithm.
> 1 votes

# Answer
> I'm probably looking at the problem from the wrong angle.

Yes, you are. You are confusing "uniform" with "random". People intuitively think that random means "more or less equal in all space". That is wrong, because that is uniform. Truly random (or pseudorandom) tends to form clusters of points close together or very far away. Here is a picture illustrating what I mean.

Image taken from here.

By the way in that image you also have your answer. You may want to take a look at Sobol Sequences, and play with them around your requirements. Or, if you really want random distributions, you will need to accept some points very close or very far away from each other.
> 1 votes

---
Tags: mathematics, algorithm
---


# Question
Title: What does the "random element" do in Cellular Automata
I'm reading this post on TutsPlus regarding procedural level generation using cellular automata. My question arises in this code snippet:

```
float chanceToStartAlive = 0.45f;

public boolean[][] initialiseMap(boolean[][] map){
    for(int x=0; x<width; x++){
        for(int y=0; y<height; y++){
            if(random() < chanceToStartAlive){
                map[x][y] = true;
            }
        }
    }
    return map;
}

```

In the first line, the author declares a float that represents 45%. This makes sense. However, the role of this is unclear to me. In this line:

```
if(random() < chanceToStartAlive)

```

A random number is being generated, and being tested if it's less than `0.45f`. Since it is an inequality, this expression can either return `true` or `false` correct?

How exactly is this percentage affecting this loop?

Thank you!

# Answer
> 1 votes
I assume random() generates a random number between 0 and 1. This number will be less than 0.45 45% of the time.

I will use an example to show you why:

Let's say these rectangles represent a field, and it's raining. We would like to know how often the drops fall on the green part. For the rectangle on the top, the green part is half the total rectangle. So the drops will fall on the green part half of the time.

On the second retangle, the green part is 25% of the total so 25% of the drops will end up there.

In your case, this means that `map[x][y] = true;` will be called 45% of the time. In other words, 45% of the map booleans will be set to true.

`chanceToStartAlive` allow you to choose the percentage of *true* cells.

---
Tags: procedural-generation, maps, random
---


# Question
Title: What is a direction vector and why should it be normalized?
I've been trying to get the hang of vectors and I read Wolfire's blog about linear algebra and I seem to understand most stuff except when it comes to storing a direction as a vector and using it by multiplying the velocity by it. I know it has to be normalized (have a length of 1), but why does it have to be 1 specifically and how would I use it?

Also how would I represent it in 2D \[x,y\] coordinates. For example if I wanted a direction such as North-East?

# Answer
A 2D vector has two values (`x` and `y`), and it basically says how far you go from the point of origin in the x- and in the y-direction. For example, a vector of (3,4) goes 3 units in x direction and 4 units in the y direction, resulting in an angled line with a length of 5 (3² + 4² = 9+16 = 25, root of that is 5). So the vector basically gives you two pieces of information:

1) Direction and

2) length

If you now want to calculate where an object moves, you take `direction * speed`, but you have to normalise the vector to the length of 1 so it doesn't skew your results. If you used the above vector as is, it would multiply your speed by 5 (its length), so your object would move five times as fast as intended. If you have a normalised vector with a length of 1, the 1 is neutral in multiplications and doesn't cause you any trouble.

I'm sure there are more technical explanations, but that's the gist of it.
> 9 votes

# Answer
Christian's answer already covers most of what you asked for expect your concrete example from the end of your question about representing "North-East":

First of all, it depends on your coordinate system. But if we look onto your world from the top and assume that North/South is the y-axis (+y = North) and West/East is the x-axis (+x = East), you could represent the direction "North-East" as the (un-normalized) vector \[1, 1\] or the (normalized\] vector:

Example visualization in WolframAlpha.
> 2 votes

# Answer
## Simple answer

It's just a standard and it makes things easier for everyone.

## More info...

> Why does it have to be 1 specifically?

It doesn't. It's just a standard. If you want so in your game, you can make all your vectors of length 2. I wouldn't call it normalized though because **normalization** has a mathematical definition of its own.

As long as you have all your vectors in the game **standard** (all of them of unit length N, doesn't matter what N is, but 1 is pretty standard), you could still do the **direction\*speed** technique.

All that said, I don't know anyone who uses other unit lengths other than 1. I just want you to know that it **doesn't have** to be so, it's just much easier for everyone.

> How would I use it?

A normalized vector would signify **direction**. That makes it convenient to mash up with **speed**.

For every frame, instead of doing `position = newPosition` or `position = position + movementVector`, you could generalize everything with `position = position + direction*speed`.
> 1 votes

---
Tags: vector, linear-algebra
---


title: LWJGL Framebuffer Texture Problem

text:
# Question
Title: LWJGL Framebuffer Texture Problem
I am trying to get a terrain rendering system I wrote a while ago with LWJGL. This terrain rendering system is quite simple: a quad mesh is split as the camera moves closer to it, each time a new quad is created a FBO is used to render a heightmap using perlin noise implemented in a pixel shader. This texture is then applied to the quad and sampled for normals and elevation. The problem I am having with it is a bit odd... So the camera starts out at a reasonable distance away from the root quad. This causes it to be split into 4 quads, each with their own heightmap. This can be represented as follows:

As the camera moves closer the program acts as expected and the nearest quad (the white one) is split into 4 children quads, again, each with their own heightmap.

Now here is where the problems start to arise... When the camera moves even closer the blue quad that you see above (the larger one) is split into 4 quads as expected. Yet what is strange is that the smallest green quad's heightmap is changed to be the heightmap of the largest red quad shown above...

1 is the quad that has it's heightmap changed when the blue quad is split. #2 refers to the quad that the green quad seems to "take" it's new heightmap from.

This continues to happen with different quads as the camera moves closer. Yet it is only the green quads that exhibit this type of behavior. I suspect this because the green quad is the last quad to have a heightmap rendered and this can be seen as follows:

```
QuadMesh q1 = q.children.get(0);
        QuadMesh q2 = q.children.get(1);
        QuadMesh q3 = q.children.get(2);
        QuadMesh q4 = q.children.get(3);

        Heightmap.getHeightmap(q1);
        Heightmap.getHeightmap(q2);
        Heightmap.getHeightmap(q3);
        //q4 is the green quad
        Heightmap.getHeightmap(q4);

```

The getHeightmap() method looks like so:

```
public static void getHeightmap(QuadMesh q){
    float scale = q.width/1024;
    float size = q.width;
    int unit = heightmapTextureUnit;
    glActiveTexture(GL_TEXTURE0 + unit);
    int heightmapTexture = glGenTextures();
    glBindTexture(GL_TEXTURE_2D, heightmapTexture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, 256, 256, 0, GL_RGB, GL_FLOAT, (java.nio.ByteBuffer)null);

    int framebuffer = glGenFramebuffers();
    glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
    glReadBuffer(GL_COLOR_ATTACHMENT0);
    glDrawBuffer(GL_COLOR_ATTACHMENT0);

    glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, heightmapTexture, 0);
    glViewport(0,0,256,256);
    glUseProgram(noiseProgram);
    glUniform1i(glGetUniformLocation(noiseProgram, "permSampler2d"), permutationTextureUnit);
    glUniform1i(glGetUniformLocation(noiseProgram, "permGradSampler"), gradientTextureUnit);
    glUniform3f(glGetUniformLocation(noiseProgram, "meshOffset"), q.meshOffset.x, q.meshOffset.y, q.meshOffset.z);
    glUniform1f(glGetUniformLocation(noiseProgram, "scale"), scale);
    glUniform1f(glGetUniformLocation(noiseProgram, "size"), size);
    glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
    drawQuad();

    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glDeleteFramebuffers(framebuffer);
    glViewport(0,0,1024,768);
    q.HeightmapTexture = heightmapTexture;
    q.HeightmapUnit = unit;
    heightmapTextureUnit++;
}

```

To render a quad, the following method is used:

```
public void render(Matrix4f view, Matrix4f projection){
    glUseProgram(p_ID);

    float scale = width/1024;

    FloatBuffer matBuffer = BufferUtils.createFloatBuffer(16);

    this.cubeMatrix.store(matBuffer);
    matBuffer.flip();
    glUniformMatrix4(glGetUniformLocation(p_ID, "cubeMatrix"), false, matBuffer);

    view.store(matBuffer);
    matBuffer.flip();
    glUniformMatrix4(glGetUniformLocation(p_ID, "V"), false, matBuffer);

    projection.store(matBuffer);
    matBuffer.flip();
    glUniformMatrix4(glGetUniformLocation(p_ID, "P"), false, matBuffer);

    glUniform1f(glGetUniformLocation(p_ID, "scale"), scale);
    glUniform1f(glGetUniformLocation(p_ID, "size"), width);
    glUniform1f(glGetUniformLocation(p_ID, "intensity"), intensity);
    glUniform3f(glGetUniformLocation(p_ID, "meshOffset"), this.meshOffset.x, this.meshOffset.y, this.meshOffset.z);
    glUniform3f(glGetUniformLocation(p_ID, "color"), color.x, color.y, color.z);
    glUniform1i(glGetUniformLocation(p_ID, "heightmap"), HeightmapUnit);

    glBindVertexArray(VAO_ID);
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO_ID);

    if(Main.wireframe)
    glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
    else
    glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
    glDrawElements(GL_TRIANGLES, QuadData.getIndexLength(), GL_UNSIGNED_INT, 0);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
    glBindVertexArray(0);
    glUseProgram(0);
}

```

EDIT: So going through the program a little bit more carefully returned a few errors. Apparently when heightmapTextureUnit gets to be 80 and above the error "GL\_INVALID\_ENUM" is returned when the texture is activated. This is returned when the arguemnt of glActiveTexture() is not within the bound of GL\_MAX\_COMBINED\_TEXTURE\_IMAGE\_UNIT. Is it impossible for me to have more than 80 textures? Also the error GL\_INVALID\_OPERATION is returned when I use the glDrawElements() method...but only when there are around 150 quads active. What causes this?

# Answer
Although your question is well formed and the screenshots help a lot understanding the problem, it would be very hard or impossible for others to identify your bug with the given information. It's also hard to tell what more information is needed. Fortunately you are asking how to proceed on debugging the problem, and that is answerable.

If a bug is too hard to find with step-by-step debugging, which seems to be the case here, it needs to be narrowed down. Here you could try the following approaches to limit the scope of the bug:

* Change the pixel shader generating the height map to produce constant height based on the quadrant. If the bug disappears, it was in the shader.
* Modify the algorithm to divide the quad to more than 4 subquads, e.g. 8 or 16. Is the bug still in the last subquad only?
* Replace the GPU terrain generation with CPU generation.
* Use static images as the height map.
* Remove the LOD and just divide the whole terrain evenly to these subquads.

Hopefully some of the above ideas allow you to narrow down the bug and to ask a more specific question or solve it yourself.
> 1 votes

# Answer
I figured out the issue... Instead of incrementing the texture unit every time I created a heightmap, I should have been just been re-using the same texture unit for every heightmap.

Thanks for your time!
> 0 votes

---
Tags: lwjgl, heightmap, fbo
---


# Question
Title: How to give a Jerk Effect when the player is moving left of right
```
float amttomove = Input.GetAxis("Horizontal") * playerspeed * Time.deltaTime;
            transform.Translate (Vector3.right * amttomove);

```

Currently, I have above script in Update function to move the object to left or right.But this movement is way smoother.To give it more realistic feel, I want it to have a slight jerk when it stops moving to left or right and not just stop right there and then.

What exactly needs to be done to have that effect?

# Answer
> 1 votes
Instead of setting velocity("amttomove") to Input.GetAxis("Horizontal") * playerSpeed * Time.deltaTime; just add it continuously until it's less than max velocity. e.g.

```
float hr = Input.GetAxis("Horizontal");

//Accelerate
if (hr != 0 && Mathf.Abs(playerVelocity) < maxVelocity)
{
    playerVelocity += hr * acceleration * Time.deltaTime;
}

//Deaccelerate
if (Mathf.Abs(playerVelocity) > 0)
{
   playerVelocity = Mathf.MoveTowards(playerVelocity, 0, friction * Time.deltaTime);
}

transform.Translate(Vector3.right * playerVelocity);

```

Tweak the values of acceleration and friction to get the desired effect.

# Answer
> 3 votes
The answer from 2600th already outlines how to smooth out your movement by using acceleration an deceleration.

From your question I understood that you not only want a smooth, realistic change but also a little jerk at the end (so first going a little beyond the target and then coming back to it, so that the position "wiggles" a bit). This is commonly revered to as "easing".

To do this there are various easing curves from which you need to choose one to implement.

This website outlines and visualizes some of the easing/"jerking" curves (although the code is for CSS/JS) the same curves of course can used in other areas too: http://easings.net/

This SO post also has some curves visualized:

*Robert Penner* additionally created sample code for various easing methods (in several programming languages) that can be found on this website along with on online easing formula generation tool.

---
Tags: unity
---


title: Unity: White line at camera meaning

text:
# Question
Title: Unity: White line at camera meaning
I'm a new comer to Unity. In Unity, when I click to `main camera` in Hierarchy view. I see 6 lines: one blue, one red, one green and three white. I know red/green/white lines for (x,y,z) location but I don't know what the meaning of 3 white lines is.

When I resize `scene view` I see that white lines change respectively. And at some points, three white line same with three color line as image below:

Please explain for me. Thanks :)

# Answer
> 5 votes
The white lines are the view frustum of the camera. It shows what is within the camera's field of vision.

The frustum can be thought of as a pyramid, with the point oriented at the camera, and the flat rectangular base pointing outwards.

This representation of a camera in virtual space is common to many 3D programs and discussions of virtual 3D space in general. In some discussions of the frustum, you will see it depicted as a trapezoidal prism (think pyramid, but with the tip cut off) because in virtual space, the camera doesn't always see all the way to the horizon (that could get very inefficient).

Thus, you get a "far clipping plane" which forms the base of the pyramid and excludes things that are too far away, and the "near clipping plane" which cuts off the tip of the pyramid, and excludes things that are too close.

---
Tags: unity
---


# Question
Title: Screen coordinates to isometric coordinates?
I know this has been discussed here before, but I couldn't find an easy solution for my particular problem. I have a tile system and I'd like to convert screen coordinates into isometric tile coordinates. Here's an image to explain what I need:

As you can see, the coordinates are between 0 and 1. I can't figure out a formula for the conversion though. Can you guys help me?

# Answer
These are (simplified version of) the formulas I use in my current project wizardwar.com:

```
 tile_x = screen_y - 0.5 + screen_x;
 tile_y = (screen_y - 0.5 - screen_x) * -1;

```

By the way: I would recommend you to use different terminology for screen-coordinates and world-coordinates to avoid mixups. I use `x` and `y` for screen coordinates and `l`eft-down and `r`ight-down for tile coordinates. This saved me from more than one brain-knot. In your example, `tile_y` would be be `l`eft-up and `tile_x` would be `r`ight-up.
> 3 votes

---
Tags: mathematics, isometric, coordinates
---


# Question
Title: Wall-sliding Collision Response Only Works On One Axis (2D)
"sprite" is the player object, velocity is a Vec2 that tracks movement (is set to -1, 1, or 0 at any given time), each sprite in "sprites" is a wall of the same size as the player (everyone is a block for testing purposes).

```
if (velocity != Vec2.Zero)
{
    Vec2 oldPos = sprite.Position;
    sprite.Position = sprite.Position + velocity;
    foreach (Sprite s in sprites.Except(new List<Sprite> { sprite }))
    {
        if (sprite.BoundingBox.Intersects(s.BoundingBox))
            sprite.Position = new Vec2(oldPos.X, sprite.Position.Y);
        if (sprite.BoundingBox.Intersects(s.BoundingBox))
            sprite.Position = new Vec2(sprite.Position.X, oldPos.Y);
    }
    velocity = Vec2.Zero;
}

```

So, this actually works quite well - except for some reason it only works in one direction. Collisions work in both, but when sliding against a wall by holding two direction keys it only works sliding along the Y axis.

The bounding box for "sprite" is updated whenever the "Position" variable is written to via an accessor, so the bounding box is always up to date. The walls do not move, so theirs are also up to date.

At first glance, it seemed that there were a few obvious spots to check - I am modifying the bounding box for the second check, and at the time I hadn't been doing it automatically, so I tried disabling that. Doing so broke the working parts, so it wasn't that. I get no change in behavior when I add "else" to the second if statement, confirming that the first block always runs and the second block never does. If I flip them around, the other axis works instead.

I tried separating them into two foreach loops (just to see) and the behavior still remained the same. I'm kinda confused as to why none of these changes produced any hints as to the issue - it's likely something I'm overlooking, so I was hoping someone else would see.

If you need me to post any other code, just ask.

I was trying to do this in 3D and had a very bad time, so I figured I'd make a 2D version of my engine and get things sorted there before moving the collision back into 3D, heh..

# Answer
OK, after much fiddling and reading and re-reading of my and others' code, I've figured it out. If anyone sees anywhere I could improve this or sees any issues, please do let me know. Also, I hope that this saves somebody out there from the same frustration that I dealt with, lol.

As I'd discovered, it would only work right on one axis at a time. The key was then to determine how to decide what axis to work with, which sounded straightforward but was eluding me last week for whatever reason, even though I'd stared right at code that could do it for me (Collision Detection - Slide Around Sprite , second answer). Somehow while nearly passing out this morning I was able to decipher the issue.

Anyway, the concept is to calculate the difference in positions, which (if normalized) is the direction from the moving object to the collidable one in question. You then check the absolute version of each coordinate of that to determine which has a greater magnitude, and do that axis first.

I also moved my collision resolution into its own function so that it could act recursively within the same update loop. Here's the resolver ("sprite" is now "a", "s" is now "b":

```
    void Resolve(Sprite a, Sprite b, Vec2 oldPos, int depth = 0)
    {
        if (++depth > 9) return; //abort if too deep
        Vec2 diff = (b.Position - a.Position);
        float adx = (float)Math.Abs(diff.X);
        float ady = (float)Math.Abs(diff.Y);
        if (adx > ady)
        {
            if (a.BoundingBox.Intersects(b.BoundingBox))
                a.Position = new Vec2(oldPos.X, a.Position.Y);
            if (a.BoundingBox.Intersects(b.BoundingBox))
                a.Position = new Vec2(a.Position.X, oldPos.Y);
        }
        else if (adx < ady)
        {
            if (a.BoundingBox.Intersects(b.BoundingBox))
                a.Position = new Vec2(a.Position.X, oldPos.Y);
            if (a.BoundingBox.Intersects(b.BoundingBox))
                a.Position = new Vec2(oldPos.X, a.Position.Y);
        }
        Resolve(a, b, oldPos, depth);
    }

```

Note that the second condition is important - if you just leave it as "else", you will get weird sticking behavior when adx and ady are equal (i.e., when you just move out of collision on one axis while holding down two directions, and both end up as 1).

I haven't tested too many values for the max depth, but 5 didn't seem to be enough and I arbitrarily picked 9 since it is greater than the number of directions (8), allowing it to compensate for collisions in more directions than can be moved in at once in the first place (I might reduce that if it ends up causing any slowdown, perhaps make it an argument or global setting).

And here's the code that now resides where the old snippet was:

```
    if (velocity != Vec2.Zero)
    {
        Vec2 oldPos = sprite.Position;
        sprite.Position = sprite.Position + velocity;
        foreach (Sprite s in sprites.Except(new List<Sprite> { sprite }))
        {
            Resolve(sprite, s, oldPos);
            velocity = Vec2.Zero;
        }
    }

```

This now works perfectly as far as I can tell. Perhaps I'll reorganize it into a movement function that performs the loop and initial movement all within the same function to be a bit tidier.
> 0 votes

---
Tags: xna, c#, 2d, collision-detection, bounding-boxes
---


title: How do I implement time scaling?

text:
# Question
Title: How do I implement time scaling?
I want to be able to change the game speed, to speed up or slow down all animations and gameplay. Ideally, this could also be set to a negative number to make everything go backwards.

I tried this:

I made everything dependent on a `time` variable, updated every frame from the OS time:

```
void calledEveryFrame()
{
    time = System.accurateTime();
}

```

Then I tried just scaling that time.

```
lastTime = time;
long now = System.accurateTime();
double diff = now - lastTime;
time = (lastTime + diff * speed);

```

That obviously doesn't work, because you can't just multiply the speed times the difference because it is not called exactly regularly.

How do I do this correctly?

# Answer
Some points:

1. You should make all your movements time-dependent, more specifically depending on the `timeSinceLastFrame`. That way, your game will run equally fast on all computers in the sense that the possible movement distances are aligned (not in the sense that you get the same FPS, because that of course depends on the hardware specs).

So, your movements would look something like this:

`newPosition = oldPosition * direction * speed * timeSinceLastFrame;`

To now slow down the whole application, you can just decrease `timeSinceLastFrame` by a certain factor, resulting in slower movements of your objects.

```
// At startup
long lastTime = 0;
long now = 0;
long timesinceLastFrame = 0;

// Each game loop run
now = System.accurateTime(); // get new time
timeSinceLastFrame = now - lastTime; // calculated time passed since the last frame, e. g. in milliseconds
timeSinceLastFrame *= 0.5; // to get the game to half speed
lastTime = now; // update the value for the next loop run

```
2. Backtracing in a game is difficult, because in order to do so, you need to store all user input to be able to un-do that in the correct reverse order. And this also only works if the rest of your application is completely deterministic which it is not when being based on variable (= un-deterministic since dependent on something as uncontrollable as the overall system performance at any given point in time) timestamps.

A good general overview about the discussion: fixed timestamp vs. variable timestamp (variable not in your sense that you can slow down or speed up the game, but in the sense that the time between frames is not constant), can be found in this GameDev.SE thread. Another important source is this blog entry by Glen Fielder.
> 1 votes

# Answer
In most rendering applications this is called `Delta` time, or the time since the last frame update. For example, in most of my applicaitons I have a master loop that looks like this:

```
while(running){
    updateDelta();
    update(delta);
    render(delta);
}

```

with the functions:

```
void updateDelta() {
    long currentTime = (Sys.getTime() * 1000 / Sys.getTimerResolution());
    delta = (int) (currentTime - LAST_FRAME);
    LAST_FRAME = (Sys.getTime() * 1000 / Sys.getTimerResolution());
}

void update(float delta){
    ...
}

void render(float delta){
    ...
}

```

If you start of with this format, your application will:

* Always run at the same speed independent of system performance
* Be able to change the update speed(delta).
> 0 votes

---
Tags: timing, scale, timestep
---


title: Scale around a point

text:
# Question
Title: Scale around a point
I am trying to create an image editing application for the purpose of generating UV maps in my own format. I am currently working on scaling the image for the purpose of zooming. I can get the image to zoom correctly, but it always zooms around the center of the image. I would like to scale around the mouse instead.

**My Question**

How can I scale a rectangle(image) around a point(the mouse)?

**My Variables**

```
float X = imgX;
float Y = imgY;
float W = imgWidth;
float H = imgHeight;
float mX = mouseX;
float mY = mouseY;

```

**My Code**

```
function scale(float ratio){
        W += ratio;
        H += ratio;
        X -= ratio/2;
        Y -= ratio/2;
}

```

**To Clarify**

I am not trying to change camera or view-port. I am trying to scale an `BufferedImage` through the `Graphics.drawImage()` function. The function take the image and the x, y, width, and height of the image to be rendered.

**Example** In the Windows Photo Viewer, when you zoom in using mouse scroll, the image is zoomed around the mouse.

# Answer
> 1 votes
You can't. Scaling is just applying a coefficient to all coordinates, it doesn't take the coordinate of the camera into account.

If what i understood is right, the visual effect you want imply to move the camera toward the coordinate of the mouse as you zoom.

You can achieve this by translating the image on the directed vector (mousePointer, centerOfTheScreen) and by the same time translating the cursor with the opposite vector.

---
Tags: java, mathematics
---


# Question
Title: Implementing Galaga Style Enemy Behavior in Unity
I've been trying to work on a space shooter with the idea of having enemies behaving like it is shown in this video : https://www.youtube.com/watch?v=3p7u8uCR6yw

In the video above, enemies fly from different portions outside the view area of the screen doing elaborate movement before finding a spot to form an organized formation.

I've been thinking of ways how this could all be done. One way is by having either the enemies and/or a manager use a Finite State Machine that will control when there is a "performing" state and when there is a "FindingSpot" state.

but at as far as implementing the complex patterns, I'm at a loss. Is there some sort of Math formulation that's used to generate those movement patterns?

# Answer
If I understand, your question is about the building of the formation (arrival of the enemies from outside the screen into a "space-invaders like" formation (aka end-formation)).

Having played this game a lot, here is how I think they have done it:

* They have a handful of "incoming trajectories" which come from out of the screen to an end-point roughly in the middle of the screen, just under the end-formation.
* Those trajectories are likely to be pre-computed, and stored as lists of x,y coordinates (regarding the age of the game, they probably have been drawn on paper and "digitized" by hand).
* Each enemy has a "terminal" position in the end-formation (some of them don't; that's the ones that will try to dive on you)
* All enemies move following the chosen trajectory until the end-point, and then they continue to their assigned position in the end-formation more or less in straight line

To make it smoother, you may give each enemy a different exit point for the trajectories (that would be the index of the last point of the trajectory before going to its end-position). It may make the transition more natural. Also the diving enemies will leave the trajectory a lot earlier, and probably re-use the algorithm that guide missiles to the player ship.

Also, the end-formation is slowly moving horizontally. When the enemy will go in straight line from the end-point toward its end-position, you need to go to the position where the end-point will be at the time of arrival (aim in advance); or you may try to aim the current position of the end point; it could make the trajectory more natural, but you'll have to try to be sure.

Bottom-line: This method was common in the 80s. On today's hardware, you can probably model the trajectories as mathematical functions; that would allow you to have a smother movement, and less pre-computed data; also you may use some polynomial function instead of "straight line" for the last part of the arrival. The rest of the algorithm doesn't change (go to trajectory end-point, then go to your end-position)

EDIT: I forgot the last part of your question: I'm not sure there is a "simple" mathematical function for those trajectories, but you may obtain something close by stitching ellipses arcs together.

Here is an attempt to visualize it:

Here the trajectory is decomposed in 3 ellipse arcs (first the black, then the red and the green. The "Pinkish" part is the last part of the arrival (the straight line).
> 5 votes

---
Tags: unity, movement, patterns
---


# Question
Title: How many OpenGL programs should I use to render multiple objects?
My scene has multiple objects in it. (Let's say 3 cubes, 1 cylinder, 8 spheres.) I assume I should create a vertex shader for each. How many programs should I have?

Alternatives:

* One program per object
* One program for all cubes and another for all spheres (assuming they use the same shaders)
* One large program for everything

What is the correct approach?

# Answer
> 8 votes
You should consider shader programs as similar part of the state as textures. Changing the state is expensive, so you may be able to get away with combining several textures to one to avoid texture changes; the same applies to shaders - you may be able to combine several shaders to avoid state changes.

Similarly to combining textures, combining shaders comes with an overhead - if you only render 16x16 pixel area out of a 4096x4096 texture, you're not using the hardware efficiently. Similarly, if the object you render only uses 10% of the code in your shader, it's possible (and even likely) that the graphics card is computing a lot of stuff unnecessarily.

In short, "depends".

# Answer
> 6 votes
It's best to keep things as simple as possible. Duplicating the same shader for every object is unnecessary and will quickly get bloated. You also don't want one giant shader that covers every possible use-case, as this causes unnecessary overhead.

There are several opinions on shader management and no "optimal" way to approach this. I've even seen some shader implementations where every shader is generated on-the-fly based off parameters (e.g. in Unreal engine).

For someone just starting out in this area, it might be good to pencil out the basic shaders first. For example, I have a shader for textureless objects, a shader with basic texture and per-pixel-lighting support, etc... Then each time I want a different effect that can't be done using a previous shader, then I'll create a new one for the new effect.

The purpose of such a system is to keep things simple. Just. Keep. It. Simple.

---
Tags: opengl, shaders, architecture
---


title: Unity create water issue

text:
# Question
Title: Unity create water issue
I use daylight water in my project but by the default it has not got any waves or light tracing effects. But in some tutorials I see how the user add standard water asset and it has got beautiful world reflection on the surface and beautiful waves. Is this issue because that I am using not a PRO version?

# Answer
> 2 votes
From the documentation:

> ...while Unity Pro includes water with real-time reflections and refractions...

Yes, you need Unity Pro to do reflections. In this case, the waves are an effect applied to the reflections, not the mesh. So you'll need Pro to do the waves too.

---
Tags: unity, water
---


# Question
Title: Unity WheelJoint2D will not rotate when increasing motor speed
I have a wheel joint 2D attached to a game object in Unity:

In its associated wheel script I am increasing the motor speed as described in the tutorial.

```
public class Wheel : MonoBehaviour
{
    WheelJoint2D wheel;
    JointMotor2D motor;

    void Start()
    {
        wheel = GetComponent<WheelJoint2D>();
        motor = wheel.motor;
    }

    void Update()
    {
        if (Input.GetKey(KeyCode.RightArrow))
            motor.motorSpeed += 10;

        if (Input.GetKey(KeyCode.LeftArrow))
            motor.motorSpeed -= 10;

        //Debug.Log(motor.motorSpeed);
    }
}

```

The problem is that the sprite does not rotate and I am not certain as to why?

Does the wheel joint have to be attached to another rigid body in order to function?

# Answer
> 2 votes
You have to attach the `wheeljoint2d` to another sprite wich with a rigidbody2d for it to work. So yes, you should attach it to another `rigidbody2d`.

---
Tags: unity, physics
---


title: Cant center screen between black bars

text:
# Question
Title: Cant center screen between black bars
As I was trying to adapt my game to different device resolutions I ran into a problem when adjusting the game screen between the "black bars." In my case I am using the `FitViewport` class from the LibGdx library to add the black bars for me. Everything works fine and the black bars (one bar in my case) are being effectively created when necessary. My problem, however, is that my screen is not centered and I end up with one ugly black bar either to the top, bottom, right, or left of my game. For example:

How can I fix this so it looks like this:

Here is my code:

```
public class NordicMadness extends Game implements ApplicationListener{
    private Camera camera;
    public static FitViewport viewport;

    @Override
    public void create () {
        camera = new PerspectiveCamera();
        viewport = new FitViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), camera);
        AssetLoader.loadAssets();
        setScreen(new SplashScreen(this));
        System.out.println(Gdx.graphics.getWidth() + ", " + Gdx.graphics.getHeight());
    }

    @Override
    public void dispose(){
        super.dispose();
        AssetLoader.dispose();
    }

    @Override
    public void resize(int width, int height) {
        // All resizing shall be done in main Game class
        viewport.update(Gdx.graphics.getWidth(), Gdx.graphics.getWidth(), true);
    }
}

```

The libgdx API states that adding `true` to the third argument of `viewport.update(width, height, boolean center)` should do the job but it's not working in my case.

After this I tried doing the following but with no success:

```
public void resize(int width, int height) {
        // All resizing shall be done in main Game class
        ScalingViewport scalingViewport = (ScalingViewport)viewport;
        float leftGutterWidth = scalingViewport.getTopGutterHeight();
        viewport.update(Gdx.graphics.getWidth(), Gdx.graphics.getWidth()); // Resize screen
        camera.position.set(0, Gdx.graphics.getHeight() - (leftGutterWidth / 2), 0);
    }

```

# Answer
I have never used a viewport without a stage, but replacing width and height with the calls to Gdx.Graphics.getHeight/getWidth that you are using causes the same behavior you are experiencing. Removing those calls and using the passed values should fix your problem.

```
public void resize(int width, int height){
     stage.getViewport().update(width, height,    true);
}

```

You might find this helpful. https://github.com/libgdx/libgdx/wiki/Viewports
> 2 votes

---
Tags: java, libgdx, screen, window-management
---


title: Fade into splash screen on game load

text:
# Question
Title: Fade into splash screen on game load
I'm using Slick2D and LWJGL for my StateBasedGame and I was wondering if there was a way to enter into my splashscreen on application load using a transition?

I tried using:

```
this.enterState(SPLASH, new FadeInTransition(Color.black), new FadeInTransition(Color.black));

```

However, it fades in nicely but then it flashes again for the second transition :(

Anyone know how I can get around that?

Would I have to create my own transition?

# Answer
> 0 votes
You can pass an empty transition to the second transition parameter to prevent the additional transition from playing.

```
this.enterState(SPLASH, new FadeInTransition(Color.black), new EmptyTransition());

```

---
Tags: java, lwjgl, slick
---


# Question
Title: How can I animate characters' static-geometry eyes?
Here's a Nintendo example:

Specifically, the animation of the pupils seems not to animate the geometry.

How is this done?

# Answer
> 2 votes
There can be a texture with the pupils and generous padding around them. On render, geometry just changes UV coords to sample from texture - hence smooth pupils movement on static geometry.

---
Tags: textures, animation, geometry, character
---


title: Creating a prefab

text:
# Question
Title: Creating a prefab
**Problem:**

The prefab script is never executed.

**What I did:**

1. Created a GameObject
2. Created a prefab
3. Dragged GameObject over the prefab
4. Deleted the GameObject from Scene
5. Added the prefab script to prefab.

The prefab is never instantiated and neither is this script executed. What have I missed? Here is the script:

```
using UnityEngine;
using System.Collections;

public class Fuel : MonoBehaviour
{
    GameObject r;

    float rmin;
    float rmax;
    float lastposition;
    private BoxCollider box;
    bool spawning;
    float timer;
    Vector3 initial;

    //public Vector3[] positions;

    void Start()
    {
        r = GameObject.Find ("Road1");
        box = GetComponent<BoxCollider> ();
        rmin = r.renderer.bounds.min.x;
        rmax = r.renderer.bounds.max.x;

    }
    void Update()
    {
        if (!spawning)
        {
            timer += Time.deltaTime;
        }
        if (timer >= 2)
        {
            StartCoroutine(Spawn());
        }

    }
    IEnumerator Spawn()
    {
        spawning = true;
        timer = 0;
        initial = new Vector3 (Random.Range(rmin, rmax), -0.23f, Random.Range(r.renderer.bounds.min.z, (r.renderer.bounds.max.z + box.size.z)));
        Instantiate (this.gameObject, initial, Quaternion.identity);
        yield return new WaitForSeconds (Random.Range (1, 3));

    }
}

```

# Answer
> 2 votes
A script is only run when it's in the scene. So any scripts on a prefab will only run *after* the prefab is instantiated. That of course means you have to instantiate the prefab from some other script, not from within its own script.

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


# Question
Title: Calculating the center of a turning circle
I'm trying to understand how to calculate the midpoint of a turning circle. In the attached picture, my unit is at location U. I want to compute the trajectory of the unit as it turns toward the starred location.

I understand that to achieve this I need to know the location of point P, whose coordinates are (a,b). I also understand that I can do this using some simple trig:

```
a = x - cos(theta) * r
b = y - sin(theta) * r

```

My problem is that I do not know the value of the angle Theta which sits between the sides of the right-triangle named "R" and "X-A". All I know is:

1. The radius of the turning circle.
2. The orientation of the unit.

How can I solve this problem and others like it more generally?

# Answer
*Question details keep on changing, so I'll post 3 different answers covering all of them*

**So you know the radius R and unit location U and facing direction F.**

* normalize the unit direction F
* make a perpendicular to F (you need to pick from 2 directions, pick one that is closer to units target), we call it F2
* multiply perpendicular F2 with radius R, (call it F2R)
* take location of the unit U and add multiplied perpendicular F2R to it
* that's your circle midpoint P.
> 0 votes

# Answer
*Question details keep on changing, so I'll post 3 different answers covering all of them*

**If we know unit location U, circle radius R and target location S**

Here's a generic approach to the case. Let's try to parametrize it now.

* Find a point in between Star and U - that is our MidPoint.
* Make a perpendicular from that point (you might want to have it facing against unit movement vector).
* Now, that MidPoint + Offset in the direction is the center of your circle. (*Note that Radius cannot be smaller than half the distance between Star and U.*)
* Now we need to find an Offset that will make the circle Radius that you need. As you see we have a right triangle between circle center (P), Star (S) and MidPoint (M).
* From the math class: `MS^2 + MP^2 = PS^2`.
* `MP = Sqrt(PS^2 - MS^2)`
* Knowing MP length it's a matter of math to find coordinates (a,b) of P
> 0 votes

# Answer
*Question details keep on changing, so I'll post 3 different answers covering all of them*

**If you know only unit location U and turning circle radius R**

This can not be done distinctively if the only things you know are the location U and circle radius R.

Take a look at illustration below:

There is infinity of circles with radius R around the unit location U. You need a rule of picking only one of those turning circles (e.g. unit facing direction will eliminate all but 2 circles and you drop one that is farther from target location).
> 0 votes

---
Tags: geometry
---