title: How/where to generate RPG world?

text:
# Question
Title: How/where to generate RPG world?
I'm programming an RPG in java. It's text based, so movement is more or less from "room" to "room." In the case of cities, they will generally be one room, with some sub rooms for important shops and things.

I have classes for locations, but where should the programming for each individual location be done? A bad idea would be to create a bunch of New Location()s in the main method. Another idea I had was to define all of their attributes in a text file (or maybe something like JSON) and then reading it in when needed. Or should it go in a class file somewhere?

# Answer
A good rule of thumb is to have your content be data driven. You would store this data externally and create a class to load in the data.

There are lots of reason to do this, such as

* You don't have to recompile when your data changes
* You can use Excel or a text editor to edit the data.
* The data load can be abstracted from the data itself
> 1 votes

# Answer
I'm currently writing a text-adventure myself and choosed the following (unoptimized, clumsy ect.) approach. Why is explained in the conclusion of the answer. For the short version, skip to the end of the answer.

My game is structured in `area`s which contain `locations`. A `player` can have `roles` which allow him to do something (or disallow him from doing so).

*Whenever a link in the following answer is mentioned, it is a ONE-WAY-Link. If two different links link each other, that may look like a two-way-link, but they are actually one-way-links which happen to point at each other.*

*When I say **type** contains **type**, I'm refering to ''contains the file name and location''. This will should be understandable from the attached pictures.*

---

# `Area`

An `area` is a folder containing four types of content. These are `exit-points`, `entry-points`, `locations` and `dungeons`.

* `exit-points` An **exit-point** contains another *areas* *entry-point* which it links to. An **exit-point** can be accessed by *locations* and *entry-points* (though later doesn't really make sense). If a player leaves a *location* through an **exit-point**, he will be transported to the *entry-point* of the linked *area*.
An *area* can have multiple **exit-points** (imagine you leave a town (*area*) through it's east-gate (*location*) to the mountains (another *area*) or through the west-gate (*location*) to the meadows (another *area*) ).
* `entry-points` An **entry-point** contains one *location* within the same *area*. **Entry-points** can only be accessed from another *areas* *exit-point* (or from the game-engine, to drop the player in the world for the first time at game start). If a player access an **entry-point**, he is immediatly redirected to the specified *location*.
An *area* can have multiple **entry-points** (imagine a town (*area*) where you can enter from the east-gate (*location*) or west-gate (*location*) ).
* `locations` **Locations** are folders bundling content-files (simply some .txt). A **location** has a *describing text*, an *interaction list* and at least one *location-exit-point* (and some other stuff not important for this question).
The *describing text* is simply the text that is shown when a player enters the *location*.
The *interaction list* contains (in a specified syntax) the reaction Y to the players action X.
Example: **LOOK AROUND** can in one location simply display the *describing text* again. In the next location, it would trigger a change to another location (because the player fell in a trap).
More often than not, the *describing text* already contains hints (or big signs, when it comes to this) what is possible in a **location**. If the *describing text* says there is a huge river next to the road, the player might want to **FISH**.
If an action is not possible in a current **location**, then the default message for this command is displayed (*"You throw out your fishing pole and it lands on the ground. After a short time, you realize that without water, you can't catch anything"*).
A *location-exit-point* is basically the same thing as an *area-exit-point*, but can only link to **locations** and *area-exit-points* inside the same *area*. This is simply to shorten path-names.
* `dungeons` These are sub-areas to have less clutter in an *area*-folder. To everything inside an *area*, they look like *locations*, but are *areas*. The only special thing is that they can have at most 1 (ONE) *entry-point*.

A little picture (sorry for my Paint-Skills):

Shown is the way my linking works. Note that Entry C.B is not accessed currently. An *Entry-Point* without a corresponding *exit-point* can exist (for example for future expansions).

---

# Conclusion

The **programming** is basically done in the *interaction-list* of the *locations*. The player issues a command, the *interaction-list* says how to react to it. Of course, the possible reactions have to be coded somewhere. Up until now, I managed to do everything with static methods, because boiled down, there isn't much a player can do (look, skill, talk, leave to another location).

**WHY? WHY ALL THIS TEXT FOR SUCH A LITTLE CONLUSION?**
Valid question. I'm wrking with two non-programmers. They are responsible for the story and stuff, I do the coding. I had the choice to teach them how to programm a location, or simply read textfiles they give me. As they were somehow resistent to learning, I got stuck with the textfiles. Today, I'm happy with this.
Need a new *entry-point*? Throw in a new file with the specifications.
Another interaction, but can't edit the basefiles (because we're modding, and basefile-edits are bad!)? Throw in a new *interaction list* with a running number, because the parser only checks if the file starts with `interaction_list_`.
Add a whole new town into the landscape? Throw the *area*-folder next to the others and add some *exit-points* to the existing regions.

All in all, this might not be the best approach, but it will definitly ease your life when your world gets bigger, **because not a single line of code has to be touched anymore!**

Thanks for your patience with me.
> 1 votes

# Answer
Cities are the same as the rest of your environment. How do you define it?

I think your 'rooms' are styled different - some with treasures and some with monsters. So your cities have some rooms with shops and some with parks. For me, it is the same approach.
> 0 votes

# Answer
Ok the question is pretty vague in that it reveals nothing about your game design but here's my take on any form of "game world":

You painted a picture of this in my head ....

```
public interface IArea
{
     public void Enter(Character newChar) { ... }
}

public class World
{
      public List<City> Cities { get; set; }
}

public class City : IArea
{
    public List<Room> Rooms { get; set; }
    void Enter(Character newChar) { ... }
}

public class Room : IArea
{
    public void Enter(Character newChar) { ... }
}

```

So in answer to your question ... Inherit one of these and create any custom code you need, then add your room implementations in to a city and your city implementations to a world to build your virtual world.

How you actually write the code is then entirely up to with regards to implementation details, and i'm sure you can think of many more ways to improve the IArea interface right :)
> 0 votes

---
Tags: java, rpg, world-design
---


title: Is Unlimited Detail real?

text:
# Question
Title: Is Unlimited Detail real?
Many aspects of Unlimited Details Unlimited Detail Technology seems dubious to me, even the introductory paragraph (because of the usage of the word unlimited):

> Unlimited Detail is a new technology for making realtime 3D graphics. Unlimited Detail is different from existing 3D graphics systems because it can process unlimited point cloud data in real time, giving the highest level of geometry ever seen.

The quote above is from the no longer existing Unlimited Detail Technology Site (archive.org snapshot from 2011)

My question is: **Does this unlimited detail technology *actually* exist? And if it does, why isn't it currently being used in games?**

Other references to the Unlimited Detail Technology:

# Update

Unlimited Detail recently released a new YouTube video. I'm not any more convinced. I wrote a blog post about it, as did Notch (he thinks it's a scam).

# Answer
> Does this unlimited detail technology actually exist?

It has for decades, although it's normally called voxels. A few games used voxels back in the 90's, most notably Commanche and Outcast. The terrain in both games looked amazing at the time compared to other stuff out there. Looking at the videos the "advances" with his system, seems mainly in handling the sheer number of points. So it's faster voxels but hardly some new unlimited technique.

> And if it does, why isn't it currently being used in games?

Like all techniques it has it's strengths and weaknesses.

You don't see many animations being shown since that's not a strength of voxels. At a brute force level you've got to store the offset positions for every point in the object per frame of animation, which is really ugly from a memory standpoint vs. a skeleton and rigging data in traditional poly rendering. I'm sure there are better solutions, but it's a weakness for voxels.

There are other issues, shadows can have some creepy artifacts and voxel tend to look a lot uglier when you get to close to them than polys do, although in theory if you've got enough voxels you won't notice.
> 17 votes

# Answer
## Yes it is real,

**It really can render things at any detail density without slowing down.**

But it does have some notable restrictions.

* The environment is static. No dynamic lights, animations, or shaders.
* All objects are data heavy both in memory and in storage.
* The amount of unique objects is limited by the amount of memory and storage that the user has.
* Character animation would either have to be standard polygon, use some kind of sparse-voxel character animation technique(computationally heavy), or load a different model for each frame of animation.

With those restrictions a large amount of game types would not be possible. But there are game types that already have static environments that could work well with this technology.

**Most likely developers who use this tech will use a hybrid approach of Point Cloud rendering for static environments, and high resolution polygon rasterization on the GPU for character and other dynamic objects.**
> 11 votes

# Answer
It has always looked like sparse voxel octrees, to me. If my guess is correct then it's real, but limited. Namely, you can't really do animation with sparse voxel octrees, so this trick is only useful for static geometry.
> 7 votes

# Answer
Current hardware supports an evolution of the kind of graphics that appeared in the 16 bit days - arguably even the 8 bit days. A completely different approach may not be a bad idea, but there already are alternative approaches - ray-tracing and voxel-based, at least.

"Unlimited detail" sounds to me like the old fractal-compression fallacy. Fractal compression *can* represent any image, but with compression ratios not so different from JPEG.

At one point, there were claims of massive compression ratios - but the logic for that was the same as for "vector graphics compression". A single rectangle is a very simple shape to represent in vector graphics, giving an impressive compression ratio, but it's a special case that isn't useful for encoding a typical photo. The same applies to the old fractal compression fallacy. A single simple fractal may have a tiny encoding using fractal compression, but that's hardly a miracle of compression.

Another answer has already associated point-clouds with voxels. The only way I can image "unlimited detail" being justified is if there's some repeating-patterns and/or fractal aspect to those point-clouds, and some of those example images seem to suggest that too. Otherwise you'd need infinite data to represent that unlimited detail.

A fractal arguably gives an infinite level of detail. Theoretically, that is - discrete rendering automatically implies a finite cutoff to that detail, and that applies to voxels as well as pixels. However, you can't easily represent anything you want in that fractal form - it may be possible to define arbitrary point-clouds, but you'll need complex point-cloud descriptions to get the forms that aren't so naturally described as a single simple fractal.

None of this means the idea isn't interesting or useful. It's just a kind of "beware of the marketing claims" thing. And just because something looks good now, doesn't mean it won't be "just another tediously obvious point-cloud effect" in five years time.
> 4 votes

