# Question
Title: How should I store a large number of rooms with objects in them?
Right now I'm using C# in XNA/MonoGame. I'm brainstorming an isometric game that consists of rectangular rooms. The allowed dimensions of each room range from 3x3x3 to 12x12x6.

The max volume of each level is 432x432x216. That volume can hold **a max of 1,492,992 rooms!** That's practically **1.5 million!** So it's important to consider how rooms are stored. My default idea is to use 2D arrays to hold a list of objects on the floor, wall, and ceiling (yes, I want to use magic spells for wall walk and even ceiling walk to get secrets on the walls/ceilings).

So, again, a 3x3x3 room would have 6 2D arrays that are each 3x3 arrays. Each array element is a list holding items. So each room would hold 54 lists. So now 1.5 million rooms would hold **81 million lists!!!** I don't know what the max or average number of elements in each list will be, but I'm guessing up to a max of 6.

If we assume each Object in the list will be only 1 kilobyte in size (that's a low estimate), we're talking **81 gigabytes of memory**. This does not even count the overhead of 2D arrays and lists.

---

Obviously, this cannot be stored in memory. So I need some other scheme. Is there some officially recommended scheme for this sort of thing?

One more caveat. The player character will not be the only guy walking around. There will be monsters too. They need to run around in other rooms.

---

Here is my explanation for the 1KB object data size.

1KB is my estimate based on past experience. Off the top of my head, here's what each object needs:

* enum byte for the type (block, food, key, etc.)
* byte for subtype (like different colored keys or different colored tiles)
* 2 bools for pushable, pullable
* byte for points (treasure might give 50 or 100 points, food might fill 10 or 20 health points)
* byte for height (some objects are flat, others have height 1, 2, 3, up to 6)
* 8 bools for 4 enterable dirs and 4 exit dirs (for force-field blocks)
* a List of target objects for switches (this is a 32-byte or 64-byte pointer depending on architecture, and each entry will also be 32 or 64 bytes).
* a pointer back to the room object (32 or 64 bytes again)

I count 14 bytes + the list and final pointer. This is probably only the beginning. I can compact some things, if I want, like compacting the 8 force field bools into a single bool (which is normally 8 bits, but I could use a byte and do integer comparisons for which bit I'm looking at).

The real question is what will be the **average** size of each object, which I think is impossible to estimate right now. I'm sticking with my 1KB estimate; I think at the very least, it's a reasonable cap on the worst case scenario.

## EDIT

Max volume is now reduced to 144x144x144. Assuming all rooms are 3x3x3, the max rooms is about 110,000, which would take **over 30 hours** just to traverse all rooms assuming 1 second is spent in each room. So 144x144x144 is plenty of volume. I will proly store levels as giant string or byte arrays since the data has to come from disk anyway (when loading a new level). A few rooms can be culled with more elaborate 2D and 3D arrays holding actually objects, which will drawing and interactions much easier.

# Answer
> 2 votes
If you store the items in a single array per room, where each item in the array looks like

```
struct ItemPlacement {
  byte X, Y, Z;
  byte Side;// Floor? Ceiling? Wall?
  ItemInstance Item;
};

```

you'll drastically cut down the number of arrays you have to deal with (down to 1.5 million). You can probably actually pack the location and side information into fewer total bits, given that each room has a small fixed upper-bound in terms of volume. If you pack everything tightly you can fit it into two bytes for both the 'side' information and the XYZ position.

This makes it a little slower to find out what items are on a specific tile in the room. You should still be able to easily draw or enumerate all the items in a room, but finding out "what can I pick up on the tile I'm on now" is slightly slower. Given an expected item stack size of six, however, and some sorting of the item list, this algorithmically slower search shouldn't be too much slower in actual practice.

With 1.5 *million* rooms, though, you're almost certainly going to run into a situation where you just can't keep the whole level in memory. There's got to be more than just item data you're storing in your game, so no matter how much you squeeze it, the scope of your game might simply be large enough that you have to resort to a streaming solution.

This means you have to be able to tell which rooms the player is in, and which rooms they can get to soon. You can build a graph of the room connectivity based on doorways, decide on a reasonable distance beyond which you start streaming rooms out, and then serialize the entire state of the room to disk once the player moves more than, say, four rooms away from any given room. Once the player gets close by again, you bring the state of the room back online. That way you can cut your working set of rooms down from the millions to something like the hundreds, and that's much more reasonable from a memory footprint perspective.

If it's important to your game that certain things continue to happen while the player isn't in a room (for example, monsters need to keep moving or whatnot), you can serialize only the static state of the room. Hopefully monsters cannot pick up or move items around in rooms when the player is far away from them in your game, so that the static state of the room includes these 1.5 million lists of item placements.

---

While it's not directly related to the storage of data for rooms or items in rooms, I think you can save some memory by splitting your items into type and instance data. I still think your estimate of 1KB per item is extremely high; your breakdown doesn't come anywhere near that, and given the type of information in your breakdown if you do get near 1KB per item instance you're probably being wasteful with memory somewhere.

What I mean by splitting the item up is to do this:

```
class ItemType {
  byte Type;    //(block, food, key, etc.)
  byte SubType; //(like different colored keys or different colored tiles)
  bool IsPushable;
  bool IsPullable;
  byte Points;
  ...et cetera...
};

```

These item type structures contain everything about an item that *will not change* for the lifetime of the item. If you have an item that is a "pile of bricks," and you have ten of these, there's no reason to duplicate that push/pull information and many of the other properties for *all ten* instances. Instead, make an item instance look like:

```
class Item {
  ItemType Type; // Simply reference the item type.

  ...per instance data here, like a pointer to the room the item is in...
};

```

Then you store `List<Item>` (no need for `List<object>`) in your rooms. You can *further* compress this data by not storing references to the `ItemType`, but instead store an index into an array of all item types. Chances are this array will be small enough that a 16-bit index will be sufficient, saving a few more bytes. You can also bitpack various flags in both the item type and item instance structures. You don't need *two bools* for push/pull. You can store that information in a single byte, using the 0th bit for push and the 1st bit for pull. The remaining six bits in the byte can be allocated to other boolean flags or similar values requiring few bits of storage.

These are all really small footprint reductions but when you multiply them out across the sheer volume of item instances you seem to expect to have they can start saving you megabytes of memory.

# Answer
> -1 votes
Have you considered external files, like xml or json? You could read and write to them, keeping them from taking up memory.

# Answer
> -1 votes
It's not realistic to keep so many rooms in memory at once en toto or to have the monsters traverse every single room and pathfind through every single object within 1.5 million rooms. It's just not reality.

You could probably store the rooms as a node structure for pathfinding purposes and have monsters just wander room to room between points a reasonable distance away over time and then only when they are very close to the user load up the actual room itself and keep track of the absolute position of the monster. 1.5 million NODES is not that hard to deal with and then the internal layout of your rooms does not really matter much from a memory conservation standpoint because you will only ever have a reasonable amount of rooms loaded into memory.

---
Tags: game-design, isometric, memory-efficiency, memory, storage
---


# Question
Title: How do I configure a joint for a sliding door in Unity?
I have this sliding door where i want to use a joint to limit its motion:

...but I am confused about how to configure a joint to provide this sliding motion.

I've found the Hinge Joint component, but the comments below say this is for rotating motion. What kind of joint do I use to create a sliding motion?

# Answer
As pointed out in the comments above, the Hinge Joint is not the right type of constraint to use for a sliding door. It handles rotational movement, like a door that swings.

For a sliding door, we'd instead use what's called a "Prismatic Joint"

Unfortunately, Unity doesn't have a built-in 3D Prismatic Joint component the way it does for springs and hinges. But we can create one using the Configurable Joint.

True to its name, this has a pile of configurable parameters, but we only need a few for this situation...

* **Connected Body**: you can leave this as "None" if you want your door to slide with respect to a fixed track in the world. Optionally, you could create a track object and connect the door to that.
* **Anchor**: this is the position in your door's local coordinates that should act as the attachment point - like where it hooks into your track. It looks here like your pivot is in the bottom-left corner of the door, and that's a sensible place, so let's use (0, 0, 0) here.
* **Axis**: this is the direction of movement, in your object's local coordinate space. In my tests, my door slid along its local X axis (1, 0, 0). If you're using Z, interchange X&Z below.
* **Auto-Configure Connected Anchor**: uncheck this. If checked, the joint will treat the door's placed position as the center of its movement range, allowing it to slide both left & right. I expect though you want to place your door in either the open or closed position, so we'll want to manually control this.
* **Connected Anchor**: this is the position of the center of your track. If you specified a Connected Body, then it's in that body's local coordinates. Otherwise, it's in worldspace. To find the right value to use, slide your door until it's half-open, copy the worldspace position of its pivot, and use this value.
* **X/Y/Z Motion**: X should be set to "Limited", and the others should be set to "Locked." This gets us the sliding motion we want.
* **Linear Limit**: This is how far the door should be able to slide from the center point of its track we defined earlier. It's measured in worldspace, and should probably be about half the width of your door, or a little less.
* Finally, select the Rigidbody component on your door and activate all three rotation constraints, to keep the door from twisting. The joint handles the position constraints just fine, so you don't need to fiddle with those.

That should do it. You can also play with the drive settings if you want the door to close itself, or adjust its Rigidbody's drag to help it slide to a stop.
> 6 votes

---
Tags: unity, physics, joints
---


# Question
Title: Box collider pushes me out of it's area slowly, I can pass through it if moving quickly
I am new to Unity. I Setup a character in unity2D with a rigidbody. I had the scale off my sprites set to 100 pixels per unit. At this scale, my rigidbody character stood on top of platforms and could not pass through walls containing box colliders. I decided, that to make things easier, I would change all sprites to 1 pixel per unit. After doing so, I scaled everything (variables, sizes, etc.) by 100. I confirmed that the box colliders on both the caharcters, floor, and walls, are all in the same places, relatively. The box colliders on the floors still work, but the wall box colliders behave differently. When I walk into a wall, the wall slowly pushes me in a direction (depending on whether or not my character has walked through half the wall or not). The wall should be stopping my motion completely.

The code is very simple, but this is what I use to move:

```
if (Input.GetKey (KeyCode.D)) {
        transform.Translate (Vector2.right*moveOffset*Time.deltaTime);
        transform.localScale = new Vector3(1,1,1);
        anim.SetBool("moving",true);
    }

```

Do note that the moveOffset variable, was scaled by 100 after the change. Thanks in advanced!

# Answer
> 1 votes
You are modifying the `Transform` of the gameObject. When using physics, changing the transform of the object is a big NO-NO (unless it's to perform a teleport or something like that).

If you want to move a gameObject with physics behaviour you should do so by adding forces to the `rigidbody`, or changing it's velocity.

Also, when applying changes to physic objects, you should be putting your code in `void FixedUpdate()` instead, and use `Time.fixedDeltaTime` (`FixedUpdate()` runs at a constant rate, unlike `Update()` )

Try this:

```
void FixedUpdate()
{
    if (Input.GetKey (KeyCode.D)) {
        GetComponent<Rigidbody2D>().velocity = new Vector2(speed,0);
        anim.SetBool("moving",true);
    }
}

```

Keep in mind that even after releasing the key, the object will keep moving, being slowed down by the ´linear drag´.

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


# Question
Title: Physically based shading - ambient/indirect lighting
I implemented a physically based path tracer after studying PBRT by M. Pharr and G. Humphreys. Now I'm trying to apply physically based rendering to real time graphics using OpenGL.

I want to start using Oren-Nayar and Cook-Torrance as diffuse and specular BRDF but I have a problem: how do I model indirect lighting?

In a path tracer (like the one contained in PBRT) the indirect/ambient light is given "automatically" from the path tracing algorithm, as it follows the path of light rays taking into account direct and indirect lighting.

How do I model the indirect lighting in a physically based render written in OpenGL, so using real time computer graphics?

# Answer
> 4 votes
<sup>**Disclaimer:** the following answer was published in its entirity by Nathan Reed an a similar question the asker posted on the Computer Graphics Stack Exchange.</sup>

Real-time graphics deploys a variety of approximations to deal with the computational expense of simulating indirect lighting, trading off between runtime performance and lighting fidelity. This is an area of active research, with new techniques appearing every year.

## Ambient lighting

At the very simplest end of the range, you can use **ambient lighting**: a global, omnidirectional light source that applies to every object in the scene, without regard to actual light sources or local visibility. This is not at all accurate, but is extremely cheap, easy for an artist to tweak, and can look okay depending on the scene and the desired visual style.

Common extensions to basic ambient lighting include:

* Make the ambient color vary directionally, e.g. using spherical harmonics (SH) or a small cubemap, and looking up the color in a shader based on each vertex's or pixel's normal vector. This allows some visual differentiation between surfaces of different orientations, even where no direct light reaches them.
* Apply ambient occlusion (AO) techniques including pre-computed vertex AO, AO texture maps, AO fields, and screen-space AO (SSAO). These all work by attempting to detect areas such as holes and crevices where indirect light is less likely to bounce into, and darkening the ambient light there.
* Add an environment cubemap to provide ambient specular reflection. A cubemap with a decent resolution (128² or 256² per face) can be quite convincing for specular on curved, shiny surfaces.

## Baked indirect lighting

The next "level", so to speak, of techniques involve **baking** (pre-computing offline) some representation of the indirect lighting in a scene. The advantage of baking is you can get pretty high-quality results for little real-time computational expense, since all the hard parts are done in the bake. The trade-offs are that the time needed for the bake process harms level designers' iteration rate; more memory and disk space are required to store the precomputed data; the ability to change the lighting in real-time is very limited; and the bake process can only use information from static level geometry, so indirect lighting effects from dynamic objects such as characters will be missed. Still, baked lighting is very widely used in AAA games today.

The bake step can use any desired rendering algorithm including path tracing, radiosity, or using the game engine itself to render out cubemaps (or hemicubes).

The results can be stored in textures (lightmaps) applied to static geometry in the level, and/or they can also be converted to SH and stored in volumetric data structures, such as irradiance volumes (volume textures where each texel stores an SH probe) or tetrahedral meshes. You can then use shaders to look up and interpolate colors from that data structure and apply them to your rendered geometry. The volumetric approach allows baked lighting to be applied to dynamic objects as well as static geometry.

The spatial resolution of the lightmaps etc. will be limited by memory and other practical constraints, so you might supplement the baked lighting with some AO techniques to add high-frequency detail that the baked lighting can't provide, and to respond to dynamic objects (such as darkening the indirect light under a moving character or vehicle).

There's also a technique called precomputed radiance transfer (PRT), which extends baking to handle more dynamic lighting conditions. In PRT, instead of baking the indirect lighting itself, you bake the *transfer function* from some source of light—usually the sky—to the resultant indirect lighting in the scene. The transfer function is represented as a matrix that transforms from source to destination SH coefficients at each bake sample point. This allows the lighting environment to be changed, and the indirect lighting in the scene will respond plausibly. Far Cry 3 and 4 used this technique to allow a continuous day-night cycle, with indirect lighting varying based on the sky colors at each time of day.

One other point about baking: it may be useful to have separate baked data for diffuse and specular indirect lighting. Cubemaps work much better than SH for specular (since cubemaps can have a lot more angular detail), but they also take up a lot more memory, so you can't afford to place them as densely as SH samples. Parallax correction can be used to somewhat make up for that, by heuristically warping the cubemap to make its reflections feel more grounded to the geometry around it.

## Fully real-time techniques

Finally, it's possible to compute fully dynamic indirect lighting on the GPU. It can respond in real-time to arbitrary changes of lighting or geometry. However, again there is a tradeoff between runtime performance, lighting fidelity, and scene size. Some of these techniques need a beefy GPU to work at all, and may only be feasible for limited scene sizes. They also typically support only a single bounce of indirect light.

* Screen-space global illumination, an extension of SSAO that gathers bounce lighting from nearby pixels on the screen in a post-processing pass.
* Screen-space raytraced reflection works by ray-marching through the depth buffer in a post-pass. It can provide quite high-quality reflections as long as the reflected objects are on-screen.
* Instant radiosity works by tracing rays into the scene using the CPU, and placing a point light at each ray hit point, which approximately represents the outgoing reflected light in all directions from that ray. These many lights, known as virtual point lights (VPLs), are then rendered by the GPU in the usual way.
* Reflective shadow maps (RSMs) are similar to instant radiosity, but the VPLs are generated by rendering the scene from the light's point of view (like a shadow map) and placing a VPL at each pixel of this map.
* Light propagation volumes consist of 3D grids of SH probes placed throughout the scene. RSMs are rendered and used to "inject" bounce light into the SH probes nearest the reflecting surfaces. Then a flood-fill-like process propagates light from each SH probe to surrounding points in the grid, and the result of this is used to apply lighting to the scene. This technique has been extended to volumetric light scattering as well.
* Voxel cone tracing works by voxelizing the scene geometry (likely using varying voxel resolutions, finer near the camera and coarser far away), then injecting light from RSMs into the voxel grid. When rendering the main scene, the pixel shader performs a "cone trace"—a ray-march with gradually increasing radius—through the voxel grid to gather incoming light for either diffuse or specular shading.

Most of these techniques are not widely used in games today due to problems scaling up to realistic scene sizes, or other limitations. The exception is screen-space reflection, which is very popular (though it's usually used with cubemaps as a fallback, for regions where the screen-space part fails).

As you can see, real-time indirect lighting is a huge topic and even this (rather long!) answer can only provide a 10,000-foot overview and context for further reading. Which approach is best for you will depend greatly on the details of your particular application, what constraints you're willing to accept, and how much time you have to put into it.

---
Tags: graphics, lighting, shading, pbr
---


title: Cannot click UI button in Unity

text:
# Question
Title: Cannot click UI button in Unity
I am working on Unity 5.4. I have an Event System, my UI has a parent canvas, Canvas has the graphic raycaster. I am not able to understand why this is not working. I have attached an image of the button script, Canvas, event system and my script.

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

public class Level01Controller : MonoBehaviour
{
    private int highScore ;

    void Update ()
    {
        if (Input.GetKey (KeyCode.Escape))
        {
            Application.Quit ();
            Debug.Log ("Clicked);
        }
    }

    public void StartGame()
    {
        Application.LoadLevel ("Level01_Game");
    }
}

```

# Answer
## Your button is not interactable

As mentioned by *DMGregory*, you have "interactable" unchecked on your button script. This tells the button it is *not* interactive. Replicating your setup with your code, I can confirm that once you check this box, your code runs as intended.

We can see the button working through my debug log; instead of changing levels, I get an error, as I have not actually set up "Level01\_Game" as a scene. I have also included a `Debug.Log()` output in the `StartGame()` method, for clarity.

## Other potential issues

While seemingly unrelated to your user interface, there are some other issues with your setup that might lead to problems. While we can not actually see if some of these problems actually exist, I will mention all possible issues, just in case.

### Close your strings!!

You have a `Debug.Log()` in your `Update()` method, where you are sending in "`"Clicked`". It ***should*** be "`"Clicked"`", and it is *imperative* you see the difference.

Without the closing quotation marks, `Clicked` will probably not be interpreted as a string. In my compiler, it interprets as a value type. Minor errors like this can present much larger problems, as they throw such ambiguous errors, that the compiler will *often* point you in the wrong direction with its error output. In this case, it does not *appear* to be that bad. My compiler reports the error only a mere 4 characters later, when it detects the end of the line without an actual closing bracket; the `);` on the end is still being interpreted as part of the string, and is not seen as actual code.

Of course, the result may be different, depending on the compiler you use. In my case, the error thrown physically prevents me from being able to play test, to begin with. If your compiler does not raise this issue, you may have run into much more perplexing problems later on, when hitting `Esc` caused your program to have *very* weird behavior.

### Input buttons must be setup

You have added a `StandaloneInputModule` through your `EventSystem`. Your `StandaloneInputModule` lists two axis and two buttons. In the given case, they are set to the defaults of *Horizontal*, *Vertical*, *Submit* and *Cancel*. These values *must* correspond to available axis and buttons via your general Input Manager. While their functionality does not directly relate to the button you have set up, the errors thrown from your input not being setup will prevent further functionality, *including* your button. You can access your Input Manager via the top menu, by selecting **Edit \> Project Settings \> Input**. Just having the correct input of the same name is enough to fix this error.

### `Application.LoadLevel` is obsolete

`Application.LoadLevel` has been marked as `obsolete`, as it has been replaced with `SceneManager.LoadLevel`. Using it might cause other problems; I currently use Unity 5.3.5, and have previously been *unable* to use `Application.LoadLevel` for the same reason.

This is actually *good* news. We now have an actual Scene Manager class to handle our scenes, so using it directly is just good house keeping. Just make sure that you include the required library, by including `using UnityEngine.SceneManagement;` at the top of your script.

Apart from that, the two methods are identical in context of your implementation. Instead of `Application.LoadLevel("Level01_Game")`, you would call `SceneManager.LoadScene("Level01_Game")`.
> 2 votes

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


# Question
Title: Rotating image angle, direction of object that is resting on floor object
I have an object, in this case a space ship, resting on a floor or platform object. The bottom of the space ship is flat, and is resting flush with the flat surface of the platform object (due to my collision detection). Now obviously, the player is able to move the space ship by pressing up. The player is also able to turn the ship (image\_angle and direction) by pressing left or right, which transfers the speed to that direction if they are flying. However, in the scenario mentioned above where the ship is currently resting flat on a flat surface, if the player presses left or right, the ship still rotates and the sides clip into the surface of the platform, which causes collision detection to essentially glue the ship to the platform. How can I use collision detection to allow the player to still rotate the ship while it is resting on a flat surface, but instead of clipping, have the object perhaps "roll" or fall over?

here is my collision detection:

```
// Gravity
if (vspeed < 10) vspeed += .02;

// Collision detection
if (place_meeting(x, y + vspeed, obj_block))
{
    while (!place_meeting(x, y+1, obj_block))
    {
        y += 1;
    }
    vspeed = 0;
    hspeed = 0;
}

```

# Answer
Place your rolling code in the if part of the Collision algorithm and Clipping code in the else part of the Collision algorithm
> -1 votes

---
Tags: game-maker
---


# Question
Title: Board Game Pathfinding - Finding optimum valid path with limited path distance?
I'm building the very earliest stages of piece movement in a digital board game I'm planning to make.

It's a browser based javascript system.

Basically the players roll to move and need to traverse the arena based on their maximum move distance. However there are floor hazards that damage the player when they are walked on. As the game elapses the arena gets riddled more and more with the hazards until one needs to make risky choices to step over them and take damage.

In the real life version it ultimately just means that you run the piece in the path that you want knowing the amount of steps you're allowed to take. Digitally it's much harder.

I've used A\* for the very first time for this and it does the job MOSTLY right. If the path can't be reached without walking through the hazards it will pick the path with the least hazards and mark it's way through which is exactly what I want. However my 'max movement' limiter is very rudimentary... I've taken two approaches:

One was to make it consider tiles that are farther than "move distance" as unpassable and not consider them when continuing the path.

The other was to make the tile resistance value skyrocket to 500 when the steps to the tile exceeds the "move distance".

The first just ends up not being able to find the route occasionally. The second will just make the path even if it is too long simply because it comes to the situation where ALL the possible tiles are 500 + regular resistances, negating the purpose of the huge resistance spike.

In most cases the limiter and the path finding is perfectly functional however I've found one particular instance where it completely fails to find the correct path: If the easiest path is to go AROUND a hazard to get to a tile beside the destination at max moves it will attempt that path for the tile beside it that will drive it into exceeding the move limit.

A couple of examples:

* Purple are the hazards. They ARE passable.
* Blue is the max radius of movement.
* Red outlines are the tiles that the pathfinding has processed to come to the concluded path.
* Pink is the final path.
* Red square is the player.

What I suspect is the problem is that as A\* is running through it's list of options it's pushing it's previous steps into the "closed list" thus solidifying it's original assumptions about the path. What happens then is that it takes 4 steps around a square, solidifying the path as it goes, only to hit the max moves before it hits its destination. With no way to re-assess the route it ends up just ending... either by failing to reach the destination via the one type of limiter or by just stepping past the limit anyways.

The Nodes (grid squares) are in a 2D array 10 x 10 called gridList.

The Node Object:

```
function Node(){
    this.element = document.createElement('div');
    this.x = 0;
    this.y = 0;
    this.caltrops = false;
    this.passable = true;
    this.pathParent = null;
    this.g = 0;
    this.h = 0;
    this.r = 0;
    this.f = 9999;

    this.element.className = "grid";

    this.checkPathValue = function(caller, destination){
        var calVal = 0;
        var moreThanMove = 0;
        if (this.caltrops)
            calVal = 25;

        /*if (caller.stepsToSource(1) > player.move)
            moreThanMove = 500;*/

        var r = calVal + moreThanMove;
        var g = 10 + caller.g + caller.r;
        var h = Math.abs(destination.x-this.x)+Math.abs(destination.y-this.y, 2);
        var f = g + h + r;

        if (f < this.f){
            console.log('Checked pathValue with caller as parent, smaller, updating.');
            this.pathParent = caller;
            this.r = r;
            this.g = g;
            this.h = h;
            this.f = f;
        }
    };

    this.stepsToSource = function(step){
        if (this.pathParent != null){
            console.log('Not at source yet, take more steps.');
            return this.pathParent.stepsToSource((step+1));
        }
        else
        {
            return step;
        }
    };
}

```

The Path Finding Script:

```
//The core pathfinding function for Gladiators movement. Uses A* with a pythagoreum direct line heuristic.
function movementPath(start, end){
        var closedList = []; //Begin closedList.
        var openList = [start]; //Begin openList. Populate it with the start node.
        start.pathParent = null;
        console.log('Just before do loop.');
        do{
            console.log('Just entered do loop.');
            //Create current node. Make it's f value impossibly high so it get's replaced
            var currentNode = new Node();
            currentNode.f = 9999999;
            console.log('currentNode.f: '+currentNode.f);
            //Set current node to the node with the lowest F value
            for (var i in openList)
            {
                console.log('Inside lowest F loop.');
                //if node[i] F is less than or equal to the current node F, replace current node with node[i]
                console.log('openList[i].f: '+openList[i].f);
                if (openList[i].f < currentNode.f)
                {
                    console.log('Node is smaller than currentNode. Updating.');
                    currentNode = openList[i];
                }
            }
            $(currentNode.element).addClass("processing");
            closedList.push(currentNode); //add current Node to closed list.
            //remove current Node from open List.
            var index = openList.indexOf(currentNode);
            if (index > -1) {
                openList.splice(index, 1);
            }
            console.log('Removed node from openList');
            //if we added the destination node to the closed list, we've found the path.
            if(closedList.indexOf(end) > -1)
            {
                console.log('We\'ve found the path!');
                break;
            }
            console.log('Path was not found this loop.');
            //Get adjacent nodes
            var adjacentNodes = getAdjacentNodes(currentNode);
            console.log('Got adjacent nodes.');
            //scan through adjacent nodes. If they are already closed, skip. If they are not in the open list, update and add them. Else just update them.
            for (var i in adjacentNodes){
                if(closedList.indexOf(adjacentNodes[i]) > -1)
                {
                    console.log('Node is in closed list, skip.');
                }
                else
                {
                    if(openList.indexOf(adjacentNodes[i]) <= -1)
                    {
                        console.log('Node is not in open list, adding then updating.');
                        adjacentNodes[i].checkPathValue(currentNode, end);
                        openList.push(adjacentNodes[i]);
                    }
                    else
                    {
                        console.log('Node is in list. Updating.');
                        adjacentNodes[i].checkPathValue(currentNode, end);
                    }
                }
            }
            console.log('Finished scanning the Nodes and updating.');

        }while(openList.length > 0) // Continue until there is no more available square in the open list (which means there is no path)
}

//Sub function for the pathfinding algorhythm. It checks the adjacent nodes to see if they are passable and returns a list of up to 4 nodes.
function getAdjacentNodes(target){
    var x = parseInt(target.x);
    var y = parseInt(target.y);
    var steps = target.stepsToSource(1);
    var list = [];
    if(steps <= player.move)
    {
        var nodeUp = new Node();
        nodeUp.passable = false;
        var nodeDn = new Node();
        nodeDn.passable = false;
        var nodeLt = new Node();
        nodeLt.passable = false;
        var nodeRt = new Node();
        nodeRt.passable = false;

        if((y-1) > -1){
            nodeUp = gridList[y-1][x];
        }
        if((y+1) < gridList.length){
            nodeDn = gridList[y+1][x];
        }
        if((x-1) > -1){
            nodeLt = gridList[y][x-1];
        }
        if((x+1) < gridList[y].length){
            nodeRt = gridList[y][x+1];
        }

        if (nodeUp.passable && hasClass(nodeUp.element,"moveSpace")){
            console.log('nodeUp is passable.');
            list.push(nodeUp);
        }
        if (nodeDn.passable && hasClass(nodeDn.element,"moveSpace")){
            console.log('nodeDn is passable.');
            list.push(nodeDn);
        }
        if (nodeLt.passable && hasClass(nodeLt.element,"moveSpace")){
            console.log('nodeLt is passable.');
            list.push(nodeLt);
        }
        if (nodeRt.passable && hasClass(nodeRt.element,"moveSpace")){
            console.log('nodeRt is passable.');
            list.push(nodeRt);
        }
    }
    return list;
}

```

I've exhausted myself trying to wrap my mind around it, I've only really figured out poor fixes that only sometimes fix the issue and otherwise I just can't find any good keywords online to figure out what I should look into, or how I should approach fixing this.

Any help is greatly appreciated.

# Answer
I added this condition instead of the add 500 resistance when you're stepped too far.

```
//Check if total steps from source to this node to destination exeedes move distance.
        var stepsToDest = caller.stepsToSource(1) + Math.abs(this.x - destination.x) + Math.abs(this.y - destination.y);
        if (stepsToDest > player.move)
            moreThanMove = (stepsToDest - player.move)*10;

```

Now the moment the path is going to throw the result beyond the maximum path limit, it gets extra resistance causing that possible path choice to be less desirable.
> 0 votes

# Answer
Personally I'd just try to remove the static penalty completely, because it falsifies your results as you noticed.

Instead, expand your A\* to Dijkstra's algorithm that always tries to estimate the remaining costs after a path is taken. It's essentially what you have now, but rather than adding a fixed penalty it's based on the remaining distance.

This way your "AI" will be able to think ahead and reach its goal next turn, still picking the least dangerous route.

The actual algorithm to predict the remaining distance/costs could also work with different parameters, estimating traps and such, which allows you to create various difficulty levels.
> 0 votes

---
Tags: javascript, algorithm, path-finding, board-game
---


title: Schlick Fresnel Shader

text:
# Question
Title: Schlick Fresnel Shader
I hope you are all doing ok. I have an issue with my Fresnel shader that doesn't allow the Fresnel to change as my camera moves around. I'm not sure what i'm doing wrong. I'm using glsl with the **Schlick** Fresnel algorithm along with a Diffuse BRDF. A picture says a thousand words, so let me show you the issue I am having. For debugging purposes, I am only rendering the Fresnel, nothing else.

The following image shows the Fresnel working perfectly from this particular angle (i'm looking along the direction the light is facing)

However, the following image shows the Fresnel not working when I pan the camera around the object to arrive at it's back (facing more or less against the light direction.)

As you can see, the Fresnel didn't change at all when i moved the camera, It's as if it's "Baked" into the object.

The code for the **Schlick** algorithm used in this application is:

```
vec3 Specular_Fresnel_Schlick( in vec3 SpecularColor, in vec3 PixelNormal, in vec3 LightDir )
{
    float NdotL = max( 0, dot( PixelNormal, LightDir ) );
    return SpecularColor + ( 1 - SpecularColor ) * pow( ( 1 - NdotL ), 5 );
}

```

All calculations are done in world space.

Any help you can provide would be a huge deal. Thank you for your time.

# Answer
The problem was that my Vertex Positions GBuffer Texture was being clamped to values between \[0,1\]. Converting the texture to Float32 format solved the issue. Thanks guys.
> 1 votes

---
Tags: shaders, glsl, hlsl, fragment-shader, pbr
---


# Question
Title: If I want to create game for mobile and tablet on android and ios, which aspect ratio or screen resolution should I use?
Now my game is currently use 3:4 aspect ratio ,which is 480\*640 , so my game has the letterbox (I don't like stretch) on my android mobile and my friend mobile. I don't like letterbox, so I have just change color of my letter box to the color that blend with my game background, but I don't like it either. So now I think about change aspect ratio and screen resolution of my game.

how about 480x800 ?

# Answer
> 2 votes
These are all of the aspect ratios you have to handle:

* 4:3
* 3:2
* 8:5
* 5:3
* 16:9

Source: https://stackoverflow.com/questions/7199492/what-are-the-aspect-ratios-for-all-android-phone-and-tablet-devices

Create 5 sets of graphics or use an engine like LibGDX and it's https://github.com/libgdx/libgdx/wiki/Viewports

@Edit When creating a LibGDX app, you can set width/height parameters

```
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.title = "Game Title";
cfg.height = 640;
cfg.width = 360;

```

(This is in your Core project in Eclipse/Intellij/Netbeans whatever).

When you set this, you can resize your window and check if it's a good resolution and if things are scaling well.

# Answer
> 0 votes
You should provide alternative resources for different screen ratios.

---
Tags: android, game-design, aspect-ratio
---


# Question
Title: How to detect a swipe and make the player GO rotate towards the end of the touch Android Unity
I am making a game where the user can swipe on the screen and the player gameobject will turn towards the end of the swipe.

I am using the following to detect the end of the swipe:

```
        if (touch.phase == TouchPhase.Ended)
        {
            swipeEndPos = touch.position;
            swipeDistance = (swipeEndPos - swipeStartPos).magnitude;
            if (swipeDistance > minSwipeDistance)
            {
                Vector3 swipeEndPoint = mainCamera.ScreenToWorldPoint (swipeEndPos);

                player.Turn (swipeEndPos);
            }
        }

```

And the following to make the player turn towards the end position:

```
     public void Turn(Vector3 direction)
     {
       transform.Rotate (new Vector3(0,direction.y,0), Space.Self);
     }

```

Can someone please explain what I am doing wrong?

Thank you.

# Answer
> -1 votes
Problem solved, it was as S.Tarik said, the perspective view was giving the "wrong" coordinates. Switched to orthographic, now things run smoothly. Thanks Tarik :)

---
Tags: unity, android
---


# Question
Title: Why does RenderTarget2D only output a black texture after a few seconds?
I encountered this strange problem where my UI drawing to RenderTarget2D works for a couple seconds and then suddenly goes black.

This is the `RenderTarget2D` function:

```
public RenderTarget2D RenderUi(SpriteBatch spriteBatch) {
    RenderTarget2D renderTarget = new RenderTarget2D(Graphics, 1920, 1080);
    Graphics.SetRenderTarget(renderTarget);

    Graphics.Clear(Color.Transparent);

    spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.Default);

    /* Goes black even if commented out
     - My draw calls
    */

    spriteBatch.End();

    Graphics.SetRenderTarget(null);

    return renderTarget;
}

```

And this is the `Draw` function:

```
public virtual void Draw(GameTime gameTime) {
    RenderTarget2D uiRenderTarget = UserInterface.RenderUi(SpriteBatch);

    /* Main SpriteBatch */
    SpriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend, SamplerState.PointClamp,
        null, null, null, Camera.TransformMatrix());

    World.Draw(gameTime, SpriteBatch);
    Entities.Draw(gameTime, SpriteBatch);

    SpriteBatch.End();

    /* Ui SpriteBatch */
    SpriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend, SamplerState.AnisotropicClamp, DepthStencilState.Default);
    if (Input.IsAction(Actions.DrawUI))
        SpriteBatch.Draw(uiRenderTarget, new Rectangle(0, 0, Graphics.GraphicsDevice.Viewport.Width, Graphics.GraphicsDevice.Viewport.Height), Color.White);

    SpriteBatch.End();
}

```

So if I hold down the DrawUI button the UI draws correctly and everything below but then it suddenly goes black, releasing the button shows that everything but that `RenderTarget` still draws fine.

Why does this happen and what can I do to avoid that?

# Answer
> 2 votes
The issue to me seems to be that you're creating a new `RenderTarget2D` on every frame, which is not a good practice. You're asking the GPU to allocate new memory for a texture constantly, which is unnecessary. I'm assuming that the GPU runs out of memory or something similar, and this is why your texture appears black after a while.

Instead, you should be able to simply reuse the same render texture. Create one in your constructor or some otherplace that gets called only once. Then, render to that texture (you probably want to clear it first) in your `RenderUi` method, and finally render the texture to the screen, properly scaled. XNA should allow you to simply specify the destination size of the texture, and that shouldn't affect that actual texture in any way.

If you decide to change your approach of resolution independent scaling, you could also simply create a new render texture when the window is resized. I'm not familiar with XNA's APIs, but I'm sure it offers callbacks on window resize.

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


# Question
Title: How to manage this problem in a multiplayer client-server game with Photon ?
Good day.

I'm developing my first simple game, a racing car, using Unity and Photon. In my game there are a function that generate random Bonus on random position each (for instance) 5 seconds.

The problem is that if I use RPC, each Peer connected generate a bonus each 5 seconds and send that bonus on other client connected . Results: if i have 5 clients, each clients generate 1 bonus each 5 seconds resulting in 25 bonus each 5 seconds.

So, i would like that ONLY the server generate bonus and send this bonus to each clients.

**In short: i don't know how to 'tell' unity and photon "If i am the server run this function, otherwise not"**

```
if (i am server )
   generate bonus
   instantieBonus on clients
}

```

Thanks

# Answer
> 1 votes
Use :

```
if (PhotonNetwork.isMasterClient){
                generate bounds
                run RPC
   }

```

master client is the first player who joined the room .

---
Tags: unity, multiplayer, photon
---


# Question
Title: LibGDX: Problems with Button Listener in a Dialog
I'm developing a game where the player has an inventory, and you can find chests in the map with items which you can collect, so I created a class that extends from `Dialog` to show both item lists, player's inventory and chest's inventory, just like this:

```
private class InventoryDialog extends Dialog{
    public InventoryDialog(boolean isPlayerInventory, Inventory inventory) {
        super(isPlayerInventory? "Inventory":"Chest", mySkin);

        final List inventoryList = new List(mySkin);
        inventoryList.setItems(inventory.getItems());
        ScrollPane pane = new ScrollPane(inventoryList,mySkin);
        getContentTable().add(pane).size(myDimensions);
        button("Back");

        if(isPlayerInventory){
            button("Use").addListener(new ClickListener(){
                @Override
                public void clicked(InputEvent event, float x, float y) {
                    super.clicked(event, x, y);
                    player.getInventory().useItemAt(inventoryList.getSelectedIndex());

                }});
        }else{
            button("Get").addListener(new ClickListener(){
                @Override
                public void clicked(InputEvent event, float x, float y) {
                    super.clicked(event, x, y);
                    player.getInventory().add(inventory.remove(inventoryList.getSelectedIndex()));
                }});}

    }

}

```

So they will use or get the item only if they click that button.

My problem is that the get/use listener is always invoked even if the clicked button is the "Back" button, what am I doing wrong? :/

# Answer
> 2 votes
The problem is, that I should not add a listener when I'm using the "button()" method, the correct way to use this method is, simply add the button, and as a second argument, you pass an object to recognize your button, once in the result method, you use an if to compare the object passed to know which button you clicked, just like this:

```
private class InventoryDialog extends Dialog{
public InventoryDialog(boolean isPlayerInventory, Inventory inventory) {
    super(isPlayerInventory? "Inventory":"Chest", mySkin);

    final List inventoryList = new List(mySkin);
    inventoryList.setItems(inventory.getItems());
    ScrollPane pane = new ScrollPane(inventoryList,mySkin);
    getContentTable().add(pane).size(myDimensions);
    button("Back");

    if(isPlayerInventory) button("Use","use");
    else button("Get","get");

}

@Override
    protected void result(Object object) {
        super.result(object);
        if(object.equals("use")){
           player.getInventory().useItemAt(inventoryList.getSelectedIndex());
        }else if(object.equals("get")
           player.getInventory().add(inventory.remove(inventoryList.getSelectedIndex()));
        }
    }
}

```

# Answer
> 0 votes
Im not sure, but I think it's because of the different Positions. There different Positions :

1. Screen Position
2. World Position

Those are different so your Button is on Screen Position x = 500, y = 500 but in the game on a totally different one.

Im not a well explainer so here's a link :

Convert Screen coords to World Coords LIBGDX

---
Tags: libgdx, scene2d, inventory
---


title: Reconciling Flocking and A* (Theory)

text:
# Question
Title: Reconciling Flocking and A* (Theory)
For my RTS game I have got A\* pathfinding working, and that's fine. Basic collision detection exists too. When a unit is moving it checks if the position it will occupy next move is a node occupied by another unit, and if so it finds another way to the destination. I also think I understand the basics of flocking; that during movement it's just making sure that boids are checking the distance to their flock friends, and then correcting for this.

But I am a little confused. Right now my pathfinding system works on a square grid of nodes, but if I'm to create a flocking system which works by taking a boid's circular footprint into account then this complicates matters, because in a tightly packed flock, or indeed a flock with a number of members with various footprint sizes, then their placement won't always match the square node grid designed for A\*.

In theory, how then do a bunch of boids pack together in a ball, or flow through terrain bottlenecks (some nodes flagged unwalkable, etc) in an orderly manner? Is this sort of behaviour emergent from a functional flocking system?

But I'm sure I'm misunderstanding this system and would like someone who understand how to implement it to explain the theory so that I can implement this myself. I assume flocking isn't really congruent with A\*: that's just used to find a path, and during movement flocking is the only way it manages collision detection and avoidance for units? But then what about obstacles which can create bottlenecks? How is A\* and flocking reconciled? Avoiding boids and terrain obstacles are different systems.

# Answer
> 10 votes
# The contradiction

Indeed the two systems are quite exclusive to one another. As you mentioned:

> A\*: that's just used to find a path, and during movement flocking is the only \> way it manages collision detection and avoidance for units

Here are key differences, pros, and cons, to keep in mind:

```
+---------------------+-------------------------------------+
| A* Algorithm        | Flocking                            |
+---------------------+-------------------------------------+
| Abstract overlay    | Real-world representation           |
+---------------------+-------------------------------------+
| Graph-Based (Nodes) | Free-Form (float coordinates)       |
+---------------------+-------------------------------------+
| Optimal trajectory  | Physical Trajectory (speed, inertia)|
+---------------------+-------------------------------------+
| Individual          | Group dynamics                      |
+---------------------+-------------------------------------+
| Global knowledge    | Local knowledge                     |
+---------------------+-------------------------------------+

```

If you want to mix the two, then I have to assume you have a way to make either work (but you want advice on how to have them work *together*). This means you already have:

* A *Physical world*, where your boids can move around, interact with each other, and collide to world boundaries.
This can be a 2D set of segments, polygons, circles that form walls and obstacles, also friendly and ennemy units and buildings, slopes, terrain type, materials, political ownership etc. That is, everything that may physically or morally affect your characters.
Now your boids can move within this representation, have inertia, react to forces (real forces like collisions, or behavioural forces like seeking, fleeing). This is likely not just discrete cells, because boids are *usually* not constrained to cells, but it could be.
Ultimately, this is our game simulation/mechanics world so make it what *you* want.
* A **Graph representation of you world**, for A-Star to work with.
This is a high-level, abstract representations (graph with nodes and weighted edges). This needs no information on terrain type or any of that: just nodes and weighted edges. An AI can quite easily handle this abstract representation to navigate it towards a goal, rather than the physical world in all its complexity.
* To let the two representations interact, you'll also need:
    + A way to map any *world position* to a **node in the graph**
    + Vice-versa, a way, **from any node in the graph**, to pinpoint a matching *location in physical world*.
    (Note, this is not a one-to-one mapping, so you could randomize the physical location of this point within the cell to get organic paths)

(In the rest of this answer, I will *italicize Flocking algo* and **embolden A-Star algo** as I did above).

So how can we let these two systems cooperate to get the best of both?

---

# Towards cooperation

Split responsibilities between your algos.

1. Let **A-Star find a reasonable global path** (think guidance system) in the abstract realm. It will be optimal in graph space, and good enough in real-world space.
2. Let *Flocking drive your boids locally* along the path.

The **A-Star will find a way to its objective**, by feeding clever *temporary 'seek' targets to the Flocking algo*.

---

# Detailed Implementation:

* Beforehand, prepare some *boids* each of which have, at all times:
    + A **macro objective, and a global path to that objective**
    + A *local tracking target for the steering behaviour*, that we will move along the desired global path
* At each time step, do the following for each boid:
    + *Move the boid according its behaviours (point seeking, plus collision, plus flocking etc.) in the physical world*
    + Map the boid's *current location* to its representative **graph node**
    + If the boid has left its previous node, it needs to recompute its path! We now give it a new target:
        - **Perform an A-Star search, from the boid node, to the discretized macro objective node. This returns a global path**.
        - **Isolate a node further in the global path** (The next node, or the one after that to get a more flowing seek behaviour?)
        - Un-descretize it (make it back into a *physical location*).
        - *Assign to the boid a Seeking behaviour towards this local target*

---

## Note 1: Separation of concerns

You've altered A-Star by having each units look at cell occupancy by other units. This has compromised many benefits of A-Star:

* Path is no longer optimal
* Path is no longer guaranteed to reach the target due to interactions
* Units will go back and forth whenever a path gets blocked/freed

This is because you've mixed concerns by having the algo both find an optimal path AND manage unit interaction. The nice thing about mixing two algorithms, is that this will allow you to resolve this by having A-Star simply find a path (regardless of other units, its the only thing it's good for) and let Flocking resolve conflicts (a task at which it is good for).

## Note 2: Unit traffic jam

If you're concerned about groups of units blocking each other (like this `(AAAA)--> <--(BB)` ) in flocking mode, there are ways of mitigating this.

* Try and recognize unit groups based on their intention (target node) and distribute a repulsive force on every unit of the smaller groups to "make way" (bigger group = bigger priority)
* If you give mass order to big groups, then take that into account in you disretization process: make the discrete graph coarser when dealing with with large groups. Coarse A-Star will only find path through large enough "holes"

## Note 3 - Unwalkable terrain

About unit walking into unwalkable terrain: Neither algorithm allows this.
At a high level, A-Star never orders a unit to pass through unwalkable edges, because those edges should not exist in the graph in the first place.
At lower level, Steering behaviout should include collision responses that keep boids out of the walls.

### Worked Example

All white space in physical world is navigable, the graph world is a corresponding navmesh. Note that I purposely not followed the geometry in the graph, because it is an abstraction, so it doesn't matter as long as the edges have a correct weight (not shown).
The boid is in `A` and `a`, the objective is in `E` and `e`, there's a door in `D` and `d`.

```
Physical world             Graph world
+--------+------+          a---b
|A      B|F    G|          |\ /|
|        |      |          | X |
|        |      |          |/ \|
|        |      |          c---(d)---f
|        |      |               |\ / |
|        +      |               | X  |
|C       D     E|               |/ \ |
+---------------+               e----g

```

So the boid is in `a`, its A-Star path is `a->b->d->e`. So A-Star decides the next high-level move should be `d` (two vertices away, to create smooth trajectories). Since `d` resolves to `D`, the boid adopts a seeking behaviour towards `D`. But the boid is also very afraid of an ennemy in `B`, so here's what happens (the dots show the trajectory):

```
Physical world             Graph world
+--------+------+          a---b
|A      B|F    G|          |\ /|
|.       |      |          | X |
|.       |      |          |/ \|
|.       |      |          c---(d)---f
| .      |      |               |\ / |
|  .     +      |               | X  |
|C       D     E|               |/ \ |
+---------------+               e----g

```

The boid steered away from `B` (comination of seek+flee), changed of node in the process, and is now on node `c` ! We recompute the path, and now get `c->d->e`. The boid is assigned `E` as a seeking target. Etc, etc.

We thus get a natural, and emotionally coherent path which is a mix of A-Star and Steering behaviour.

---
Tags: unity, collision-detection, path-finding
---


title: MonoGame - 2x2 texture scaling issue

text:
# Question
Title: MonoGame - 2x2 texture scaling issue
I've just recently switched from XNA to MonoGame and now I've run into something that has never happened to me in XNA before.

I've created a 2x2 texture and filled it with a color by doing this:

```
//Generates a texture from the color.
Texture2D texture = new Texture2D(Constants.GAME.GraphicsDevice, 2, 2, false, SurfaceFormat.Color);
texture.SetData<Color>(new Color[] { alternateColor });

AlternateColor = texture;

```

What I use this texture for is for drawing rectangles of different sizes using the specified color. This has usually worked just fine for me in XNA but when I do this in MonoGame I get this:

The screen is suppose to be black here as I'm scaling that 2x2 texture up to fill the entire screen.

I've tried turning mipmaps off, I've tried turning multisampling off and I've tried setting my sample state \[0\] to use PointWrap but I just can't seem to get this to work.

Any suggestions would be much welcomed.

Thanks!

# Answer
Another solution that also explains the problem you ran in to:

```
Texture2D texture = new Texture2D(Constants.GAME.GraphicsDevice, 2, 2, false, SurfaceFormat.Color);
texture.SetData<Color>(new Color[] {
    alternateColor,
    alternateColor,
    alternateColor,
    alternateColor
});

```

One color for each pixel in the texture (2x2 = 4)
> 3 votes

# Answer
I ran into this (two years later) and found a different solution. The way you're creating your texture is fine (you can even create a 1x1 texture), and then specify a `Rectangle` when you draw it.

Creation:

```
var texture = new Texture2D(this.graphicsDevice, 1, 1, false, SurfaceFormat.Color);
texture.SetData<Color>(new Color[] { Color.White });

```

Drawing:

```
spriteBatch.draw(texture, null, new Rectangle(x, y, width, height), null, null, 0, Vector2.One, Color.MyChoiceOfColorHere)

```

As @Felsir pointed out, this is more efficient, because it shares a single white texture across all your coloured rectangles.

The four default-valued parameters preceeding the colour are the source rectangle, the origin, rotation, and scale.
> 1 votes

# Answer
I changed the texture size to 1x1 instead of 2x2 and that seemed to fix it.
> 0 votes

---
Tags: c#, textures, monogame, scale
---


# Question
Title: Why won't character stay at the x-axis rotation I set In the inspector?
Here is a snippet of my Update function, which contains everything regarding my rotations for the character:

```
// Higher the Z float, the LESS of a rotation when moving
Vector3 v3 = new Vector3 (Input.GetAxis ("Horizontal"), 0.0f, 1.5f);

// A Quaternion variable named "quaternion" that's equal to LookRotation class that takes
// the "v3" variable
Quaternion quaternion = Quaternion.LookRotation (v3);

// The actual rotation is done using the Slerp class
transform.rotation = Quaternion.Slerp (
  transform.rotation,
  quaternion,
  Rotspeed * Time.deltaTime);

// When Countdown timer is done, then the animator is enabled
adventureAnimator.enabled = true;

```

When I put "357" on the X-Axis tab of Rotation, why does it go back to 0 whenever the game starts? After some debugging I know it is because of my logic contained in my "transform.rotation = Quaternion.Slerp" line of code. What do I need to change?

If you need more information or need me to elaborate, please let me know.

# Answer
Having tested your code, I find that your problem occurs due to several faults.

* Your telling your rotation to move with a time value of `Rotspeed * Time.deltaTime`. I have previously mistaken this value to represent *how long* the rotation should take. If you have taken the same misinterpretation, there is a good chance your *actually* telling it to complete the rotation *immediately*.
* Your telling your rotation to move between 357 degrees and 0 degrees. That gives us only 3 degrees of rotation, which is not a lot. Depending on your setup, you might very well be completing the rotation in such a small amount of time that you simply do not notice.
* As *InfiniteCanvas* points out, your taking `Input.GetAxis("Horizontal")` at *every* `Update()` call. Whenever your not providing input, this will return a value of `0`.

## Using `Quaternion.Slerp`

Since you have neglected to tell us what you are setting `Rotspeed` to, this could easily be a red herring. That said, I see this error a lot, and have made it myself when first starting to use `Quaternion.Slerp`.

As per the API, the method takes two `Quaternion` values to represent the start and finish rotations, and a `float` to represent the time. While *time* is commonly interpreted as "how long should my rotation take", it is actually a *normal* for *how quickly* your object should *complete* the rotation.

If the combined value of `Rotspeed * time.deltaTime` reaches the value of `1`, your effectively telling your code "perform the entire rotation in a single frame". This will move the rotation *immediately* to the `b` quaternion, in this case, `(0, 0, 0)`.

---

***This is the only fault that specifically results in your reported problem***. All other potential faults result in a *similar* problem, but instead of skipping straight to 0, the rotation still "teeters" for a little. For example, with the *input* problem, rotation moves back and fourth between -0.01 and 0.01.

## Understanding `Transform.Rotation`

There is a possibility you interpret the move between `(357, 0, 0)` and `(0, 0, 0)` to be quite large; the gap between 357 and 0. It is important to know that this is *not* the case.

The rotation displayed on the transform via the inspector *can* be interpreted as *degrees*. You can submit *any* value, but as soon as you hit play, the transform will scale these values back to the *true* degrees. Once a rotation value reaches 360, it has performed a full rotation. It may as well be returned to 0 - and that is exactly what it does. You can see this by setting the rotation to values *higher* than 360, via the inspector. Once you hit play, these numbers will immediately scale down to values between 0 and 360.

As you can see, rotation between 357 and 0 is not that much - it is *actually* only a difference of 3. The object is rotated *clockwise*, and once it reaches a rotation of 360, the transform resets this value to 0. The `Quaternion.Slerp()` is successfully carried out over a mere *3* degrees.

## Ensuring Input

As mentioned by *InfiniteCanvas*, constantly updating your rotation means that whenever the user is not actually providing input, you will update your rotation to 0. This might have a secondary effect on your logic, as you might reset the *look at* rotation when you do not mean to. Further testing has confirmed that this alone will not cause the problem you describe, but it is worth addressing how you might better your input.

Keep in kind that if you did not intend to pass non-values at `Update()`, you will want to declare `Vector3 v3` as a *class variable* rather than a *method variable*. This way, if your current input as a non-value, you still have the rotation from your last value input.

---

Continuing use of the Input Manager, you could simply exclude non-input in an if statement, prior to setting it as your new rotation:

```
// we should initialise the vector with a default value.
Vector3 v3 = new Vector3(0, 0, 1.5f);

void Update()
{
    if(Input.GetAxis("Horizontal") != 0)
    {
        Vector3 v3 = new Vector3 (Input.GetAxis ("Horizontal"), 0.0f, 1.5f);
    }

    ...
}

```

---

You might consider checking direct key presses to influence a set vector, instead. Ideally, you would set a class variable to represent `rotationMovement` per input update. You could than tailor your code to rotate *once* per key press with `Input.GetKeyDown(KeyCode)`, during *ever* update where the key is pressed with `Input.GetKey(KeyCode)`, or even *once* at the update where the key is *released* with `Input.GetKeyUp(KeyCode)`. The choice is yours, but it would look something like this:

```
// we should initialise the vector with a default value.
Vector3 v3 = new Vector3(0, 0, 1.5f);
float rotationMovement = 0.1f;

void Update()
{
    if(Input.GetKey(KeyCode.LeftArrow))
    {
        v3.x -= rotationMovement;
    }
    else if(Input.GetKey(KeyCode.LeftArrow))
    {
        v3.x += rotationMovement;
    }

    ...
}

```
> 1 votes

# Answer
Wrap it all in an `if` statement, like so:

```
if(Input.GetAxis("Horizontal") != 0)
{
    //your code
}

```

As it is now it updates on every frame, regardless of your input. That means that you update your rotation to

```
v3 = new Vector3(0f, 0f, 1.5f)

```

when you're not pressing anything.
> -1 votes

---
Tags: unity, c#, rotation, transformation, quaternion
---


# Question
Title: Single pass box blur is not giving same result as double pass box blur
I've been using 2-pass box blur written in GLSL in Blender without problem.

Blur horizontally:

```
uniform sampler2D bgl_RenderedTexture;
void main()  {
    float blur = 0.3;

    float resolution = blur * 0.1;
    int n = 10;
    int i = -n;
    int totalWeight = 0;

    vec2 st = gl_TexCoord[0].st;

    vec4 outColor = vec4(0.0);
    for(; i < n; ++i) {
        vec2 uv = st + vec2(float(i) / 2.0 / float(n) * resolution, 0);
        outColor += texture2D(bgl_RenderedTexture, uv);
        totalWeight += 1;
    }
    gl_FragColor = outColor / float(totalWeight);
}

```

Blur vertically:

```
uniform sampler2D bgl_RenderedTexture;
void main()  {
    float blur = 0.3;

    float resolution = blur * 0.1;
    int n = 10;
    int j = -n;
    int totalWeight = 0;

    vec2 st = gl_TexCoord[0].st;

    vec4 outColor = vec4(0.0);
    for(; j < n; ++j) {
        vec2 uv = st + vec2(0, float(j) / 2.0 / float(n) * resolution);
        outColor += texture2D(bgl_RenderedTexture, uv);
        totalWeight += 1;
    }
    gl_FragColor = outColor / float(totalWeight);
}

```

The output is as desired:

But when I try to do it with single pass, it's only blurring in the direction of the inner loop.

```
uniform sampler2D bgl_RenderedTexture;
void main()  {
    float blur = 0.3;

    float resolution = blur * 0.01;
    int n = 10;
    int i = -n;
    int j = -n;
    int totalWeight = 0;

    vec2 st = gl_TexCoord[0].st;

    vec4 outColor = vec4(0.0);
    for(; i <= n; ++i) {
        for(; j <= n; ++j) {
            vec2 uv = st + vec2(float(i), float(j))
              * resolution / float(n) / 2.0;
            outColor += texture2D(bgl_RenderedTexture, uv);
            totalWeight += 1;
        }
    }
    gl_FragColor = outColor/ float(totalWeight);
}

```

I must be missing something really simple but it's not visible to me. Can anyone help me?

# Answer
> 5 votes
I can see this question is old, but the answer is kind of trivial. **Omitting the initialization in a nested loop is *not* equivalent to omitting it when it's the topmost level of the loop.**

Let's walk through executing the code to see why:

```
int i = -n;
int j = -n;

for(; i <= n; ++i) {
    for(; j <= n; ++j) {
        vec2 uv = st + vec2(float(i), float(j))
          * resolution / float(n) / 2.0;
        outColor += texture2D(bgl_RenderedTexture, uv);
        totalWeight += 1;
    }
}

```

For simplicity, let's say n is 1.

1. We encounter the top for loop. We don't initialize i, so it's still i = -n = -1.

* we test i \<= n (-1 \<= 1) and pass, so we continue...
2. Next we encounter the inner for loop. We don't initialize j, so it's still j = -n = -1

* we test j \<= n (-1 \<= 1) and pass, so we continue...
3. We sample our texture with an offset of (-1, -1)
4. We loop and increment j, so it's now 0

* we test j \<= n (0 \<= 1) and pass, so we continue...
5. We sample our texture with an offset of (-1, 0)
6. We loop and increment j, so it's now 1

* we test j \<= n (1 \<= 1) and pass, so we continue...
7. We sample our texture with an offset of (-1, 1)
8. We loop and increment j, so it's now 2

* we test j \<= n (2 \<= 1) and fail, so we fall through to the outer loop
9. We loop and increment i, so it's now 0

* we test i \<= n (0 \<= 1) and pass, so we continue...
10. We encounter the inner for loop a second time. **We don't initialize j, so it still has its previous value of 2**

* we test j \<= n (2 \<= 1) and **fail**, so we immediately fall through to the outer loop.
11. This pattern repeats: only the first trip through the outer loop actually samples the texture. Every subsequent pass skips the inner loop entirely because we incremented j beyond the loop limit and never bothered to reset it. So we only get one vertical strip of samples, resulting in the image shown.

The solution is dirt simple, as noted in the comments: **initialize your iteration variables.** There's no weird undocumented feature or optimization or trick of the language happening here - the shader is doing exactly what you asked it to do, increasing j without ever reducing it back to -n.

# Answer
> 0 votes
It would appear omiting the loop init statement is not formally supported by GLSL, although probably widely implemented. Here is a link to someone else having similar problem:

https://bugs.chromium.org/p/angleproject/issues/detail?id=140

I did an honest attempt reading the GLSL grammar section but was unable to make much sense of it. Some token (conditionopt) explicitly states empty to be ok. The for init statement does not. (It would be great if someone could verify this.)

---
Tags: glsl, blur
---


# Question
Title: Reference sf::RenderWindow from another source file in SFML
In SFML, How would you be able to reference a window in your `main.cpp` file to another source file? I want to be able to reference the window made in `main.cpp` from `player.cpp`, so I can keep everything organized and not have so much stuff in `main.cpp`. Any help is greatly appreciated.

Main.cpp

```
#include "SFML/Graphics.hpp"
#include <iostream>
#include "Player.h"

int main()
{
    sf::RenderWindow window;
    sf::VideoMode vmode(800, 600, 32);
    window.create(vmode, "Test");

    PlayerTest(2);

    //Game Loop
    while (window.isOpen())
    {
        // REMEMBER TO FIX PLAYER.CPP

        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        window.draw(text);
        window.display();
    }

    return 0;
}

```

Player.h

```
#ifndef PLAYER_H
#define PLAYER_H

#include <SFML/Graphics.hpp>
#include <iostream>

void PlayerTest(float speed);

#endif

```

Player.cpp

```
#include "SFML/Graphics.hpp"
#include <iostream>
#include "Player.h"

void PlayerTest(float speed) {

    sf::RectangleShape square(sf::Vector2f(100, 100));
    square.setFillColor(sf::Color::Cyan);

    //window from Main.cpp I need to reference
    while (window.isOpen())
    {
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) {
            square.move(0, -speed);
        }
        else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) {
            square.move(0, speed);
        }
        else if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) {
            square.move(-speed, 0);
        }
        else if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) {
            square.move(speed, 0);
        }

        //Window from Main.cpp I need to reference
        window.clear();
        window.draw(square);
        window.display();
    }
}

```

# Answer
Have your main.cpp call an object `Game`. This Game object contains everything else. Your game first initializes the Window, then passes the reference to Player when it initializes it.
> 0 votes

---
Tags: c++, game-loop, sfml
---


title: Inventory Table efficiency

text:
# Question
Title: Inventory Table efficiency
I'm building an inventory system for a MMORPG game that can possibly contain massive numbers of players (~20.000). Is it smart to make an InventoryTable where each row contains only one item, or should I make one big VarChar column that contains all of the information about all Items for a player.

A player has about 200 items.

And every item has about 20 additional pieces of information: `ItemID, Amount, ...`

So this big varchar column can be something like 15000 chars long.

Here are some basic attributes:

What will be faster?
\- Reading maybe 200 lines from a big table for each player
\- Or one big line for every player and serialize it in my server.

Is use a MSSQL database with ODBC.

# Answer
If you want to do relational database design by the book, you would use the first solution. Encoding multiple independent values into the same column by encoding them in a string is a big no-no.

However, in the context of a game your usual use-case is to save or restore a player completely. Putting all the info into fewer tables and rows will improve performance.

But there is a price you pay for that performance improvement. No, not just that the ghost of Edgar F. Codd will haunt you and write bugs into your code while you sleep. You will lose the ability to effectively analyze and modify the inventory data outside of the game with simple SQL queries. For example, these are some SQL operations you might want to do one day which **only work well with the first solution**:

* Create a report of how many items of what kind are currently in the game (`SELECT ItemId, SUM(Amount) FROM Inventory GROUP BY ItemId`)
* Remove an item from the game completely (`DELETE FROM Inventory WHERE ItemId = 42`)
* Give a free item to a player (`INSERT INTO Inventory VALUES( 13, 42, 1)`)
* Give a free item to a subset of players (`INSERT INTO Inventory SELECT PlayerId, 42, 1 FROM Players WHERE RegistrationDate < '2016-01-01 00:00:00'`);

But when you don't think you will ever need to do any of these or are comfortable with building a more expensive workaround for them, sure, go ahead.
> 3 votes

---
Tags: databases
---


# Question
Title: Collision handling for grid based games and simulations
I'm trying to implement a grid based game where there are many creatures moving in the grid from square to square. I'm having a hard time handling collision with creatures in the grid (multiple creatures trying to move into the same square or cell). Where can I find information on how I should handle a game (or simulation) where multiple creatures in a grid want to move into the same cell but aren't allowed to? It's easy to handle 2 creatures, but handling n object collision is tough.

I'm looking for info on how to handle collision in a grid world. I don't expect a specific answer as much as resources or suggestions to find more info.

EDIT: To clarify, I'm looking for info on HOW TO HANDLE COLLISIONS BETWEEN MULTIPLE OBJECTS IN A GRID. In a grid world where multiple objects want to move into the same cell at the same time, how do I resolve this? Does one object get to move into the cell and the other objects remain stationary? Do I make each object push the other object out of its cell? These are the questions I want to answer.

An example of the problem I'm looking to answer: Consider a grid where there's 3 creatures who move from tile to tile. What do I do when two creatures, A and B, try moving into the same tile? Let's consider if I allow creature A to move into the tile but creature B remains stationary. What happens if a different creature C wanted to move into the tile that creature B was stuck in? Then creature C also wouldn't be able to move.

This would cause an issue if I would evaluate creature C's movement first, telling it that he can move into the tile that creature B is in (because creature B plans to move out) but then creature B ends up never moving out.

How do I determine which creatures to evaluate first? Also, how do I avoid this huge chain of creatures being forced to remain stationary (in this example, only 1/3 creatures were able to move).

# Answer
> 2 votes
Hard to say without knowing how movement is programmed. If your "simulation" is turn based you should be able to change the status of any tile. When the creature(s) move then have the creatures A.I query the status of what ever tile it wants to move to. It it's free the creature moved and changes the status of the tile it just left and the tile it just moved to. If It's not turn based the same method can be applied but it has to be separated out int it's component steps and done all together (I hate working with stacks!);

1: Query every creature and load their infomration into a stack

2: Query the tile each creature is standing on...into a stack

3: Change that status of each creatures current tile to free

4: Run each individual creatures movement A.I and update the new tiles

5: Move the creatures in the stack to their new tiles

# Answer
> 0 votes
If every entity in your game has a uniform movement speed or "initiative" ranking, then you don't want to give any particular entity priority over the others when a conflict is detected.

A really straight forward way to do this might be to do something like the following psuedocode:

```
// Loop over every entity and update their tile information, then move them
for (entity in entities) {
  entity.lastTile    = entity.currentTile
  entity.currentTile = entity.desiredTile
}

recheck:
collisionFlag = false

// Loop back over the entities and check for collisions with other entities
for (entity in entities) {
  // If this entity hasn't moved we can skip it
  if (entity.currentTile == entity.lastTile) continue

  for (other in entities) {
    if (entity.currentTile = other.currentTile) {
      // When a collision is detected, revert both entities' movement
      entity.currentTile = entity.lastTile
      other.currentTile  = other.lastTile
      // and flag for recheck
      collisionFlag = true
    }
  }
}

// Check the entities again if there was a collision to handle cascades
if (collisionFlag) goto recheck

```

If your entities have different speeds or "initiatives" then you might want to instead have them stay where they moved where slower creatures are returned to their previous tile.

Most implementations you'll find will simply employ a series of movement rules that determine when and where you can move and don't care *too* much about perfect movement resolution.

---
Tags: collision-detection, game-mechanics, collision-resolution, grid
---


# Question
Title: Rotating vector based on the position of another vector?
Sorry for terrible picture but lets say we have a unit vector A and we have vectors B and C. So for vector B I would want to rotate in a positive direction because the vector is "above A" and for vector C i would want to rotate downwards. Is there an easy way of detecting which way to rotate?

# Answer
The naïve approach would be to use the trig function `arctan` to calculate their current angles, then decide which way to rotate and at what speed to do so.

For example:

```
function rotateTowards(from, to, speed) {
  // τ is Tau, ~= 6.28318530718

  diff = to - from; // Find the angle delta
  if (diff < 0) diff += τ; // If the delta is out of the unit circle, wrap it back in.
  if (abs(diff) < speed) return to; // We're within speed of our target, return target.

  if (diff < 0) newAngle = from - speed;
  newAngle = from + speed;

  // Make sure our new angle is still valid.
  if (newAngle > τ) newAngle -= τ;
  if (newAngle < 0) newAngle += τ;

  return newAngle;
}

// Declare our vectors.
A = new Vector(-1, -0.5);
B = new Vector(-2, -3);
//C = new Vector(-1, -2.5); Not using C, but it's here for completeness.

// Calculate each vector's angle using atan2
angle_a = atan2(a.y, a.x);
angle_b = atan2(b.x, b.y);
//angle_c = atan2(c.x, c.y); Same as above.

// Calculate A's magnitude
magnitude = sqrt(A.x ^ 2 + A.y ^ 2);
// Use our rotate function to adjust A's rotation
angle_a = rotateTowards(angle_a, angle_b, 0.01);

// Set A's x/y as per the new angle and old magnitude
A.x = cos(angle_a) * magnitude;
A.y = sin(angle_a) * magnitude;

```

In the above example the vector would rotate 0.01 radians per execution, but in practice you'd want to use something like `rpm * 60 * dt` where `dt` is your delta time in seconds.
> 0 votes

---
Tags: trigonometry
---


# Question
Title: What happens with associated animation clips when I copy a gameobject in Unity?
I have a gameObjectOne that has two animation clips: move into the screen and move out of the screen. This gameObjectOne has an animator that checks when each clip has to be played.

Now I duplicated this gameObjectOne via the edit menu and named the copy gameObjectTwo, and to my surprise the animator and the animations still work. I expected that the animation clips were associated with gameObjectOne but this is not the case....

The animation clips are not duplicated. There are still only two clips and one animator in the project window. But when I click on gameObjectTwo in the animation window, you can see that there are two animation clips associated with gameObjectTwo as well.

So my question is: how is this possible? And is there a way to see what is "inside" an animation clip file? If I click in the project window on an .anim file, it doesn't say which gameObject it belongs to.

# Answer
For starters if you select the serialization to be Force Text from Editor settings \> asset serialization \> Force Text and the open the .anim file with lets say notepad++ you can its contents. Now to answer your actual question: Animation files are just encoded information about the movement, rotation ,state change, sprite change etc of a object but they are in no way tied to any particular object. For example lets say you record a animation on a cube that moves it from X=1 to X=10. The thing that is recorded is move a transform from coord A to coord B so you can apply this animation to anything with a transform. I hope I have explained what you needed :)
> 1 votes

---
Tags: unity, gameobject
---


# Question
Title: Improving bouncing logic - Atari breakout clone
I'm creating an Arkanoid clone using Haxe and Openfl. I'm thinking the bouncing algorithms could be improved. But I'm not sure how to handle those. I was hoping you guys could help.

```
    private function bounceBall():Void {
    var direction:Int = (ballMovement.x > 0)?( -1):(1);
    var randomAngle:Float = (Math.random() * Math.PI / 2) - 45;
    ballMovement.x = -1 * Math.cos(randomAngle) * ballSpeed;
    ballMovement.y = Math.sin(randomAngle) * ballSpeed;
}

```

Since I've never coded anything in Haxe I followed a tutorial to build a pong game. This is one of the functions that was used in the pong exercise. I think it's causing the ball to bounce left/right and rarely up or down. Can you guys help me out? How can I recreate the arkanoid bouncing ball logic?

You can find the rest of the source Here

# Answer
The system in both the original arkanoid and pong work the same way.

You need to know 2 things, the distance of the bounce position on the paddle from one if the edges of it (here marked as d) and the total length of the paddle (marked as l)

The ball should bounce off in 90 degrees when it hits the exact middle, and 45-45 degrees from the edges. The points between these should interpolate linearly between these values.

To calculate the angle, you divide `d` by `l`, subtract 0.5 from it, divide it by `2` and multiply it with pi (the last 2 steps converts it to radians).

```
angle := (d / l - 0.5) / 2 * π

```

Using trigonometry, you can convert them to a direction vector (if you're not familiar with any one of these, then A) just take my word and B) learn it because you'll need it).

`angle` is what you got above, speed is the speed of the ball:

```
x := cos(angle) * speed
y := sin(angle) * speed

```
> 1 votes

# Answer
Line by line

Function void return nothing

```
   private function bounceBall():Void {

```

Declare direction as integer and assigned the opposite sign to the balls x movement. So if the ball is traveling right direction is -1 else 1. Though this is not used in this function as is.

```
var direction:Int = (ballMovement.x > 0)?( -1):(1);

```

Declare randomAngle as float and assigned a random angle but the assignment is incorrect. Angles are in radians and Math.PI /2 is 90deg but then the 45 is in deg which is equivalent to 2000deg Should be Math.PI / 4 which is 45 deg. So get a random angle between -45 and 45 deg pointing to the right of screen

```
// Remove var randomAngle:Float = (Math.random() * Math.PI / 2) - 45;
var randomAngle:Float = Math.random() * Math.PI / 2 - Math.PI / 4;

```

Math.cos and Math.sin return the unit vector that represent the angle. Multiplying by ball speed set the vector length to equal the speed, thus maintaining the ball speed.

The odd thing is the negative -1 which in effect mirrors the vector back along x. This is where the direction var needs to be.

```
ballMovement.x = -1 * Math.cos(randomAngle) * ballSpeed;
ballMovement.y = Math.sin(randomAngle) * ballSpeed;

```

ballSpeed seams out of place as well.

To fix it up.

```
private function bounceBall():Void {
    var direction:Float = (ballMovement.x > 0)?( -1):(1);
    var ballSpeed:Float = Math.sqrt(ballMovement.x * ballMovement.x + ballMovement.y * ballMovement.y);
    var randomAngle:Float = Math.random() * Math.PI / 2 - Math.PI/4;
    ballMovement.x = direction * Math.cos(randomAngle) * ballSpeed;
    ballMovement.y = Math.sin(randomAngle) * ballSpeed;
}

```
> 0 votes

---
Tags: 2d, haxe, flashdevelop, arcade
---


# Question
Title: HLSL texture sampler always returns white
I'm facing in problem in HLSL with Monogame that I can't figure out. The gist is that sampling from a texture seems to always return white rather than the texture's actual color. My pixel shader code is below, and then I'll say more.

```
texture2D fillTexture;

sampler fillSampler = sampler_state
{
    Texture = <fillTexture>;
};

sampler s0;

struct VertexShaderOutput
{
    float4 Color : COLOR0;
    float4 Position : SV_POSITION0;
    float2 TexCoords : TEXCOORD0;
};

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    return tex2D(fillSampler, input.TexCoords);
}

technique Technique0
{
    pass Pass0
    {
        PixelShader = compile ps_4_0 PixelShaderFunction();
    }
}

```

First, in my C# code, I'm using the SpriteBatch to draw a large rectangle. That part works fine. Second, I have a smaller texture that I'm passing as a parameter into my pixel shader (fillTexture). No matter what I try, the resulting large rectangle is pure white.

I've already verified that my shader is being applied, as the following code results in a red block.

```
float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    return float4(1, 0, 0, 1);
}

```

I've also verified that my texture coordinates within the pixel shader function are correct. The following code produces the image below.

```
float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    float2 texCoords = input.TexCoords;

    return float4(texCoords.x, texCoords.y, 0, 1);
}

```

I've also verified that the fill texture itself has valid colors (i.e. it isn't pure white itself).

Apart from that, I've tried every combination I've seen. I've tried using sampler2D rather than sampler, fillTexture.Sample rather than tex2D, even compiling with ps\_4\_0\_level\_9\_1 and level\_9\_3. I've tried using SamplerState rather than sampler\_state, binding registers, everything I can think of.

Any help would be greatly appreciated. Thank you :)

# Answer
> 4 votes
The problem is this: *the compiler optimizes the effect file*.

So in your code only ONE sampler is created. However in reality you are using TWO textures. The first one, being the *Texture provided as parameter* in your spriteBatch, the second one is the one you set as the `fillSampler` parameter. When creating 'test' code it is easy to overlook the fact that the first sampler plays a role as well.

The effect compiler optimises the HLSL code; it simply maps the first sampler to the S0 address. So what happens, is your code does not sample from the `fillSampler` but from the Rectangletexture you supply as parameter in the `spriteBatch.Draw()` method.

As a test; replace the texture in your `spriteBatch.Draw()` function by the one you wish to use as `fillSampler`; chances are you'll see the expected result.

How to fix this? Simple; add two samplers, the first one named `textureSampler` the 2nd one your `fillSampler`. Remember to use both in the PixelShader Function or it will be removed as result of the effect file optimization.

To summarize:

```
float4 spriteCol = tex2D(textureSampler, input.TexCoords); //reads 1st texture
float4 fillCol = tex2D(fillSampler, input.TexCoords); //reads 2nd texture

return float4(fillCol.r,fillCol.g,fillCol.b,spriteCol.a);

```

will result in a sprite being colored using the fillSampler, using the alpha of the spriteBatch texture.

Additional info:

```
float4 spriteCol = tex2D(textureSampler, input.TexCoords); //will be optimized...
float4 fillCol = tex2D(fillSampler, input.TexCoords);

return fillCol;

```

...wil return the color of the texture passed in the spriteBatch. Why? Because the optimizer will simply note that the `spriteCol` isn't required to calculate the end result and thus will be removed. This results in that the `fillSampler` will read from `S0` register- which is filled by the spriteBatch.

---
Tags: shaders, monogame, hlsl, fragment-shader, sampler-state
---


# Question
Title: How to avoid multiple draw calls when actors stack on top of each other?
I am writing a card game with multiple cards that will stack up on the unplayed deck, and also in player hands.

Currently I add all 100 card actors to the screen at the start to make it easier so I don't have to manage adding them when they are needed. They all start on top of each other and some get dealt out to players' hands, which are also just piles of cards. So in theory with a 5 player game there are only 6 cards visible, the deck and the top of each player's hand.

I'm hoping someone can tell me of a clever method to mean that only 6 draw methods get run on the actors that are visible, or do I have to manage all this myself?

If I do, would you suggest adding the actors only when I need them, or adding them invisible and then setting them visible when I need to?

Or another method?

# Answer
Best option is of course having one actor if one is visible on the screen, but the solution below could help you in the future. You can create your own class with a name `Card` or smth which will extend the `Actor` class.

After that you can create a variable in that class, for example:

```
private boolean isOnTop; // set it to false in constructor and create getters and setters

```

Now you can override the `draw()` method like this:

```
@Override
public void draw(Batch batch, float parentAlpha){
   if(isOnTop)
        super.draw(batch, parentAlpha);
}

```

Now, when you create your 100 Card objects, you can set one of your cards to `isOnTop` and it will be drawn. I hope you get the idea!
> 1 votes

---
Tags: libgdx, culling
---


# Question
Title: How do I combine mesh to all move together with an armature?
I can't figure out how to make all these parts move together. I joined them, however, they are still separate? How do I make my model move its parts together?

# Answer
First: because you joined different objects that are now part of the same mesh, you have useless vertices. The fact that these vertices arent connected might create small gaps in your mesh during animation. I would suggest fixing this by either using 'remove doubles' or doing so manually in case remove doubles doesnt do the trick.

Second: weight painting should fix the problem.

1 of the many videos you can find on the subject: https://www.youtube.com/watch?v=5MJPq4k\_aU4
> 1 votes

---
Tags: 3d, blender, mesh
---


# Question
Title: Adjust Line Renderer start position to follow bone rotation
I'm trying to make my first game in Unity and I want a line renderer to draw from the end of a turret's gun barrel. The problem is I'm rotating 2 bones in the turret to make it look at the enemy. I've used the bounding box of the turret to calculate the offset from the turret's origin to the end of the gun barrel. But when the turret rotates this position is obviously wrong. How can I calculate the correct starting point for the line renderer after performing a rotation?

Here is the code for the rotation and the line renderer:

```
void Start () {
    enemyManager = GameObject.Find("EnemyManager").GetComponent<EnemyManager>();
    lazerLine = GetComponent<LineRenderer>();

    platform = transform.root.Find("Armature/BaseBone/PlatformBone"); //Get the root transform of this turret (I.e. the turret itself, not the gun barrel)
    gunBox = transform.root.FindChild("Armature/BaseBone/PlatformBone/LowerArmBone/UpperArmBone/GunBoxBone");

    gunBounds = transform.parent.GetComponent<SkinnedMeshRenderer>().bounds.size; //Get the bounding box of the turret
}

void LateUpdate()
{
    Vector3 lookAt;
    Quaternion platformRotation;
    Vector3 gunLookAt;
    Quaternion rotation;

    if (enemiesInRange.Count > 0)
    {
        //Rotate Platform (The silver platform at the base of the turret)
        lookAt = enemyManager.activeEnemies[enemiesInRange[0]].transform.position - platform.position;
        lookAt.y = 0; //0 the Y axis to stop the turret tilting up or down

        platformRotation = Quaternion.LookRotation(lookAt);

        float rotateSpeed = 10.0f * Time.deltaTime;
        platform.rotation = Quaternion.Lerp(platform.rotation, platformRotation, rotateSpeed);

        //Rotate GunBox
        gunLookAt = enemyManager.activeEnemies[enemiesInRange[0]].transform.position - gunBox.position;

        rotation = Quaternion.LookRotation(gunLookAt);
        gunBox.rotation = Quaternion.Lerp(gunBox.rotation, rotation, rotateSpeed);

    }

    if (timer <= effectsDisplayTime)
    {
        Vector3 lazerStart = transform.position;
        //Adjust the lazer to draw from the default position of the top gun barrel (using the bounding box of the turret to calculate the position)
        lazerStart.y += (gunBounds.y * 0.85f);
        lazerStart.z += (gunBounds.z / 2) + 0.05f;

        //Adjust the lazer to follow the current rotation of the gun
/* ##### This is the part I need to add ##### */

        //Draw the lazer
        lazerLine.enabled = true;
        lazerLine.SetPosition(0, lazerStart);
        lazerLine.SetPosition(1, enemyManager.activeEnemies[enemiesInRange[0]].transform.position); //Of the enemies in range, shoot the first enemy that entered the turrets range

        effectsEnabled = true;
    }
}

```

Here are 2 picture to give you a better idea of what's happening.

This is with the rotation code commented out.

This is with the rotation code running.

# Answer
It might be simpler to use an empty gameobject on the tip of the barrel, with the head of your turret as its parent, and use that as a starting point for your line renderer.

EDIT: Final sollution (can be found in comments as well): Make an empty gameobject the child of the bone that controls the head of the turret. Use this as a startingpoint for the line renderer.
> 0 votes

---
Tags: unity, rotation
---