title: How to draw text on screen in LWJGL

text:
# Question
Title: How to draw text on screen in LWJGL
Before this question is criticized for lack of research effort, please read the whole description, as I know there are other similar questions out there.

I am making a 3D game, and would like to put text on the screen (FPS counter, different stats for me while I am designing that won't go into the final product). I have followed this tutorial on how to use `TrueTypeFont` fonts.

This is in my main game loop:

```
TrueTypeFont font = Text.prepareFont("WasterMaster10");
Color.white.bind();    //this is Line 163 in MainGameLoop.java
font.drawString(100, 50, Integer.toString(fps), Color.red);

```

And this is my preparation method in my `Text` class:

```
public static TrueTypeFont prepareFont(String fontname) {

    TrueTypeFont font = null;

    // load font from a .ttf file
    try {
        InputStream inputStream = ResourceLoader.getResourceAsStream("res/" + fontname + ".ttf");

        Font awtFont = Font.createFont(Font.TRUETYPE_FONT, inputStream);
        awtFont = awtFont.deriveFont(24f); // set font size
        font = new TrueTypeFont(awtFont, false);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return font;

}

```

However, I keep getting this error:

```
Exception in thread "main" java.lang.IllegalStateException: Function is not supported
    at org.lwjgl.BufferChecks.checkFunctionAddress(BufferChecks.java:58)
    at org.lwjgl.opengl.GL11.glColor4f(GL11.java:893)
    at org.newdawn.slick.opengl.renderer.ImmediateModeOGLRenderer.glColor4f(ImmediateModeOGLRenderer.java:124)
    at org.newdawn.slick.Color.bind(Color.java:182)
    at engineTester.MainGameLoop.main(MainGameLoop.java:163)

```

I have been referring to this question and this question, as well as *a lot* of research on the web, but I still can't find why it won't work. The game works fine when the `Color.white.bind()` and `font.drawString(...)` lines are commented out. There are no syntax errors and the project compiles successfully. When I comment out just the `Color.white.bind()` line, then the program compiles but throws an error at the `font.drawString(...)` line during execution.

Does anyone know a better way to print text to the screen? Or is there a problem in my implementation?

# Answer
> 2 votes
Slick-util depends on deprecated API that is not available anymore with the latest version of lwjgl2. You could try to enable deprecated APIs when you create the context, but LWJGL2 is old. If you just started, you should switch to the newer and currently supported LWJGL3.

I don't know whether this is the best solution for LWJGL3, but here's a tutorial I found for LWJGL3: https://github.com/SilverTiger/lwjgl3-tutorial/wiki/Fonts

---
Tags: opengl, java, lwjgl
---


title: Anchored Unity text ...not anchoring!

text:
# Question
Title: Anchored Unity text ...not anchoring!
I've added some text to a unity UI and set both the achor and pivot to the top right corner as shown here:

When I start this in debug in unity the text looks fine:

What's weird is that when I build the app and run it as an executable as a host (this is a multiplayer networked game) the text also looks fine. But when I start a client instance the text doesn't appear.

I debugged and paused the game in unity in client mode and noticed that the text object is miles away from where I'm expecting it to be (and as a result doesn't show on the camera).

You can just about see the black line on the below image which is my level and the text anchored miles up and right of the level.

It seems like I've done something stupid here but I can't work out what :s

EDIT: Leo's answer was correct conceptually, but here's how I implemented the suggestion.

1. Created an empty game object `GameStateManager` in the hierarchy
2. Add a `GameState` script to the manager with a network identity
3. Added my 'RemainingTime' property to the game state script and put the \[SyncVar\] attribute on it
4. Put logic in the game state `Update` method to update the remaining time
5. Added a `ClientTimer` script to the text object (mono behaviour), which retrieved the `GameState` from within the clients copy of the game state manager.
6. In the update method of the client time, get a reference to the `Text` object and set the `.text` property to the value of the remaining time.

I'm not sure if this is correct, but it does seem to work, and now the `ClientTimer` script isn't networked, which resolved the issues with placement of the text.

# Answer
> 1 votes
If you are using Screen Space, you shouldn't worry about where you see your text in the scene, as the position of the canvas elements will most likely not match the scene positions and scale, since it's using its own position and scale reference to display stuff on the screen.

But from your screenshot, you can see the canvas and the Text are disabled in the hierarchy. Since the problem is in the clients, maybe you are enabling the UI in a script that is only running in the server, or maybe you added the Network Identity component to it, and set it to "Sever only", which disables the gameObject on clients.

# Answer
> 1 votes
In what mode are you rendering the canvas , "Screen space overlay" or "Screen space camera" , if in camera mode you may consider that your scene will have 2 cameras and the canvas will recognize only the host camera , so you must disable the other player camera , using unity OnClientCreate() or whatever UNET call it.

---
Tags: unity, rendering, text
---


title: Formula For Finding Out Price of Item?

text:
# Question
Title: Formula For Finding Out Price of Item?
I've been working on a game with a friend for a while now. I'm in charge of plotting most of the stats on the weapons.

Weapons have several attributes:

* Four damage types: Base, Impact, Punct and Slash
* Two special damages: Elemental and energy
* Stats: Speed, durability, crit. chance and crit multiplier

Can anyone think of a way to calculate the price of an item using the weapon stats?

# Answer
I'd say this question is really open to opinion, but that would only be the case if we give you an actual formula.

But there are some generic rules and considerations that might lead you to a formula you are satisfied with:

* **Attributes metrics:** You should first find a way to generate metrics on your weapon's stats. Not something opinion based, but hard math stuff, combining several stats to generate a single value. For example:

```
DPS = attackDamage*attackSpeed
DamageSpecialization(*) = StandarDeviation(base, impact, punct, slash)
DamageAmp = (CriticalChange/100)*CritMultiplier

(*) DamageSpecialization would be 0 if all damage types are the same, and a greater
    number if one of the values deviate a lot from the mean.

```
* **Calculate the weapon rating:** Using the values generated in the step before, you should create another formula to generate a rating for your weapong. Just by comparing the rating of two different weapons, you should clearly see how better one is compared to another. Example:

```
WeaponRating = DPS*DamageAmp

```
* **Price curve**: Now you have a rating for your weapon. But imagine you have a weapon that has double weapon rating compared to another weapon. You could just make it as twice as expensive. That would be a linear growth of the price, but you could apply a geometric growth, or any other formula. **You could even calculate the highest possible weapon rating for the very best buyable weapon in the game, and divide every weapon rating by that value, so you have a normalized weapon rating**. That way it would be easier to apply a more complicated formula to calculate the price, like `price = (1+(rating/maxRating))^10`.

Spreasheets are your friends here.

Of course is up to you decide what is more valuable in a weapon and the weight it has to it's rating. Maybe weapons that only deals one kind of damage are most valuable, because they deal better with one kind of enemy (but are trash against others), or maybe an all-around weapon with balanced damage is the best since you don't have to switch weapons.

**Important bottom line:** The price of the weapon has to fit in the general economy of the game. Even if you specify the price of the weapon, if the player can never buy it because he'll have to grind for years, that's not good. And if he can buy it very early in the game, that will throw the balance of the game off.
> 4 votes

# Answer
I believe the best formula should be : PRICE = BASE * 4 + IMPACT * 6.8 + PUNCT * 0.7 + SLASH * 5

Just kidding, just choose anything, there is no existing formula for that.
> 1 votes

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


# Question
Title: Need some Help in unity personal edition License matter
I am an independent developer, and I just started to look into Unity. I downloaded Unity Personal, and started setting it up. After sign up, a license page opened, in which I intended to selected a license for Unity Personal edition.

However, there are three options to choose from, and I don't know which one I should choose. Will I be able to make commercial games if I choose the 3rd option? I don't use Unity in a professional capacity.

Here are all the three options:-

1. The company/organisation I represent earned more than $100,000 in gross revenue in the previous fiscal year.
2. The company/organisation I represent earned less than $100,000 in gross revenue in the previous fiscal year.
3. I don't use unity in professional capacity.

# Answer
> 1 votes
The below answer reflects the current licensing restrictions as of 16/9/2016. It is important to remember that Unity Technologies has the right to change this *at any time*. They also reserve the right to change these conditions under *pre-existing* licenses. It is therefore important that you *cross-check* this answer with the official Unity page, and perhaps even a legal representative, when using this answer as the basis to determine the viability of a particular Unity license for commercial release.

---

> If your company currently makes more than $100k in annual gross revenues or has raised funds in excess of $100k, you are not permitted to use Unity Personal as defined in our EULA Agreement. You may use Unity Pro with an unlimited revenue capacity.
>
> **-- Unity Personal download screen**

There is also a secondary restriction in the EULA that states that *all* members of your team must be using the same license.

This means that you can use *Unity Personal* to release a commercial game, providing that

1. Your company1 does not make over $100,000 USD2 a year,
2. You are not able to raise over $100,000 USD2 to fund your game and
3. If you work with other users, they also only use *Unity Personal*.

---

### Revenue Restrictions

As per the Unity EULA agreement, you are restricted by how much your company makes. This is determined by annual gross revenues (how much you earn before deducations) and raised funds. This is great news, if you are an independent developer. Ultimately, you only have to pay for Unity *if* and *when* you can afford to.

Note that the direct quote from the *Unity Personal* download screen reads that *"in excess of $100k, you are not permitted to use Unity Personal (...) You may use Unity Pro"*. This is *slightly* misleading. While you *may* directly upgrade to *Unity Pro* for an unlimited revenue cap, the licensing page clearly supplies a middle option. We can presume that Unity Technologies are simply trying to "up-sell" in the above quote.

Licensed revenue restrictions are as follows:

* **Unity Personal**: Allows up to $100,000 USD2 a year.
* **Unity Plus**: Allows up to $200,000 USD2 a year.
* **Unity Pro**: Allows an unlimited revenue.

### Team Restrictions

There are also restrictions when it comes to a team. It is simple enough, really. If you are making a game as a team, everybody needs to be using the same level of license. This makes fair sense. You can not simply buy one user license, so that one of your members has access to and can implement the advanced features.