# Answer
This technology is very real but its nothing to do with gaming it's purely a search algorithm that they have invented for quickly retrieving a subset of points in a point cloud database.

The idea is that given any amount of data in a sort of "database" of points in their format the "algorithm" they have developed will quickly return a sub selection of those points, a point for each pixel on the screen.

This is not however your typical "voxel engine" type technology used in games (eg minecraft, everquest next, or similar) as this data is nothing more than coloured pixels. This is purely spitting out a colour at a specific position in the 3d world and cannot be interacted with in any way.

Games have a bigger more complex problem to solve with animation and interaction with such data and the fact that the data is not static and changes constantly presents a bigger problem than just storage and retrieval.

People claim this technology is a hoax because they assume that Euclidean are targeting the games industry but after an initial video showcasing the technology and comparing to the graphics in modern games they have only delivered solutions for things like mapping technology to show areas of the real world from survey data. IMO: Euclidean were idiotic to even suggest a link to gaming in the first place because this technology is clearly not capable of doing all that a game engine does it purely finds a set of sets ... nothing more.

So in short ... Yes its real but no its not anything we can use to build games with and its hardly massively ground breaking technology.

It's a bit like saying "we found a new way to query a blob of data and it's really fast".

Good for them, but that's not useful to the gaming world!
> 1 votes

# Answer
IMO, it's a hoax at best, and a scam at worst.

Don't believe it until you have got a demo so you can verify the "extraordinary" claims for yourself, or at least until any industry experts vouch for it (John Carmack, Epic Games etc).

Notice the claim on the site that it's being released in "16 months" from now, since they haven't set a definitive date they can continue claiming it's a future technology even when nothing shows.
> 0 votes

---
Tags: 3d, voxels, point-cloud
---


# Question
Title: Too much delay while sending object over UDP to server
I'm getting 4 sec delay when sending objects over UDP. Working on small game and trying to implement multiplayer. For now just trying to synchronize movements of 2 balls on the screen. StartingPoint.java is my server(first player), that receiving serialized objects (coordinates). SecondPlayer.java is client that sending serialized objects to server. When I'm moving my first object it appears 4 seconds later on different screen.

StartingPoint.java

```
@Override
public void run() {

    byte[] receiveData = new byte[256];
    byte[] sendData = new byte[256];
   // DatagramSocket socketS;
     try {
        socket = new DatagramSocket(5000);
        System.out.println("Socket created on "+ port + " port");
    } catch (SocketException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    while(true){

        b1.update(this);
        b3.update();

        System.out.println("Starting server...");

        //// Receiving and deserializing object

            try {
                //socket.setSoTimeout(1000);
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                socket.receive(packet);

                 byte[] data = packet.getData();
                    ByteArrayInputStream in = new ByteArrayInputStream(data);
                    ObjectInputStream is = new ObjectInputStream(in);
                  //  socket.setSoTimeout(300);
                        b1 = (Ball) is.readObject();

            } catch (IOException | ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        repaint();

        try {       Thread.sleep(17);
        } catch (InterruptedException e) {
                e.printStackTrace();
        }

```

SecondPlayer.java

```
@Override
public void run() {

    while(true){

        b.update();
        networkSend();

        repaint();

        try {
            Thread.sleep(17);
        } catch (InterruptedException e) {
                e.printStackTrace();
        }

    }

public void networkSend(){

    // Serialize to a byte array
    try {
                ByteArrayOutputStream bStream = new ByteArrayOutputStream();
                ObjectOutputStream oo;
                oo = new ObjectOutputStream(bStream);
                oo.writeObject(b);
                oo.flush();
                oo.close();

                byte[] bufCar = bStream.toByteArray();

                //socket = new DatagramSocket();
                //socket.setSoTimeout(1000);
                InetAddress address = InetAddress.getByName("localhost");
                DatagramPacket packet = new DatagramPacket(bufCar, bufCar.length, address, port);
                socket.send(packet);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

```

# Answer
> 2 votes
Ok the obvious stuff ...

Remove all the timeout calls. Remove the Thread.Sleep() calls.

Have you tested just this code on its own? How do you know its "slow"?

Are you sure the code that reacts to this isn't slow?

Why are you creating a new connection on every send ...

The process should be ...

1. create "connection" / stream reference.
2. send, send, send.
3. dispose.

It appears at a glance to be creating the stream references and buffers on every send ... creating that can be time consuming as there's a sort of negotiation / resolution process that needs to happen under the bonnet and of course the time spent creating objects in ram that you then just bin.

Do you have a garbage collection issue with this ... my thought is yes if you use this a lot?

I have a network client class that holds on to a stream and a buffer that when I call send gets reused. I then have a second buffer for receiving which again is reused on every receive.

Much more efficient IMO.

---
Tags: java, udp
---


# Question
Title: What are the recommended approaches for an event system in Java?
What are the recommended approaches for an event system of a turn-based RPG's battle engine?

The system I'm currently working on has a `runEvent` method that sorts the actions queue based on their priorities. This method should also call the object's (item, player, condition) method according to an `eventid`, which currently is a `String` ("TurnStart", "TurnEnd", etc). The different objects may or may not have the same parameters for the same `eventid`.

In JavaScript, it would be something like the following:

```
retval = action['on' + eventid].apply(this, args);

```

I've read about using Java's Reflection to call a method through a `String` stored in a variable, but some people advise against it because of its security flaws.

I also thought about having a `switch (eventid)` inside a handler method that would call the appropriate method, but I think that would become impractical, given the substantial amount of different parameters combinations.

So, what is the recommended approach for this kind of situation in Java?

Note: It doesn't need to be based on `String` passing.

# Answer
> 3 votes
I'm not too sure if I understand the question correctly so forgive me if my answer if off, but this is how I would go about a turn-based event system.

Firstly, the actions that are represented by strings and ids can be converted into something more object-oriented which would be something like:

```
public abstract class Action {
    public abstract void execute();
}

```

That way you don't have to use switch or if-else statements; you would have to extend the action class.

To sort these actions out I would probably use an enumeration as each instance implements `Comparable`:

```
public enum Priority {
    PRE_TURN, PHASE, POST_TURN
}

```

And implement it into the action class like so:

```
private Priority priority;

public Action(Priority priority) {
    this.priority = priority;
}

public Priority getPriority() {
    return priority;
}

```

`Action` is an abstract class because there are no arguments in the `execute` method. This means you will have to specify the necessary fields in the constructor of the extending class which acts as a work-around to the many different parameters. It also enforces you to specify its priority. An example would be:

```
public class BattlePhase extends Action {
    private Entity e, Entity target;
    private Attack attack;

    public BattlePhase(Entity e) {
        this(e, e.inLineTarget(), e.getCurrentAttack());
    }

    public BattlePhase(Entity e, Entity target, Attack attack) {
         super(Priority.MEDIUM);
         this.e = e;
         this.target = target;
         this.attack = attack;
    }

    @Override
    public void execute() {
        attack.perform(e, target);
    }
}

Character c = scene.currentCharacter();
scene.queueAction(new BattleAction(c, selectedTarget, c.getMove(selectedMove)));

```

In the class that manages event you could use a priority queue that will sort actions added to the queue if you specify a 'Comparator'.

```
Queue<Action> actions = new PriorityQueue<>(10, new Comparator<Action>() {
    public int compare(Action a1, Action a2) {
        return a1.getPriority().compareTo(a2.getPriority());
    }
});

```

(the first argument, 10, is the initial capacity)

Or you could use a `List` and sort it when you add actions by calling the `Collection#sort`

Then your `runEvent` method would be something like:

```
public void runEvent() {
    Action a;
    if ((a = actions.poll) != null) {
        a.execute();
    }
}

```

That's just the outline of it, you might want to add a procedure to sequence the actions so that they don't all run at once.

# Answer
> 0 votes
ouch ! ... eventing is normally pub sub ... I say "this happened" and you as a handler go "ok now i need to do ..." this presumably is like some sort of action list system in which case I would implement it as such.

Does java have lambdas yet? I would have somehting like this in c# ...

```
class EventManager
{
    List<Action> actions;

    void AddAction(Action action)
    {
        actions.Add(action);
        actions.Sort(...);
    }

    void ExecuteNextAction()
        var nextAction = actions.FirstOrDefault();
        if(nextAction != null)
           nextAction();
    }
}

```

then you can do something like ...

```
var actionManager = GetTheGlobalactionManagerFromSomewhere();

actionManager.AddAction(() =>
{
   DoStuff();
   DoMoreStuff();
});

```

You could also make ActionManager static if its a global thing. This is sort of how tasks work in .Net but with added clever threading abstraction.

---
Tags: java, architecture, rpg
---


# Question
Title: confusion in animating a sprite sheet using craftyjs
can anyone help me with this : http://jsfiddle.net/B5UsC/15/

you can see that the sprite animation is not rendering correctly and i am guessing that i am not using the exact width of the sprite ,i tried to change the width but also didn't work out

**THE CODE :**

```
// initialize the sprite
Crafty.sprite(52,123,"http://i.imgur.com/bkYVEe5.png", {
              Ryu: [0,0]
          });

// initialize the component
Crafty.c("RyuAnimation", {
              init: function () {
                  this.requires("SpriteAnimation,Keyboard")
                .addComponent("Ryu")
                .reel('idle', 1000, 0, 0, 9);
                this.animate('idle', -1);

              }

// creating the player
player = Crafty.e("2D,DOM,Canvas,RyuAnimation")
                    .attr({ x: 15, y: ch - 123, w: 52, h: 123 })
                    .start(3);

```

i am pretty sure the missing element is hidden somewhere in this code :

```
Crafty.sprite(52,123,"http://i.imgur.com/bkYVEe5.png", {
              Ryu: [0,0]
          });

```

but help me in figure out the real problem behind this confusion because i have no idea why this error in rendering is occurred

# Answer
> 1 votes
A few things. First, your sprite is 49 pixels in width, not 52. Second, let the sprite size determine the width and height of your player. You don't have to declare it.

