# Question
Title: How do you create an outdoor map without letting in leaks?
With the Source engine, I want to make a map in the outdoors (similar to something like Dust2 or Inferno) but not let in leaks due to the open top part of the map. Is there a way I can do it without the leaks?

# Answer
> 2 votes
This is done with a **skybox**. In reality, the maps are still closed; they are simply using a special material which marks the space as to render the skybox, which is what ends up looking like the sky. Therefore, you must enclose the level with the "tools/toolsskybox" texture, while leaving sufficient space for things like grenade throws to happen. There are multiple versions of skyboxes, I suggest you read through the VDC article here.

---
Tags: source-engine
---


# Question
Title: Adding a video to a Level in a Portal 2 Mod
I'm currently working on my Portal 2 mod and I'd like to add a video to be displayed on a projector like the Dollar$ and SENSE video at the end of Portal 1. Currently what I have is a simple recreation of a room in The Fall chapter of Portal 2, and I want to have a video displayed on the projection screen.

If anyone could give me instructions, or point me a link on how to do this that would be great.

# Answer
> -1 votes
You'll want to use an animated texture or vgui\_movie\_display.

---
Tags: modding, video, source-engine, valve, hammer
---


# Question
Title: Better way of handling the relation between Bullet and Enemy
I was wondering how should I design this relation in terms of "better OOP"?

Should I have a Singleton EnemyManager which contains a list of enemies (EnemyList); then Bullets can access the EnemyList to check for collision?

Or should I just pass EnemyManager as a reference to each Bullet so Bullets can still access the EnemyList but not in a Singleton way?

Or is there any other better ways of doing?

Please advise.

# Answer
> 2 votes
> or is there any other better ways of doing?

What is your metric for "better"? Setting aside the comments on the question that "it isn't the Unity way", both of your approaches are just fine.

Another option is to pass in IEnemyManager (an interface or superclass of EnemyManager) to each Bullet, which exposes some but not all features of EnemyManager. The usual reasons for this approach are:

* For testing, you might pass in a test-only implementation of IEnemyManager.
* For safety, to prevent whoever's working on Bullet code from inadvertently or sneakily using methods on EnemyManger that you didn't intend for a Bullet to use, like creating new enemies or what not. (Less of an issue on a solo or small team effort.)

But probably a singleton is just fine for now if it lets you move forward on your project. (Or switching over to a more Unity-conventional way.)

# Answer
> 0 votes
In my experience, the structure you use should always be the least abstract (most understandable) that you can come up with, in a way that is also efficient. Think hard about the physics behind what you're trying to achieve. What should the bullet know about it's environment? What does the enemy need to know? How does the interaction take place?

Now there is probably a penultimate way of doing things, but it's so complex, and considers so many different things.. like motion prediction optimizing, event listeners, grid-based object-pointers, bounding-box trees. The question is whether you need any of that.

When you don't know what method to use, just go with whatever inspires you. You're probably not going to find entirely the right answer whatever you do, but it's the only way you're going to find out what that right answer is. If you get stuck, consider re-writing whatever it is that lead you to that dead end. In a sense, I'm saying it all depends on your game.

That said, I agree with the other posters that if you can, follow Unity's guidelines. Unity was built assuming that you use it to its full potential. You will always encounter brick walls if you don't (however climbable those walls might be :P).

# Answer
> 0 votes
Don't keep a list of enemies. Make your health script generic. So when bullet hits a gameobject tagged "enemy", you can call like:

```
if(hittedCollider.gameObject.tag == "enemy")
{
    hittedCollider.gameObject.GetComponent<HealthManager>().AddDamage(damageAmount);
}

```

(this is an example of course, names are up to your decision)

# Answer
> 0 votes
Put safe that in Unity the suggested/best way of managing collision is using Unity colliders.

Let's follow your aproach. As the max numbers of enemies and bullets you may have at the same time and the dimension of your map grows, you may consider managing your enemies and bullets not in single list but in a Geometric hashing structure. Here you find a didactic Spatial hashing implementation for fast 2D collisions and this also helped me for collision detection in love2d.

# Answer
> 0 votes
> An interface contains definitions for a group of related functionalities that a class or a struct can implement.
>
> By using interfaces, you can, for example, include behavior from multiple sources in a class. That capability is important in C# because the language doesn't support multiple inheritance of classes. In addition, you must use an interface if you want to simulate inheritance for structs, because they can't actually inherit from another struct or class.

For example these classes have Color Interface:

https://msdn.microsoft.com/en-us/library/ms173156.aspx

https://unity3d.com/learn/tutorials/topics/scripting/interfaces

---

First you should define interface.

```
using UnityEngine;
using System.Collections;

    public interface ITakeDamage<T>
    {
        void Damage(T damageTaken);
    }

```

this is Bullet script:

```
using UnityEngine;
    using System.Collections;

    public class Bullet : MonoBehaviour
    {
        public int amount = 10;

        void OnCollisionEnter(Collision other)
        {
            if (other.gameObject.tag == "Enemy")
            {
                other.gameObject.GetComponent<ITakeDamage<float>>().Damage(amount);
            }
        }
    }

```

by using interfaces you can have many object that they have ITakeDamage like car , player , etc.so you can have condition if object have ITakeDamage then decrease health value.

```
void OnCollisionEnter(Collision other)
{
    var TakeDamage = other.gameObject.GetComponent<ITakeDamage<float>>();
    if (TakeDamage != null)
    {
        TakeDamage.Damage(amount);
    }
}

```

implementing ITakeDamage interface in Enemy script

```
using UnityEngine;
using System.Collections;

public class Enemy : MonoBehaviour,ITakeDamage<float>
{
    public float health;
    public float Health { get { return health; }
    set {
        if (health > 0) {
            health = value;
        }else
        {
            Destroy(gameObject);
        }
     }
  }

    public void Damage(float damageTaken)
    {
        Health -= damageTaken;
    }
}

```

---
Tags: unity, design-patterns, oop
---


# Question
Title: How to de/activate HDR option in camera with code?
I have some glowing objects in my scene, that with HDR off are inactive, so i want to add the option to turn HDR off in my settings to increase performance.

If the code bellow is correct, what should i write inside get component:

```
public GameObject currentActiveCamera;
currentActiveCamera.GetComponent<???>.hdr = false;

```

# Answer
> 2 votes
Instead of using the `GameObject` type, use `Camera`.

```
    using UnityEngine;
    using System.Collections;

    public class CameraManager: MonoBehaviour
    {
        public Camera currentActiveCamera;

        void Start()
        {
            currentActiveCamera.GetComponent<Camera>().hdr = false;
        }
    }

```

---
Tags: unity, camera
---


# Question
Title: Monogame - How do I make a moving game such as terraria or stardew valley?
Alright so after some long hours and a lot of work I finally understand the basics of Monogame and am able to create a simple game with menu, sounds, the whole lot. But now I want to create a map game, like for example in stardew valley you're able to walk around and the camera will move with your character to a different location. Another example is terraria where you can keep going left for ages and the game will keep on going.

Currently for me I'm limited to the window box of my screen.

# Answer
> 2 votes
Use `Matrix.CreateTranslation` to create a matrix which moves the camera a certain offset, then pass it as the last parameter to `SpriteBatch.Begin` for 2D, or to your `Effect` for 3D. Draw objects at their world position as desired.

This is the standard way of doing camera movement which has the GPU do the heavy lifting on where object will end up, and will allow you to easily combo it with other matrix transformations (such as `Matrix.CreateScale` for zoom).

---
Tags: c#, monogame
---


# Question
Title: Unity custom font all glyphs on top of each other
I'm trying to create a custom font to use (just for numbers). I've divided a 1280x512 file into a 5x2 grid of 256x256 spaces, put my custom drawing into the boxes through 0 to 9, saved it as transparent PNG. Here is a screenshot from Photoshop:

I've created a custom font, made the ASCII start offset 48, left everything default, created 10 character rects from index 0 through 9. Here is a screenshot showing everything clearly instead of writing everything one by one:

On the sixth element UV Y becomes 0, the rest goes the same.

I create a default GUI text, select my font and write 0123, but here is the result:

All the characters are on top of each other. The font is not obeying the Advance property. I've tried different values but it doesn't work for any positive value for the advance property. If I give a negative value, it works (e.g. puts the character at the right, as if I'm using a RTL language like Arabic) but of course, this is not what I want. If I type just one character it displays perfectly at the right place so I don't think there's any UV issue here. It really looks like I'm doing something wrong with the Advance value, but whatever I've tried (positive, negative, zero, huge numbers, fractions etc.) it doesn't work (with the exception of negatives that I've explained) I'm on Unity Personal 5.4.3f1.

What am I doing wrong?

**UPDATE:** Just updated to the new 5.5 version, still the same.

# Answer
> 1 votes
I've replicated your font and it seems to do the job on my end (of course mine changed the pixel sizes etc. but still it works quite well, apart from the obvious quality flaws from copy pasting) Also, I've used a png file, which seems to work better with Unity.

Here are some screenshots so you can compare yours to mine (I'm thinking you're using the wrong shader for your material or the import settings of your texture might be wrong because the font file seems identical to mine):

# Answer
> 0 votes
I was trying to replicate a YouTube tutorial at https://www.youtube.com/watch?v=GRvey8Pb\_Fo.

The original author of the tutorial suggested me to change the Horizontal Overflow property to Overflow instead of Wrap the Text object that was using the font with (not the font asset itself). That was it.

Because my font was too big, it was wrapping on itself as the text area wasn't wide enough.

---
Tags: unity, fonts
---


# Question
Title: SDL_Mixer functions Mix_Quit versus Mix_CloseAudio
Could someone please explain me the differences between the `SDL_Mixer` functions `Mix_Quit` and `Mix_CloseAudio`? I've read the documentation but couldn't really understand it clearly. When to use them and in which row (first `Mix_Quit` or `Mix_CloseAudio`?)?

Also, is it ok to use `Mix_Quit` after using `Mix_CloseAudio`? The documentation states that you should not call any `SDL_Mixer` function after `Mix_CloseAudio`, but it worked when I tested it.

# Answer
From the SDL 1.2 documentation (assuming that the functions in the API have not changed meaning):

> `Mix_Quit` cleans up all dynamically loaded library handles, freeing memory.
>
> `Mix_CloseAudio` shutdown and cleanup the mixer API. **After calling this all audio is stopped, the device is closed, and the SDL\_mixer functions should not be used**.

Each `Mix_Init` call can load different dynamic library resources since it can have different flags

So, `Mix_Quit` must be called one time for each `Mix_Init` call and before `Mix_CloseAudio` (that must be called only once).
> 1 votes

---
Tags: c++, sdl2
---


# Question
Title: Handling multiple controllers in a single player game
Currently implementing input support for a single player game and I'm unsure how best to handle the (admittedly odd) situation where the user plugs in 2 or more controllers. Should only one be active, or should they all control the character?

What I'm currently doing is the following:

* If there are multiple connected when the game starts I just using the first one that's picked up.
* If the user connects another controller I ignore it.
* If the user disconnects a controller I pause the game and ask them to reconnect or press a key to drop back to keyboard/mouse controls.

But I'm wondering if this is reasonable. Should all controllers pass input to the character (this is going to be a nightmare for button mapping though, I'd need to implement some way of providing profiles for different controller types). If not, should I just allow the user to switch controller after disconnecting by pressing one of the buttons? Should a newly connected controller override the previous one?

There's just so many options here...

# Answer
> 3 votes
TL;DR - Ideally you should allow all controllers to open up your game's options menu and select the "Primary" controller (which can be defaulted to the first controller you see). That controller is the only one that can make changes to your game. If you detect that controller disconnecting, you can pause your game and open up the same options menu and ask the player to select another controller.

That being said, this problem can be solved multiple ways, and the more helpful answer would be to the question "How do I approach this kind of complex problem where all sorts of things can go wrong?"

## Enumerate

When you run into a problem like this, it's often a good idea to list out the list of scenarios you can think of possibly occurring:

* Your player has multiple controllers connected, but prefers the red one.
* Two or more players are screwing around and trying to control the same game character all at once.
* The controller runs out of battery while the player is playing.
* Two players are taking turns playing your single-player game; they each have their own controllers.
* etc.

Your real list will likely be longer, depending on how complicated or broad the case you're studying is.

## Prioritize

Next, you want to prioritize these use cases. The unfortunate truth is that corner cases and user stupidity will have you outnumbered- you can only prepare for so many problems.

1. Battery Runs Out
2. Player wants to use on of multiple controllers

---

3. Two players want to take turns using their own controllers
4. Multiple people want to share the same character.

Notice first how the one the user had little control over (running out of battery) got prioritized, and the one that fits our game the least (multiple players controlling a game intended to be single-player) is at the end. Notice also how we drew a divider down the middle. This divider shows us items that are important enough to build into our game, and the items that go into our backlog of "nice to have" things.

## Empathize

Now let's solve the first scenario (Controller battery dying). Let's flesh out our fictional scenario:

1. Little Timmy is playing your shiny new game, but his older brother forgot to charge the controller. Half-way through a boss fight, the controls stop responding.
2. Little Timmy mashes the buttons for fifteen seconds as his character dies a horribly unresponsive death.
3. Little Timmy finally looks down at the controller and realizes the lights are off- battery must be dead.
4. Little Timmy is so frustrated that his careful boss-slaying plans have been thwarted by so cruel a fate, so he throws down the controller and vows never to play the game again.

Now Timmy could just get more batteries and retry the boss fight, but it actually doesn't hurt to assume the worst when starting out.

Now at this point there should be a little voice in your head saying "But wait, that's not how the story goes!" Good! Listen to that voice and see how we could change the story:

1. Little Timmy is playing your shiny new game, but his older brother forgot to charge the controller. Half-way through a boss fight, the controls stop responding.
2. The Game pauses and a screen opens up asking Timmy to check his controller.
3. Timmy realizes the lights on the controller are off, and gets new batteries or plugs the controller in.
4. Once the controller is working again, Timmy presses the "Continue" key and keeps playing.

This scenario has a much happier ending, but it can be improved- what if at step #3 we find out that Timmy is out of batteries? He has another (wired) controller on standby, but he can't use it since the game only 'sees' controller #1. We could run through the scenario a third time and say "Timmy picks up another controller and clicks "Continue"- the game uses this as the primary controller going forwards.

Again, you have to budget your time and choose how much time you want to spend helping Timmy with his wireless controller vs. building the actual game Timmy will be playing, but this technique allows you to iterate just as many times as you need.

## Conclusion

If you find this technique useful and are interested in learning more about UX, you might consider looking at more advanced UX techniques such as formal UML use cases or Journey Mapping (but if you're just an indie developer, they may be overkill).

Let me know if that answers your question.

---
Tags: libgdx, input, control, controllers
---


# Question
Title: What do sandbox games usually do when generating new terrains?
I am trying to make a minecraft. In my game, when the player moves to the boundary, new chunks will be generated.

What I do is creating new chunks in my main thread and generating a new VBO to store them. But I find that it's quite inefficient and you can obviously feel the FPS is decreasing.

What do these kinds of games usually do when generating new terrains? Do they use multi-threads or some specific efficient algorithms or compute shaders (I still don't know much about OpenGL)? I once tried to generate my new terrains in another thread. But I found I can't use GL operation to generate VBO in another thread. I am thinking about pre-generated some VBOs in my main thread. Is that the right way?

I want to know what most people do in this situation.

# Answer
> 0 votes
Believe it or not, Minecraft actually uses immediate mode with Display Lists to render the chunks. They generate the chunk using a noise algorithm, then use greedy meshing to combine neighbor voxel faces, and lastly, throw it all into a display list so a chunk can be drawn with a single draw call.

---
Tags: terrain
---


# Question
Title: Unity 2D UI Scrollview Stretch settings not staying
So I'm trying to make a Scrollviewer and inside that will be aload of boxes stacked on top of each other (the boxes have information in them - like the boxes in this screenshot here but they will always be the same size).

My problem is that whenever (in Unity's UI) I set where the Text UIs (in-game) should be, they will revert to some random place whenever I start the game.

For example: I set the X: 0 Y: 50, start the game changes are made and it looks right. But when I exit game mode the X: Some random number between 0-1000 Y: Also the same, some random number between 0-100.

Anyone know why this is happening?

# Answer
First of all, to achieve something like Clash of Clans chat, you need something to procedurally adjust rect-transforms of that boxes. That is how it works.

---

But if you still want to adjust them manually and want it to persist:

It seems like you have a layout component or another script controlling rect transforms of your scroll rect elements. Make sure none of the following are attached to ScrollRect or the boxes:

* Layout Element
* Content Size Fitter
* Aspect Ratio Fitter
* Horizontal Layout Group
* Vertical Layout Group
* Grid Layout Group

These components I listed are automatic layout components, they adjust layout of descending UI objects depending on your settings. So they overwrite your manual settings.

If you make sure none of these exist but problem is still present, then you must have a script of your own controlling rect transforms, find and delete it.
> 0 votes

---
Tags: unity, gui
---


# Question
Title: How do game makers (without coding) work?
How do game makers/engines like Buildbox, GameSalad, Construct, GameMaker, etc work? What technologies (programming languages, APIs, etc) are used to build the and how does the program convert the user's interactions into exportable code?

I realize this is a very broad question. What I'm looking for is how the software creates code/source files from the user interactions with the software. While details would be awesome, a high level overview would be great too.

I'm a second year CS major and have some experience with Java/C/C++ as well as some web languages and framework. It's hard to find information on **how** a game creation software works because there's more content on how to make games in general.

If there is a more appropriate forum/site to ask this, **please** point me in that direction!

# Answer
> 3 votes
You can (and you should) create scripts while using these engines (except maybe buildbox). They usually work by having a literal engine usually written in c++ running under them, and they take your scripts and interpret them (again, except buildbox) (this is why you don't see c++ or c in these, because they would be too hard to run at runtime).

They also store what you put on the screen with data files. From there, they just work as regular engines.

---
Tags: scripting
---


title: Sticking things to Walls in 3D

text:
# Question
Title: Sticking things to Walls in 3D
I'm trying to leave the second dimension and finally make a 3d game, but I'm having a hard time coming up with a way to implement a certain concept. I am trying to make a flat object which would "stick to walls." It's a bit difficult to explain, so I'll just add a picture here.  The way I see it, there are a few parts to this problem. Firstly, how would I specify which edge on one polygon leads to an edge on another? Secondly, how would I make sure that the object never gets excessively deformed when on a corner of 3 or more edges? (As in, how do I assure the gaussian curvature always stays as 0) And thirdly, how would I split the object along the two surfdaces it's on without having a ton of polygons?

I'm not sure what engine I'll be programming this in yet, because as I said, it's my first foray into 3d, so if responses could either just explain concepts or use pseudocode, that would be optimal, but if you want to use examples from a specific language it'll work.

Thanks in advance for anyone who wants to respond!

# Answer
> 1 votes
A popular technique to handle this is called projection. Shadow mapping and decal placement are popular use cases of this.

A few good tutorials are on http://rastertek.com/tutdx11.html (see shadow mapping and projective texturing)
How do I create a decal system? for more info

---
Tags: 3d, software-engineering, 3d-meshes
---


# Question
Title: How to optimize collision detection in a lane-defense game?
Somebody told me that don't use the physical collision detection(don't use Collider,Rigidbody,Raycasting) because performance loss.instead of it use the mathematical way for collision detection.

**Physical collision detection:**

> **Raycasting** is a very useful and powerful tool available on the physics engine. It allows us to fire a ray on a certain direction with a certain length and it will let us know if it hit something. This however, **is an expensive operation**; its performance is highly influenced by the ray’s length and type of colliders on the scene.

in this game enemies randomly create in some points.is it that better instead of checking by Raycasting call the `fire();` method(foreach plant in them row) when created zombies?

**mathematical collision detection:**

Vector3.Distance(a,b) is the same as (a-b).magnitude.

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

```

is better checking distance than using mentioned components(Collider,Rigidbody). he believes using `Colliders` and `Rigidbody` component produce lag in game.

# Answer
First of all, "performance loss" is only an argument in situations where performance actually matters. When your framerate is good enough and your code is easier to read and maintain with colliders and raycasting, then by all means, stop fixing what isn't broken.

But in the case of a lane defense game like plants vs. zombies, you have very simplified game physics where the Unity collision detection engine indeed seems overkill.

1. Objects can only collide with objects in the same lane
2. When two objects are in the same lane, all that matters is the x-coordinate and the width of the objects involved.
3. All objects only move in one direction and only collide head-on. So you only need to check for collisions in one direction.

First you need to know which lane each object is in. There are several ways you could do that.

* You could make each lane an own object in your scene hierarchy and all objects on that lane child-objects.
* You could have a `public int lane` variable on each object which says which lane it is on.
* You could have a `List<GameObject>` for each lane somewhere.

Each of these approaches has advantages and disadvantages. Pick the one which seems to fit best into your overall architecture.

If you want to check collisions of an object `obj` with other objects, get all objects in the same lane. Then if you want to check for a collision to the right, do `if (other.x - obj.x) < (obj.width + other.width) / 2` for each eligible object in that lane. To check for a collision to the left, do `if (obj.x - other.x) < (obj.width + other.width) / 2`.

---

**A side-note about the Rigidbody component:** You only need rigidbodies when you want to have kinetic physics (gravity, mass, friction, objects bouncing off each other, etc.). When your game isn't supposed to have anything like that, you shouldn't put a rigidbody on anything. I am not saying that adding realistic physics couldn't be an interesting spin on the overused tower defense formula, but when you want to create an authentic Plants vs. Zombies clone, you likely don't want that. When all you want is collision detection, then all you need is a Collider.
> 3 votes

# Answer
It all depends on your game. Typically you would use distance methods combined with other methods like GJK and SAT to calculate the collision detection mathematically. Using raycasting (in combination with the methods above) is good for things that move very fast. If you have two objects moving towards each other at a high enough speed such that they pass each other during the one frame, then you would need to raycast to make sure that you dont travel through the object.

e.g.:

```
frame 1   |   frame 2
[A]><[B]  |  <[B]  [A]>

```

(because you are just adding velocities to their positions, you are not moving them one pixel/unit at a time)

However, if you are making a game like Plants V Zombies as you pictured, you could get away with far less.
You know that objects are only on one axis and things fit into cells. You can simply check whether or not x values overlap/pass each other.
Or, more simply, check what cell an object is in and see if something else was there already
> 1 votes

---
Tags: unity, collision-detection, tower-defense
---


# Question
Title: What are some basic zoning guidelines for designing game cities?
I am planning out a fictional game city. Based on the gameplay and story I have decided on several locations which will need to exist. I'm wondering though to what extent I need to take zoning into consideration when planning everything out. For example, there is an industrial area with processing plants, but there is also a residential area fairly close to this.

It is my understanding that industrial areas need to be a certain distance away from residential areas due to health concerns. This varies of course based on many factors, but I'm wondering to what extent I should be considering this when planning out the city. The game in no way requires realistic city planning, but for the sake of not making it obviously unrealistic I'm wondering if there are any rules of thumbs when planning this.

# Answer
best way to create something realistic is to take your time and simulate the evolution from the original settlement. It'll also create some historical background for the city.

You can look for historical maps of cities of the type you want to create. Track the changes and try and reason why they happened and if you need something similar to yours.

City layouts are heavily influenced by the main mode of transport at the time they are first built. In old European cities the main mode of transport was on foot and carriage for long distance which means that industry will be close to the residence of the people working there. In the modern US preplanned towns the main mode of transport is by personal car. This allows a greater distance between the residence and the place of work and more distinct regions for residential, offices and processing plants.
> 1 votes

# Answer
When developing games, gameplay considerations usually trump realism. Also, there are technical limitations and development resource constraints which limit what you can reasonably achieve.

For these reasons, even the largest open world games still condense cities down a lot. Landmarks and zones are usually far closer together than would be reasonable in the real world. This reduces the player's travel time (gameplay consideration), reduces the amount of city which needs to be created by 3d artists and mappers (development resources) and keeps the amount of data within reasonable orders of magnitude (technical limitations). It also leads to a far richer game experience when the player experiences something new and relevant at every street corner than when they take minutes traveling through copy&paste environments. Quality of game content is usually far more important than quantity.

But you should still try to make different areas of your city look and feel different. Industrial, upper-class residential, lower-class residential and office zones have very different aesthetics, so you should avoid mixing them too much. A good method to separate zones is to use some kind of physical barrier between them. Possible barriers are:

* Rivers / canals
* Railroad lines
* Broad highways
* Parks
* Cliffs
> 3 votes

---
Tags: architecture, level-design, planning
---


# Question
Title: Is it a good idea to use a single sqlite database to store all occurring multiplayer matches?
I have a turn based strategy game for desktop and mobile, the game app uses a sqlite database to play local games. There's nothing special about the database design, I have tables to keep track of units in the game, player commands, etc.

I want to implement multiplayer now on a dedicated game server, and am thinking of using the same setup as the client apps. I'd create a sqlite db on the server file system for each game my users create. I'm expecting around 1,500 simultaneous games (based on other games I've run).

Here are the pros I imagined:

1. I can reuse all the game code as-is - I just point the game wrapper server-side to a sqlite db on the server machine.
2. Cheap to start and delete games (happens quite often with turn based games).

Downsides:

1. Hitting disk a lot, since sqlite is a wrapper around a file basically (my game server has SSD drives, tho).
2. Portability - I'd have a mess of sqlite files on the file system. If I have to move servers, could be a little gross copying them to a new machine. Also have to check the # of files in a directory limit for my OS, or shard them.
3. Front end synchronization - I'd still have to have a centralized mysql db or similar to keep track of all the individual games on disk, their general states (started, waiting, ended etc) for general user queries on their games list.

I'd be interested if anyone has tried a setup like this. I can always use a single mysql instance and one set of tables shared between all games, just need to add a gameId column to separate all the data. It would be interesting to see the Units table though with millions of rows shared between all the games.

Thanks

# Answer
I implemented a setup like this on my game Spider Solitaire Online however even with an ssd on the server, the disk usage kept going up to 100% due to the sheer volume of players. You can start off with an approach like this but it is not scalable. The best way we found to do this was to use a service such as smartfox server to control the game play. You will find this will be more efficient.
> 1 votes

# Answer
i would suggest you to use in memory db such as Redis etc to manage all currently happening matches. e.g. give a uniques name to each match, store this match as a key and player ids as value.
> 0 votes

---
Tags: architecture, server, client-server, databases
---


# Question
Title: Triggering an animation on a gameobject with a collider2D
I'm creating platforms that break on trigger. The animation works and the colliders are set like they should, but I can't seem to figure out how to trigger the "stepBreak" animation I have.

---

This is what I have, so far:

```
using UnityEngine;
using System.Collections;

public class breakablePlatforms : MonoBehaviour
{
    public GameObject steps;
    private Animator animator;

    void Start()
    {
        animator = GetComponent<Animator>();
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if(other.tag == "Player")
        {
            animator.Play("stepBreak")
        }
    }
}

```

---

These are my animations and transitions:

# Answer
> 2 votes
You have a bool value on your animation state, you have to use the `SetBool` method.

Basically it´s playing stepIdle over and over and waiting for a if statement, **if break is true play stepBreak** and **if break is false go back to play stepIdle**

```
// play anim
animator.SetBool("break", true);

// exit anim and go back to idle state
animator.SetBool("break", false);

```

Here is a link to description https://docs.unity3d.com/ScriptReference/Animator.SetBool.html

# Answer
> 0 votes
An easy way to trigger animations by code is to set up a trigger, set it as the condition for the transition, and trigger it with `animator.SetTrigger()`.

---

## Setting up a Trigger

Looking at the Animator window, you should see a tabbed window to the left of the controller chart. Select the *"Parameters"* tab. Click on the button marked *+* and select *"Trigger"*. Give it a meaningful name, and your done.

If you are missing the *"Layers / Parameters"* window, check for a closed eyelid (), along the same bar. Clicking this button unfolds the window.

---

## Setting up the Transition

On the transition to the desired animation, in your case *"stepBreak"* and in my case *"twitch*", you will find the trigger you made listed under the *"Conditions"* option. Select your trigger, and set it as the only condition.

Depending on your circumstance, you probably want to set up a transition in the opposite direction. Given that you are animating something being broken, I would assume you probably wouldn't transition back to the mended state. Either way, you can set (or not set) your additional transitions up however you want.

---

## Triggering the Trigger

Now everything is set up, all you need to do is grab a reference to the specific `Animator` instance attached to the game object, and call `animator.SetTrigger(triggerName)` where `triggerName` is the name you gave to the trigger you just created and set up.

I've done mine using the `UnityEditor` namespace to give me a quick and easy button to click from the Inspector:

```
using UnityEngine;
using UnityEditor;

public class TriggerAnimator : MonoBehaviour
{
    // Reference to the Animator, which I add from the Inspector.
    public Animator animator;
}

[CustomEditor(typeof(TriggerAnimator))]
public class TriggerAnimatorEditor : Editor
{
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector()
        TriggerAnimator triggerAnimator = (TriggerAnimator)target;

        // If the created button "Animate" is clicked,
        if (GUILayout.Button("Animate"))
        {
            // Set off the trigger "twitch" on the animator in triggerAnimator.
            triggerAnimator.animator.SetTrigger("twitch");
        }
    }
}

```

You would probably use something more simple, like this:

```
void OnTriggerEnter2D(Collider2D other)
{
    if(other.tag == "Player")
    {
        animator.SetTrigger("stepBreak")
    }
}

```

---

That's all there really is to it.

---
Tags: unity, c#, 2d, animation, platformer
---


# Question
Title: Prevent Unity click from going through Canvas
I'm currently facing this problem: If I click on a Button on my Canvas, the currently selected Unit moves towards the location under the Button.

Is is there any option to solve this? I'm using the A\* Project for this.

Sadly, I can not provide a lot of things I've done so far as I absolutely have no clue how to solve this problem.

If I disable the Button Option "Raycast Target" it still moves to this position but holds a bit earlier.

Also, adding this as check didn't work:

```
if (!EventSystem.current.IsPointerOverGameObject() )

```

I also checked if the Raycast hits the layer of the GUI

My Movement code so far:

```
public override void MouseClick(GameObject hitObject, Vector3 hitPoint, Player controller)
{
    base.MouseClick(hitObject, hitPoint, controller);
    if (hasAuthority && player && player.human && currentlySelected)
    {
        if (hitObject.name == "Ground" && hitObject.name != "UI" && hitPoint != ResourceManager.InvalidPosition)
        {
            float x = hitPoint.x;
            float y = hitPoint.y + player.SelectedObject.transform.position.y;
            float z = hitPoint.z;
            destination = new Vector3(x, y, z);
            //Debug.Log("Start_Move");
            StartMove(destination);
        }
    }
}

```

# Answer
> 1 votes
It looks like you're using raycasting. Put a 3D object behind your interface, make it really small on Z coordinates and scale it to your interface on X and Y (or the coordinate system you are using). Make sure they are hidden behind your interface (make Z coorditane 1 or more).

You do need to use the Screen Space - Camera option with this, because Screen Space - Overlay won't work (as seen in the gif). That should stop any raycasting from going through.

Something like this:

---
Tags: unity, gui
---


# Question
Title: How can I ensure free graphics are suitable for use in a game?
We want to program a small minigame where we need a lot of icons for all kind of things (like in "Alchemy"). We looked through some free vector graphics pages, like http://www.freepik.com/, but they all state some vague instructions where and where-not to use the images.

For example this site writes

* For both personal and commercial projects and to modify it.

but on the other hand:

* Include FreePik Contents in an online or offline database or **file**.

Which sounds contradictionary, you need to store it in a file to modify it.

How can we get sure, that images that we use from such sites are really free to use on attribution and we don't get any problems later?

How should the licences look like, so we can be sure to get no problems later,if we use free icons from there?

# Answer
> 7 votes
When a site does not provide clear guidelines on where and when assets it offers you can be re-used, you need to get clarification before you start using them.

The best ways to do this are generally:

* contact the author or rights holder and ask them to clarify their license text to make it clear whether or not your goals are or are not covered by the licensing agreement
* get a lawyer to review the terms of the license and your own needs and make sure they are covered

In either case, if you aren't permitted by the license to use the assets the way you need to, you can consider getting a customized license agreement between yourself and the rights holder. This will also be something you want a lawyer involved with, probably.

---
Tags: copyright
---


# Question
Title: Converting data file of Sprite Atlas from JSON to Cocos 2D
I have an existing Sprite Atlas with its data file in JSON format. How do I convert it for use with Cocos 2D and other frameworks ?

I tried poking around in Texture Packer which supports publishing to multiple formats. But I can't figure out how to convert from one format to another

EDIT : Is there any other software that is able to convert between different formats ?

# Answer
> 2 votes
Texture Packer won't convert it's exported data from one format to another. To export in different formats you need to have the Texture Packer (tps) file used to create your JSON atlas.

If you have the tps file, just select the exporter you need from the "Data Format" drop down list in the left-hand pane. The TP home page has a graphic that explains the process succinctly.

If you don't have the tps file you have two options:

1. Write a script to parse the JSON format you have into the Cocos 2D format you need.
2. Recreate the tps file so you can easily export whatever format you may need in the future. This assumes you have the source sprites that are packed into your atlas.

# Answer
> 0 votes
I just found this java tool:

~~https://github.com/thomas-villagers/gdxtococos2d~~

**update:** previous link doesn't work anymore, I found a fork:

https://github.com/midworld/gdxtococos2d

run on terminal:

```
java -jar gdxtococos2d-0.0.1-standalone.jar <inputfile>.atlas <outputfile>.plist

```

...and done!

it worked for my game.

---
Tags: textures, cocos2d, texture-atlas
---


title: UI Text in Unity World Space Canvas

text:
# Question
Title: UI Text in Unity World Space Canvas
I've been struggling with the text for my game labels, as can be seen below. Unity has even included it as an official bug, although no timeline is set to fix it.

The text just looks poor. I've seen artifacts too, like this one:

Looking around the internet, the suggestion seems to be buy Text Mesh Pro, currently on sale for $69.50. While it's not completely out of possibilities I have, I'd rather not pay so much for a tool that has uses far beyond what I need. All I really want is a UI Text that looks reasonable!

My questions are these:

1. Will Text Mesh Pro work as a drop in replacement for world space UI.Text?
2. Are there any other options out there to improve the text quality?

# Answer
> 2 votes
I found these settings to make my world space text look crisp.

Set the Dynamic Pixels Per Unit on the canvas scaler to 1.

Set the Reference Pixels Per Unity on the canvas scaler to 100.

Use a font size of \>230 for the actual text component. And also for good measure set the font rendering mode to Smooth.

# Answer
> 0 votes
I used a PPU of 1. In the UI gameObject I set PixelPefect to true. Check your display preferences for no anti-alias. Also on the imported font I used the same font size as the setting UI Text.

See if these can help

# Answer
> 0 votes
In reference to other answers, setting a font to Dynamic means that it will recalculate its atlas every time the text to be displayed changes. If it happens often (score, timer, counter, etc.), it might be a problem. Also setting the size to be huge might result in a huge atlas.

The image you posted looks like you have a UI.Text with an Outline attached to it. If that's the case, Outline will never look good (anti-aliasing bug or not). It is just the algorithm that they use (copy the text mesh and give it an offset). Actually, I would recommend never to use it with offset larger than 1, but I guess it depends on the font you are using as well.

That being said, it looks like your game is 2D from the look of the image you posted? In that case you don't need the anti-aliasing anyway as it only applies to 3d meshes. In 2d, the sprite transparency is used for the same role.

About TextMesh Pro: is not a drop-in replacement for UI.Text. You will need to change any script that references UI.Text to TMPro.TextMeshProUGUI, but there's nothing else to do.

TMPro is also usable in your general UI. And their text is very crisp. I've been using the asset for a year, it is very professionally made and it is well worth the money.

---
Tags: unity, text
---


title: Barter system data type

text:
# Question
Title: Barter system data type
My game has 4 supplies, `Gold Wheat Iron Fuel`, a player is allowed to select a supply to trade and what supply to receive from merchant NPCs.

Currently, when the user trades an item I have the following logic I am using c# but this is not the exact code used.

```
if(sellGold){
    if(buyGold){
        tradeRatio = .5;
    }
    if(buyWheat){
        tradeRatio = 3;
    }
}
else if(sellIron){
    if(buyGold){
        tradeRatio = 1;
    }
    if(buyFuel){
        tradeRatio = 2;
    }
}
...etc

```

Where the amount a player receives is calculated by multiplying the trade ratio by the amount sold.

This works, it is just rather tedious and would be a pain to add more supplies later. What would a better approach be? I'm thinking of assigning each item a value and that value is different based on the trade type, but that still involves a whole bunch of nested conditionals.

# Answer
It's going to be much easier if you use currency to express all prices. It doesn't have to appear in game, just something used to express the underlying value of all these supplies. Then add a buy/sell offset (or spread). Trade ratios can be calculated by dividing those prices.

For example, if we have `goldBid = 1.23`, `goldAsk = 1.25`, `wheatBid = 0.34`, `wheatAsk = 0.38`, then selling 1 gold for wheat gives you `1.23 / 0.38 = 3.23` wheat, and doing the reverse (selling 1 wheat for gold) gives you `0.34 / 1.25 = 0.27` gold.

Using a currency is not only simpler, it helps you avoid pricing mistakes that inadvertantly lead to *negative cycles* that can be arbitraged (a.k.a. "free money"). For example, what happens if you can trade 1 gold for 2 wheat, and 1 wheat for 2 gold?

But if you want to express all your prices manually, as is often the case in inefficient markets, the usual representation is a weighted directed graph, where edge weights represent trade prices. But a simpler representation would be a *matrix*, like this one:

Then you can just read off values in the matrix to get the trade ratios. In code you can represent this as a 2D array, where the dimensions are the number of assets you have.
> 2 votes

---
Tags: data-structure
---


# Question
Title: How to directly set a value to an UI Image's alpha channel(not the percentage of rendering)
When you write the code bellow, it renders a percentage of an image's predefined alpha value (which you define in unity's inspector - for example if you define the alpha value of an image to 100, the code bellow actually makes it 25, when the scene is being rendered)

```
_image.GetComponent<CanvasRenderer>.SetAlpha(.25f);

```

How can i rewrite the code above, to directly set an alpha value? Thanks.

# Answer
Your wanting to edit the alpha of an `Image`, but your attempting to change the alpha on the `CanvasRenderer`. This value only *multiplies* the alpha value of the image, resulting in the behaviour you describe.

---

Instead, you should edit the alpha attached to the `Image`. This is fairly simple to do, but you need to remember that you are using `UnityEngine.UI.Image`. You will need to include the `using UnityEngine.UI` namespace, or write the complete address.

From there, it is as simple as retrieving the `Color` and changing the `a` value. Note that you actually have to retrieve the `Color`, as shown in the code below, as you can not directly change `Color.a` from another script.

```
using UnityEngine;
using UnityEngine.UI;
using UnityEditor;

public class MockTransition : MonoBehaviour
{
    public Image image;
    public float newAlpha;

    public void ChangeAlpha()
    {
        Color newColor = image.color;
        newColor.a = newAlpha;
        image.color = newColor;
    }
}

```

---

You can see this method in action, below. For testing purposes, I attached the method to the editor, and used it to submit values of `0` and `255`. While the `Image` does not actually have an *image* attached to it, you can still clearly see the change in the `Color` value.
> 2 votes

---
Tags: unity
---


# Question
Title: Creating Multiple Render System to Draw Different Entities in Entity-Component-System
When creating ECS based game engine, do you (or can I) create multiple rendering systems?

Let's say I have an **Entity** class which is the basic unit in my engine, all it can do is add, remove and get components attached to it.

I have a **Component** class which is just a class where other components can derive from and holds data that can be used to define an Entity.

And I have a **RenderSystem** with a Draw method that accepts the Entity to be drawn.

> My questions is, do I have to (or can I) create different derivations of RenderSystem to satisfy different rendering?

One example is when rendering sprites do I have to create a separate **SpriteRenderSystem** and with animations do I have to create **AnimationRenderSystem**? Also I have a **World** class which manages everything, with Entity & Component managers and Systems in it. That class has an Update and Draw method. So do I have to check if the Entity being processed is of a specific type **SpriteEntity** or **AnimationEntity** and use a specific renderer?

```
// World class
...
void Draw()
{
    // Loop through all entities
    for (...)
    {
        // Check for specific entities
        if (entities[i] is SpriteEntity)
        {
            // Call specific sprite renderer
            _spriteRendererSystem.Draw(entities[i]);
        }
        else if (entities[i] is AnimationEntity)
        {
            // Call specific animation renderer
            _animationRendererSystem.Draw(entities[i]);
        }
    }
}

```

Is this a good practice? Is this the right way? Is this fast? Thanks for any answer.

# Answer
> 1 votes
What you should ask yourself is what is the actual *difference* between the two types?

An animated entity typically has both some form of a skeleton of bones which are animated through various animation tracks which a non-animated Sprite likely does not.

That would mean for animated entities, their skeletal pose needs to be properly set based on the current frame's time advancement, physics, and perhaps other external input factors. Perhaps there are multiple animations at play which need to be blended. All of these tasks are performed by a separate *AnimationSystem* and generates a final skeletal pose for rendering.

The render system then takes your mesh plus the pose and draws the final result. How the render system acquires the skeletal pose can occur multiple ways, through the animation component or even by asking for it to the animation system.

As to the render loop, my caution is to avoid if-else blocks inside a for-loop if you can. That means, try to decouple the data storage about renderable entities by somehow storing a separate list of those which are animated. This way you can easily deduce those which you need poses for and set that information.

```
void Draw(float deltaTime) {
  // for each animated entity, acquire the pose data and store it on the
  // renderable element.
  for( int i = 0; i < animatedEntities.size(); ++i ) {
    uint64_t entityId = animatedEntities[i];
    applyAnimatedPose( entityId, animationSystem.getSkeletalPose( entityId ) );
  }

  // draw all renderables in the batch
  std::vector<uint64_t>& renderables = getBatchRenderables();
  for ( int i = 0; i < renderables.size(); ++i ) {
    uint64_t entityId = renderables[i];
    draw( entityId );
  }
}

```

The psuedo code illustrates that its best to small incremental updates to data on very explicit subsets. This allows for better cache locality, thus improving performance. But more importantly, when operating on like subsets of data, this has the added benefit to avoid branching (if-else statements) inside tight loops, thus adding yet another performance benefit.

At the end, I show to iterate over all *applicable* renderables. That may mean to exclude those culled by the frustum, those which aren't visible or applicable to the scene's environment, etc. The returned list is properly sequenced so that the call to draw simply adds a specific draw command to the driver's batch list.

---
Tags: rendering, entity-system, entity-component, entity, draw-order
---


# Question
Title: How can I rotate objects around a given point, and then move them to their correct world location?
I'm building a 2D game using LibGDX. I have a collection of Entities each with their own X and Y positions within the 'world'. The player moves around the world and also has its own X and Y world coordinates, and I use the LibGDX OrthographicCamera which is updated each loop to center on the player location. The player's forward direction is always north relative to the viewport.

What I want to be able to "rotate" the view of the player (essentially by reverse-rotating the world objects using the player location/camera centerpoint as the origin).

I'm attempting to do this using Affine transformations. I had tried something like this each time render is called for the world entities.

```
Affine2 af = new Affine2();
af.translate(player.x, player.y);  // Move origin to centerpoint
af.rotate(entity.rotation); // For testing this value has 1 added or subtracted to it
                            // when I hold down Q and E to simulate the camera rotation.
af.translate(-player.x, -player.y); // Reset origin transform
af.translate(entity.x, entity.y);  // Move to world location
.... // Draw with the af matrix

```

The thing that I didn't realise at first, is that once the rotation is performed, it also rotates the X and Y axis. So any subsequent translations are done relative to the rotation, and not along the original vertical and horizontally aligned axis, so these objects are not ending up in the correct location at all, and additionally they move around as the player moves which is incorrect behaviour.

What would be the correct way to calculate the transforms so I can rotate these Entities around the player, and then move them into the correct world position based on the rotation?

I'm not sure I've managed to explain this too well, so I drew something to try and show this better:

So when I would want the view to "turn" clockwise, the objects would rotate around the player location counter-clockwise (dotted green box), but if the player moves around the world (i.e. forwards, backwards, left, right) then the entity locations shouldn't be changing.

**Edit**: After thinking about this more, I'm wondering if I'm going about this entirely the wrong way? I still need the character's X/Y to be "correct" within the world based on the rotation, so actually I should be rotating the player, and then also the view of the world?

# Answer
> 1 votes
This is usually solved by creating a view matrix, but because you're using libgdx, you can just use your camera's translate and rotate methods.

```
Camera#translate(float x, float y, floaf z)
Camera#rotate(float angle, float x, float y, float z) // Set the axis you're currently rotating around to 1
Camera#zoom(float n)

```

# Answer
> 0 votes
Assuming that you mean that when you are rotating the character, the objects will rotate so it looks like you look to another side, then the camera should rotate and not objects.

---
Tags: libgdx
---


# Question
Title: On Function event of button is not loading C# Script?
I am making a car game in unity 5.0.4f1. I am facing two snags.

1. While installing 3.5 net framework, it gives an error. I searched, it took my 2hrs and problem couldn't solve. Then, I reinstalled Unity. For this snag, what is the best solution in a way I won't waste my time anymore?
2. On the other hand, when I added a C# script using VS community 2015, after dragging the script on the click event, **No function** doesn't show me the script name in the drop down menu. I'm following this tutorial, tutorial link. At 7:58 he added the script in on function. For me, it is not working.

```
using UnityEngine;
using System.Collections;

public class LevelLoader : MonoBehaviour {

    GameObject menu_Canvas;
    GameObject settings_Canvas;

    void Start () {

        menu_Canvas = GameObject.Find ("MainMenu_Canvas");
        settings_Canvas = GameObject.Find ("Settings_Canvas");

        settings_Canvas.SetActive (false);
        menu_Canvas.SetActive (true);
    }

    public void LoadLevel (int a) {

        Application.LoadLevel (a);
    }

    public void Quit () {

        Application.Quit ();
    }

    public void loadMenu () {

        menu_Canvas.SetActive (true);
        settings_Canvas.SetActive (false);
    }

    public void loadSettings () {

        menu_Canvas.SetActive (false);
        settings_Canvas.SetActive (true);
    }
}

```

Please help, as I have been trapped in the problem since few days.

# Answer
Ok you seem to be directly dragging the script to the Onclick event. What you need to do is drag the script onto a game object that is in the scene. Then select that object in the event and then select the script component. Monobehaviours dont work if they are not on a game Object.
> 0 votes

---
Tags: unity, c#, visual-studio
---


# Question
Title: When should new threads be created in a game or how should time consuming task be handled?
This has been a question that has always troubled me while thinking about the code and logic behind gaming, I was wondering when and when not, is it appropriate to create new threads for different tasks or how should I handle long tasks that could potentially freeze my game?

The first situation I could think of would be the rendering and the update loop. My thought behind this is that keeping these two seperate would prevent update problems because of a low frame-rate so even if the frame rate is changed there would still be a consistent update cycle.

The second situation is somewhat more specific and is just an example but say my game has multiple building components that can be placed over the world and my game updates them every second or so to check maybe if they are floating (if they have physics) or maybe if it's environment has changed, should this update cycle also be in another thread because it could take a long time?

How about if I was pinging a client, would my server not freeze whilst waiting for a response? Is this another situation where threads should be created? or is there another technique that I should be using to enhance performance and efficiancy?

# Answer
First of all IO should be asynchronous. A roundtrip (client-server-client) can easily take up to 200 milliseconds (especially when crossing oceans). That is time you just cannot afford to be simply waiting.

Asynchronous means that you set up a event to be triggered/pushed to the queue/... by the OS as the packet arrives or the disk read is complete. Then every frame you check if it is complete and then handle the result.

Next tasks that don't need to complete in the same frame they are started in (for example a path search for a mob that has a reaction time/animation) should be split up into smaller chunks. This will require a bit of rewriting to make sure that any state that needs to carry over from chunk to chunk is preserved and passed along properly.

Threads can be more of a burden than a help because the overhead of synchronizing the tasks and guarding against data races can easily overtake any benefit multithreading could bring.
> 1 votes

---
Tags: java, multithreading, pc
---


# Question
Title: Check collision between two rectangles - libGDX
I'm making a game in which the objective is to collect the maximum amount of balls(Rectangle) to get the highest score. The balls spawn randomly from the middle of every side of your smartphone, and you use the square in the middle of your screen (**the square rotates 90 degrees to the right every time the screen is touched**) to get the balls. Here's the square(Rectangle):

What I'm trying to accomplish here is to make so that if a ball hits the yellow side of the square you get one point but if a ball hits the black side of the square, you lose the game.

Here's what I have so far (**Already have the collisions, rotation and the balls spawning**):

```
@Override
public void create(){

    batch = new SpriteBatch();

    Ball = new Texture("energyball.png");
    Up = new Texture("up.png");

    upSprite = new Sprite(Up);

    upSprite.setOriginCenter();
    upSprite.setX(615);
    upSprite.setY(340);
    upSprite.setRegionWidth(64);
    upSprite.setRegionHeight(64);

    square = new Rectangle();

    square.set(630, 360, 32, 32);

    cam = new OrthographicCamera();
    cam.setToOrtho(false, 1280, 720);

    upSprite.setPosition(upSprite.getX(), upSprite.getY());

    // calls the functions to spawn balls randomly
    balls1 = new Array<Rectangle>();
    spawnBalls1();

    balls2 = new Array<Rectangle>();
    spawnBalls2();

    balls3 = new Array<Rectangle>();
    spawnBalls3();

    balls4 = new Array<Rectangle>();
    spawnBalls4();

    score();

    //if the screen is touched sprite rotates 90 degrees clockwise
    Gdx.input.setInputProcessor(new InputAdapter() {

        @Override
        public boolean touchDown(int x, int y, int pointer, int button) {

            return true;
        }

        @Override
        public boolean touchUp(int x, int y, int pointer, int button) {

            upSprite.rotate(-90);
            return true;
        }
    });

}

//shows score
private void score() {

    score = 0;
    showScore = "Score: 0";
    scoreFont = new BitmapFont();

}

//creates the balls and sets their position as well as the random timer for each
private void spawnBalls1() {

    ball1.x = MathUtils.random(639, 641);
    ball1.y = 720;
    ball1.width = 32;
    ball1.height = 32;
    balls1.add(ball1);
    lastDropTime = TimeUtils.nanoTime();

}

private void spawnBalls2() {

    ball2.x = 0;
    ball2.y = MathUtils.random(359, 361);
    ball2.width = 32;
    ball2.height = 32;
    balls2.add(ball2);
    lastDropTime = TimeUtils.nanoTime();
}

private void spawnBalls3() {

    ball3.x = MathUtils.random(639, 641);
    ball3.y = 0;
    ball3.width = 32;
    ball3.height = 32;
    balls3.add(ball3);
    lastDropTime = TimeUtils.nanoTime();
}

private void spawnBalls4() {

    ball4.x = 1280;
    ball4.y = MathUtils.random(359, 361);
    ball4.width = 32;
    ball4.height = 32;
    balls4.add(ball4);
    lastDropTime = TimeUtils.nanoTime();
}

@Override
public void render() {

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    cam.update();

    //draws the game itself as well as the balls on the screen
    batch.setProjectionMatrix(cam.combined);
    batch.begin();

    upSprite.draw(batch);

    //draws the balls
    for (Rectangle ball1 : balls1) {

        batch.draw(Ball, ball1.x, ball1.y);
    }

    for (Rectangle ball2 : balls2) {

        batch.draw(Ball, ball2.x, ball2.y);
    }

    for (Rectangle ball3 : balls3) {

        batch.draw(Ball, ball3.x, ball3.y);
    }

    for (Rectangle ball4 : balls4) {

        batch.draw(Ball, ball4.x, ball4.y);
    }

    scoreFont.setColor(1, 1, 1, 1);
    scoreFont.draw(batch, showScore, 25, 100);

    batch.end();

    // if the time minus the time of the last ball spawn is less than x then spawn another ball in a random place

    if (TimeUtils.nanoTime() - lastDropTime > 1000000000) {

        switch (MathUtils.random(4)) {

            case 0:
                spawnBalls1();
                break;

            case 1:
                spawnBalls2();
                break;

            case 2:
                spawnBalls3();
                break;

            case 3:
                spawnBalls4();
                break;
        }
    }

    Iterator<Rectangle> iter1 = balls1.iterator();
    while(iter1.hasNext()) {

        Rectangle balls1 = iter1.next();
        balls1.y -= 350 * Gdx.graphics.getDeltaTime();
        if (balls1.overlaps(square)) {

            score++;
            showScore = "Score: " + score;
            iter1.remove();
        }

    }

    Iterator<Rectangle> iter2 = balls2.iterator();
    while (iter2.hasNext()) {

        Rectangle balls2 = iter2.next();
        balls2.x += 550 * Gdx.graphics.getDeltaTime();
        if (balls2.overlaps(square)) {
            score++;
            showScore = "Score: " + score;
            iter2.remove();
        }

    }

    Iterator<Rectangle> iter3 = balls3.iterator();
    while(iter3.hasNext()) {

        Rectangle balls3 = iter3.next();
        balls3.y += 350 * Gdx.graphics.getDeltaTime();
        if (balls3.overlaps(square)) {

            score++;
            showScore = "Score: " + score;
            iter3.remove();
        }
    }

    Iterator<Rectangle> iter4 = balls4.iterator();
    while(iter4.hasNext()) {

        Rectangle balls4 = iter4.next();
        balls4.x -= 550 * Gdx.graphics.getDeltaTime();
        if (balls4.overlaps(square)) {

            score++;
            showScore = "Score: " + score;
            iter4.remove();
        }

    }

}

```

Will be really glad if anyone could help me out. Thanks!!

# Answer
> 1 votes
For important performance and clearly code you have to use Box2D.

If you create those rectangles in box2d world you can add them a fixture. So, your all rectangles will earn a unique fixture. Then you should give them a **sensor** to where your rectangles top side and set category bits/ mask bits (this is for understand which rectangle colliding which object). So, you no longer have to calculate the rotation,colliding and position factors.

Finally, you should add the **ContactListener** to your project for catch the collidings events.

I leave an example;

**CircleObj.java**

```
BodyDef bdef = new BodyDef();
        bdef.type = BodyDef.BodyType.DynamicBody;
        bdef.position.set(50 / PPM, 150 / PPM);
        body = world.createBody(bdef);

        CircleShape circleShape = new CircleShape();
        circleShape.setRadius(25 / PPM);

        FixtureDef fdef = new FixtureDef();
        fdef.shape = circleShape;
        fdef.filter.categoryBits = CIRCLE_BIT; //We told box2d that it's a circle
        fdef.filter.maskBits = TOP_SIDE_BIT; //will collide just TOP SIDE of the rectangle, if you want to collide with rectangle just add " | RECTANGLE_BIT
        body.createFixture(fdef).setUserData(this);

```

**RectangleObj.java**

```
BodyDef bdef = new BodyDef();
        bdef.type = BodyDef.BodyType.DynamicBody;
        bdef.position.set(200 / PPM, 150 / PPM);
        body = world.createBody(bdef);

        PolygonShape pShape = new PolygonShape();
        pShape.setAsBox(20 / PPM, 25 / PPM);

        fdef = new FixtureDef();
        fdef.shape = pShape;
        fdef.filter.categoryBits = RECTANGLE_BIT; // It's a rectangle !
        fdef.filter.maskBits = CIRCLE_BIT; // Collide with circles
        body.createFixture(fdef).setUserData(this);

        //Defining the top side

        Vector2[] vertices = new Vector2[3];
        vertices[0] = new Vector2(25f / PPM, 25f / PPM);
        vertices[1] = new Vector2(25f / PPM, -25f / PPM);
        vertices[2] = new Vector2(55f / PPM, 0f / PPM);
        //Note : The values are almost the what should be.

        PolygonShape topShape = new PolygonShape();
        topShape.set(vertices);

        fdef.shape = topShape;
        fdef.isSensor = true;
        fdef.filter.categoryBits = TOP_SIDE_BIT;
        fdef.filter.maskBits = CIRCLE_BIT;
        b2body.createFixture(fdef);
        topShape.dispose();

```

# Answer
> 0 votes
You can solve it easy by making additional rectangle above the rectangle attached with it, and respond differently for each rectangle, by this way you can control the collision

---
Tags: android, collision-detection, libgdx, rotation
---


title: Unity - Toolbox pattern is not safe

text:
# Question
Title: Unity - Toolbox pattern is not safe
When I create a toolbox such is in this tutorial. How do I defend against breaking the pattern with multiple instances like this:

```
gameObject.AddComponent<Toolbox>();
gameObject.AddComponent<Toolbox>();

```

I when calling `Toolbox.Instance` I get following message:

*\[Singleton\] Something went really wrong - there should never be more than 1 singleton! Reopening the scene might fix it.*

Is there a way to defend against it ?

# Answer
> 2 votes
Add `[DisallowMultipleComponent]`before your class to make sure you can't add more than one instance of it.

example:

```
[DisallowMultipleComponent]
public class Toolbox : MonoBehaviour

```

Also, I recommend reading DMGregory's comment before implementing this, it might be better to just create a static class instead.

# Answer
> 1 votes
You can use my singleton class. It is a singleton MonoBehaviour. Use it by extending it:

```
public class MyClass : MonoBehaviour<MyClass>

```

The most current version is available on GitHub, but here is the current version of it:

```
using System.Text.RegularExpressions;
using UnityEngine;

/// <summary>
/// Extending this class creates a MonoBehaviour which may only have on instance and will not be destroyed between scenes.  When extending, the type of the inheriting class must be passed.
/// </summary>
public abstract class ManagerBehaviour<TManager> : MonoBehaviour where TManager : ManagerBehaviour<TManager>
{
    private const string ManagerName = "Manager";

    private static TManager instance;

    /// <summary>
    /// Gets the singleton instance of the Manager
    /// </summary>
    public static TManager Instance
    {
        get
        {
            if (!instance)
            {
                instance = FindObjectOfType<TManager>();
                if (!instance)
                {
                    var masterManager = GameObjectUtility.GetOrAddGameObject(ManagerName);
                    var managerName = Regex.Replace(typeof(TManager).ToString(), @"((?<=\p{Ll})\p{Lu})|((?!\A)\p{Lu}(?>\p{Ll}))", " $0");
                    var manager = GameObjectUtility.GetOrAddGameObject(managerName);
                    manager.transform.SetParent(masterManager.transform);
                    instance = manager.AddComponent<TManager>();
                }
                var root = instance.transform;
                while (root.parent)
                {
                    root = root.parent;
                }
                DontDestroyOnLoad(root.gameObject);
            }
            return instance;
        }
    }

    protected virtual void Awake()
    {
        DestroyDuplicateManagers();
    }

    private void DestroyDuplicateManagers()
    {
        var managers = FindObjectsOfType<TManager>();
        foreach (var manager in managers)
        {
            if (!manager)
            {
                continue;
            }
            if (Instance != manager)
            {
                bool sharesGameObjectWithManager = Instance.gameObject == manager.gameObject;
                bool hasExtraComponents = manager.GetComponents<MonoBehaviour>().Length > 1;
                bool hasChildren = transform.childCount > 0;
                bool destroyGameObject = !sharesGameObjectWithManager && !hasExtraComponents && !hasChildren;
                if (destroyGameObject)
                {
                    Destroy(manager.gameObject);
                }
                else
                {
                    Destroy(manager);
                }
            }
        }
    }
}

```

I aim to make it a fully functional singleton MonoBehaviour. It is still a work in progress, but it is getting close. (I need to look into DisallowMultipleComponent posted in other answer...I didn't know that was a thing.)

# Answer
> 0 votes
The method `gameObject.AddComponent<component-class>()` creates a new instance of the component-class. But a singleton only ever has one instance, and that instance is supposed to be created by the singleton internally. That means a class which is supposed to be a Singleton should not be used as a component.

However, a component can *use* a Singleton internally to share data with other components. That component would then use the static property `SingletonClass.Instance` to get the global instance of the singleton. When you follow that pattern, reconsider if it really makes sense for your `Toolbox` class to inherit from `MonoBehavior`.

# Answer
> 0 votes
All the source I read here still seems a bit unsafe to me, you are not using the lock, even with a lock in a paranoid area of my mind I feel that it is sill possible (though improbable) to create more than one singleton instance (bad).

People have suggested Static Classes, why does no-one just create their manager script in the scene beforehand? Then there is only one! Are some people really that bothered about automatic manager script creation when it's a bad design pattern?

Make a static class that searches for the script and saves a reference, the worst that can happen now is multiple searches might occur for the manager script, but they will just overwrite each other (but not duplicate the manager script).

I wanted to make this comment as I think this toolbox pattern leads people astray, it's only required if you need your units to set up automatically, it's much safer to manually ensure you just have one script!

# Answer
> 0 votes
`MonoBehaviour`s aren't designed to be singletons. They are designed to be instantiated by the Unity engine whenever it feels like that.

And most uses of the "Toolbox Pattern" don't actually need to be `MonoBehaviour`s because there is no good reason for them to be added to any particular game object or for them to implement the Unity standard methods like `Update` or `Start`.

* If they need initialization, do it in a C# constructor.
* Static methods inherited from MonoBehaviour, like `Instantiate`, can be called by explicitly writing the class in front of it (`UnityEngine.Object.Instantiate(prefab)`).
* One thing you lose is the ability to create coroutines, but you can still implement a method which returns an `IEnumerator` so it can be used to start a coroutine from a MonoBheaviour.

So just don't use that Toolbox pattern. Just create a plain old C# class instead.

---
Tags: unity, design-patterns
---


title: Best practice for RTS accuracy/aim

text:
# Question
Title: Best practice for RTS accuracy/aim
As I'm developing a RTS game set during the Napoleonic Campaign, I've got a question about the best method to implement 'bad aim' for the AI, as the accuracy of muskets were quite terrible back then.

Currently, in my GDD, the accuracy is calculated based on: stamina, dexterity, weapon accuracy and range. But this will result in calculating the chances of a hit in a Pen-and-Paper like style. If it fails the unit will shoot somewhere else (threshold around the target), as I want to have some visible tracer for optical reasons (even though this isn't historical accurate).

Is this method okay?

Because of this the damage is calculated instantly and prevent me theoretically from implementing a first person option for the player, as this would need a second aim&shoot calculation script.

What would be another solution for this?

# Answer
> 1 votes
You should create a parametrical equation. Map each variable (weapon accuracy, stamina, etc.) between 1 and 0, then multiply each value with a weight (if a lower stamina causes lower precision aim more than the precision of the gun, then it should have a higher weigh than the gun value), add them together, then divide the sum with the sum if the weights. This brings this value between 0 and 1.

# Answer
> 1 votes
It really depends on the scale of your game, calculating hit detection can be very expensive if you have a game with units on the scale of a total war kind of game, where you may have hundreds of shots per minute. In that case you would have to sacrifice realism for the simple random number generator.

On smaller scales it might be possible to use proper hit detection, but this will be much more expensive.

It might also be worth making the accuracy a pseudo random distribution, so that it becomes increasingly easier for the ai to make a shot if they have already missed multiple in the past, making the game feel 'fairer' to the player.

---
Tags: unity, bullet-physics, rts, projectile-physics, combat
---


# Question
Title: C# Script file is not showing in Onclick Event in Unity 5.0.4f1?
I uploaded the levelLoader file to the gameobject. Still, when I drag the script file onClick Event, the no function is null. Why? Can anybody help me?

C# code:

```
using UnityEngine;
using System.Collections;

public class LevelLoader : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame

    public void LoadLevel(int a)
    {

        Application.LoadLevel(a);
    }

    public void Quit()
    {

        Application.Quit();
    }
}

```

Correct me where I am wrong. I am following this racing car game tutorial. At 7:58 he added this event. Please help me!!!

# Answer
> 3 votes
You need to add the `LevelLoader` script to the LevelLoader object in the hierarchy panel. Then drag the entire LevelLoader *object* (not script) from the hierarchy panel to the OnClick selected object.

---
Tags: unity, unityscript, events, visual-studio
---


title: Rotating a sprite around its center

text:
# Question
Title: Rotating a sprite around its center
I also use Farseer Physics and Artemis ECS. Here is RenderingSystem Process method:

```
    public override void Process(Entity entity, TransformComponent transformComponent, RenderingComponent renderingComponent)
    {
        Vector2 dimension = transformComponent.Dimension * camera.ScalingFactor;

        Vector2 rotationOrigin = new Vector2(dimension.X,dimension.Y)/2;

        Vector2 renderingPosition = new Vector2(1, -1) * transformComponent.RenderingPosition * camera.ScalingFactor + camera.BitmapPosition;

        Rectangle rectangle = new Rectangle((int)(renderingPosition.X), (int)(renderingPosition.Y), (int)dimension.X, (int)dimension.Y);

        spriteBatch.Draw(renderingComponent.Texture, rectangle,
            null, Color.Wheat, -transformComponent.Rotation,rotationOrigin, SpriteEffects.None, 0f);
    }

```

That's what i get:

And that's what I get if

```
Vector2 rotationOrigin = new Vector2.Zero;

```

What's the reason for such a weird behavoir of rotationOrigin parameter and how to correctly rotate the sprite around its center?

# Answer
> 2 votes
Turns out the origin parameter represents an offset in the sprite's original terxture, not the scaled one being showed on screen. So here is the correct version:

```
Vector2 dimension = transformComponent.Dimension * camera.ScalingFactor;

        Vector2 rotationOrigin = new Vector2(dimension.X/2,dimension.Y / 2);

        Vector2 renderingPosition = new Vector2(1, -1) * transformComponent.Position * camera.ScalingFactor + camera.BitmapPosition;

        spriteBatch.Draw(
             renderingComponent.Texture,
             renderingPosition,
             null,
             Color.White,
             -transformComponent.Rotation,
             new Vector2(
                 renderingComponent.Texture.Width / 2,
                 renderingComponent.Texture.Height / 2),
             new Vector2(dimension.X / renderingComponent.Texture.Width, dimension.Y / renderingComponent.Texture.Height),
             SpriteEffects.None,
             1.0f);

```

---
Tags: xna, rotation, monogame
---


# Question
Title: Automatic audio segmentation and find the most energetic segments
What algorithm can be used for audio segmentation? I want to divide song to segments and find the most energetic segments (*begin and end in seconds*). It is needed for the rhythm-game.

**Examples**:

https://soundcloud.com/dieantwoord-yolandi/die-antwoord-cookie-thumper (most energetic segments: *first 3:09-3:38; second 5:02-5:27*)

https://www.youtube.com/watch?v=StZcUAPRRac (rammstein - sonne) (most energetic segments: *first 0:55-1:20; second 1:52-2:44*)

# Answer
> 1 votes
I think I have found an answer for this one.

You first load the audio data to an AudioClip of course. Then you sample the data from that clip into an array.

```
AudioSource aud = GetComponent<AudioSource>();
float[] samples = new float[aud.clip.samples * aud.clip.channels];
aud.clip.GetData(samples, 0);

```

Now, you have your data in hand. What you want to find out is the different segments of songs. So, I suggest (because this part can be done in numerous ways) going through the clip, X samples at a time, and getting the mean value of those samples.

Since samples vary between -1.0F and 1.0F, you do need to get rid of the negative values (or the positive whichever you prefer) for this method to be of any value.

```
int X = Y; //Y is the number of samples you want to consider, X is any name you want
int checkNum = samples.Length/X; //because we don't want this to be done a lot of times
float[] sampleMeans = new float[checkNum];
float currentMean = 0;
int j, i;
for (j = 0; j < checkNum; j++)
    {
    currentMean = 0;
    for (i = 0; i < X; i++)
        {
         if(samples[i+j*X]==null) //check whether the value is null
             {break;} //and insure we don't go past the array
         if(samples[i+j*X]>=0) //make sure values are positive or taking a mean will not mean much (get it?)
             {currentMean = currentMean + samples[i+j*X];}
        }
    sampleMeans[j] = currentMean / i;
    }

```

After this is all done, you will have an array that represents the means of every X samples. You can check this array to see whether that part is more energetic.

For example if `sampleMeans[2]` is bigger than 0.5F, then you can say that the third X samples are energetic and start from `samples[3*X]` and iterate to `samples[4*X-1]` adding each element into a new array.

If the next part also suits your conditions, then add that part into the array you just made, if not, then make the last one into a new `AudioClip` by using `SetData` method. Then repeat the process with this new data set. (It's going to take some thinking, but it's all essentially gruntwork.)

---
Tags: unity, c#, algorithm, sound, audio
---


title: Unity 2d coordinates

text:
# Question
Title: Unity 2d coordinates
I'm trying to get a 2d tilemap rendering but somethings not clicking with me about the 2d coordinates...

Here's my basic tilemap class -

```
public class Map : MonoBehaviour {
public Transform tilePrefab;

public int mapWidth;
public int mapHeight;
public Transform[,] map;

// Use this for initialization
void Start () {
    map = new Transform[mapWidth, mapHeight];

    for (int y = 0; y < mapHeight; y++)
    {
        for (int x = 0; x < mapWidth; x++)
        {
            Transform tile = Instantiate(tilePrefab, new Vector3 (x, y, 0), Quaternion.identity) as Transform;
            tile.parent = transform;
            map[x, y] = tile;
        }
    }
}

```

But this is rendering the tilemap from the origin -

I want that tilemap to be dynamically centered on the camera like -

What I can't seem to work out is how to dynamically work out the coordinates to move that tilemap so that it's centered in the camera after it has been created?

Any additional help, or pointers to some decent resources would be much appreciated, cheers.

# Answer
you can make prefabs child of another object.so when you move parent , childs move along parent.then place it center of your scene.

```
 clone.transform.parent = newEmptyGameObject.transform;

```

create empty `Transform` as spawnPoint

```
    if (spawnPoint != null)
        newEmptyGameObject.transform.position = spawnPoint.position;

```

I wrote a quick sample, the grid is always centered to the spawn position. You can adjust the following:

> * number of objects in x and y direction, just like you already had it
> * distance between objects in x and y direction (seperately)
> * assign a transform which provides the spawn position, if it's null, the grid will stay at the world origin

Looks a bit confusing, but just to get an idea...

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

public class GridManager : MonoBehaviour
{
    public int GridWidth;
    public int GridHeight;
    [Range(0,5)]
    public int distanceX;
    [Range(0,5)]
    public int distanceY;
    public Transform spawnPoint;
    public GameObject myPrefab;
    public List<GameObject> list = new List<GameObject>();

    void Start()
    {
        CreateGrid();
    }

    public void CreateGrid()
    {
        GameObject newEmptyGameObject = new GameObject("Grid");
        // following line is probably not neccessary
        newEmptyGameObject.transform.position = Vector3.zero;

        // some math to find the most left and bottom offset
        float offsetLeft = (-GridWidth / 2f) * distanceX + distanceX / 2f;
        float offsetBottom = (-GridHeight / 2f) * distanceY + distanceY / 2f;
        // set it as first spawn position (z=1 because you had it in your script)
        Vector3 nextPosition = new Vector3(offsetLeft, offsetBottom, 1f);

        for (int y = 0; y < GridHeight; y++)
        {
            for (int x = 0; x < GridWidth; x++)
            {
                GameObject clone = Instantiate(myPrefab, nextPosition, Quaternion.identity) as GameObject;
                clone.transform.parent = newEmptyGameObject.transform;
                // add to list
                list.Add(clone);

                // add x distance
                nextPosition.x += distanceX;
            }
            // reset x position and add y distance
            nextPosition.x = offsetLeft;
            nextPosition.y += distanceY;
        }
        // move the whole grid to the spawnPoint, if there is one
        if (spawnPoint != null)
            newEmptyGameObject.transform.position = spawnPoint.position;
    }
}

```

here you can change color of prefabs:

```
using UnityEngine;
using System.Collections;

public class Gem : MonoBehaviour
{
    private Color[] Colors = new Color[4] { Color.red, Color.blue, Color.green, Color.yellow };
    public int index;

    void Awake()
    {
        index = Random.Range(0, Colors.Length);
        var spriteRenderer = GetComponent<SpriteRenderer>();
        spriteRenderer.color = Colors[index];
    }
}

```
> 2 votes

# Answer
Looks like you've already gotten an answer, but here's a solution I implemented. My problem was similar to yours: I was procedurally generating a grid/tile-based level and I needed to center it in my camera view (at least with respect the y-axis). I actually created my grid such that it'd be centered already rather than creating the grid and moving all of the objects.

The code could definitely be improved: I've got a couple of "magic numbers" in there, and I've hard-coded things that should be programmatically determined. I'm definitely neither a C# nor Unity pro.

Another note: I also generate my level room-by-room and stitch them together, generating more level as (and if) the player progresses. Those influenced my solution a bit, but might not be relevant for your needs.

The currentSpace calculation in Start() begins in the top-left of the camera's field of view, leaving a little bit of space for UI elements. The currentSpace recalculations in PlaceRoom() for positioning to fill each column in one row in the inner loop, each start of a row in the middle loop, and the starting row and column for the room in the outermost loop.

Here's my relevant code:

```
void Start () {

    ...

    mainCam = GetComponent<Camera> ();
    sceneHeight = 2 * mainCam.orthographicSize;
    sceneWidth = sceneHeight*mainCam.aspect;
    blockSize = 0.16f;
    uiOffset = blockSize * 2;

    // currentSpace is how we tell where to put the blocks; we initialize it
    // like so to align it with the camera field-of-view
    currentSpace = new Vector2( -1*sceneWidth/2 + blockSize/2,
        sceneHeight/2 - blockSize/2 - uiOffset );

    // Generate first x rooms
    ...

    for (int r = 0; r < nInitialRoom; r++) {
        PlaceRoom (lvl [r]);
    }
}

```

And:

```
void PlaceRoom( Room room ){
        int nRow = room.Height ();
        int nCol = room.Length ();
        SpaceType st = SpaceType.emptySpace;
        Vector2 roomStartSpace = currentSpace;

        for (int r = 0; r < nRow; r++ ){
            for (int c = 0; c < nCol; c++ ){
                st = (SpaceType)room.room[r, c];
                switch (st) {

                case SpaceType.blockSpace:
                    Instantiate (blockSpace, currentSpace, Quaternion.identity);
                    break;

                ...

                default:
                    break;
                }
                currentSpace = currentSpace + new Vector2(blockSize,0f);
            }
            currentSpace = new Vector2 (roomStartSpace.x, currentSpace.y - blockSize);
        }

        currentSpace = roomStartSpace + new Vector2 (blockSize * nCol, 0.0f);
    }

```
> 0 votes

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


# Question
Title: Directx 11 How to set Texture2D in constant buffer
I have a texture2D packed within my constant buffer. how do i set the texture using ID3D11DeviceContext::UpdateSubresource or another method?

# Answer
> 2 votes
Constant buffers can not be used this way, constant buffers are holders for global constants and are not used for buffer\texture data types.

It is imposable to have a texture packed inside a constant buffer.

Constant buffers have a very small size limit, well not super small but I really don't think even if you could put a texture into it that it would be of much use.

Constant buffers are also optimized so that there can be a few in flight on the GPU at any time so having a texture packed inside of it would be very bad for performance as you would end up with many copy's of the texture flying around the GPU taking up memory.

You want to keep the constant buffer size down so as not to use up all the constant buffer renaming memory that the driver uses to update them while they are still in flight on the GPU.

> **Organizing constant buffers**
>
> Constant buffers reduce the bandwidth required to update shader constants by allowing shader constants to be grouped together and committed at the same time rather than making individual calls to commit each constant separately.
>
> **The best way to efficiently use constant buffers is to organize *shader variables* into constant buffers based on their frequency of update**. This allows an application to minimize the bandwidth required for updating shader constants. For example, a shader might declare two constant buffers and organize the data in each based on their frequency of update: data that needs to be updated on a per-object basis (like a world matrix) is grouped into a constant buffer which could be updated for each object. This is separate from data that characterizes a scene and is therefore likely to be updated much less often (when the scene changes).

Some reading for you on constant buffers

---
Tags: directx, directx11, hlsl
---


# Question
Title: UnityEngine.Camera doesn't contain definition for "active"
So I'm just trying to create a simple script in C# which will allow me to switch between two cameras, named Camera1 and Camera2. But I have run into the error UnityEngine.Camera doesn't contain definition for "active". Which I can't seem to figure out at all. I would really appreciate any help I can get so that I can keep working on my project. I will put the code for the cameras below.

```
using UnityEngine;
using System.Collections;

public class CameraSwitching : MonoBehaviour {

public GameObject Camera1;
public GameObject Camera2;

    public void ChangeCamera () {

        if (Camera1.camera.active) {
            Camera2.camera.active = true;
            Camera1.camera.active = false;
        } else if (Camera2.camera.active) {
            Camera1.camera.active = true;
            Camera2.camera.active = false;
        }
    }
}

```

# Answer
> 2 votes
Check the current active camera by comparing the gameobject

```
using UnityEngine;

public class CameraSwitching : MonoBehaviour {
    public GameObject camera1, camera2;

    public void SwitchCamera() {
        if (Camera.current.gameObject == camera1) {
            camera1.SetActive (false);
            camera2.SetActive (true);
        } else if(Camera.current.gameObject == camera2) {
            camera1.SetActive (false);
            camera2.SetActive (true);
        }
    }
}

```

# Answer
> 0 votes
Try accessing it like this

```
 Camera2.camera.gameObject.SetActive(true);
 Camera1.camera.gameObject.SetActive(false);

```

*note*: if you are using Unity 5, directly accessing `active` is deprecated and you should use `SetActive(bool b)` instead.

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


# Question
Title: Determining which point is further along a direction vector
I am attempting to write a frustum culling algorithm simply by testing axis aligned boxes against a plane, while researching this i came across an article here: enter link description here The trouble i am having is determining which points are furthest along the normal of the plane as illustrated here:

For each box i need to determine which corner or of the box is furthest along the direction normal of the plane. The pseudo-code on the website has no meaning to me as my box class is structured differently, any help would be appreciated.

# Answer
> 0 votes
My answer would not answer your direct question, but will lead you to your goal.

In 3d games you do not test bounding boxes against camera's line of sight. Instead, you take your ViewPerspective matrix and do manipulations with it.

The most common way is to extract 6 planes from ViewPerspective matrix and test bounding box against all 6 planes. Test will show whether object is inside frustum or not.

For reference:

http://www.iquilezles.org/www/articles/frustumcorrect/frustumcorrect.htm http://www.iquilezles.org/www/articles/frustum/frustum.htm

# Answer
> 1 votes
Considering you know a point of the plane (Camera position) and the normal, I would just do the dot product for each corner.

For example if `O` is the camera position, `n` the normal vector and `P1` a corner of the box, that would lead to do the operation : `(P1 - O) . n`.

Do that for each corner, the one with the higher result will be the further along the normal.

---
Tags: mathematics, cg
---