It is worth double checking with your team, if working with other independent game developers. There are more than 3 Unity licenses, including an *Enterprise* license and an *Educational* license. It is important to know in certain contexts, other licenses *may* be made available to a particular user for free. For example, your fellow developer may report not having to pay for their Unity license. This *does not* mean they have the *Unity Personal* license. They might be using a *Unity Educational* license, provided through a college or university.

## Upgrading and Downgrading Licenses

As mentioned, you are allowed to upgrade licenses at your discretion. This means that you can simply start with the *Unity Personal* license, and upgrade to the *Unity Pro* license when your revenue reaches *Unity Personal* cap. You are also free to upgrade *early*, if you decide you wish to take advantage of the additional features.

It is important to note that during your subscription period, this move is one-way. During your "commitment period" (likely the subscription period, given that all licenses are now subscription based), you are not permitted to downgrade to a lower license.

> **Can I downgrade to a different tier?**
>
> No, you cannot downgrade to a lower tier during your commitment period. You can upgrade to a higher tier within your commitment period, however, you cannot reduce the number of seats if you upgrade.
>
> **--*Frequantly Asked Questions* posted on the unity store front page**

---

1 There is no mention of how this may be interpreted for an independent developer, who may be considered a *sole trader*. In these cases, I can only advise you not to make assumptions, and to seek advice from a professional, such as a tax accountant or a lawyer. 2 I make the presumption that figures are in US dollars, but this seems fairly obvious. The figures do not change with other localisation-based changes, and *Unity Technologies* is based in San Francisco, California.

# Answer
> 0 votes
*"Will I be able to make commercial games"* and *"I don't use Unity in a professional capacity"* is a contradiction. You find an overview of the differences between the different license plans on store.unity.com.

When you are just checking it out and are not sure if you want to use it commercially, you can start with the gratis version ("Personal Edition"). Should you later decide that you want to release a game you made commercially and think you will make more than $100,000 (or just want to get rid of the "Made With Unity" splash screen) you can always get a subscription plan for one of the paid versions. A project started under the personal license can be continued after upgrading to a paid license.

---
Tags: unity, legal
---


title: Tiling Challenge

text:
# Question
Title: Tiling Challenge
I have a problem and I hope I am in good hands. I recently started using Gamemaker Studio and I intend to create a 2d game where a room can be tiled seamlessly from the wall to the floor with wall objects the player can interact with. Anyone with ideas or pointers?

PS: I am an artist and have little/no knowledge of gml.

# Answer
In `Room Create` event, you can just put the following code:

```
// Create a grid of square tiles to fill the whole room
var len = 20;    // Width/height of a tile
for (var i = 0; i < room_width; i += len)
{
    for (var j = 0; j < room_height; j += len)
    {
        instance_create(i,j,obj_InteractiveTile);
    }
}

```

This code starts from position *(0,0)* in the room, creates a tile, then starts moving downwards; when a tile column is as high as the room height (in pixels), it moves next to it and starts again, until the whole room is filled.

Although Game Maker: Studio is a simple environment to work with, it doesn't mean you don't need to learn some programming first. Please, have a C language course first, because there are many basic concepts behind creating a game which can simplify your life only if you do know them.
> 0 votes

---
Tags: platformer, game-maker, level-design
---


# Question
Title: Sprite framework binding multiple textures
In an attempt to batch render as many quads (sprites) as possible, I'm instance rendering a single unit-sized quad and passing in a buffer of per-instance data that includes width/height, texture coordinates, color, **texture Id**, etc.

Offline, I have a tool that constructs texture atlases based on any particular sprite animation, so the output is flexible in terms of texture atlas width/height, which sprites reference which texture atlas, and so on.

The end result is that I may have many texture atlases, and sprites which reference any one of those atlases for their current frame.

I need a robust solution that'll allow me to draw these sprites in **any order** while reducing texture binding as much as possible. After some research there are two options:

* combine multiple 2D textures into a 2D array texture (up to GL\_MAX\_ARRAY\_TEXTURE\_LAYERS\_EXT)
* bind multiple textures in array of samplers (up to MAX\_TEXTURE\_IMAGE\_UNITS)

The first solution I believe requires all textures to be the same height/width. The second solution seems to have a limitation that requires a constant index to access the array of samplers in the fragment shader.

I think I want to go with the second solution, but I'm worried I won't be able to properly write a fragment shader if I have to use a constant index, as I'd be getting the index via per-instance data input.

Are my above suspicions correct? Is there a known work-a-round for the second solution? Or is there a better way to do this than what I presented.

# Answer
I settled on forcing my offline tool to specify a texture atlas width and height for all the textures of that group. I now can simply use a 2D texture array and can batch an entire scene in one draw call.
> 0 votes

---
Tags: opengl, textures, shaders
---


# Question
Title: How to design a multi-step game menu system?
I am getting started with game programming. I am designing a game that starts by taking you through a series of menu screens. I am interested in learning how this is typically structured in professional game development.

Currently I handle the controller inputs from the main file and have individual classes for each menu screen. When the user makes a selection, I need to transition to the next menu screen. It seems like I either need some sort of "menu screen manager" for keeping track of the previous selection and transitioning between menu screens, and/or I need to pass the controller input handling down to the menu objects, since I want to use up/down on one menu and left/right on the other menu.

How would a professional game programmer architect/design this?

```
require "components/first_menu"
require "components/second_menu"

first_menu = FirstMenu.new
second_menu = SecondMenu.new
menu = first_menu
menu.render

on(controller: "up")   { menu.prev_option }
on(controller: "left") { menu.prev_option }

on(controller: "down")  { menu.next_option }
on(controller: "right") { menu.next_option }

on(controller: "buttonA") do
  if menu.is_a? FirstMenu
    menu.hide
    selected_option = menu.select_option
    menu = second_menu
    menu.show(selected_option)
  else
    selected_option = menu.select_option
    launch_game(selected_option)
  end
end

```

# Answer
If you have nested menus, you can use a stack. I'm not familiar with Ruby, I think there is no 'stack' object. Similar behavious can be created using an Array. You only add items to the end (push), remove the last item (pop) and can interact with the last item (peek).

So the basic idea is: you define a menu class with update() and draw(). This should be a basic menu implementation. Then you create a menumanager that controls what menu gets updated and displayed in the gameloop. This implements the stack: it can add or remove menu's but only displays and updates the top item in the stack. If a nested menuitem should appear, push the new menu class on the Stack. Your controller and display logic should only display the menu that is on top of the stack.

Example:

Base Menu:

* Game Settings -\> push gamesettings menu on stack
* Graphic Settings -\> push graphics menu on stack
* Audio Settings -\> push audio menu on stack
* Exit -\> exit menu

Gamesettings menu:

* Number of lives \[1|3|5\]
* Difficulty \[easy|normal|hard\]
* Choose language -\> push language menu on stack
* Exit -\> pop self from stack

Language menu:

* Language \[English|Deutch|Nederlands|Français\]
* Subtitles \[Off|White|Yellow\]

Start with the stack by pushing the base menu onto it.

The menumanager will only update and display the top of the stack (this is a 'peek' at the top of the stack).

If the player picks the game settings menu; we push that menu onto the stack. Since we're only updating and displaying the top of the stack the 'game settings' menu is shown and manipulated. Suppose the menu goes deeper; you can just push the next menu onto the stack and update and display that one.

The neat trick is, that if the top menu is removed ("popped") from the stack, the underlying menu is shown - you simply go down a level. As added bonus, that menu will be in te state the player left it!

Now to expand this idea; you can use a stack for your game states as well. This way a menu can be pushed onto the game in progress and when it is popped the game can continue as if nothing happened.
> 4 votes

# Answer
I am going to give a non-Ruby answer, because I don't know Ruby.

I would have lots of classes for this:

```
MenuOneController
MenuTwoController
MenuOneView
MenuTwoView
InputNames

```

The controllers navigate the menu. Pressing up and down changes the selected item, pressing enter selects the item. Selecting the item would call code elsewhere to perform the actual action. All the while, anything the controller does is update the views. (Depending on your menu system, you can have a single controller.)

The views draw the actually menu, showing the currently selected option, providing feedback when an option is changed, etc.

Input names is a file of strings such as:

```
string up = "Up"

string select = "Enter"

```

This way, if you decide you want spacebar to select instead of enter, you change the string in one place, instead of all of your controllers. So instead of `on(controller: "buttonA")`, you would use `on(controller: InputNames.select)`.

So if you start in menu one, `MenuOneView` would draw what you see. The `MenuOneController` would be active. Then if you select "Menu Two" from menu one, it would start drawing `MenuTwoView` instead and listen to `MenuOneController` instead.

Here is some pseudo-code:

```
Class InputNames
{
    string up = "Up";
    string down = "Down";
    string select = "A Button";
}

Class MenuOneController
{
    int selectedMenuOption;

    void GameLoop()
    {
        if(ButtonPressed(InputNames.up)
        {
            selectedMenuOption++;
        }
        if(ButtonPressed(InputNames.down)
        {
            selectedMenuOption--;
        }
        if(ButtonPressed(InputNames.select))
        {
            if(selectedMenuOption == 0)
            {
                MenuOneView.ShowButtonBeingPressed();
                MyCodeElsewhere.DoStuffFromMenuOne();
            }
            if(selectedMenuOption == 1)
            {
                MenuOneView.ShowButtonBeingPressed();
                GameLoop.Remove(this);
                GameLoop.Add(MenuTwoController);
            }
        }
        MenuOneView.DrawUI(selectedMenuOption);
    }
}

Class MenuOneView
{
    void DrawUI(int selectedMenuOption)
    {
        //draw the UI for the currently selected menu option
    }

    void ShowButtonBeingPressed(selectedMenuOption)
    {
        //draw the UI such that the button is pressed
    }
}

Class MenuTwoController
{
    int selectedMenuOption;

    void GameLoop()
    {
        if(ButtonPressed(InputNames.up)
        {
            selectedMenuOption++;
        }
        if(ButtonPressed(InputNames.down)
        {
            selectedMenuOption--;
        }
        if(ButtonPressed(InputNames.select))
        {
            if(selectedMenuOption == 0)
            {
                MenuTwoView.ShowButtonBeingPressed();
                MyCodeElsewhere.DoStuffFromMenuTwo();
            }
            if(selectedMenuOption == 1)
            {
                MenuTwoView.ShowButtonBeingPressed();
                GameLoop.Remove(this);
                GameLoop.Add(MenuOneController);
            }
        }
        MenuTwoView.DrawUI(selectedMenuOption);
    }
}

Class MenuTwoView
{
    void DrawUI(int selectedMenuOption)
    {
        //draw the UI for the currently selected menu option
    }

    void ShowButtonBeingPressed(selectedMenuOption)
    {
        //draw the UI such that the button is pressed
    }
}

```
> 0 votes