```
//.attr({ x: 15, y: ch - 123, w: 52, h: 123 })
.attr({ x: 15, y: ch - 123 })

```

Third, your animation is smearing. I think it is because you use Crafty.background("#XXX") in Canvas mode. Maybe Crafty.background is only for DOM mode? So you probably need to draw a background image instead.

---
Tags: javascript, jquery
---


title: Are random generated mazes a nuisance?

text:
# Question
Title: Are random generated mazes a nuisance?
To me, random generated maps such as in Diablo2 were often a nuisance. Many times, you find yourself in a dead end and have to find another way. However, Diablo2 became a very popular and addictive game.

My Conclusion:

Pros:

* players don't get bored as fast as if you have a static map
* players have to spend more time for levels
* there are more surprises

Cons:

* players (like me) are getting bored. They rather want to get to the boss (e.g. Mephisto) quickly

However, is there a general answer if random generated mazes should still be considered when developing a new game?

# Answer
> 3 votes
Randomized worlds exist to improve replayability. Any gameplay element can be a nuisance for some people, which is why the focus should be on minimizing the nuisance without damaging the whole gameplay, not removing it completely. You achieve this with mechanics that balance your "possibly annoying" mechanic.

You gave Diablo 2 as an example, so I'll stick to that. Randomized levels mean you get a new level each time, and you don't know anything about it. You don't know where's everything, so in theory you have to re-explore it all the time. However,

> They rather want to get to the boss (e.g. Mephisto) quickly

Blizzard most likely thought of this too. That's why the game has waypoints. Once a waypoint is activated, you can get to it on each newly generated map. This is a very useful mechanic to keep the players with less patience happy: you can go to the closest waypoint to Mephisto, and reduce the search efforts tremendously.

Also, notice how important areas on each map *have noticeable particularities that remain constant across newly generated maps*. That means that even if you're on a new map, you can reduce the search effort by paying attention to these specifics. There may not be 100% excellent examples of this in Diablo (hordes of imps in the same place? chances are you're getting closer to the Cairn Stones), but it's another mechanic that can help with re-exploration.

In the end, if you really want for your game to not annoy any player ever, just don't release it. It's the only way.

---
Tags: game-design, maps, random
---


# Question
Title: How to show NGUI menu in the upper of a Game Scene?
I am new to Game Development. I made a menu with NGUI plugin. I have a background image in the behind of this menu. Now, I want to place my Game Scene in place of the background image. I have tried in several ways. But, Failed. Any suggestions will be highly appreciated. Thanks

# Answer
> 0 votes
You'll have to load your scene as normal, so that your menu objects and scene objects are in the same area. You'll then use culling to separate out which camera displays what objects.

So you'll want to use two cameras - one for GUI objects and another for everything else.

1. Set all of your GUI objects' layer to "UI", and your GUI camera's *Culling Mask* to UI only.
2. The GUI camera's *Clear Flags* should be set to *Depth Only*.
3. The scene camera's Culling Mask should be set to everything but UI.
4. UI Camera's Depth should be set to 1, Scene Camera's Depth should be set to 0.

---
Tags: unity, ngui
---


title: Pause on scrolling backgrounds

text:
# Question
Title: Pause on scrolling backgrounds
I have a typical parallax backgrounds. They are scrolling by

```
public float Speed=0f;

void Update ()
{
    renderer.material.mainTextureOffset = new Vector2 (Time.time*Speed,0);
}

```

I have a character. OnKeyDown he starts to move: Speed of background sets to 0.4f for example. OnKeyUp a character stops by setting the speed of background 0f. The problem is: when backgrounds stop to scroll, they return to its start position. They must just to pause the position. How to do?

# Answer
> 2 votes
You should use delta time instead of total time. And keep the "running total" in your offset variable, instead of in time.

```
renderer.material.mainTextureOffset += new Vector2 (Time.detlaTime*Speed,0);

```

Then, when you come back from a pause, the `mainTextureOffset` is where you left it.

---
Tags: unity, parallax-scrolling
---


# Question
Title: Architecture design in "buff-heavy" game?
I've been trying to wrap my head around this architectural design problem. Think of a game that has lots of spells and buffs (World of Warcraft, Diablo II etc), i.e. spells may cause buffs on characters. Each buff may affect one or several properties. For example a frost bolt normally slows down the target it hits, but if it does a critical hit, it will freeze the target for a moment. The frost bolt will also cause cold damage. A shadow bolt might cause some kind of "black" damage and cause confusion (i.e. invert controls, randomize spell target etc).

I tried to map out the architecture for this kind of spell-buff system, but I'm having trouble connecting the dots. First I thought of entity-component system where each character would have a list of components (health, mana, input...), and each buff would "affect" all these components. The components would then choose whether or not the buff affects it. For example, a "damage-over-time" buff should affect the health component, but not the mana component. The aforementioned shadow bolt would affect both health and input components. However, this feels a bit iffy to do if there's tens or hundreds of buffs and components.

Any ideas on how to approach such a design?

# Answer
> 2 votes
The way I am implementing this in the game I am working on is to have a mixture of character states and what I have termed damage pipelines.

So a character can be `normal`, `disorientated`, `slowed`, `stunned`, `paralysed` or `dead` and character skills check against that state when deciding what options are available to them right now. Some attacks will change character state.

The damage pipeline idea works on the concept of having a tree of increasingly specialised damage types, a bit like this:

```
sharp      |
blunt      |- - - - - - - - physical
projectile |

fire       |
cold       |
shock      |- elemental |
acid       |            |
                        | - magical
                        |
infernal   |- spiritual |
soulfire   |

```

Basically a creature has both an incoming and outgoing damage pipeline and a buff can be applied at any level, so something that buffs magical defences or attacks will affect everything to the left of `magical` whereas one could alternatively apply a very specific buff to - for example - `fire` which only affected attacks with that aspect.

This can simply model both positive and negative buffs and as long as you remember to pass all your attacks and defences through the pipeline, it's reasonably easy to work with.

Edit: In terms of my game I have two types of buff that typically come into play, some are standing buffs, typically related to equipment so while a certain item is equipped the user has a bonus to a certain defence or damage type, others are per-use or power based buffs where a character has a buff placed on them for a certain number of turns ( I'm working with turn-based play, which makes it easier, but could work fine otherwise ) in both cases the buff which is added to the pipeline has a value by which it affects that pipeline and a timeout - technically I am using an internal timeout so buffs remove themselves when they hit their limit, but you could as easily have a manager attached to your damage pipeline that just sweeps the buffs on that pipeline before running damage through it and removes any that are out of date - how exactly you would choose to operate this would probably depend somewhat on other factors, such as what you are showing in the interface to indicate if a buff is active- if you're timing out the "active buff" indicator you might as well pop it off the damage pipeline at the same time.

Damage Over Time is not treated as a buff in quite the same way - that is operated as an effect that - once per turn - inflicts typed damage through the damage pipeline for a certain number of turns. I use the same timed counter model for the cooldown on most powers- a turn based environment makes this easier but if I was working it in a real time system I would probably have this on virtual "turns" ever second or part thereof to get the same effect.

This DOT model gives some interesting possibilities because it is always going through the pipeline so if a character is hit with a 5 point fire DOT they apply a fire defence buff on the next turn to reduce the effect or on the other hand apply a weakness against fire debuff to an opponent after inflicting a damage over time attack.

# Answer
> 1 votes
I've seen this done two ways for sure, and no doubt there are plenty of others I don't know about.

1. Buffs directly add to stats. When they end they subtract their value from the stats.
2. Buffs are tracked in an array or list and when the stats are relevant, the array or list is processed to find the current value.

The advantage to the first is that it's relatively easy to manage. The disadvantage is that it is relatively easy to get strange behavior when buffs wear off. As a result you tend to do a lot of sanity checking before and after the buff, but don't have to worry about it during the buff period.

The advantage to the second is that you don't have to do any sanity checking before or after the buff. The disadvantage is that you constantly have to do sanity checking while it's active.

DOTs are a bit different. Depending on your system, it might be easiest to make them invisible short lived enemies that do the damage rather than being part of the same system as stat boosters.

# Answer
> 1 votes
You could use an event system where you can have abilities and buffs emit and listen for events. In your example you could have a character emit a 'damage taken' event that contains the source and type of the damage upon taking damage. You can then listen for these events and if it was critical hit by a frost bolt, change the state of the character to frozen. If it was frost damage, add a timed listener for shadow damage, if the character then gets hit by shadow damage, your can set the character state to confused.

This allows you to create complex interactions fairly easily while keeping it scalable.

# Answer
> 0 votes
I would go for a model that allows the actual state to be easily determined.

Something like ... Create a character component that has all the various properties like health, mana move speed ect. Create your buff objects and hand them to the Character as "child components".

Whilst active (which the buff component should be able to figure out for itself by seeing if it is attached to a chracter) the buff would examine its parent and ensure its effects are applied (as needed, or possibly on attach) to the parent character objects properties.

Then when it ended it would revert its changes and remove itself from the parent.

Each update cycle in the game would result in the character calling update on each buff to allow it to "redetermine" any thing that needs to be done (like applying damage, or removal)

Taking this approach, the current value for any property on the character is always the fully calculated one "rollup of all buffs and the base stats".

This is of course very subjective as it very much depends on your engine design.

---
Tags: architecture, effect-modifier
---


# Question
Title: How to smooth mask texture edges correctly regardless it's size
I have a texture intended as a mask. The texture type is `GL_R32F` (32 bit float) and the data inside is a signed distance field (= value of each texel is distance to nearest mask edge). For test purposes, the mask is just a circle part and is directly drawn in greyscale. The fragment shader handling this texture has following code:

```
void main() {
 float mask = texture( tex, fragTexCoord).r;
   vec4 res = vec4(1.0,1.0,1.0, 1.0);

   if(mask > 0.0) //test failed, outside of mask
      res = vec4(0.0,0.0,0.0, 0.0);
   //smoothing if there is an edge nearby
   //0 or 1 otherwise
   res.w = smoothstep(0.0, 1.0, -1.0 * mask);
   finalColor = res;
}

```

however if the mask is drawn too big, its edges appear blurry, because smoothstep afflicts too many fragments. This could be solved by multiplying the mask by some value, however it would stop smoothing if is the mask was drawn too small.
For illustration, on left is the mask(100px), in the middle is its zoomed edge and on right there is zoomed edge of mask if drawn big(600px). How to smooth the edge to appear correct regardless of the size? (=zoomed edges should always look the same, like the middle image)

# Answer
Assuming that the distances in your SDF are measured in pixels your current function is performing the smoothstep across one pixel of the source mask. This is about right if your mask is being used on screen at 1:1 scale but as you point out it doesn't work out so well if the mask is being used at larger or reduced scales. To fix this you need to calculate the smoothstep according to how big the fragment pixels are instead of how big the mask pixels are.

Now, your SDF contains by definition a gradient that changes at a rate of +/- 1.0 (or some other fixed amount) per source mask pixel in the direction of the nearest edge. You can therefore calculate the destination pixel size by differentiating the SDF function using GLSL's `dFdx` and `dFdy` functions which return the rate of change, in x and y respectively, of whatever parameter they are given:

```
float someFactor = 1.0; // <-- value can be played around with a bit
float mask = texture( tex, fragTexCoord).r;
float stepWidth = someFactor * length(vec2(dFdx(mask), dFdy(mask)));
float value = 1.0 - smoothstep(-stepWidth/2.0, stepWidth/2.0, mask);

if(value == 0.0)
{
    res = vec4(0.0, 0.0, 0.0, 0.0);
}
else
{
    res = vec4(1.0, 1.0, 1.0, value);
}

finalColor = res;

```

The (untested) code above also fixes another issue: Your fade was occuring entirely inside the mask i.e. finalColor was 0.0 at SDF==0.0 and faded to 1.0 towards the inside of the shape. This results in drawing the shape slightly smaller than it should be. The correct rendering should result in a value of 0.5 at SDF==0.0, fading to 0.0 towards the outside and to 1.0 towards the inside of the shape.

By the way, another answer suggested passing the zoom level in from the previous shader. If you can make that work (it's easier if you're rendering flat shapes onto the screen) then that's not a bad idea and is likely to outperform the `dFdx`/`dFdy` per-fragment method.
> 1 votes

# Answer
I would say you have two options: 1.- Pass the zoom level to the shader and use it to sample more pixels depending on it then average those pixels. 2.- Use a bigger mask texture with mip mapping.

I would recommend #2.
> 0 votes

---
Tags: opengl, signed-distance-field
---


# Question
Title: Question about separating game core engine from game graphics engine
Suppose I have a `SquareObject` class, which implements `IDrawable`, an interface which contains the method `void Draw()`. I want to separate drawing logic itself from the game core engine.

My main idea is to create a static class which is responsible to dispatch actions to the graphic engine.

```
public static class DrawDispatcher<T>
{
    private static Action<T> DrawAction = new Action<T>((ObjectToDraw)=>{});
    public static void SetDrawAction(Action<T> action)
    {
        DrawAction = action;
    }
    public static void Dispatch(this T Obj)
    {
        DrawAction(Obj);
    }
}

public static class Extensions
{
    public static void DispatchDraw<T>(this object Obj)
    {
        DrawDispatcher<T>.DispatchDraw((T)Obj);
    }
}

```

Then, on the core side:

```
public class SquareObject: GameObject, IDrawable
{
    #region Interface
    public void Draw()
    {
        this.DispatchDraw<SquareObject>();
    }
    #endregion
}

```

And on the graphics side:

```
public static class SquareRender{
    //stuff here
    public static void Initialize(){
        DrawDispatcher<SquareObject>.SetDrawAction((Square)=>{//my square rendering logic});
    }
}

```

Do this "pattern" follow best practices?

And a plus, I could easily change the render scheme of each object by changing the DispatchDraw parameter, as in:

```
public class SuperSquareObject: GameObject, IDrawable
{
    #region Interface
    public void Draw()
    {
        this.DispatchDraw<SquareObject>();
    }
    #endregion
}
public class RedSquareObject: GameObject, IDrawable
{
    #region Interface
    public void Draw()
    {
        this.DispatchDraw<RedSquareObject>();
    }
    #endregion
}

```

`RedSquareObject` would have its own render method, but `SuperSquareObject` would render as a normal `SquareObject`

I'm just asking because i do not want to reinvent the wheel, and there may be a design pattern similar (and better) to this that I may be not acknowledged of.

Thanks in advance!

# Answer
> 5 votes
I don't think dispatching events is the best way to do this. If you have a high amount of draw calls the event dispatching and listeners will have a lot of overhead.

Also you might want to look what classes you have, because you don't need a class for each color of square, or even if there are more properties. You could be able to just store the color or other information in a variables on each instance instead of having a lot of classes for really similar objects.

For the drawing, you can just set up either a static or non static function in the class that has the Update. So you will have an Update() and a Draw() method in one class. In the main game's Update method, call the Update() method on the instance(s) that need to be updated. Depending on your logic, if there is enough time left over, you then call the Draw() method.

Make sure that the game doesn't require the Draw() method to run exactly at your refresh rate. If the game cannot keep up, it is best to skip Drawing for that frame, so the game will have more time to run the next step in the simulation.

# Answer
> 6 votes
The best practice for separating the game logic from game rendering is to have separate objects for the logic and the renderable, instead of having one large object that performs both tasks. The renderable object has a reference to the logic object so that it can update its own state (eg. animations) based on data in the game logic, or just query for relevant properties directly (eg. current position).

Once you make that separation, most of these issues above disappear, and you don't have to worry about complicated observer patterns or event dispatch.

# Answer
> 1 votes
We use a component class with optional interfaces for IUpdatable and IRenderable that tie into the scene container which handles the component life cycle (when the game engine core says "time to render", the scene container updates all the updatable components, then renders all the renderables). Since we construct lists of updatable and renderable components every time the scene graph changes... dispatching the update and render calls is very simple -- a couple of for each loops... we even sort the renderables based on the material/shader so that we can eliminate some rendering calls related to setting up the shader state when we are using the same shader over and over (simple shader batching)

---
Tags: architecture, graphics-programming, logic
---


title: 2 component unit vector

text:
# Question
Title: 2 component unit vector
Is it possible to store a 3d unit length vector with only 2 components, for example as coordinates on a unit sphere? It seems possible but I have never seen anyone do this. Would this be at all practical?

# Answer
> 5 votes
No, it is not usually possible. But when it is, it’s quite useful.

The problem is that there will always be two possibilities for the missing coordinate. For instance, if you store `[x,y]` as `[0,0]` this could mean the unit vector was either `[0,0,1]` or `[0,0,-1]` and without additional information there is no way to tell which of the two it was.

Fortunately, in some cases that information is known. For instance if the vector is a **normal to a surface**, *most of the time* it is pointing outside the surface and so a local coordinate system can be chosen so that the missing coordinate is always positive.

Memory is indeed cheap nowadays; however, it is not always the case (think mobile platforms) and what’s not so cheap is the **GPU bandwidth**. The main advantage of packing vectors is that they help reduce that bandwidth usage.

So, what you mention does exist and does have practical uses, the most prominent example being the compression of **normal maps** (the Unity engine uses this technique to compress normal maps, and so does the C4 engine) and **normal buffers** (see this comprehensive article on compact normal storage that explores several other packing techniques, and this other article for yet another method).

# Answer
> 3 votes
Yes it's possible. Instead of using 3 cartesian coordinates \[x, y, z\] you can use 2 spherical coordinates \[theta , phi\] to represent any 3d unit vector. It depends on the case if it's useful or not. For example it can be useful for compressing animation data. There are also other representations you could use and there was actually an interesting paper released about compact 3d unit vector representations recently.

# Answer
> 0 votes
For many cases, it's possible. But it's not practical.

Pros:

* Reduced memory requirements

Cons:

* Reduced precision
* Increased complexity

By today's standards, memory is pretty cheap compared to time. Implementing and using a two component vector will take more development time as well as processing time whenever it's used. Keeping a three component vector only takes a little more memory, and is pretty straight forward to implement and quick to process.

There are, of course, exceptions to this. As explained in Sam's answer, where you can easily embrace the reduced precision I mention. You embrace reduced precision when you can make assumptions about what your third coordinate is going to be (typically, -1, 0, or 1 depending on the context).

---
Tags: 3d, mathematics, vector
---


# Question
Title: Swapping Framebuffers or swapping attachments?
I wanted to know what the better approach would be for post-processing: swapping between framebuffers or swapping between textures attached to one framebuffer?

# Answer
It's almost always better to change a state's object instead of changing an object's state. Mostly for readability, as thats how GL is expected to be used. Even if you have multiple attachments in common between FBOs, I would still suggest binding them to each FBO.

As for performance, its implementation dependent, but framebufferTexture is likely slower due to it having to compute the mapping for the fragment outputs into the texture, while a complete framebuffer already has this mapping computed and just needs to load it.
> 2 votes

---
Tags: opengl, rendering
---


# Question
Title: How can I make an object change direction?
I have a moving cube that, when it moves over an arrow, should change its direction to the direction of that arrow. What would I need to do in order to accomplish this?

# Answer
Depending on how much arrows you have, you could simply check the distance from the arrows center to the cubes center and do something if it is below a threshhold.

```
//I assume ARROWS to hold the Transform of all arrows
foreach ( Transform arrow in ARROWS)
{
    if ( (arrow.position - cube.position).magnitude  <= (Time.fixedDeltaTime * cube.speed) / 2)
        cube.changeDirection (arrow.direction);
        break;
}

```

This will ensure, that the cube moves as close as possible to an arrow before changing direction.

**ATTENTION:**
I totally made up the fields `speed`, `changeDirection ()` and `direction`. You have to define them yourself or derive them from the existing data.

The best place for this would most likely be the `fixedUpdate()` of your cube.
> 0 votes

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


title: Steering behavior using nodes

text:
# Question
Title: Steering behavior using nodes
I've started rewriting some of my code (npcs, navigation and such) and I need some help with my new navigation system.

Basically the way it works is: the game generates a random dungeon. For example:

With the black representing walls. After the map generates, it goes through the map and finds all the outward corners and places a node on them. The end result is something like this:

When it finishes that, it goes through the nodes and connects the nodes that have a clear line of sight to each other. Like this:

So it works like this: enemies use the nodes to navigate their way around the map. When they want to do things like wander, they choose a random node (one they can see) and go to it. Every node has a list of the nodes it's connected to, so from there they choose another node and head towards that one. The enemies keep a list of the previous three node locations, so they don't wander in circles (if there's only one node connected to the current node, they head back.)

The whole thing is based on line of sight, basically. However, there are some limitations, namely: movement. Creatures in my game have tile based movement and can only move in cardinal directions. I also need enemies to try to avoid each other and change direction based on stimuli (such as a change in "bravery" level, causing them to rush the player, retreat or stand their ground.)

Given all that, how can I calculate the ai's next move?

Edit: To be more clear: I want to know how I can have the ai calculate the direction it will move in next. So I need to know what kind of formula the ai needs to determine which tile is the best to get it to it's destination. Something that takes into account the target, other enemies (if there are any) and the bravery level of the ai (which will change player interactions and make them group with other enemies when their bravery is low and they're alone.)

Edit 2: Okay, let me change the question and add some information. **My game is turn based, so I need to make steering behaviors work in a system where it can only move once per update (one tile length) and can only move up, down, left and right. I'm not sure how to do this, can you help me?**

# Answer
Okay, through some trial and error, I've come up with a system that works. The ai chooses a target node, then uses this method:

```
public Point Next()
    {
        Point r = new Point(0,0);
        float weight = float.MaxValue;
        Point o = new Point(loc.X + 1, loc.Y);
        float heuristic = Heuristic(targetNode.Position, o);
        float distance = DistanceTo(targetNode.Position, o);

        float op = heuristic + distance;
        if (heuristic + distance < weight && CheckTile(o))
        {
            weight = op;
            r = new Point(1, 0);
        }

        o = new Point(loc.X - 1, loc.Y);
        heuristic = Heuristic(targetNode.Position, o);
        distance = DistanceTo(targetNode.Position, o);
        op = heuristic + distance;
        if (heuristic + distance < weight && CheckTile(o))
        {
            weight = op;
            r = new Point(-1, 0);
        }

        o = new Point(loc.X, loc.Y + 1);
        heuristic = Heuristic(targetNode.Position, o);
        distance = DistanceTo(targetNode.Position, o);
        op = heuristic + distance;
        if (heuristic + distance < weight && CheckTile(o))
        {
            weight = op;
            r = new Point(0, 1);
        }

        o = new Point(loc.X, loc.Y - 1);
        heuristic = Heuristic(targetNode.Position, o);
        distance = DistanceTo(targetNode.Position, o);
        op = heuristic + distance;
        if (heuristic + distance < weight && CheckTile(o))
        {
            weight = op;
            r = new Point(0, -1);
        }

        return r;
    }

```

To determine which direction will bring it closer to the target. It then adds "r" to it's location, moving it one tile in the right direction. Heuristic is the Manhattan distance and DistanceTo is the Euclidean distance. CheckTile just checks if the tile is a floor tile or not. When it reaches the target it chooses another target and the process continues.

Right now I have a problem where the ai wanders in circles while going from node to node so feel free to give me advice on that, but I've solved the problem.
> 0 votes

# Answer
Often times your ai is the result of several components working together, not just one master ai piece of code. The solution you are after can be achieved in this manner. As already mentioned you can give your creatures states so that they know what their current task is, roaming, rushing, standing ground, retreating, etc. Next you can add pathfinding. This will tell the creature how to get to where it needs to go, regardless if it is chasing a player or roaming. Finally, once the creatures know what they are doing and they know how to get there you can implement object avoidance, so that the creatures will dynamically adjust their paths as they travel to avoid one another.

EDIT: This solution is relevant whether your game is real time or turn based. If a creature is: Roaming state - it will target and seek the nearest empty node x tiles away. If the player comes withing y tiles from the creature and the creatures bravery is high enough then the creature will enter Attack state. If the bravery is not high enough then the creature will switch to Congregate state.

Attack state - creature targets and engages player. If bravery drops too low creature state will change to Retreat.

Congregate state - creature targets and seeks nearest enemy. If creature is within 2 tiles from target state will change to Pack state.

Pack state - closely follows lead creature and gains a bravery boost. If lead creature attacks, this creature will switch to Attack state, regardless of its bravery level. If the "pack" does not engage the player within 10 turns then the creature will "forget" threat and switch to Roaming and its bravery boost will fade.

Retreat state - each turn creature targets the nearest node to the creature that is the farthest from the player. Once the creature is 10 tiles away from player then it state will switch to Roaming. If the creature is "cornered" in Retreat state, it will switch to Attack state regardless of its bravery level.

Once the creature has a target, you can calculate a path, tile by tile that the creature needs to take to reach that target. Each turn the creature takes the next step to reach the target.

To avoid collisions with other creatures during movement you can check "a move ahead" and see if there will be a collision. If you find a collision, you can choose to let it be first come first serve. So, first creature on the list gets to move to that tile on the next turn. The other creature can choose an alternate route around that tile, or choose to wait and not move for that turn, hoping that next turn that tile will be vacant.
> 1 votes

# Answer
You should be able to accomplish this with "creature" states.

1. Roaming
2. Attacking
3. Retreating
4. Defending

On each "turn" you evaluate what the state of each creature should be and handle their movement accordingly. For example, if the current state is "Roaming" and the engine evaluates that an enemy is now in front, the state is changed to "Attacking" and a new path is generated. If the state is the same as before, keep the same path.

You can add as many states as you need and evaluate the "what to do" on the code of each state.
> 0 votes

---
Tags: c#, ai, steering-behaviors
---


title: Story for an iPhone Game from a book?

text:
# Question
Title: Story for an iPhone Game from a book?
I'm making a story-intensive game (RPG) for the iPhone and want to distribute it over the AppStore. But AppStore Apps have the potential to be distributed internationally, so I need kind of legal advice - maybe someone of the independent developers here was already in a similiar situation.

I'm planning to use an book (i.e. classic literature, world literature or fairytales) as foundation for the storyline of my game: So what are the basic conditions, if I dont want to run into big problems? I heard about 70 years after first publishing (or after death of the author?) a book would be "out of copyright" - but is that true for every country? Could I get problems in the App Store?

My Background: It doesn't seem economical to pay a scenario writer for my game (no budget) - and myself isn't "talented" so much in this field. But there are already tons of great stories out there, which never get a game release so far. Because of that, I was thinking: "Why not use this, instead of making a crap story by myself"...

I know that I can't get here a reply from a lawyer - but I hope for tips from other independent developers with experience in such cases...)

# Answer
It can get very complicated. Have a read of http://en.wikipedia.org/wiki/H.\_P.\_Lovecraft#Copyright for example.

You should seek specific legal advice from a professional on your situation.
> 2 votes

# Answer
Along the same lines of what Adam said, you will want to get very specific with this. Pick a specific story and then see if it is available in the public domain. Otherwise this is too broad of a question to answer and it can get tricky with authors assigning their books over to estates to get extended renewal rights and such.
> 1 votes

# Answer
I'm not sure about international public domain, but there are ways you can circumvent this problem entirely. Certain things, like for instance most fairytales are completely public domain. Another route you may consider are the ancient mythologies. This would be the way I would go. Zeus, Thor, Hades et al are all free to use without restriction.

EDIT: As jhocking pointed out, using a subsequently copyrighted version of these characters is NOT permissible.
> 1 votes

---
Tags: iphone, books, legal, storyboard
---


title: What data to store along a vertex

text:
# Question
Title: What data to store along a vertex
Is there any other recommended data I should store in the vertex buffers aside from a vertex' coordinates, normals and texture coordinates? For example data I'd need for a feature that almost every mature game engine implements later on?

# Answer
If you do tangent space normal mapping, as practically every game does nowdays, you should also store tangent space (binormal and tangent in addition to normal). For skinned characters you also need to store multiple (usually 4) bone indices and weights.

In addition there can be multiple UV coordinates, some texture blending weights, color data, spherical harmonic coefficient, etcetc. as well, but it really depends what kind of graphics features and algorithms you implement.
> 3 votes

---
Tags: vertex, data, vertex-arrays, vertex-buffer, vertex-attribute
---


# Question
Title: Grants a Higher Texture downsized a better quality than a texture with the downsized resolution?
if i use a texture in a game with a resolution of 128\*128 for a tile which is actually 64\*64 on screen and both textures show the same image just in different resolutions. One in 128\*128 and one in 64\*64. How big are the quality bennefits and is it a good idea to use the texture with the higher resolution even if it will be downscaled anyway?

Thx

# Answer
> 1 votes
When you downscale an image that's when mipmapping kicks in and GPU uses lower resolution version of the texture (assuming the texture is mipmapped). So if you render 128x128 texture in 64x64 pixels on screen GPU is actually using 64x64 image for the rendering due to mipmapping. If you don't use mipmapping though, GPU uses the original 128x128 image, but there are texture aliasing issues which result it worse quality than using texture resolution which closely matches the screen size.

There are different ways to create downscaled versions of the texture as well to improve quality. The standard box filter simply averages 2x2 pixels for every pixel in lower-res mip level. You can have more sophisticated mip generation though by using for example bicubic or sinc filters which better preserve frequencies of the original image.

---
Tags: textures, tiles, performance
---


# Question
Title: Is Unity NGUI still that usable after Unity has add support for 2D?
I am tempted to refactor out the existing component which uses NGUI ("Next-Gen UI kit") given that what I needed is only the sprite and texture atlas.

Since in the newer versions of Unity those parts are natively supported, is there any reason I should still keep NGUI?

# Answer
> 3 votes
I am assuming you are referring to the new GUI system available in the 4.6 beta.

If you are already using NGUI on a project I would recommend you just stick with it. While Lyashenko (NGUI creator) did work on UGUI system during his brief stint as a Unity employee the two systems are not identical. Currently there may be a few features NGUI has that may be worth keeping it around for.

If you are considering which to go with for a new project, the biggest factor is that 4.6 is still technically a beta release. While it seems pretty stable, doing production work on beta software is always a risk and we don't know when it is going to leave beta.

# Answer
> 0 votes
Unity 4.6 is in beta. Which means, other than possibility that certain features may change at final release, you cannot publish anything with it. A simple web build generated in beta will run only on the computer it was generated on.

---
Tags: unity, ngui
---


title: Pair collision detection on quadtree

text:
# Question
Title: Pair collision detection on quadtree
I'm planning to use a quadtree for optimizing collision detection. But this quadtree can handle only one type of objects (so I used a base class for my objects).

If I use double dispatch after two object pointers are returned by the quadtree in a collision (derived from the same base class that the quadtree can handle) knowing their ID that identifies their type (an int in the base class) , how am I able to use these pointers with their respective type in order to double dispatch?

A LIMITED SOLUTION:

Before double dispatching, I could make a resolver function that combines both IDs as they were flags into a single parameter, and make a switch that decides which type are obj1 and obj2.

However, its still not very elegant. Any solution or better way to do this? thanks.

# Answer
> 2 votes
It depends how you implement double dispatching how elegant it is. You are effectively trying to dispatch to a function that's able to handle collision between types X and Y and execute function for that type pair. This is basically a matrix lookup and you could implement it by registering collision functions to this matrix.

Let say your type-ID is 0-based number. You can allocate a 2D array of function pointers of type `bool(const void*, const void*)` and register functions to the array look-up based on the type-ID's. Because this matrix/array is symmetric about the diagonal (e.g. testing OOBB vs Capsule is the same as Capsule vs OOBB with the parameters swapped), you can register only the lower-triangle of this matrix. At the dispatch you check which type-ID is smaller and set that as your first argument to cut the collision test functions in half. Then fetch the collision test function from the matrix using the type ID's as indices to the matrix.

---
Tags: collision-detection, quadtree
---


# Question
Title: Moving gameobject with animation according to my script Unity3D
I am developing a game with Unity3D with an horizontal list of elements which you can move with arrows. Here you can see an example:

I have created animations in order to modify the alpha value of the elements and to move them according to my script:

```
void Update () {
    if (managePositionInUpdate) {
        transform.position = Camera.main.ScreenToWorldPoint (new Vector3 (Screen.width * positionX, Screen.height * positionY, 10));
    }
}

```

In my animation, the alpha value of the centered element is initially 1 and after the animation the alpha value is 0.5, this works correctly; however, in this animation I have also put positionX of my script initially with a value A, and after the animation with a value B, and this doesn't work correctly.

I have tested the code and it works correctly without animation, but I can't get it works according to my animation. What can I do? I have read about apply root motion but It also doesn't work for me.

# Answer
The answer was here: http://answers.unity3d.com/questions/194798/scripting-animated-variables.html

> Animations always "take over" the control of the animated value (position / rotation / or a script value) because it always sets the value to an absolute value. However you still can affect the value but you have to decide what's the better solution in your case:
>
> Use \[LateUpdate()\]\[1\] to modify the value. Modify means you just scale the actual value instead of setting it to a new value. In LateUpdate all animation components have applied their values for thi frame and you can "overwrite" the value as you need it.
> 0 votes

---
Tags: c#, unity, animation, gameobject
---


# Question
Title: Composition and passing pointers to parent, or work inside namespaces
My application right now has a Game class, which contains other classes that receive a Game pointer. Also these classes passes the Game\* pointer to their subclasses. I do this to keep communication between objects. Is this a bad way to keep all communicated? This looks like a "god object" antipattern.

The only alternative I've found to avoid this is simply instanciate my objects globally, inside namespaces, like they did int his project https://github.com/thelaui/M.A.R.S. . But this also looks as an antipattern, where almost everything is global.

What is then the correct way to design a program where the objects keep communicated?

Or the objects shouldn't keep communicated? Which looks hard to make a game.

# Answer
I personally have found it difficult at best to write clean code for a game without at least one singleton/static object that holds references to frequently required information. Passing around references and keeping local copies of references to things you may only need once or twice in a given class just wastes memory and gives you headaches doing all the boilerplate for each class

You are thinking about god objects incorrectly -- a god object knows too much about what is going on outside of its context... an object that you need access to a single instance from many places is not a god object, and can be a good thing :)