---
Tags: architecture, design-patterns, menu, ruby
---


# Question
Title: Deserialise Nested JSON with JSON Utility Unity 5.4
This is what my JSON looks like: {"series":\[{,"points":\[{"ts":"1473850836254","value":"11.27"},{"ts":"1473851256637","value":"6.44"}\]}\]}

I am trying to access the values in "points" by calling something like: ***data.series.points\[0\].ts***

```
    Void Start(){
    IncomingData data = IncomingData.CreateFromJSON(jsonResponse.text);
    print("Series point length" + data.series.points.Count);
    print("Series point 0" + data.series.points.get_Item[0].ts); // error
    }

```

//----------------------------------------- classes -------------------------

```
    [System.Serializable]
    public class IncomingData
    {
        public Series series;
        public static IncomingData CreateFromJSON(string json)
        {
            return JsonUtility.FromJson<IncomingData>(json);
         }
    }

    [System.Serializable]
    public class Series
    {
        public List<Points> points = new List<Points> { };
    }

    [System.Serializable]
    public class Points
    {
        public int ts;
        public int value;
    }

```

My error:

// error CS0021: Cannot apply indexing with \[\] to an expression of type \`method group'

# Answer
> 2 votes
You say you want to use `data.series.points[0].ts` but then you... don't, you use `data.series.points.get_Item[0].ts`

The thing you say you want to use works perfectly fine so let's dig into why the other thing is not working:

* `get_Item` is a function, not a field or property. So you need to call it with `(0)` and not with `[0]`
* `get_Item` is a magical function that should *never ever* be called directly. There is a special error for it as well (CS0571, "cannot explicitly call operator or accessor").
* `get_Item` is called if you use the syntax `points[0]`, the *compiler* translates this to `.get_Item(0)` so you can use the neat looking fancy syntax and not worry about anything.

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


title: synchronizing client-server actions

text:
# Question
Title: synchronizing client-server actions
What's the usual way to handle events that are checked both on server and the client, like attacking? There's a cooldown timer to an attack of which the client is aware (so to prevent spamming server requests and attack button is held).

Next there's a cooldown timer on the authoritative server. My problem is that sometimes attacks that end up firing on the client aren't executed on the server, because the server timer (serverFrameTime - lastAttackFrameTime \> attackCooldown) didnt count up to the desired time, and so those are 'blank' attacks on the client.

Is there a standard way to handle that without emiting too many messages? This is a problem for me because i might be firing more of those events and more timers, so autoattacking without clicking is not a long term solution for me.

# Answer
> 3 votes
The short of it is that your game design and art both need to be built around the realities of networked play.

When the user clicks, they should not immediately attack. Instead, the animation/effects should be a "pre-attack" visual that can be smoothly transitioned into a full attack animation/effect or a canceled effect. More over, this pre-attack should be of indefinite length; this allows the request to smoothly cover up any of the unpredictable network latencies.

Once this pre-attack animation is started, the client just waits for the server's authoritative notification that the attack has started or failed. The server should also allow some graceful flexibility in timings to account for expected inaccuracies, e.g. if the client's attack request comes in a few ticks before the timer expires then the server can just enque the attack and have it fire when the timer fully expires. From the client's perspective, this delay is no different than any other network latency.

Once the client receives the server confirmation, it can transition into the proper attack animation. The other clients likewise play the attack. The server indicates the time that the attack should have started; using this and the client's estimated latency, the clients can compress or lengthen the pre-attack/transition animation so that all the clients play the actual attack animation at roughly the same time that the attack happens on the server.

If the server sends back a `MSG_ID_NO_WAY_JOSE` message then you can instead transition from the pre-attack animation to an attack failed animation of some kind (using whatever in-game fiction you want to illustrate the failure). Using the above tricks, though, these failures should be extremely rare (to the point that they are probably only happening on clients with very low framerates or which have been hacked in an attempt to subvert cooldowns).

A lot of this also somewhat depends on the style of game. What is going to work best in an FPS is not the same as what works best in an RTS, for instance. Something at the pace of a typical MMORPG should work with what I've outlined above.

Exanple: client A presses the Lazer Beam Attack button. The game is dsigned for laser beam to have a ~0.4s warmup animation. Every client currently has a server latency of ~0.1s. The client sends the attack request to the server at t=0. The server receives it at t=0.1. The server confirms the attack and tells all the clients that client A started the attack at t=0 and the attack will go off at t=0.4. Client A receives this at t=0.2 so it knows that it has 0.2s left of the warmup animation to play. The other clients likewise just found out about the attack, so they know to play 0.2s of warmup animation for player A's avatar and then to play the attack animation.

Example 2: client A presses the Lazer Beam Attack button but due to client performance its timing is off and the client allows the player to press the button early. The server receives the request at t=0.1 and rejects it. The client receives the rejection at t=0.2, so the warmup animation has already been playing for 1/5th of a second. The client then transitions to a failure animation. None of the other clients ever know that anything happened.

Example 3: client A presses the Lazer Beam Attack button a hair earlier than allowed because of minute timing differences. The client sends the request at t=0 and the server receives it at t=0.1. The server knows that the client isn't *allowed* to attack until t=0.2. It waits until then and then tells all the clients that client A is attacking; the server offsets the time from the allowed time, not the received time, so it tells all clients that client A attacked at t=0.1 and the attack will go off at t=0.5. Client A receives this at t=0.3 and knows that it needs to length the warmup animation out a bit longer to t=0.5 (the animation normally takes 0.4s but in this case it needs to be slowed/extended to take a total of 0.5s). The other clients instead play the shortened warmup animation (because they only found out about it at t=0.3 and will do the full attack at t=0.5, for a duration of only 0.2s).

Note: these are not the only ways to solve these problems. There are other potential solutions, but they *all* involve some level of game design consideration and some amount of art support.

In short: you can't possibly force the client and server to be in sync, but you can use game design and art to *hide* the network latencies incurred by server-authoritative play.

# Answer
> 2 votes
With the following model the client will render **only** what the server tells him to render.
**The client** becomes an **input & input-pre-emission-validator**
**The server** is the **final-validator** (don't trust clients)
**Then the client renders what the server told him**

**\[1\]** Client action request creation upon user input :
Client clicks on an enemy, triggering your custom clickEvent(e)
obtaining the target\_id & creating the following *requestObject* :
(assuming the action has been already client-validated \[target is in sight, etc...\])

```
{action:'attack', timestamp:e.timestamp, target:'target_id'}

```

**\[2\]** Client pre-emission verification :
Throttle & prevent spam of action\_request to server checking the request :
*requestObject.action* & *requestObject.timestamp*

```
switch(request_action){
case 'attack':
    if(request_timestamp > localUser.attack.lastStamp + 1000){ // 1000 ms
        //emit request to the server
    }else{/*the request was too premature to be sent to the server */}
break; }

```

**\[3\]** Server validation & response :
Upon reception, generate a receptionTimestamp and perform a check to see if the timestamp sent by the client is close enough (taking in account latency) to the one generated by the server.
Then verify that the client is allowed to perform the requested action,
and finally notify the clients involved in it.
(the server adds the resulting data after performing action calculations to the verified client\_action to the object)

```
{action:'attack', target:'target_id', aggressor:'sender_id', result:'target_hit', damage:'damage_dealt'} //...etc...

```

**\[4\]** Clients receive the client\_action from the Server :
Clients finally render the action, updating the game with the data contained in the client\_action object sent previously by the server.

I hope it helps :\]

---
Tags: mmo, rpg, timer, node.js
---


# Question
Title: Assigning jobs to in-game entities to carry out tasks (move object, build item etc.)
I'm not really sure what to call this so I'm struggling to Google for solutions.

Basically my game will have resources (wood, stone, etc) that are "delivered" to a point on the map. I want worker entities to collect resources and deliver them to where they need to be (a building site or put them in storage).

My problem is that I don't know how to structure this kind of "job queue".

My first idea was that when a resource is delivered it creates a "job" object in a queue. Then in the game cycle I'll find all workers that are idle, pop the next job off the stack and assign it to him.

Am I heading down the right path? Is there a better way of doing this? Can someone tell me what I should be Googling to find examples of what I'm trying to achieve?

# Answer
> 2 votes
A queue is a reasonable approach: when a resource is spawned in the world, put a job in the queue for somebody to go pick it up. When a worker is idle, dequeue a job and process it. If no jobs are in the queue, sit around and have a drink.

You may want to add additional layers of abstraction for realism, depending on your game mechanics. For example, by queuing up the jobs immediately when a resource spawns, your workers are basically all-seeing. They will always "know" that resources are available and where they are. If that's a problem you can introduce a layer of abstraction where nothing happens when a resource is spawn (except it is marked as "undiscovered") and any unit that gets within *X* distance or otherwise has an undiscovered resource end up in its line-of-sight causes the resource to be marked as "discovered" and *then* queues up the work order.

---
Tags: architecture
---


# Question
Title: Prevent tires from tunneling in 2d sidescrolling car game
I am working on creating a 2d sidescoller car game (Think hill climb racing). The land is a line and generated at once. I have been setting up the physics for car tires and them hitting the lines and have the problem of tunneling. Currently when the tires are touching the ground I add 1 to the height of the car. This is a basic fix and does not solve my tunneling. Any idea on getting the tunneling to stop? If you need my code here it is. Also the code for the collisions is in Car.collide