Our Game object is such an object, and it contains a list of service objects that get updated/rendered as part of the main game loop to handle things that need to occur outside the normal scene graph rendering process.. examples of services might be input management, HUD/GUI , and physics ... things that need to happen at specific points in the rendering lifecycle and that persist through the lifespan of the game no matter what scene is being rendered. The game object manages activating these services at the right time before or after scene graph processing, but knows nothing beyond the fact that is activating a service, or rendering a scene... thus it is not a god object :) services and scene graphs are handled in completely separate classes that the Game object just makes calls on without knowing how they work internally. If you piled input management, scene graph management, etc, etc all into the Game class -- THAT would be a god object :)
> 1 votes

---
Tags: design-patterns
---


# Question
Title: How are the Unreal Development Kit (UDK) and Unreal Engine 4 (UE4) related?
I'm thinking of learning Unreal Engine 4, but it costs money, and I want to try and keep costs as low as possible while I'm learning. In contrast, the Unreal Development Kit is free.

How similar are the two? If I learn UDK first, how easily can I transition to UE4?

# Answer
> 13 votes
Yes. The UDK is related to UE4 - The UDK is based off of Unreal Engine 3 to which Unreal Engine 4 is the successor.

To the initial end user a number of things have changed. Unreal Engine 4 replaces UDK's Kismet Visual Scripting system with Blueprints. You can do practically everything with Blueprints and in some ways Blueprints can be considered a replacement for UnrealScript.

UnrealScript is also gone. Instead of this you would now use Blueprints, or C++. Unrealscript is object-oriented and had some similarities with C++ and Java syntax, so while a lot has changed using C++ won't be too unfamiliar with someone who is well versed in UDK.

The interface has changed, things have moved around and what not - all of this will take some time but thanks to the comprehensive documentation it shouldn't be to difficult to figure out what is what.

One of the biggest changes, is that with UE4 all of the engine's source code is made available to you. For most users this won't matter, but for those that it does matter to - this is a very good thing. To gain access to the Unreal Engine 3 source as a UDK user - you had to license UE3.

The running suggestion has been, if your game is currently near completion in UDK then stick with UDK. Otherwise it's worth it to check out UE4. UDK projects will not open in UE4 - and you'll have quite a bit of work porting things over (as the scripting system, and visual scripting have all been replaced). That said Epic does provide a handy Transition Guide for people leaving UE3 (and UDK) for UE4.

---
Tags: udk, unreal
---


# Question
Title: Gameobject-Component model with many background tiles - long iteration time
So I'm making a game engine for a game I'm making - the game is a 2D tile-based game

I've implemented a gameobject-component style for the engine, for decoupling reasons

However, every frame, the engine iterates through every gameobject, and calls the update method of every component on that gameobject - as it's a tile-based game, every tile is a gameobject, which means that that update loop could go through several thousand gameobjects every frame. Add into that the fact that each gameobject could have multiple components (transform component containing location/rotation info, renderer component, collider component etc), and a hell of a lot of time is spent in that loop. This is only magnified by the fact that the game is a mobile game, and as such the processing power isn't as great as on a desktop

Any ideas on algorithms/programming styles/design styles that would help to minimise this performance sinkhole please?

# Answer
In our engine, the component class only manages the scene graph, dirty state management and notifying the root scene that the scene graph has changed.. components may implement IUpdatable and IRenderable as needed, and the root scene tracks any graph changes and maintains lists of updatable and renderable components to process during a frame update. This interface based technique will also be used later for other "lifecycle" events such as IPhysicsUpdatable. Overall the result is we have a reasonably short list of updatables, another of renderables, and making calls on these 2 lists in order (updates then renders) handles rendering our scene graph very quickly :)
> 0 votes

# Answer
Normally different sub-engines take care of ticking their associated components in game objects. For example your rendering engine ticks only the rendering components of game objects that are visible on the screen, while your AI/physics engine could tick what's on the screen + outside with some decreasing frequency based on the distance. You don't tick all the components in the world every frame because like you said that gets expensive for larger worlds.
> 0 votes

---
Tags: tiles, tilemap, component-based, gameobject
---


title: How to handle network game

text:
# Question
Title: How to handle network game
I'm currently building my own game using LIBGdx in JAVA but i'm facing some trouble. My game is base like this :

A player have a position and some other parameters that are float, int types. He also have a class name Launcher that contains 3 array list and every update of my game it sends way to much datas and it's making the game very laggy.

How my system work :

Serveur launch and is waiting for connection in another thread. Meanwhile the main thread of the server is updating the map. Suddenly a player connect to the server, it add a new PlayerGestion inside the server which allows me to receive update from this single player. Meanwhile the server keeps updating the maps with the players datas. My problem is that after every map update, when the server send datas to every players, it sends heavy datas that is the arraylist of players (containing the datas i listed below). So my question, is :

Is the way i'm doing a client / server good ?

Is the writeObject method good to use in a server / client

Is it possible to do an online by sending only the x / y players position ?

I'll be able to answer more question if you need to and show some line of code if it can help you help me.

Thanks !

# Answer
> 2 votes
From my knowledge using the Serializable language feature for realtime game networking thats running at 40+ FPS is very bad.

I would send data in a plain binary stream for example Ive got to send the following variable in a class...

(String) player name, (Integer) player health, (Integer) player model id, (Integer) player x, (Integer) player y

I would send the player name as length and then name, so for 'John' I would write.

4John

Followed by the Integers (Limited to 9999) health 100, model id 1, x 30, y 30

health (100) 0100 model id (1) 0001 x (30) 0030 y (30) 0030

So the full message would be...

4John0100000100300030

Totalling 21 bytes which is massive reduction in data compared to serialization of objects, And I'm guessing that there is some overhead writing and reading objects anyway.