```
 var keys = [];
 var keyPressed = function() {
     keys[keyCode] = true;
 };
 var keyReleased = function() {
     keys[keyCode] = false;
 };
 var transX = 0;
 var transY = 0;
 var level = [

 ];
 var collide = [];
 {
     var createTerrain = function(size, dist, store, scale, scm) {
         this.dist = dist;
         this.size = size;
         this.storage = store;
         this.scale = scale;
         this.scm = scm;
     };

     createTerrain.prototype.pushNoise = function() {
         for (var i = 0; i < this.size; i++) {

             noiseDetail(7, 0.69);
             this.storage.push([abs((noise(i * random(0, 100) * 0.02, i * random(0, 100) * 0.02) - 1) + 1) * 165]);
            //this.storage.push([1,1]);
         }

 };
     createTerrain.prototype.drawMap = function() {

         for (var i = 0; i < this.storage.length - 1; i++) {
             stroke(82, 35, 35);
             //nnslate(10,10);
             // scale(this.scale);
             line((30 * i + 110) * this.scale - this.scale * this.scm + transX, (this.storage[i] / 1.5 + 100) * this.scale - this.scale * this.scm+transY, (30 * i + 140) * this.scale - this.scale * this.scm + transX, (this.storage[i + 1] / 1.5 + 100) * this.scale - this.scale * this.scm+transY);

         }
     };
 } //Terrain
 {
     var isBetween = function(c, a, b) {

         return (a - c) * (b - c) <= 0;

     };

     var isInCircle = function(x, y, cx, cy, diam) {

         var dx = x - cx;

         var dy = y - cy;

         return dx * dx + dy * dy <= diam * diam / 4;

     };

     var lineCircleCollide = function(x1, y1, x2, y2, cx, cy, diam) {

         var m = (y2 - y1) / (x2 - x1);

         if (abs(m) > 1024) {

             return lineCircleCollide(y1, x1, y2, x2, cy, cx, diam);

         }

         if (isInCircle(x2, y2, cx, cy, diam)) {

             return true;

         }

         x1 -= cx;

         x2 -= cx;

         y1 -= cy;

         y2 -= cy;

         var r = diam * diam / 4;

         var k = y1 - m * x1;

         var a = (1 + m * m) / r;

         var b = 2 * m * k / r;

         var c = k * k / r - 1;

         var discrim = b * b - 4 * a * c;

         if (discrim < 0) {

             return false;

         }

         discrim = sqrt(discrim);

         a *= 2;

         return isBetween((-b - discrim) / a, x1, x2) || isBetween((-b + discrim) / a, x1, x2);
     };
 } //Bob lyon
 var distance = function (P1, P2, C) {
    return abs( (P2.y - P1.y)*C.x - (P2.x - P1.x)*C.y + P2.x*P1.y - P2.y*P1.x ) / sqrt( pow(P2.y - P1.y, 2) + pow(P2.x - P1.x, 2) ) < C.radius; //If the distance from the center of C to the closest point on line P1P2 is less than the radius of C, returns true. Otherwise, returns false.
};
 {
     var car = function(locatio, accel, image, dragcoof) {
         this.loc = locatio;
         this.accel = accel;
         //this.power = power;
         this.image = image;
         this.volocity = new PVector(0, 0);
         this.acceleration = new PVector(0, 0);
         this.drag = new PVector(0, 0);
         this.dragcoof = new PVector(dragcoof.x, dragcoof.y);
         //this.trans = new PVector(0,0);
         this.rot = 0;
         this.wheelX = 0;
         this.wheelY = 0;
         this.canFall = true;
     };
     car.prototype.draw = function() {
         if (this.image === null) {
             //println("please put a nice image but I will supply a simple box for testing");

             pushMatrix();
             translate(this.loc.x, this.loc.y);
             rotate(this.rot);
             fill(255, 0, 0);
             rect(0, 0, 50, 10);
             ellipse(7, 10, 10, 10);
             ellipse(45, 10, 10, 10);
             //this.wheelX= this.loc.x+7;
             //this.wheelY = this.loc.y+10;

             popMatrix();
             this.wheelX = mouseX;
             this.wheelY = mouseY;
         } else {
             this.image(this.loc.x, this.loc.y);
         }
     };
     car.prototype.update = function() {
         //this.momentum = this.volocity.mult(this.mass);
         if (this.volocity.x >= 10) {
              this.volocity.x = 9.99;
         }
         if (this.volocity.x <= 0.1) {
            // this.volocity.x = 0;
         }
         if(this.canFall){
             this.acceleration.add(0,0.072);
         }
         if(!this.canFall){
             this.acceleration.y = 0;
             this.volocity.y = 0;
         }
         this.volocity.add(this.acceleration);
         transX -= (this.volocity.x);
         this.drag = PVector.mult(this.volocity, this.dragcoof);
         this.volocity.sub(this.drag);
         transY -= (this.volocity.y);
         //translate(-this.trans.x,0);
     };
     car.prototype.move = function(keycodeLeft, keycodeRight) {
         if (keys[RIGHT] && this.volocity.x < 10) {
             this.acceleration.add(this.accel.x, 0);
         }
         if (!keys[RIGHT] && !keys[LEFT]) {

             this.acceleration.set(0, 0);
         }
         if (keys[LEFT] && this.volocity.x >= -0.5) {
             this.acceleration.set(-0.1, 0);
         }
         if(keys[DOWN]){
             this.rot--;
         }
         if(keys[UP]){
             this.rot++;
         }

     }; // x1, y1, x2, y2, cx, cy, diam
     car.prototype.collide = function(lanvar) {

         for (var i = 0; i < level.length - 1; i++) {

        //     fill(255, 255, 255,       2);
          //      ellipse(this.loc.x+6,this.loc.y+10,10,10);
             if (lineCircleCollide((30 * i + 110) * lanvar.scale - lanvar.scale * lanvar.scm + transX, (lanvar.storage[i] / 1.5 +100) * lanvar.scale - lanvar.scale * lanvar.scm+transY, (30 * i + 140) * lanvar.scale - lanvar.scale * lanvar.scm + transX, (lanvar.storage[i + 1] / 1.5 + 100) * lanvar.scale - lanvar.scale * lanvar.scm+transY, this.loc.x+6,this.loc.y+10, 10)) {
                 this.canFall=false;
              //   collide.push([i, i + 1]);
               //  println(this.loc.x+45-transX);
                 //            println(this.loc.x+55-transX+"  "+this.loc.y);
                 transY++;
                fill(3, 3, 3);
                 text("Back Wheel hit",100,100);
                 break;
             }
             if (lineCircleCollide((30 * i + 110) * lanvar.scale - lanvar.scale * lanvar.scm + transX, (lanvar.storage[i] / 1.5 + 100) * lanvar.scale - lanvar.scale * lanvar.scm+transY, (30 * i + 140) * lanvar.scale - lanvar.scale * lanvar.scm + transX, (lanvar.storage[i + 1] / 1.5 + 100) * lanvar.scale - lanvar.scale * lanvar.scm+transY, this.loc.x+45,this.loc.y+10, 10)) {
                 this.canFall=false;
               //  collide.push([i, i + 1]);
                 fill(3, 3, 3);

                 text("Front Wheel hit",100,100);
             {
                 var n = new PVector(-this.loc.x+45+(30 * i + 110) * lanvar.scale - lanvar.scale * lanvar.scm + transX,-(this.loc.y+10)+(lanvar.storage[i] / 1.5 + 100) * lanvar.scale - lanvar.scale * lanvar.scm);
                 ///println(n);
                var u = new PVector((this.volocity.x*n.x)/(n.x*n.x),(this.volocity.y*n.y)/(n.y*n.y));
                //var w = new PVector(PVector.subt(this.volocity,u));
                var w = new PVector(this.volocity.x-u.x,this.volocity.y-u.y);
             }//Just some math that is not used (now but also never is possible)
             //
                //transX-=this.volocity.x;

              /**

              var slopeX = ((30 * i + 140) * lanvar.scale - lanvar.scale * lanvar.scm + transX)-((30 * i + 110) * lanvar.scale - lanvar.scale * lanvar.scm + transX);
                var lastX=this.loc.x-this.volocity.x;
                if((this.loc.x-lastX)%slopeX){
                    println(this.loc.x+" ");
                    println(lastX+" lastX");
                    println(slopeX+" slopeX");
                    var slopeY = ((lanvar.storage[i + 1] / 1.5 + 100) * lanvar.scale - lanvar.scale * lanvar.scm+transY)-((lanvar.storage[i] / 1.5 + 100) * lanvar.scale - lanvar.scale * lanvar.scm+transY);

                    println(slopeY);
                    if(slopeY<0){

                        this.transY+=slopeY;
                    }

              *///junk
                transY++;

                 break;
             }

             this.canFall=true;
         }
     };
 } //Car
 {
     var a = new car(new PVector(300, 200), new PVector(0.01, 0), null, new PVector(0.022, 0));

     var b = new createTerrain(200, 2000, level, 4, 130);
     b.pushNoise();

     var draw = function() {
         background(255, 255, 255);
         a.draw();
         a.update();
         a.move();
         text(a.acceleration + "\n" + a.volocity + "\n" + a.drag + "\n" + mouseX + "  " + mouseY + "\n" + a.loc, 400, 100.5);

         b.drawMap();
         a.collide(b);
         //println(collide[0]);
         //  println(collide[1]);
     };
 } //Draw and other things that don't deserve another bracket

```

https://www.khanacademy.org/computer-programming/car-physics-thingy/5378059343

# Answer
> 1 votes
Your code is a bit confusing to follow, due to poor indentation, useless commented code and lack of intermediate variables width a meaningful name.

That said, I can locate your problem to in the current algo to the following pseudo-code:

```
For each(roadSegment: in road) {
    If(frontTyre intersects roadSegment or rearTyre intersects roadSegment) {
        carHeight++
    }
}

```

I can point to several issues in this approach, by order of priority:

* You're artificially raising the height of the car, but do nothing to the vertical speed. As a result, the car lifts by 1px, but keeps its downward speed (which will actually increase due to gravity!) until it is fast enough downward to tunnel one full tyre diameter's length through the road segment. You need to *at least* cancel that speed to prevent this.
* You should aim at matching the car's vertical speed with the slope of the road upon contact (i.e. to cancel the relative vertical velocity), to make it follow the ground instead of sinking through an uphill, or flying over a downhill. Try the following

`RoadSlope=(y2-y1)/(x2-x1)`