Then later when you need to update due to the player moving you send the new health (100), x (35) and y (30)

010000350030

# Answer
> 1 votes
It depends a lot of how your game actually works, but in most games it is not necessary to send all positions of all objects after every frame. In most cases, most of the information will either not change right now or will be changing in very predictable ways (like an object moving in a straight line).

It is often a lot more bandwidth-economic to only inform the clients when things change and send nothing when things stay the same. So instead of sending the equivalent of

```
bob is standing at 12 45
bob is standing at 12 45
bob is standing at 12 45
bob is standing at 12 45
bob is walking at 13 45
bob is walking at 14 45
bob is walking at 15 45
bob is walking at 16 45
bob is standing at 16 45
bob is standing at 16 45
bob is standing at 16 45

```

you just send

```
bob is standing at 12 45
bob starts walking east with speed 1 tile per frame
bob stops walking at 16 45

```

Using Java `ObjectOutputStream` and `ObjectInputStream` to serialize your messages as objects is a quick, but dirty solution. The ObjectOutputStream will add a lot of meta-data you don't really need (like the fully qualified class-name for example), so it will use a lot more bandwidth than necessary. But it is really easy to implement a network protocol this way because the classes are able to exchange almost any object over-the-wire without requiring any additional code (the objects need to implement `Serializable`, but this is just a marker-interface without any methods, so adding it to any classes you want to exchange is trivial). When you want to develop a working prototype as fast as possible, you can use these classes as a stopgap measure, but you should be prepared to replace them with your own serialization and deserialization system to encode your messages in as few bytes as possible.

# Answer
> 0 votes
To your 3rd question, yes, you could preload the necessary models and just update positions and whenever a new players connects, load the extra info (you could do this asynchronously so as to prevent lag spikes).
You could also calculate movement cycles (animations) on the client or on the server and then send the player's current animation 'step' to the client (where the steps would also be defined). Of course, you can do the same for all other aspects of your game, this is just an example.

The rest seems fine.

\*Note that I don't have personal experience in creating server-based games, but these are my observations from playing them.

---
Tags: java, networking, multiplayer, game-mechanics
---


title: How to reuse code

text:
# Question
Title: How to reuse code
I have three classes.

Monster derives from Animation. Animation derives from Collider. This is, monster is an animated collider.

However, I'd like to have animated objects that are not colliders.

Maybe it's a newbie question, but how?

# Answer
> 3 votes
This is one of the best examples why use composition over inheritance. When you learned coding OOP, you were very often advised to derive... and derive, and derive. This is usually not (that) bad for applications but you will run into serious problems in games very soon. Exactly whose what you posted.
Entity component system design is frequently advised solution for games.

---
Tags: inheritance
---


# Question
Title: How can I move an object in a direction other than the ordinals?
I want to move a game object from its current position to the mouse position, but my current code only ever moves in one of the eight ordinal directions. In other words, I want it to move along the **red path**, but I only know how to move it along the **white path**.

Here's my code:

```
while(cont){
    if(x1 > x){
        x++;
    }else if(x1 < x){
        x--;
    }
    if(y1 > y){
        y++;
    }else if(y1 < y){
        y--;
    }
    frame.repaint();
    sleep(); // Thread.sleep(200)
}
// x1 y1 - mouse position
// x, y - sprite position

```

What am I missing?

# Answer
The white vector is the correct vector with the code you have. If you're only ever adding integers to your position, the movement is going to be at increments of 45 degrees. That's restricted to orthogonal and diagonal movement only. If you want free movement you should be normalizing the movement vector.

Check to see if the libraries you're using have a vector class with a normalization method, or create your own. Then you can move your sprite by the normalized vector:

```
Vector2 movementVec = (target-position).normalized();

```
> 2 votes

---
Tags: movement, angles, direction
---


title: Hexagonal Game Board Modal?

text:
# Question
Title: Hexagonal Game Board Modal?
Tile-based games like Chess have a simple modal: an array of arrays, each coordinate with an X and a Y value. This is easy to implement, and it is easy to figure out what is going on.

Chess Board http://www.chesscentral.com/EasyEditor/assets/chess\_board\_blank.gif

However, when I see games like Civilization 5, I am not sure how hexagonal worlds are implemented. I have a couple ideas, but cannot confirm them.

1. Each row of hexagons is represented in the modal by an array of tiles. This would be much like the first chess board, but would require more effort to figure out adjacent tiles.
2. Each tile only know what tiles border it. When the game renders one tile, that tile loads the 6 around it, which repeats until the screen is filled with tiles.

Are either of these guesses correct? If not, **how do developers implement these hexagonal maps?**

# Answer
> 3 votes
For me, I do not see much difference hex-maps and plain 2D arrays. If you look at following picture - it is nothing more then array with some render offset for rows:

As you can see, it technically really is an array. Array with "overriden" getUpper and getLower - some playing with indexes. Though I dont really know how they did it in Civ5, it really appears just as special case of "classic" tiled map.

---
Tags: tilemap, tiles, maps, hexagonal-grid
---


# Question
Title: Meshes imported into Unity into Blender always corrupt
I want to import a terrain mesh I made in Blender into Unity, however Unity seems to fail to load it correctly. What could be the reason behind this and how can I fix it?

# Answer
(╯°□°）╯︵ sןɐɯɹou

As per the comments, I'll repost this as an answer, so that the question has some closure.

That means you will have to recalculate your normals. Edit mode, `A` to select all of the faces, then `Ctrl` \+ `N` to recalculate the normals (outside).
> 1 votes

---
Tags: unity, blender, models, terrain, mesh
---


# Question
Title: Terrain (mesh) textures in Unity - blurry?
I've created a 3D mesh in blender which will be used as a terrain in Unity. Additionaly, I created a 900x900 texture which I'd like to apply as material to the mesh. However, unlike with the normal Unity terrain, the material is only blurry/unrecognizable, not matter how many times I repeat the texture/what import settings I set for the texture.

Some googling brought up that it may have to do something with the shader, but I tried many with no results.

## current result

## texture

# Answer
> 1 votes
I think your model doesn't have texture coordinates. While Unity generates texture coordinates for its generated terrain. Unfortunately this is not the case with your exported model. What you need to do is to create UVs for your mesh in your modeling program.

---
Tags: unity, textures, mesh, materials
---


title: Rendering Many Objects in OpenGL4

text:
# Question
Title: Rendering Many Objects in OpenGL4
Sorry for asking such a basic question. I am reading books on OpenGL4 but in most examples they generally render only objects. So I understand how to deal with vertex buffers and vertex array buffers, etc. but my question is does it work when you have say hundred of objects to draw?

Should you have 1 vbo for example and replace the data in the buffer each time you need to draw a new object?

Should you have hundreds of vbos? By my understanding was that you were limited in the number of buffers you could create (using getBuffer()).

How would one typically do this?

Thank you.

# Answer
> 4 votes
Even when you have hundreds of objects to draw, typically those are many copies of the *same* object. E.g., you might a stack of 10 crates, or two goblins, or a hundred trees. You only need to store this identical data once. You'd then have a structure similar to:

```
struct Material {
  Shader shader;
  vector<Texture> textures;
  UniformMap parameters;
};

struct Mesh {
  VBO vertices;
  IBO indices;
  InputLayout layout;
  Material mat;
  size_t startIndex;
  size_t numIndices;
};

struct MeshInstance {
  Mesh* mesh;
  Matrix4x4 transform;
};

```

You'd then be able to have many `MeshInstance` objects for each `Mesh` object.

Rendering is (in the naive, simple case with bad perf) something like:

```
for (auto& object : objects) {
  device.BindLayout(object->mesh.layout);
  device.BindMaterial(object->mesh.mat);
  device.BindVBO(object->mesh.vbo);
  device.BindIBO(object->mesh.ibo);
  device.SetUniform(object->transform);
  device.Draw(object->mesh.startIndex, object->mesh.numIndices);
}

```

The good version would sort objects by material/buffer and possibly using instanced drawing rather than setting a uniform and making a draw call for each individual object, but the gist is pretty much the same.

If you have a lot of unique objects, you may indeed need many different `Mesh` objects. Note in the above definition that there are both `startIndex` and `numIndices`. This is important: it allows you to put multiple models into a single VBO/IBO! For example, the goblin might use indices 0-10,000 and a tree might be at indices 10,001-12,400 and a crate could be 12,400-12,423.

This reduces the number of buffers you need but not the number of vertices you need, of course. Cutting down on buffers has speed advantages in that you no longer need to swap buffer bindings when drawing any of the objects that share that buffer, of course; do the same with texture atlasing (or array textures) and you can get very high draw-call rates.

If you have still more objects than can possibly fit in the limitations of your GPUs memory... have less objects. You can't expect to have more data than the machine can handle and expect a magic trick to make it work. A game for instance will carefully control how many assets are needed at any given time; you won't see one of every enemy on screen at once, for example. Many games need to implement sophisticated streaming technologies in order to allow large open worlds or exceptionally long/detailed linear levels and then still have to put constraints on designers to keep distinct objects and level features spread out and not over-concentrated in one area.

# Answer
> 1 votes
You probably would want to do it like this:
Have a VBO (+index buffer) for each mesh in the scene (a mesh is just the collection of vertices and indices). Have your objects separately hold a reference to their meshes and store their transformation. From there you can have multiple objects referencing the same mesh with different transformations which is memory efficient and you can sort your drawing to bind each mesh's VBO once while drawing.
A bit more advanced technique would be geometry instancing which could be done as the next step. This way you won't even have to do a draw call for each object separately.

---
Tags: opengl
---


# Question
Title: Vertex Skinning Looks Messy on Real Android Device using Monodroid
I have no problem doing the "vertex skinning" for three-dimensional animation. All goes **well** when using the **emulator** (and genymotion). However, when run on a **real device** (such as Samsung and Lenovo) looks **messy**.

## Screenshoot (Emulator)

## Screenshoot (Real device)

## Passing skin transform matrix

```
int location = ...;
int arrayCount = ...;
float[] skinTransform = ...;
GL.UniformMatrix4(location, arrayCount, false, skinTransform);

```

## GLSL vertex

```
uniform mat4 World;
uniform mat4 View;
uniform mat4 Projection;
uniform mat4 Bones[20];

attribute vec4 Position;
attribute vec4 BoneIndices;
attribute vec4 BoneWeights;
attribute vec2 UV;
varying vec4 v_Position;
varying vec2 v_UV;

void main()
{
    mat4 skinTransform;
    int boneIndex = int(BoneIndices.x);
    skinTransform += Bones[boneIndex] * BoneWeights.x;
    boneIndex = int(BoneIndices.y);
    skinTransform += Bones[boneIndex] * BoneWeights.y;
    boneIndex = int(BoneIndices.z);
    skinTransform += Bones[boneIndex] * BoneWeights.z;
    boneIndex = int(BoneIndices.w);
    skinTransform += Bones[boneIndex] * BoneWeights.w;
    vec4 skinPos = Position * skinTransform;
    vec4 worldPosition = skinPos * World;
    vec4 viewPosition = worldPosition * View;
    v_Position = viewPosition * Projection;
    v_UV = UV;
    gl_Position = v_Position;
}

```

## APK

http://1drv.ms/1BzYV3Q **Touch** screen to **on/off** animation.

## Info

1. Xamarin.Android = 4.10.x.x
2. Emulator Target = API 16 or 4.1
3. Real device Target = API 16 or 4.1
4. App Target = API 10 or 2.3 (tested also in API 14 and API 16), **results remain the same**

Is there any solution to solve this problem?

Best regards and thank you.

# Answer
> 1 votes
I guess that the problem is in the uninitialized variable *skinTransform*. You should always explicitly initialize all your variables. So, you need to define and initialize the variable *skinTransform* like this:

```
mat4 skinTransform(0.0);

```

See The OpenGL ES Shading Language documentation at section *5.4.2 Vector and Matrix Constructors* for more information.

In addition, linear blending of transformation matrices is not a good idea for several reasons. Try to blend position values instead.

# Answer
> 1 votes
This is a known bug in Adreno GPUs.

Your problem is this little snippet of code:

```
Bones[boneIndex]

```

Many Adreno GPUs have a bug when accessing `mat4` uniform arrays with non-constant indices. They will always silently return the first element in the array. This discussion on the qualcomm forums has some more background on this problem.

This bug applies only to uniform arrays of `mat4`. A known workaround is to encode each matrix as four `vec4` instead, as proposed in this answer

Another way to solve this problem is to encode your matrices in `OES_texture_float` textures, as proposed in this answer. However, not all devices support `OES_texture_float`, and not all devices (including many Samsung devices) support accessing texture units from the vertex shader.

There is some more information in this question I posted a while ago.

---
Tags: c#, glsl, opengl-es2, mono, xamarin
---


# Question
Title: Rendering after interpolating, renders inside/outside other objects
So, we're working out our interpolated render-coordinates during our render call and it's doing a fantastic job of smoothing everything out. All is great and collision detection is working to a perfectly acceptable level (for simple CD - ie, player hits other object, looses a life, starts over...).

However, how do we deal with situations that require 'collision and resolution'? The classic example, of course, being our player character colliding with a solid object (usually a platform or the ground) and then being 'resolved' to bring the 2 entities out of collision.... here is what I mean:

Even if we say something simple like 'just don't interpolate vertically when touching a platform' - that wouldn't seem a very clean solution because we need to think about slopes where the player is moving both left/right as well as up/down.

What is the easiest and cleanest way to protect ourselves from this happening?

# Answer
> 1 votes
The physics engine should not report the player's position within the platform. Collision detection and resolution are both part of a single physics simulation time step.

Your rendering lerp function will not have this this problem if it is correct. Again, this is because the physics engine should have resolved the player's correct position after collision detection, all before the render logic takes over.

# Answer
> 0 votes
The case of your problem is that the time of collision (as know as time of impact, TOI) does not match the time of current neither next frame. In fact, any collision potentially can happen between two render frames. All you can do is only to cheat and pass not a real time, but a TOI to your lerp function.

---
Tags: collision-detection, collision-resolution, interpolation, lerp
---


title: 2D Lighting Glitch

text:
# Question
Title: 2D Lighting Glitch
I've been working on a game in Java, and recently I decided to try out my game on a netbook just to see how it would run. While I do get a constant and decent FPS, it appears that my lighting rendering decides to freak out a bit. This only happens on the netbook, however, and I'm not sure how I can fix it.

Here's the lighting glitch:

I'm doing my lighting simply by drawing black rectangles with certain alpha values over each tile.

As you can see, for some reason there are sometimes vertical and (although not shown) horizontal lines that the alpha rectangles apparently aren't drawing over.

The lines flicker on and off as I move around, and placing two blocks on top of each other prevents the glitch for those blocks.

I'm using Graphics to draw on a JFrame, and the block rendering code looks like this:

```
g.drawImage(sprite, (int)x, (int)y, null);
g.setColor(new Color(0,0,0,<insert darkness level>));
g.fillRect((int)x,(int)y,32,32);

```

Someone on another forum thought it could be rounding errors with the block positions, but all the blocks are snapped to a 32x32 grid on creation.

I'm not sure there's anything wrong with the code itself, which is why I'm not sure how to fix this. If someone could help, I'd be really, really grateful, because I'm truly stuck here. Thank you in advance!

# Answer
> 2 votes
I know this is old, but I finally discovered the solution. In my game, I am using `g.translate(x,y);` but I was using a float for the x and y values. So I did this:

```
g.translate(Math.round(transX),Math.round(transY);

```

Now there are no more vertical lines! Hopefully this helps anyone else with this problem.

# Answer
> 2 votes
This sounds to me like a pixel mapping issue. First try varying the resolution to see if the problem appears on other systems and whether a resolution change affects it on the problematic device.

When rendering the sprite needs to be mapped to screen space. Let's say its a 400x400 resolution and your drawing 12 blocks horizontally. That means your 32 width rectangle maps into 400/12 pixels which comes out as 33.33. Not very nice.

But we can't do a third of a pixel, although that would be nice, so we hope that while some are rounded down to 33, the others are rounded up to span 34 pixels thus leaving no gap. However that doesn't happen. So the best way to handle this is to make sure the resolution is always a power of 2 and so are our sprites. That should make them map directly.

Note: I mention this because the sample image seems to be 378x368 pixels.

---
Tags: java, rendering, lighting
---


# Question
Title: Simultaneous Animation for a GameObject - Unity3D
Its my second week with Unity. I am doing a 2D game and I have a small GameObject which should change its sprite along with following a definite path defined in Animation Curves.

I did both of them in separate .anim files since the transform animation had many keyframes, i thought it wont be good to put the '2' sprite keyframe repeatedly along side the transform keyframe.

But the problem is, I cant get it both working together at the same time. I dont want any blending because the animation is timed well already.

Also, I tried deleting the sprite change animation and tried it under script changing the SpriteRenderer.Sprite property under Update(); but it works only when the Animator component is disabled in the GameObject.

Any Solutions ? :)

# Answer
> 1 votes
In the Animator put the 2 animations on different layers. You might have to play with the `Weight` and `Blending` options on them a bit but it should do the trick.

The Unity3D documentation for the Animtation Layers resides at: http://docs.unity3d.com/Manual/AnimationLayers.html

# Answer
> 0 votes
I suppose what you mean by "change its sprite" is to change its texture. If so, have you tried something similar to this?

```
// Inside a co-routine after you have started playing the animation "my_sprite_anim"...
float previousTime = 0;
while (animation.IsPlaying("my_sprite_anim")) {
    // A value of 1 is the end of the animation. A value of 0.5 is the middle of the animation.
    float normalizedTime = animation["my_sprite_anim"].normalizedTime;
    // Change the texture at certain moment.
    if (previousTime < 0.5f && normalizedTime >= 0.5f) {
        Sprite mySprite = Sprite.Create(my_texture, new Rect(0, 0, my_texture.width, my_texture.height), new Vector2(0.5f, 0.5f), 100);
        my_spriteRenderer.sprite = mySprite;
    }
    // Update "previousTime"
    previousTime = normalizedTime;
    yield return previousTime;
}

```

So you have an animation clip responsible for translating your game object, and its sprite texture is updated via the code snippet above.

Of course, you need to make sure the references used are not null (`animation`, `my_spriteRenderer` etc.).

---
Tags: 2d, unity, animation, sprites
---


# Question
Title: Possible to create transparency shader which doesn't stack alpha values
The image above best demonstrates what I'm trying to achieve. It's a transparent shader for objects, but wherever the objects with this shader intersect they don't add together but simply merge with the same amount of transparency.

It seems like a simple thing, but I can't tell if it's even possible from my understanding of how the shader pipeline works. From what I understand of the process (and please correct me if I'm wrong), a fragment is created by each independent object. Once all the fragments for each object are created, the depth buffer chooses which fragment to write to that pixel in the framebuffer at a time, layering them on top of each other, so to speak. Once they've all been added to the framebuffer, the final result becomes the pixel.

If I could access the individual fragments to compare them against each other before they get written ('layered') into the frame buffer, it would be a simple case of tracking them and discarding any extra fragments in the same pixel space that are part of this shader / render queue. But I don't think this is possible with OpenGL?

Is there perhaps another way I can achieve the same effect?

# Answer
One way of doing this is using min blending. With Unity this can be set up in ShaderLab using the BlendOp command.

If your objects are all monochrome as seen here, you may simply be able to use min blending directly on the objects as they're rendered and avoid having an alpha channel at all. (White is transparent when using min blending.) Min blending also works on colors, but it will take the minimum of each RGB channel individually, which could lead to some weird effects (e.g. min of magenta and yellow will be red).
> 2 votes

# Answer
I would go by giving a z-order to your objects, and

1. Draw all non-transparent objects
2. Draw the transparent object ***which are closer first***.

Using this order, the z-depth test will prevent from merging.
> 0 votes

---
Tags: opengl, unity, shaders, cg, alpha-blending
---