`vertSpeed=max(vertSpeed, horizSpeed*roadSlope)`
* `carHeight++` is very arbitrary. It could be replaced by `carHeight=roadHeightUnderTheTyre+tyreRadius` or something similar
* You're not using a timestep (or, more accurately you're using a timestep of 1, implicitly). This will give you raw, jumpy movement, prevent increasing time resolution of collisions, and increase likelihood of tunneling. I really recommend you to read this excellent blog entry as a reference (I'm not affiliated to this blog in any way, but it *is* a good read)
* The car has no suspensions, so the collisions will feel very "sticky", try to implement springs in the tyres. This will mitigate contact forces and also reduce tunneling as collisions will be smooth
* The car has no angle, so it will stay awkwardly horizontal on slopes. While this is fine for now, be careful that a collision event on the front tyre doesn't cancel a rear tyre collision reaction and vice-versa. That may undo your hard work and insist on tunneling again.

Happy coding!

---
Tags: 2d, collision-detection, physics, side-scroller, car
---


# Question
Title: What algorithms are used for force dispersal between rigid objects attached by joints?
I have in mind a 2d, side-scrolling game which requires the construction of vehicles and/or structures built of conjoined rigid structures, like beams or platforms. These structures will be impacted from various angles.

What algorithms and data structures are used typically in, say, bridge-building games, to determine the force dispersal between such attached, rigid objects, and at what point the joints bend or break?

# Answer
If you are content with equilibrium cases (just finding distribution of forces in a static structure, possibly detecting destructive overload), and all your structures are discrete (e.g., built from trusses not cast from iron), and all your joints are pins (cannot support torque, so you only solve for forces), then you can use the method of joints.

https://en.wikipedia.org/wiki/Structural\_analysis discusses both the method of joints and the method of sections.

If your structures are even more regular (e.g., built from axis-aligned trusses), then it is possible to optimize algorithm even more.
> 1 votes

---
Tags: algorithm, physics
---


# Question
Title: Unity3d c# NullReferenceException keeps showing up
```
using UnityEngine;
using System.Collections;

public class SphereObj : MonoBehaviour {

    private GameObject manager;

    void Awake () {
        //things
    }

    public void SetParent(GameObject myManager) {
        manager = myManager;
    }
}

```

test

```
using UnityEngine;
using System.Collections;

public class SphereManager : MonoBehaviour {

    int position;
    int detail;

    public GameObject preSphere;

    void Start () {

        for(int i = 0; i < detail; i++){
            SphereObj itsMe = Instantiate(preSphere, new Vector3(0, 0, 0), Quaternion.identity) as SphereObj;
            itsMe.SetParent(gameObject);

        }
    }
}

```

So im building a game with basicly an unlimited amout of spheres and im instantiating all from a prefab. the prefabs got the first script attached managing sphere stuff, but i want them to have access to variables from the manager script, which is linked to an empty gameobject spawning things. my plan was to link the manager to the sphere scripts by this function:

```
itsMe.SetParent(gameObject);

```

but im geting this error

```
NullReferenceException: Object reference not set to an instance of an object

```

refering to the line mentioned above.

please help

thanks ahead.

# Answer
### You can not explicitly cast an `Object` as a `Component`

`Instantiate()` returns an `Object`, where you state return `as SphereObj`. Your attempting to return an `Object` as a `SphereObj`, which is not allowed. It is also important to note that `SphereObj` is derived from your newly created object, despite the fact that it is a *component*. For this to work, you must ensure that the game object referenced with `preSphere` contains a `SphereObj` component.

### Use `GetComponent<>()` to retrieve a `Component` from a `GameObject`

Instead, try explicitly casting the return as a `GameObject`, and appending a `GetComponent<>` inline.

```
SphereObj itsMe =
        (Instantiate(preSphere, new Vector3(0, 0, 0), Quaternion.identity)
        as GameObject).GetComponent<SphereObj>();

itsMe.SetParent(gameObject);

```

---

By explicitly returning the game reference as a `GameObject`, you are able to retrieve the `SphereObj` component, and set it up as intended.

---

### Further Thoughts

You describe setting up a "sphere manager", in a context where there would only logically be one "sphere manager". Perhaps it might be easier, in the long run, to set this up as a singleton-styled script.

```
class SphereManager
{
    public static SphereManager selfReference;

    void OnStart()
    {
        selfReference = this;
    }
}

```

In the above example, I create a class that holds a static self reference. This self reference sets itself up during `OnStart()`, but presuming I only ever have one instance of `SphereManager`, I do not have an issue with future instances potentially breaking my reference.

I can now call `SphereManager.selfReference` from *anywhere* in my code, to access this single instance I have running in my scene. Without having to use the `SetParent()` function in your `SphereObj`, you could still call `SphereManager.selfReference` to call to the manager. You could *also* access it from *other* classes, if you need to perform any other logic that involves your spheres.
> 0 votes

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


# Question
Title: Assign player currentLocation based on array coordinates
I wanted to incorporate changing location in an rpg, so I began by creating a class Location and assign every Location to a multi-dimensonal array, like so:

```
WorldMap[0, 0] = new Location("Majula");

```

I created two int variables named LocationY and LocationX set to the starting location. Now I got a command handler, when I type "Move South", I update the position with this dead simple code:

```
LocationY++;

```

Mind you, this is just for testing purposes, I just like to break a game into many small components that gets added as I get, or know better.

Now when I want to get my current location, I call it like this:

```
Console.WriteLine("He then headed south, until he arrived at {0}", WorldMap[PlayerLocationY, PlayerLocationX].Name);

```

That's cool and all, and it works, but I don't like typing too much if I can avoid it, so I wanted to change the call of `WorldMap[PlayerLocationY, PlayerLocationX].Name` to something more readable like `currentLocation.Name`.

So I tried this bit of code:

```
Location currentLocation = WorldMap[PlayerLocationY, PlayerLocationX];

```

Obviously, I get a NullReferenceException... I'm completely clueless, and I'm sure I'll probably say to myself "duh" when I'll get an answer.

And yeah, still learning, Console still rocks my socks!

# Answer
> 1 votes
It looks like you want a C# Property with a getter:

```
Location currentLocation
{
   get
   {
       return WorldMap[PlayerLocationY, PlayerLocationX];
   }
}

```

Put this in the body of your class, along with the declarations for member variables like `WorldMap` and the player's coordinates. You can add an access modifier if you want it to be public or protected.

Now when you write something like `currentLocation.Name`, it will call this `get` function internally, return the requested value from the `WorldMap`, and then dig out the `Name` of that returned location.

(Note: this will still give you a NullReferenceException if either your WorldMap is undefined or lacks an entry at this X,Y coordinate - so make sure your data is properly initialized!)

---
Tags: c#, console
---


# Question
Title: UPDATED: Deserialise Nested JSON with JSON Utility Unity 5.4
I am trying to deserialise a JSON with Unity 5.4's JSON utility (here).

This is what my JSON looks like:

```
{
    "series": [
        {,
            "points":[
                {"ts":"1473850836254","value":"11.27"},
                {"ts":"1473851256637","value":"6.44"}
            ]
        }
     ]
}

```

I am trying to access the values in "points" by calling something like: data.series.points\[0\].ts

```
void Start(){
    IncomingData data = IncomingData.CreateFromJSON(jsonResponse.text); // **error 1**
    print("Series point length" + data.series.points.Count);
    print("Series point 0" + data.series.points[0].ts); // **error 2**
}

```

//----------------------------------------- classes -------------------------

```
[System.Serializable]
public class IncomingData
{
    public Series series;
    public static IncomingData CreateFromJSON(string json)
    {
        return JsonUtility.FromJson<IncomingData>(json);
    }
}

[System.Serializable]
public class Series
{
    public List<Points> points = new List<Points> { };
}

[System.Serializable]
public class Points
{
    public int ts;
    public int value;
}

```

**Errors**

1. keystr == NULL UnityEngine.JsonUtility:FromJson(String)
2. Unexpected node type. UnityEngine.JsonUtility:FromJson(String)
3. ArgumentOutOfRangeException: Argument is out of range. Parameter name: index

I think it has something to do with how I embed the classes within each other - I am not really good at OOP ...

# Answer
Your JSON firstly is faulty and secondly does not match the data model.
To break down your JSON:

```
{
    "series": [
        {,
            "points":[
                {
                    "ts": "1473850836254",
                    "value": "11.27"
                },
                {
                    "ts": "1473851256637",
                    "value": "6.44"
                }
            ]
        }
    ]
}

```

Do you see the problems?

1. There is a `,` right after the first `{` bracket in `series`.
2. `series` is an array and not an object like in your C# object model.

To fix these errors and make your JSON compatible with the C# object model, remove the `[]` brackets for `series` and the leading comma:

```
{
    "series": {
        "points":[
            {
                "ts": "1473850836254",
                "value": "11.27"
            },
            {
                "ts": "1473851256637",
                "value": "6.44"
            }
        ]
    }
}

```

Also, change your data type of `value` in the `points` class to `double`, otherwise your values won't parse or will be truncated (I don't know how JSON Utility handles this). Your JSON should be valid and parse without errors.
> 4 votes

---
Tags: unity, c#, oop, json
---


title: Allow user to load remote assetbundle

text:
# Question
Title: Allow user to load remote assetbundle
How can I change the script to allow the end user to enter a URL, in the game view themselves, instead of me at the back end?

Here is the Unity script that I am using successfully to allow me add an asset bundle in the scene view at the back end:

```
using System;
using UnityEngine;
using System.Collections;

class NonCachingLoadExample : MonoBehaviour
{
    public string BundleURL;
    public string AssetName;

    IEnumerator Start()
    {
        // Download the file from the URL. It will not be saved in the Cache
        using (WWW www = new WWW(BundleURL))
        {
            yield return www;

            if (www.error != null)
                throw new Exception("WWW download had an error:" + www.error);
             AssetBundle bundle = www.assetBundle;

             if (AssetName == "")
                 Instantiate(bundle.mainAsset);
             else
                 Instantiate(bundle.LoadAsset(AssetName));

             // Unload the AssetBundles compressed contents to conserve memory
             bundle.Unload(false);

        }
        // memory is freed from the web stream (www.Dispose() gets called implicitly)
    }
}

```

It should look something like this:

# Answer
*I'm not exactly sure what you're asking, but I'll try anyway*

First of all you're gonna have to call `Start` when you click on the Load button, and as you can't start coroutines from the editor, you're need a wrapper that looks something like this:

```
public InputField URLField; //For pointing to the inputField

public void StartWrapper() //Add this to the Button's onClick field
 {
     BundleURL = URLField.text; //get url from field
     StartCoroutine(Start());
 }

```

This gets the text from the InputField you've selected **As long as you remember to select the InputField in the Editor!**

Lastly add this to the top of the file to be able to refer to UI elements like the InputField:

```
 using UnityEngine.UI;

```

Since you already use BundleURL in you `Start` coroutine, no editing is necessary there.
> 0 votes

---
Tags: unity, c#, networking, assets, streaming-assets
---


# Question
Title: Draw wrong faces in obj model with OpenGL VBO
I am trying to draw a 3D model from an **.obj** file, and have met big trouble. I think my model draws with wrong faces, but I can't understand why.

**Original model:**

This is my code for reading the model:

```
        using (StreamReader streamReader = new StreamReader("Content/Models/" + path))
        {
            while (!streamReader.EndOfStream)
            {
                List<string> words = new List<string>(streamReader.ReadLine().ToLower().Split(' '));
                words.RemoveAll(s => s == string.Empty);

                if (words.Count == 0)
                    continue;

                string type = words[0];
                words.RemoveAt(0);

                switch (type)
                {
                    // vertex
                    case "v":
                        vertices.Add(new Vector4(float.Parse(words[0], new CultureInfo("en-US").NumberFormat),
                            float.Parse(words[1], new CultureInfo("en-US").NumberFormat),
                            float.Parse(words[2], new CultureInfo("en-US").NumberFormat),
                            words.Count < 4 ? 1 : float.Parse(words[3], new CultureInfo("en-US").NumberFormat)));
                        break;

                    case "vt":
                        textureVertices.Add(new Vector3(float.Parse(words[0], new CultureInfo("en-US").NumberFormat),
                            float.Parse(words[1], new CultureInfo("en-US").NumberFormat),
                            words.Count < 3 ? 0 : float.Parse(words[2], new CultureInfo("en-US").NumberFormat)));
                        break;

                    case "vn":
                        normals.Add(new Vector3(float.Parse(words[0], new CultureInfo("en-US").NumberFormat),
                            float.Parse(words[1], new CultureInfo("en-US").NumberFormat),
                            float.Parse(words[2], new CultureInfo("en-US").NumberFormat)));
                        break;

                    // face
                    case "f":
                        foreach (string w in words)
                        {
                            if (w.Length == 0)
                                continue;

                            string[] comps = w.Split('/');

                            // subtract 1: indices start from 1, not 0
                            vertexIndices.Add(uint.Parse(comps[0]) - 1);

                            if (comps.Length > 1 && comps[1].Length != 0)
                                textureIndices.Add(uint.Parse(comps[1]) - 1);

                            if (comps.Length > 2)
                                normalIndices.Add(uint.Parse(comps[2]) - 1);
                        }
                        break;

                    default:
                        break;
                }
            }
        }

```

This is code is also available on GitHub - github.com/Freaky-Brainstorm/Deep.

# Answer
> 1 votes
There are better ways than what I show here, but if you're working on a small game (aka.: you're not working on an A++ game) then you'll be fine with this:

The part where you extract the vertex, texture and the normal information from the file is good and should work, but you need to rearrange them so the information for the same vertex should have the same index.

So, I assume you have three lists, `vertices` for the vertices (obviously) the `textureVertices` for the UV coords, and the `normals` for the normals.

The output lists are going to be `verts`, `texs`, `norms` and `indices` for the vertex positions, UV coords, normals and indices respectively.

```
vertexIndex := 0
// Processing stuff for the vertices, UV coords and normals
// the "row" string contains the current row
case "f":

   data := split(row, " ")
   // data: ["f", "1/2/3", "4/5/6", "7/8/9"]
   for (i = 1; i <= 3) do
       info := split(data[i], "/")
       // info: ["1", "2", "3"]
       verts.add(vertices[parse(info[0] - 1)])       // Rearrange vertex data
       texs.add(textureVertices[parse(info[1] - 1)])
       norms.add(normals[parse(info[2] - 1)])
       indices.add(vertexIndex)                      // Add the index for the vertex (if you use drawArrays, you can leave out this part)
       vertexIndex = vertexIndex + 1
   end

   break

```

---
Tags: c#, opengl, vbo, opentk, obj
---


# Question
Title: How does the Unity coordinate system map to screen pixels?
If I have a `GameObject`, say at **x = 0, y = 0**, and I want to move it for a **40** pixel to **x** how can I make that?

In don't understand which is the unit of measurement in Unity.

If I make something like this where `mov` is **40** the sprite goes out of screen!

```
void Start()
{
    transform.Translate(new Vector3(mov, 0, 0));
}

```

it seems like the correct values must be very low, say 0.6, 1, 3, etc.

But why?

# Answer
> 4 votes
In Unity you don't use pixels as a distance measurement, you use units.

"How much is a unit?" well... it is whatever you want it to be. It's just a reference.

If you select your sprite in the assets window, in the inspector you will see it's properties. One of them is "Pixels per unit", which by default is 100.

If your sprite is 100x100 pixels, and you set it to 100 Pixels per unit, you sprite will be 1x1 units in your scene. If you want to use the pixels in your sprites as a size reference you have to use the same "Pixels per unit" in all of your sprites. There are several aproaches when it comes to deciding what Pixel per unit to use:

* If you are using cell based sprites to generate terrain, you could use a Pixels per unit equal to the number of pixels of your cell's size. This way, **each unit will be equal to 1 cell distance**.
* Set Pixels per unit to 1. This way 1 pixel will be the size of a unit. This is more intuitive when coding, but in the long run, I'd say its not really convenient. This would make game objects and collider HUGE. This might not look like a big issue, but it **can actually impact the performance or behaviour of the physics engine** for example. I have also experience interface problems with having such big objects: Having to zoom out some much, some gizmos stopped being displayed in the scene window, maybe because Unity though it was too far away to display.
* Just leave it at 100. This is the default value, and it fits the rest of the default values: For example, gravity acceleration will look too slow if you set Pixels per unit at 1 and leave the default gravity force. **If you are a begginer, and want to mess around with forces and masses, I'd suggest you take this approach**, as this way if something doesn't work as you expected, it's provably because you did something wrong, and not because you didn't change some default value, or overlooked some other interactions.

Anyway you should take into account what Pixels per unit value you are using when measuring distances: `units = pixels/pixel per unit`

So, in your particular case, having the default Pixels per unit, to move the object for 60 pixel, the distance would be: `units = pixels/pixel per unit` =\> `units = 60/100` =\> `0.6 units`

# Answer
> 1 votes
The unit of measurement in Unity are "world space" units. Unity is still a 3d engine at heart, and in 3d space, pixel coordinates are quite meaningless.

How world space coordinates translate to screen coordinates depends on how you set your camera. When you have a 2d project, then your camera is likely set to orthogonal projection. In that case you can use the size settings to control how many world space units are shown on the screen. With the camera on perspective projection it gets more complicated, because object scaling is affected by distance from the camera and field of view.

Keep in mind that changing your camera size also scales all your images. Use the "Pixels per unit " setting in the image import settings to control how large your images will be in the game. The question "How can I set up Unity so that 2d images are displayed in their original resolution?" goes into further details how to achieve a 1:1 scaling.

---
Tags: unity
---


# Question
Title: Why is the bullet not created realitive to the player?
I'm using GameMaker to make my game and I'm trying to get the player bullet to fire out of the players gun but for some reason even though I checked 'relative', the bullet is still being created at the top of the room.

Why? How could I have the bullet created relative to the player?

# Answer
> 1 votes
The `relative` label can give different results, depending on where used. When an object is created `relative`ly to another object, it means the `x` and `y` coordinates you are giving as parameters will be summed to the object calling the *Create Instance* function. You can achieve this in different ways.

### Fix your function

Since you want the bullet being created at player's position, you should call the *Create Instance* from within the player object. If you are calling the function from another object, you will get wrong results.

### Delegate the function

You can also put the *Create Instance* function anywhere you want, as long as the *Applies to* field is referring the player object:

To do so, from the *Applies to* field select "Object", then choose your player object from the list, and you're done.

### Use absolute coordinates

Maybe not the best solution, but it will work as well. Instead of creating the bullet `relative`ly, create it at an absolute position (uncheck the `relative` field) and set such position as the player's: use `oPlayer.x` and `oPlayer.y` as *x* and *y* coordinates (change the `oPlayer` object name according to your project).

That's it. Let me know if something isn't working, I'll try to help you. Also, if you could provide some info such as a screenshot of the functions inside your object, we may take a deeper look to solve your issue.

---
Tags: game-maker
---


title: Use raycast to fix bullet's direction?

text:
# Question
Title: Use raycast to fix bullet's direction?
Player cam has a raycast. I need it to work as pointer for player's bullet direction. If the ray hits any kind of object this spot will be the aim of player's bullets.

Here is my script

```
public class camraycast : MonoBehaviour {

Camera mycamera;
GameObject prefab;

public int bulletSpeed = 10;
public GameObject angle; //  camera
public GameObject players;

void Start () {
    prefab = Resources.Load("bullets") as GameObject;
    mycamera = GetComponent<Camera>();
}

void Update() {

    if (Input.GetMouseButtonDown(0))
    {
        Vector3 camScreen = new Vector3(0.5f, 0.5f, 0f); // center of the screen
        float rayLength = 100f;
        Ray ray = mycamera.ViewportPointToRay(camScreen);
        RaycastHit hit;
        Debug.DrawRay(ray.origin, ray.direction * rayLength, Color.red);

        if (Physics.Raycast(ray, out hit, rayLength))
        {
            print ("Looking at : " + hit.transform.name);
            GameObject bullets = Instantiate(prefab) as GameObject;
            bullets.transform.position = players.transform.position + angle.transform.forward * 0.1f;
            Rigidbody rb = bullets.GetComponent<Rigidbody>();
            rb.AddForce((hit.point - angle.transform.position) * bulletSpeed);
            Destroy(bullets, 9f);
        }
    }
    Vector3 camScreens = new Vector3(0.5f, 0.5f, 0f); // center of the screen
    float rayLengths = 100f;
    Ray rays = mycamera.ViewportPointToRay(camScreens);
    Debug.DrawRay(rays.origin, rays.direction * rayLengths, Color.red);
}
}

```

# Answer
Most FPS games just use HitScanning, where they fire a ray out the centre of the screen and get back the first object it hits, applying logic to that object. Any bullets coming out of the weapon itself are just graphical assets and don't actually interact with anything.

If, however, you do really want to simulate the physics of bullets, then what you can do is add in the line

```
bullets.transform.LookAt (hit.transform);

```

after you instantiate but before you add the force and it should make the bullet rotate to look directly at the object that the raycast hit, before you fire it off.
> 1 votes

---
Tags: unity, raycasting
---


# Question
Title: Wrong object is being detected on OnMouseUpAsButton
In my 2d game project I have an object A moving above map. Both object and map have colliders (circle collider and polygon collider respectively), as well as actions to be performed on OnMouseUpAsButton. Objects are displayer properly in the game, however, when I click on the object it usually detects map (usually as in sometimes it detects the object if I press in the very centre of the object). How to ensure that my objects of type A are always checked first for MouceUp?

# Answer
> 0 votes
Well I found an answer that seems to work- even though it is a 2d project set Z transform position of the object to -1. It's a hack but it works

---
Tags: 2d, collision-detection, mouse
---


# Question
Title: How do I get access to the PS4 platform tools for Unity?
I know that you can go to the "Xbox ID" program to get all the resources you need for the Xbox platform (developer forums, Unity SDK, etc.). but there is not really information about how to get the PlayStation tools.

...Well other than the contact sales button in Unity which links to Unity and not Sony (oddly enough).

So where does someone who hopes to put their games onto one of the Sony platforms (PS4, Vita, PS3, etc) go to get the build tools (and other things) they need? Do Sony contact you about it if they're interested or is it really only for developers who are considered above Indy?

# Answer
Searching "PS4 tools for Unity" turns up this site:

> How can my team get Unity for PlayStation®4?
>
> Start by registering with Sony. Once registered, developers can download Unity for PlayStation®4, get creating and self-publish. It’s that simple.

You can also register to be a PlayStation(R) Partner at this link:

> Before applying, you will need the following:
>
> * If you are based in the US, a corporate entity and an Employer Tax ID Number (see www.irs.gov)
> * A Static IP address (required for access to SIE developer and publisher websites)
> * A non-public domain email address (Gmail, Hotmail, etc. are not acceptable)
>
> For any questions, please contact:
>
> SIEA (Americas): Selfpublish@playstation.sony.com
>
> SIEE (Europe, Middle East, Africa, India, Australia, New Zealand): PS\_Partners\_Registration@scee.net
> 2 votes

---
Tags: unity, publishing, playstation4
---


# Question
Title: why is my OnCollisionStay is not calling?
I am very new to unity, i have used onCollitionStay() method but its not doing anything, i wanted to do in my code is "if zombie stays for 20 seconds with player the player life should be reduced", could anyone can help me out with this? my code is

```
void OnCollisionStay(Collision collisionInfo) {
    if (collisionInfo.collider.tag == "zombie") {
        transform.GetComponent<Renderer>().material.color = Color.red;
        dieTime += Time.deltaTime;
        if(dieTime>20.0){
            noOfLivesLeft--;
            if(noOfLivesLeft<=0){
                transform.localScale = new Vector2(0,0);
                Application.LoadLevel ("GameOver");
            }
        }
    }
}

```

# Answer
> 2 votes
You're using 2D colliders and Rigidbodies, but 3D collision functions

Switch to using OnCollisionStay**2D**(Collision**2D** collision) to respond to 2D collisions.

---
Tags: unity, c#, collision-detection
---


# Question
Title: how to get width and height of TiledMap in the latest Version of Libgdx
I am making a tiled based game, I want not to let the camera show places, where there is no map... this is a obvious solution I got from a tutorial

```
if(camera.position.x<400){
    camera.position.x=400;
}else if(camera.position.x>map.width*map.tileWidth-400){
    camera.position.x=map.width*map.tileWidth-400;
}

if(camera.position.y<240){
    camera.position.y=240;
}else if(camera.position.y>map.height*map.tileHeight-240){
    camera.position.y=map.height*map.tileHeight-240;
}

camera.update();

```

but I don't know how to get width & height of the tiledMap in the latest version of libgdx

https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/maps/tiled/TiledMap.java

Seems strange... I even tried the Super classes but couldn't find. Please help.

# Answer
```
TiledMap tiledMap = new TmxMapLoader().load("path/to/tiled/map.tmx");
MapProperties prop = tiledMap.getProperties();

int mapWidth = prop.get("width", Integer.class);
int mapHeight = prop.get("height", Integer.class);
int tilePixelWidth = prop.get("tilewidth", Integer.class);
int tilePixelHeight = prop.get("tileheight", Integer.class);

int mapPixelWidth = mapWidth * tilePixelWidth;
int mapPixelHeight = mapHeight * tilePixelHeight;

```

The `mapWidth` and `mapHeight` are the dimensions of the map in tiles. So they would both be 10 in a 10x10 grid. The `tilePixelWidth` and `tilePixelHeight` are the dimensions of the tiles in pixels. In a 32x32 tileset they would both be 32. Multiplying the dimensions together you will get the map dimensions in pixels.
> 20 votes

# Answer
The information you seek is in the object of TiledMapLayer.

```
TiledMapTileLayer layer = (TiledMapTileLayer)tiledMap.getLayers().get(0);

```

or

```
TiledMapTileLayer layer = (TiledMapTileLayer)tiledMap.getLayers().get("my_layer");

```

then you can use:

* `layer.getTileWidth();` to access tile width in pixels.
* `layer.getTileHeight();` to access tile height in pixels.
* `layer.getWidth();` to access number of tiles, horizontally.
* `layer.getHeight();` to access number of tiles, vertically.
* `layer.getTileWidth() * layer.getWidth();` to work out the map width in pixels.
* `layer.getTileHeight() * layer.getHeight();` to work out the map height in pixels.

To set change a specific tile,

```
TiledMapTile tile = null;
int column = 0;
int row = 0;
Cell cell = new Cell();
cell.setTile(tile);
layer.setCell(column, row, cell);

```

and to get a specific tile,

```
int column = 0;
int row = 0;
Cell cell = layer.getCell(column, row);
TiledMapTile tile = cell.getTile();

```
> 0 votes

---
Tags: libgdx, tilemap
---


title: Getting Image name given a canvas WPF

text:
# Question
Title: Getting Image name given a canvas WPF
I have a bunch of images I'm using for a chess game in a canvas using wpf, xaml, and C#. I want to use

```
Canvas.SetTop(image, position);

```

to set the position of this image. However I am given the index of child in my canvas and that is it.

```
myCanvas.children[index]

```

I tried

```
Canvas.SetTop(myCanvas.children[index], position);

```

but that did not work. How can I change the position of the image given only the index of the image in the canvas?

Edit: Another option would be to change the position of the canvas child. But I couldn't find anything for that.

# Answer
> 1 votes
Since you're using WPF I expect you don't plan to use a lot of animation, so a better way to do this would be with a Grid:

```
<!-- XAML -->
<Grid x:Name="Board">
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
</Grid>

```

To place something in a cell:

```
void SetPosition(UIElement element, int x, int y)
{
    if (!Board.Children.Contains(element))
        Board.Children.Add(element);
    Grid.SetColumn(element, x);
    Grid.SetRow(element, y);
}

```

You could also use a UniformGrid.

A completely data-driven answer can be found in StackOverflow: WPF controls needed to build chess application

# Answer
> -1 votes
```
myCanvas.Children[index].SetValue(Canvas.TopProperty, position);

```

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


# Question
Title: Is there a reason not to delete the System.Collections namespace in Unity3D?
I find various scripts on tutorials, books and even on the community wiki `using` the `System.collections` namespace without ever actually *using* it.

Is this an obscure Unity3D requirement, or are the authors using the default script template and forget/don't bother deleting the import?

# Answer
The only statement that is truly required is the `UnityEngine` as that allows you to use the Unity specific classes and systems (`Vector3`, `Input`, Collides, GUI elements, particle systems, etc.). You can delete the other one if you wish, it won't affect anything (as long as it's not used, see co-routines) and in some cases you might not even needed the Unity engine but thats for a different question :)

The reason that you see some using statements at the top of new files is because Unity thinks that it might come in handy for you to have them before you start. They allow you to use slightly more advanced parts of the language than is strictly needed (Array lists, Dictionaries, Queues, etc.).

Though development you will add quite a few extra `using` statements to your code that won't be needed by the end as the project develops, so you **can** delete them without it affecting the performance of the project your working on at all. In fact there are several benefits to deleting the `using` statements that aren't used:

1. The code will take a **shorter period of time to compile**, that small lag that appears when you move from your code to the unity window when the engine looks at the new code and interprets it,as there are less files to look through and build.
2. The built project will be **smaller**, This isn't really a concern for games that run on platforms with lots of space (PC, Console, etc.) but it might be useful to shave a few MB from the size of mobile games (`using system` is usually a culprit)
3. **Cleaner code**, not really an actual advantage to the player/user of the end product but I have found that going though each script as the project develops can make you think about how your code looks and might get you to make a small improvements to the structure to make it easier to read, debug and update when you look at it again.

Just make sure that each class has what it needs otherwise you will get a lot of errors, but they are easy to fixed by just adding in the bits that are used in that piece of code.
> 2 votes

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


# Question
Title: How do I get basic collision, in Unity, for an imported sketchup model?
How do I get basic collision, in Unity, for an imported sketchup model?

My friend and me are new to game development, and we have to submit the game within a week. Please help me.

I downloaded an airport model from 3D Warehouse, and we imported it in to Unity 5.1.2, but our character is going through all the objects in the airport. Please find us find a solution.

# Answer
> 2 votes
You mean collision, not trigger. Trigger volumes are non-solid.

In Unity, in the Component menu under physics, add a Mesh Collider.

By default, it will select the same mesh as the model, but you will probably want to make a low-poly mesh to use for collision instead of the full detail one you use for visuals.

# Answer
> 0 votes
Add 3D cubes in the scene near the floor of the stadium, it will have a default 3D box collider in it. Scale it as your need. Then it will work as collider which will keep your character just in the stadium plane.

Trigger is an another variable that makes the collider component penetrable. I guess that's not what you want.

# Answer
> 0 votes
To stop your player from being able to walk through objects in the scene, you need to use colliders. Colliders are components that allow us to define a shape or area for processing collision events. This includes physically preventing a player from walking through walls and other game objects.

## Adding a Collider

Adding a collider is fairly simple. Select the object you wish to add the collider to from your hierarchy, and on the inspector, select **Add Component**. From here, you can select the type of collider you wish to add, or type "collider" to view all of the collider components presently available to you.

## Choosing the right Collider

There are many possible collider types to choose from, so which one should you choose? First and foremost, since you are creating a 3D scene, you should not be using any *Collider 2D* component. Physics works differently for 2D and 3D, so 2D colliders will only interact with other 2D colliders, and by default will only respond to 2D physics events. The same goes for 3D colliders and 3D physics events.

Of the remaining options, there are five particular colliders that stand out:

* **Box Collider**: A simple box without further detail. A great option for your average building.
* **Sphere Collider**: A simple sphere without further detail. A great option for spherical objects, such as balls or character heads.
* **Capsule Collider:** A simple capsule, with rounded faces. A great option for basic player colliders and poles.
* **Mesh Collider:** A collider derived from a 3D model. By default, this will automatically link to the model you are currently using on the game object. While this is the way to go for more complex models where basic shapes simply won't cut it, you would normally make a specific collider object from your 3D model, by scaling down its polygon count. Remember, the more polygons, the more complex the collider.
* **Terrain Collider:** A collider derived from a terrain object. You should not be specifically creating one of these, as they only provide collision for the Unity terrain object, and are loaded in by default. If you made the ground using terrain editing, in Unity, you probably already have one of these in your project.

Choosing between them depends on the object you are placing the collider on, how detailed you want your collision to be, and how efficient you want your collider to be. Consider the detail in your game objects. As an example, consider a brick wall. In the real world, you could feel the detail on the bricks, and in indent of the mortar between each brick. In a 3D game, this detail is unlikely to be noticed, apart from your game potentially stalling to calculate collision due to the far more complex collider. In this case, a simple box would suffice, as the player would still react to the basic shape in practically the same way.

## Choosing the objects to place the colliders

For the purpose of simply preventing the player from moving into objects, its important to note that it really does not matter *what* game object you place the collider on. For organisational sake, it is probably best to simply add the collider to the object the collider represents. In the case where you have a collider spanning multiple game objects, these game objects should likely be grouped under a parent game object, with the parent game object holding the collider.

If you ever want to have any other reaction to collision, such as having the player take damage or triggering a door to open, you will want the collider to be on the same game object as the script in charge of its reaction. This is because colliders automatically call a number of `MonoBehaviour` functions, such as `OnCollisionEnter(Collision)` and `OnCollisionStay(Collision)`, which greatly help you perform your collision logic. *You do not need to set any of this up for simple 'prevent the player from walking through this' collision*.

## Further requirements

To get everything working, there are a few tiny details you need to ensure.

* First of all, and it should go without saying, colliders only react to other colliders by default. Your player *also* needs a collider, in order to respond to attempts to move into the space of *another* collider. With greater complexity and character animation, this would normally be made up of a series of colliders, to represent each part the player can move. For something more simple, you should typically use a *Capsule Collider*.
* For collision to work, one of the objects involved in the collision *must* have a rigidbody. This is a very important part; if two objects collider, and neither have a rigidbody, they will still pass through each other. This is also the step most commonly missed with beginner collision detection in Unity. Typically, your player game object should already have a rigidbody. If it does not, you can add one in the same way you add the collider, just make sure to add *Rigidbody* and not *Rigidbody 2D*. Rigidbodys also provide physics, using the Unity physics engine. It is important to know this, as your object will respond to physics differently, with a rigidbody attached. While this will not affect direct transform translation, you may want to ensure that the component shows `Use Gravity = false`. Once things are up and running, have a play around with this component, and observe how it affects the way your character moves.
* As a last matter of importance, you need to ensure that your collider shows `Is Trigger = false`. Colliders set to act as a trigger will not respond to normal physics-based collision. These colliders will freely allow other objects to move through them. As an example of when you might use one of these, you might have an area the player can move through that triggers an event when the player reaches it. A trigger collider would detect that the player has reached the location, while still allowing the player to pass through.

## Further Reading

You can read up on colliders in the Unity Manual. There is also a good Unity tutorial on colliders that will show you the basics. If you are more experienced with the programming side of Unity, you might also want to read through the API entries, including Collider which acts as a parent class for all 3D colliders.

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


# Question
Title: Game asset : some are handled by POINTER, some by VALUE ; fear of inconsistency
A part of my game asset manager are divided into 3 layers.

## **1. Loader** (Opengl-related) : **MeshInternal**, **TextureInternal**

A manager will ensure that 1 filename will be loaded only once.

## **2. Handle** : **MeshPtr** , **TexturePtr**

This can be stored in game logic, and can be used in Material.
Each instance can be duplicated and can be stored by game logic.
They are just pointers to \[1\].

```
//game logic
MeshPtr meshptr=meshManager()->get(ROCKET_MESH);

```

## **3. 3D Material** (**Material**)

It contained a fix amount of textures (e.g. lambertian, specular, emit, ...) and some tweaked color values (e.g. lambertian color multiplier).

It is stored by value, because each instance of in-game 3D-object may duplicated it and customize it to match its unique attribute (e.g. red=low HP).

Game logic will cache it *by value*.

```
//game logic
Material mat=material()->mat_ROCKET; //shallow copy work well
//can also be called using enum

```

# Question

Although everything work really good, my fear arise.

```
I store [2] by value.  It means I stored [1] in term of pointer.
I store [3] & [4] by value.

```

I think it is inconsistent, especially when I look at example code in \[2\]&\[3\] above.

How to professionally avoid this type of inconsistency? ... or is it the correct way to go?
Are there any disadvantage/limitation of this design?

# Answer
> 3 votes
You want to be able to easily sort by material in order to render everything that has the same material at once. This helps a lot with efficiency. So it's almost definitely a bad idea to store materials by actual value though this may seem handy for some reason. Instead move to some kind of index into a materials array.

The rest is fine, logically speaking. Since they are variable size objects there is no reasonable way to put them all into a flat object so pointers are fine here.

---
Tags: c++, asset-management
---


# Question
Title: UV mapping in blender for use with Unreal Engine material
I have a room that I want to import in Unreal Engine 4.

When I do it, I apply a material to the walls (for example), and the walls look like this:

My question is, how can I map the object to the unreal engine material? I've seen some tutorials but I don't specifically know what I must do, since I only apply the material in Unreal.

# Answer
> 1 votes
I guess yo don't understand UV Mapping.

Let's say you have one texture, for example a brick texture. Since every wall should have the brick texture, you have to map all quads of the wall to the \[0,1\] UV Space to fit the texture.  This is the original UV setup. similar to yours. To "distribute" the texture evenly on the faces, you need the faces to fit in the \[0,1\] UV-Space.  Here I only did one side of the object. As you can see, the left side is now properly textured.  Here I did the same for the second face. The UVs are now overlapping!

In your example mesh, some faces don't need the \[0,1\] space completely. Play around until it fits your needs.
Overlapping UVs are no Problem for the texutre Channel. You need a second UV Channel for Lightmaps. There you can't have overlapping UVs or UVs that are not in \[0,1\] space

For creating lightmaps (proper UV setup for them) look at this: https://docs.unrealengine.com/latest/INT/Engine/Content/Types/StaticMeshes/LightmapUnwrapping/

Edit: Here's an example of a mirrored UV Map:  Each side of the mesh uses the same UVs

---
Tags: blender, unreal-4, uv-mapping
---


# Question
Title: Rendering with sdl_gfx is so slow, any alternative?
I have been using sdl\_gfx ( sdl2 extension library https://github.com/ferzkopp/SDL\_gfx ) to make Android games, I have always noticed that rendering primitives is so slow.
So I was rendering it once to a texture then drawing the texture on each frame to the screen, but now I'm working on a game project in which that method is not possible.

I am looking for an alternative, is there a way to render primitives ( with alpha ) on Android using SDL2? A crossplatform method (not GLES). sdl\_gfx is fine but soooo slow (double slow on Android but even under Windows so slow) I think that's because it is using the SDL2 renderer to render to the screen, by calculating the pixels of the primitive and draw each pixel to the screen, so it is using the CPU not GPU (software rendering), that makes it so slow.

# Answer
You can render a quad image directly to the screen using OpenGL.

http://www.learnopengl.com/#!Getting-started/Textures

```
void RenderTests::RenderQuad()
{
    static GLuint quadVAO = 0;
    static GLuint quadVBO;

    if (quadVAO == 0)
    {
        GLfloat quadVertices[] = {
            // Positions        // Texture Coords
            -1.0f, 1.0f, 0.0f, 0.0f, 1.0f,
            -1.0f, -1.0f, 0.0f, 0.0f, 0.0f,
            1.0f, 1.0f, 0.0f, 1.0f, 1.0f,
            1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
        };
        // Setup plane VAO
        glGenVertexArrays(1, &quadVAO);
        glGenBuffers(1, &quadVBO);
        glBindVertexArray(quadVAO);
        glBindBuffer(GL_ARRAY_BUFFER, quadVBO);
        glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), &quadVertices, GL_STATIC_DRAW);
        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
        glEnableVertexAttribArray(1);
        glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    }
    glBindVertexArray(quadVAO);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    glBindVertexArray(0);
}

```

You will have to start by initializing OpenGL and have quite a few steps to go before you can actually just draw an image, but the tutorials cover all that as well, just start from the beginning with hello triangle tutorial.

http://www.learnopengl.com/#!Getting-started/Hello-Triangle
> 0 votes

---
Tags: rendering, performance, sdl2, gpu, sdl-gfx
---