# Question
Title: How to make texture size correctly in THREE.js?
I'm new to THREE.js and I have a frustrating problem. I can't get my grass texture to size "normally" on the terrain.

I get it, the terrain is steep, but that doesn't mean the grass should be stretched as well!

I don't want the textures to scale, resize, stretch, or distort. I want the textures to render the same size as the original image. The image is 128x128, so why can't the texture be the exact same?

THREE.js doesn't allow me to make the texture repeat as much as it needs to fill the plane. It only lets me set a fixed number of "repeats." That's what most likely causes the distortion.

```
texture.repeat.set(10, 10);
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;

```

How can make the size of the texture not be affected by the size of the polygon it's on? If the image is 128x128, it should still be 128x128 on the terrain.

> **EDIT:** *Is it possible to use pixel coordinates instead of UV?*

# Answer
This isn't really a THREE.js problem (although THREE.js may limit your options for a solution); it happens with any terrain implementation of that type.

From the screenshot, it looks like you're using a regularly-tessellated grid of geometry where each vertex is mapped to a height map point. Such a grid generally generates triangles in a pattern, for example:

```
 A -- B -- C -- ...
 | \  |  / | \
 |  \ | /  |  \
 D -- E -- F -- ...
 |  / | \  |  /
 | /  |  \ | /
...  ...  ...

```

The triangle mesh generally maps UV coordinates to textures regularly along that grid (for example `A` may have UVs of `0,0` while `B` may have UVs of `1, 0`.

The grid is regular in the X and Y dimensions, but it's *not* regular in Z (which comes from the heightmap). This means while the similar edges in each cell are the same length prior to being displaced vertically by the height map, they probably *aren't* the same length afterwards. In particular, extreme elevation changes (like in your screenshot) create longer triangle edges.

Because the UV coordinates are regular, this means longer triangles "stretch" that texture over a longer physical region, resulting in the artifacts you see.

You can try to fix this by scaling your UV generation, but this will generally just make *small* terrain cells look muddy as your texture is compressed into a small space; it's not a good solution. It is not really possible to "use pixel coordinates" instead of UV coordinates to map the texture to the geometry, as you asked in on of your edits. That's not how the 3D pipeline works.

There are solutions though. Common ones include:

* adaptive tessellation of the grid; you can "peek" at the height map values for a cell and its neighbors and if the height differential is above a threshold you set, try to split that cell into smaller cells, adjusting UV coordinates proportionally. This can be tricky, because you want to make sure all the seems line up well and need to avoid creating unlinked T-junction constructs.
* decals or similar detail texture splatting; use these to simply cover up the stretched terrain like you might patch a hole in a shirt.
* props or other 3D meshes. Terrain with those kinds of elevation differentials rarely looks like that, with the grass just wrapping down around it. Often there are rocks there, or a dirt bank with old tree roots or whatever sticking out.
> 5 votes

---
Tags: 3d, textures, image, uv-mapping, three.js
---


# Question
Title: How are the positions of skinned mesh vertices with multiple weighted parents stored?
I'm trying to wrap my head around the basics of skinning and skeletal animation. I understand not every skeletal animation implementation works exactly the same, but I'm just trying to understand the generally accepted practice.

I'm not sure if I used the correct terminology for my question, but my issue is this - if I have a vertex with a single bone as a parent, I can just store the local coordinates to the parent.

So if my parent bone is at any random location and the vertex is located exactly where the parent bone is, I would store it's x,y location as 0,0. If it were to move the vertex down the length of the bone parallel to it, regardless of the parent bone's angle and location, the local x value for the vertex would increase and the y would stay the same. This makes sense, and the math to get from any arbitrary point in world space to that local position to it's parent is also very straightforward. This position local to the parent also seems like the ideal way to store the vertex information for any given vertex with a single parent bone.

My question is if the vertex has multiple weighted parents, what xy location is stored? Would I need to store the relative coordinates to each parent for each vertex, or is there some way to store a single coordinate that represents it's weighted position relative to all parents? And if the math isn't simple enough to be explained here, what is the math required to get this multi-weighted relative coordinate called so I can go find more information?

# Answer
A skeletal animation consists of three things, really: the bones, the skin, and the animation itself.

The bones form a "skeleton," a rig which is a crude representation of the overall thing being animated. A stick figure version, essentially. Every bone has a *single* parent except for the root bone, which is an orphan.

The animation drives the skeleton. An animation is essentially a collection of transformations to apply to each bone to move the stick figure in the desired fashion.

The skin is the actual vertices of the mesh in question. Every vertex is weighted to some collection of bones. The weight determines how much influence each bone's position has on the vertex position.

Each bone contributes to the vertex first in isolation. That is, the vertex is transformed into bone space, transformed per the bone's current transform (based on the current animation frame's impact on the skeleton), and back into mesh space. This yields, as you note, a position. For the sake of this discussion, call this an "intermediate position."

This is done for each contributing bone. The final resulting vertex is generally a simple linear combination of the intermediate positions based on the associated weight. That is, a vertex with weights (0.1, 0.2, 0.7, 0) against bones (1, 9, 2, 15) is 10% of bone 1's intermediate position, 20% of bone 2's, 70% bone 3's, and bone 15 has no influence since its weight is zero.

That final combined position is what is rendered.

The position of the vertex relative to the parent bone doesn't *need* to be stored. It's directly computable from the position of the vertex in bind (basically model) space and the bone in bind space. All you need is the vertex's bind space position, the four bone weights, the four bone indices, and the transformations for each bone (which the bone indices index into).
> 2 votes

---
Tags: skeletal-animation, vertex, mesh, skinning
---


title: How do engine sounds for vehicles work?

text:
# Question
Title: How do engine sounds for vehicles work?
How does the engine sound for a car (or whatever has an engine) work?

When you increase the throttle the engine sound changes but it's never quite the same. When programming such a system what is the high level view of how it works. I know that there is some looping involved in the sound files but how do you transition when for example you change gear or you increase/decrease the throttle? How would one go about getting and preparing the sound files?

# Answer
That's such an interesting topic, I definitely want to implement that one day, and I have given it random thought for many years.

I imagine that I would create a little library of base sounds. That is at least 3 sounds.

1. auto-rotation sound (drive by momentum).
This would be the sound the engine makes when not injecting gasoline (thrust pedal fully released).
2. injection sound.
That would be the sound of the engine when thrust is applied, or at least the component that we can add-mix over sound 1.
3. turbo sound.
that's a whistling sound caused by the high revs of the turbo blades which can be heard only from about 3500rpm and when gas are applied.

All 3 would have to be "tileable" like a texture, and last a very short amount of time. I guess about 350ms.
The playback will have to mix these sounds using weights according to real time driving condition, and all sounds will have a playback speed that is a linear function of RPM. (turbo is not linearly bound to main RPM but turbine RPM rather).

So anyway, a library that allows pitch/play speed adjustment is needed, and mixing.

Of course for cosmetics, 2 things on top:
1. doppler effect when using external camera
2. muffling when using in-cabin camera

the muffling could be low pass filter or something of the like.
> 0 votes

---
Tags: audio, sound-effects, vehicle
---


# Question
Title: Changing some color of a texture using C# in Unity
It's almost 2 days that I'm looking for a way to do this in **Unity** using **C#**, but still no luck.

Imagine you have a texture with different colours (this texture can be a rug), and you just want to change the colour of the parts that you click on it. e.g. I click on blue and the blue part turn into yellow. take into consideration that the parts we click on it are irregular.

The images are png, but created in Photoshop using different layers. for example, in the following texture, we have 2 colours of pink and purple. if I click on purple I want it to become yellow, and if I click on pink I want it to become green

How can I do it in Unity C#?

Thanks for all your helps.

# Answer
You actually have two problems here. Problem A: how do I find image pixels to change? Problem B: how do I change specific pixels in Unity with C#?

As it happens, problem B is straightforward: you use `Texture2D.GetPixels` to read an array of pixel colors, change those colors and call `Texture2D.SetPixels`, followed by `Texture2D.Apply`. A couple caveats: first, make sure the texture in question is readable (i.e. it has "Read/Write Enabled" checkbox set in import settings). Second, this method is quite slow, and can cause a noticeable hitch with a large-ish texture. The faster way is to work with shaders.

Problem A is harder to solve, especially since you don't state your requirements here. When you click on blue, do you need to change *all* blue pixels, or a region of blue pixels? Do you need to change *exact* color, or do you handle halftones and transitions too? And if so, *how* do you handle them?

The most trivial case is when you just switch all pixels of an exact color. Then you can just go

```
var colors = myTex.GetPixels();
for(int i=0; i<colors.Length; i++)
    if(colors[i]==clickedColor)
        colors[i]=newColor;
myTex.SetPixels(colors);
myTex.Apply();

```
> 2 votes

# Answer
Make each of these coloured blobs a seperate gameobject with a spriterenderer. Have the blobs saved as white or grayscale only.

Then, just apply the color you want in your SpriteRenderer. It will draw that blob at whatever color you want, and you can easily change the color programatically.

```
entity.GetComponent<SpriteRenderer>().color = new Color(0.5f, 0.5f, 0.1f, 1);

```
> 1 votes

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


title: C++ class hierarchy issue

text:
# Question
Title: C++ class hierarchy issue
I am taking the step of moving on from Java over to c++, I have been working on my own custom game engine in java for a while so have a good understanding of polymophism, inheritance etc.

**Now to the issue:**

Currently I am working on a basic level format trying to get entities to render to the screen, this all goes well if i change the code to what i don't want it to be below is the code:

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

#include "Layer.h"

class TileMap: public sf::Drawable, public sf::Transformable {
private:
    std::vector<Player> entities;
public:

    Player* addEntity(Player player) {
        entities.push_back(player);
        return &entities[entities.size() - 1];
    }

    void update() {
        for (unsigned int i = 0; i < entities.size(); i++) {
            entities[i].update();
        }
    }

    virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const {
        for (unsigned int i = 0; i < entities.size(); i++) {
            target.draw(entities[i]);
        }
    }

};

```

The player that is returned in the function is then stored in a DrawableEntiity\* player; variable. & this works fine everything updates

As I want a generalized list of entities and not a list for each entity i add to the game i want to be able to change this from

```
std::vector<Player> entities;

```

and change it too (obviously including the include for it too)

```
std::vector<DrawableEntity> entities;

```

The issue is everytime i store it this way the draw and update functions of the lower level Entity class isn't called and instead the default function inside of the DrawableEntity is called.

This is probably a easy mistake on something I've overlooked but i can't find anything online anywhere that fixes the issue. a full code listing of the Entity classes can be found at http://pastebin.com/3rRuzZHs

Thanks for taking your time to read this Jordan

P.S: If you need any more information let me know.

# Answer
When storing items of a child class in a vector, the vector will call the father's constructor (constructor of the type the vector was appointed to.)

To avoid that, you'll want a vector of pointers instead:

```
 std::vector<DrawableEntity *> entites;

```

For this approach you will likely have to dynamically allocate your entities manually using, say, the *new* keyword of course.
> 0 votes

---
Tags: c++, sfml, eclipse
---


title: AddComponent with string in unity5

text:
# Question
Title: AddComponent with string in unity5
At runtime I want to copy one Gameobject component to another gameobject. In my case I have one camera where multiple scripts are added with values settings.

the same components i want to add into my antoher camera at runtime i have tried this so far, Getting all compoenent of an object then tryting to add but it is not working.

```
Component[] components = GameObject.Find("CamFly").GetComponents(typeof(Component));
            for(var i = 0; i < components.Length; i++)
            {
               objCamera.AddComponent<components[i]>();
///error in above line said adds a component class named/calss name to the gameobject

            }

```

# Answer
> 2 votes
Well, AddComponent's generic parameter expects a type, not a string. AddComponent actually creates an entirely new component of the given type. As far as I know there is no way to get unity to add a new component AND copy the values from another.

However, what you seem to be doing is copying ALL the components of one game object to another. If appropriate, I'd recommend just using GameObject.Instantiate, which creates a copy of an entire game object, including all it's components.

If you really need to copy components without creating a new game object, there's an answer here:

http://answers.unity3d.com/questions/458207/copy-a-component-at-runtime.html

# Answer
> 0 votes
The main issue here is that you're trying to call `AddComponent` with an object rather than a type, which is what's causing your issue. There are 3 possible ways you can fix this:

**Solution 1**
*Use AddComponent with a generic function*

This is very close to what you already have, and only requires you to use `GetType` rather than the object itself

```
Component[] components = GameObject.Find("CamFly").GetComponents(typeof(Component));
for (var i = 0; i < components.Length; i++)
{
    objCamera.AddComponent<components[i].GetType()>();
}

```

**Solution 2**
*Use AddComponent with a type as a parameter*

Very similar to the first solution, but uses `GetType` as a parameter. If you were using the return value, then you'd notice that the type returned here is `Component`, whereas the solution aboves return type is whatever you pass in to the generic function

```
Component[] components = GameObject.Find("CamFly").GetComponents(typeof(Component));
for (var i = 0; i < components.Length; i++)
{
    objCamera.AddComponent(components[i].GetType());
}

```

**Solution 3**
*Use AddComponent with a string argument*

Again, this relies on `GetType`, but uses a string instead of the type object. I haven't tested this, and my gut says it will be the slowest solution (because Unity will need use reflection to find the type you want), but is here so you can see the possible uses

```
Component[] components = GameObject.Find("CamFly").GetComponents(typeof(Component));
for (var i = 0; i < components.Length; i++)
{
    objCamera.AddComponent(components[i].GetType().ToString());
}

```

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


title: How should my creatures see the world?

text:
# Question
Title: How should my creatures see the world?
This may not be the best forum for this question, but I know a lot of you have dabbled in the field of general AI for games so here it is.

I'm doing the cliche population evolution of creatures in a simulated ecosystem (with some cool irrelevant twists) where each creature is its own neural network. Specifically, I'm using the NEAT algorithm to evolve creature brains over generations.

My problem is that I can't figure out what to feed as input to the creature neural networks. I haven't found any relevant literature on it either.

The world right now is composed of prey/predator creatures and grass for the prey to eat. I want all creatures to see all three objects (prey, predators, and grass). The other important point is that the populations are not fixed. Prey can become endangered, grass can become limited, etc.

Initially I was going to have a list of all objects as relative positional vectors within a radius of a given creature as input, but variable sized inputs are basically a no go for neural networks. My second idea was just show everything in the scene (even if it may be a sensory overload), and when an object dies just replace it with a -1 hot vector. But that would just confuse the ANN.

I'm out of ideas and flailing in the water. Any thoughts are appreciated.

# Answer
A tutorial for "Enemy Sight" exists in Unity's documentation, here

Basically, it uses Raycasts to detect the presence of other objects within a certain radius. This is a simple but effective approach that will tell your creatures where everything is and also what it is.

The other approach (one that I have used in the past) is to create / obtain a cone mesh. The mesh is used to create a collider that is set to be a trigger zone. This results in a *vision cone*, and when an object moves within this *vision cone*, Unity calls OnTriggerEnter(), which is where you can put your logic of what the AI does when it encounters a particular entity.
> 0 votes

---
Tags: unity, ai, simulations
---


# Question
Title: Did they remove Sprite sorting layers from Unity?
I can't figure out how to set it. I thought it was a setting on the sprite renderer but it doesn't seem to be there? Google isn't turning up any results.

# Answer
Top right of the inspector right next to the little lock icon -\> select normal. You should now see the sorting layers and order.
> 4 votes

---
Tags: unity, sprites, sorting
---


title: Check if thread has OpenGL context

text:
# Question
Title: Check if thread has OpenGL context
I'm looking for a way to check if a thread accessing a namespace function has a OpenGL context attached to it. I have looked around and all I can find is,

```
GLFWwindow* glfwGetCurrentContext();

```

Which will return NULL if there is no context, but is there a better way?

I'm using OpenGL 4.5 and GLFW 3.2

# Answer
> 2 votes
As far as I know that's the best solution to check if there is an active context.

---
Tags: opengl, c++, multithreading
---


# Question
Title: How to render more than one object in OpenGL or DirectX 11/12
https://www.youtube.com/watch?v=1ogg4ZfdBqU I am new to OpenGL, but I have similar objective as you can see in the video. Can we have one shader for all objects? Is there any sample in OpenGL? Any help will be very much appreciated.

# Answer
> 0 votes
You can have one shader for refractive/reflective objects and one for objects that have different materials (different textures and surface properties) or you can have one big shader (uber-shader) that will determine in runtime (via uniforms) how the object should be rendered.

There is a bunch of tutorials. The best one, in my humble opinion is this one: http://learnopengl.com/.

---
Tags: opengl, directx11
---


# Question
Title: What's wrong with my food generating code?
This script is intended to produce amount of (food) objects for the players over the network. What should happen is that when a player eats one food, another food object gets created in another random place. Somehow it doesn't do that.

Here's the script.

```
 public class FoodManager : Photon.MonoBehaviour {

 [SerializeField] GameObject smallCirclePrefab;
 [SerializeField] float widthOfBoard = 100;
 [SerializeField] float heightOfBoard = 100;
 [SerializeField] int amtOfSmallCircle = 100;
 [SerializeField] int sizeOfCircle = 5;
 // Use this for initialization
 void Start()
 {
    if(PhotonNetwork.isMasterClient)
    produceSmallCircle(amtOfSmallCircle);
 }
 // Update is called once per frame
 void Update()
 {
 }
 void produceSmallCircle(int n)
 {
     Vector2 position;
     GameObject circle;
     float positionX, positionY;
     int ratioOfSize = 5;
     for (int i = 0; i < n; i++)
     {
         positionX = Random.Range(-widthOfBoard / 2, widthOfBoard / 2);
         positionY = Random.Range(-heightOfBoard / 2, heightOfBoard / 2);
         position = new Vector3(positionX, positionY,0);
         circle = PhotonNetwork.InstantiateSceneObject(smallCirclePrefab.name, position, transform.rotation, 0,null) as GameObject;
         circle.transform.localScale = new Vector3((float)sizeOfCircle / ratioOfSize, (float)sizeOfCircle / ratioOfSize, (float)sizeOfCircle / ratioOfSize);
     }
 }

 }

```

and here's the other script

```
 using UnityEngine; using System.Collections;

 public class FoodCollision : Photon.MonoBehaviour {

 public static float amtOfIncreaseSpeed = 1f;
 public static float amtOfIncreaseHealth = 1f;
 public static float ratioOfSpeed = 150.0f;
 public static float increaseSize = 0.001f;
 PhotonView photonView;
 BoxCollider2D boxCollider;
 SpriteRenderer sp;
 void Awake()
 {
     photonView = PhotonView.Get(this);
     boxCollider = GetComponent<BoxCollider2D>();
     sp = GetComponent<SpriteRenderer>();
 }
 // Use this for initialization
 void Start()
 {
 }
 // Update is called once per frame
 void Update()
 {
 }
 public void DestroyGO()
 {

     photonView.ownerId = PhotonNetwork.player.ID;
     boxCollider.enabled = false;
     sp.enabled = false;
     photonView.RPC("DestroyRPC", PhotonTargets.MasterClient);

 }
 [PunRPC]
 void DestroyRPC()
 {
     PhotonNetwork.Destroy(gameObject);
 }

 }

```

# Answer
> 1 votes
I'm not sure how your code is failing (you only say it doesn't do the right behavior, not what the actual observed behavior is), but I can see what looks like two issues. A better explanation of what is actually happening would help a lot.

One, you don't have any code to react to the collision. If the food is not being consumed when the player hovers over it, it is because you don't have any OnTriggerEnter or OnTriggerStay (or OnCollisionEnter/OnCollisionStay depending on if the collider is a trigger type or not) calls to actually cause the food consumption to happen. You need these event methods for the BoxCollider to do you any good. That's where you would call DestroyGo to remove the eaten food.

Two, it looks to me like you don't have anything that would create a new food object when the old one is removed.
Assuming that DestroyRPC/DestroyGO is called by something in a collider event as above or some other script that isn't included, you need to call produceSmallCircle on your FoodManager to generate a new one when the old one is eaten.

---
Tags: unity, networking, photon
---


# Question
Title: Correctly creating/handling events for keypress in MonoGame C#
I'm having trouble finding the best approach to registering an instantaneous user key-press with MonoGame (where the key has been held down and then released), using events in C#. Unlike the click of a mouse button where only two events are usually required, it seems to me that a keyboard would require a considerable number of events where it would seem infeasible (and incredibly messy) to declare them all. I don't want to have classes individually handle the input themselves by checking the current keyboard state against the last etc.

This is the solution I've come up with, but something tells me it isn't very well designed.

```
public static class Input
{
    private static KeyboardState ks, ks_old = Keyboard.GetState();

    private static Dictionary<Keys, List<Action>> OnKeyPress = new Dictionary<Keys, List<Action>>();

    public static void AddKeyPressHandler(Action handler, Keys key)
    {
        if (!OnKeyPress.ContainsKey(key))
            OnKeyPress.Add(key, new List<Action>());
        OnKeyPress[key].Add(handler);
    }
    public static void Update() //Update function called every game update
    {
        ks = Keyboard.GetState();

        foreach (Keys key in Enum.GetValues(typeof(Keys)))
            if (!ks.IsKeyDown(key) && ks_old.IsKeyDown(key) && OnKeyPress.ContainsKey(key))
                foreach (var handler in OnKeyPress[key])
                    handler();
        ks_old = ks;
    }

}

```

With the current setup, objects needing to handle a key-press subscribe their methods in the following way in their constructor:

```
Input.AddKeyPressHandler(delegate() { Input_OnAPress; }, Keys.A);

```

What is the optimal way to handle keyboard input with MonoGame? Are there any obvious pitfalls with my code, functionally or design-wise?

# Answer
For all intents and purposes what you have is essentially the Observer pattern in that you have an input class that maintains a list of callbacks or input handling objects. Other objects can then register with the input system to be notified when certain things happen(in this case when each key has been pressed).

I might extend this system to allow users to also register for when a key has been released as opposed to just when a key has been pressed; to allow you to do this if might be worthwhile keep some class that would be updated that maintains the current state of the key press/release. This could also be made more generic to allow us to do the same for mouse presses, gamepad presses etc.
> 1 votes

---
Tags: c#, xna, monogame, events, keyboard
---


title: How to slow down this rotation

text:
# Question
Title: How to slow down this rotation
My goal here is simple. I am making a top down shooter kind of game, and I want the player to simply rotate in one axis, towards where the mouse is on the screen. I got it working, but it rotates so fast that everything is out of control. The following method is called in Update() on my player's game object

```
void RotatePlayer()
{

    var targetPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 100);

    targetPosition = Camera.main.ScreenToWorldPoint(targetPosition);

    targetPosition.y = transform.position.y * Time.deltaTime;

    transform.LookAt(targetPosition);

}

```

That rotates in the direction of the mouse, but like I said it rotates so fast that you cannot control it.

As you can see I tried to multiply by delta time, but that did not seem to do anything. Also, changing that last parameter of "100" to a lower number also does not do anything.

Any help is greatly appreciated.

# Answer
> 1 votes
Add a `float rotateSpeed` variable from `0.00f` to `1.00f` and multiple your `targetPosition.y` by that after `Time.deltaTime`.

I can't test this right this very moment, but I'm fairly certain that should work.

# Answer
> 0 votes
I have found another way to do this,

```
void RotatePlayer()
{
    var xDeg = Input.GetAxis("Mouse X") * m_TurnSpeed;

    transform.Rotate(0f, xDeg, 0.0f);
}

```

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


# Question
Title: What is the "TangentsW" attribute inside the FBX file format for?
sometimes it is -1, sometimes is +1. Do I need it for the rendering of the normal maps?

# Answer
> 0 votes
Looks like the tangent handedness that's needed for proper normal mapping. It can be used for calculating the bitangent for TBN matrix. Example in GLSL: `vec3 bitangent = normalize( normalMatrix * (cross( aNormal, aTangent.xyz ) * aTangent.w) );`

---
Tags: fbx
---


# Question
Title: Virtual game dimensions - how to implement?
I'm creating a fighting game in LibGDX with a static board, camera moves only right\<\>left.

There are 5 screen aspect ratios in Android and Apple so I have created 5 different background graphics:

* 2560x1440 16:9
* 2560x1920 4:3
* 2700x1800 3:2
* 3000x1800 5:3
* 3200x2800 8:5

Each background width is multiplied by 1.5, cause I need to zoom-out the game when players are too far away from each other, so for example 16:9 isn't 2560x1440 but 3840x1440. (I just realised that I should expand the height too LOL, gamedev is a fantastic place).

When I load the background I check the screen size and scale the background to fit.

The thing I need to implement is: Virtual Coordinates which are the same for each device.

Let's get the screen below:

I need to set virtual board dimensions to for example 2000x1000 units/meters whatever.

When the server sends a message: Spawn a bomb on (1000,1000), left device spawns it at x=512, right device at x=960 (both on the half).

I think working on pixels is a bad idea, cause I would need to calculate things with each move, jump etc.

If someone could help me, how should I achieve this, I would be grateful for pointing me a way.

Thanks!

# Answer
> 2 votes
Take a look at Viewports. Many of the `Viewport` subclasses take virtual height and width in their constructors. There are different flavors of viewport depending on how well you want Libgdx to keep to your desired aspect ratio.

---
Tags: libgdx, camera, coordinates
---


title: How to merge two objects in Blender

text:
# Question
Title: How to merge two objects in Blender
## What I've Done

1. I created a **Cube** object **with Subdivision Surface modifier** in order to model a spehere.
2. I created a cuboid object looking like a angled, longish baton.

## What I Want to Do

I want to merge these two objects. So I want to have got just one object - a (cube locking like a) sphere with a baton sticking out on one side. It should look a bit like a head with a throat attached at the bottom.

## How I Want to Do It

* **I don't want to apply the Subdivision Surface modifier** \- I want to be able to edit my object later on nicely.
* I don't want to have any space between the baton and the sphere. It should be coherent.
* It should be possible without any bad artifices. Everything should be nice.

## My Question

How can I **merge these two objects** nicely? Thanks. - I hope it's clear what I want to describe.

# Answer
> 35 votes
On each object you will choose one or more faces that will be removed. In between these faces will be your connection.

* Select both objects in object mode. Press `Ctrl+J` to join the objects into one. Then enter edit mode and change to face manipulation mode.
* Remove the faces that will be joined. Select them and press `X`, remember to delete faces, not vertices.

* Switch back to Vertex manipulation mode. Join the objects by selecting the corresponding vertices from each object and using `F` to create a new face. For example, in the image below I've selected two of the vertices on the sphere and one on the cuboid. When I press `F` Blender will create a new triangle face there. It also supports quads if the vertices share a common plane. I typically limit the vertex selection to three or four vertices at a time, I tend to think I know where I want the faces to be better than Blender. But you can try selecting all the vertices and see what Blender does for you.

* Continue the previous step until all faces are joined.

# Answer
> 6 votes
If the result in the image satisfies you, here's how I achieved it.

1. Subsurfed the initial cube once
2. Created a second cube and scaled it
3. Added a `boolean` modifier to the first cube and chose `union`
4. Selected the second cube as the modifier target object
5. `Ctrl+P` Set the first cube as parent of the second so that both move together when moving the first cube
6. `Tab` Entered edit mode on the second cube, `A` selected everything and on the `N` properties panel I set `Mean Crease` to 1. This makes the second subsurf (see step 8 below) "ignore" the baton
7. `H` Hid the second cube. Some times this causes the modifier to get confused and the baton hides altogether, but moving the first cube should refresh the view.
8. Added a second `subsurf` below the `boolean`. This actually merges the object so that your second requirement is fulfilled

---
Tags: 3d, models, blender, 3d-meshes
---


# Question
Title: Irrlicht engine game wont compile on linux. Undefined refrences(opengl and xfree)
I'm trying to port over my game I'm developing to Linux. But when i compile i get a lot of undefined references to mostly functions that look like they belong to OpenGL. Most are titled gl... But one of them is called XFree.

I compiled it with this command:

```
g++ main.cpp -L../../../LIB/irrlicht-1.8.3/lib/Linux/ -lIrrlicht -I../../../LIB/irrlicht-1.8.3/include/

```

one of the errors:

```
/home/owner/LIB/irrlicht-1.8.3/source/Irrlicht/COpenGLDriver.cpp:3746: undefined reference to `glVertex3f

```

# Answer
> 0 votes
For future people running into my problem i found the solution. I was able to compile my project with this.

-w is for removing warning its optional. I also found you need to link with -lXxf86vm

```
g++ main.cpp -w -I../../../LIB/irrlicht-1.8.3/include/ -L ../../../LIB/irrlicht-1.8.3/lib/Linux/ -lIrrlicht -lGLU -lGL -lX11 -lXxf86vm

```

# Answer
> 1 votes
You'll need to install development libraries for OpenGL and X11. You didn't state what distro you're using, but in Ubuntu OpenGL development library is in package `libgl1-mesa-dev`.

---
Tags: opengl, linux, irrlicht
---


# Question
Title: 2d block based game storing water simulation
I am making a 2d block based sandbox game like terraria.

I'm trying to think where is the better place to store water in, data structure wise.

That is, to store it in the block world array, or to store it in its own sparse data structure. Does doing this have any benefits?

If I store it in the world array I have to store the fluid level (which would be like 16 levels possible). The other way I could simply have a fluid cell struct or something.

It might make things more clear separating it, but not sure if it would possibly affect performance either way.

In a game like this, the simulation is of course usually done via cellular automata (just in case that affects which data structuring I should use)

# Answer
Gonna go with manipulating bits to store it in the world array like most do. We'll see if it has its trade offs
> -1 votes

---
Tags: simulations, block-world
---


# Question
Title: Should I load scenes from files, or hard code them?
In a game engine I'm working on, I'm using scenes similar to what you would find in Unity. The entities, in my game, are composed of reusable components and custom data which is linked to those components. Entities have children, and one parent. This is shown, below:

```
class Entity {
    ...custom data here...
    let parent : Component
    var children : [Component] = []
    var components : [Component] = []

    ...methods...
}

```

---

If the entities did not have custom data, then creating a scene would be described by the following steps:

1. Loading a file into memory.
2. Creating a tree of entities.
3. Adding components to them, with parameters listed in the file.

However, this does not leave room for custom data. My other alternative is to create a scene by creating a scene object, then hard-coding the entities in. It would look something a bit like this:

```
var opening_scene = Scene()

opening_scene.addEntity(Player())
opening_scene.addEntity(Car())
opening_scene.addEntity(Terrain())
...

```

The downside to this is that everything is hard coded. What can I do to create scenes in a game more efficiently?

# Answer
Game Coding Complete book addressing exactly this problem,where the engine architecture is entity component data driven,so in chapter 6 "Game Actors and Component Architecture" where here "Actor" is the same as entity,the writer says:

"All actors are defined with an XML data file. This data file allows you to def component configuration and any default values for that component. Here’s s sample XML for an actor......Keep in mind that these actor XML files define the template for a type of actor, not specific actor instance. There can be many instances of this actor running around, each with completely different sets of data within their components. The XML file onl defines the definition. You can think of it as defining a class for this type of actor."

then he create a factory method to create all components at runtime , the book is full explanatory for all areas of game engine programming and it contains full engine source , and a game
> 1 votes

---
Tags: entity-system, level-design
---


title: Object is moving more than it should

text:
# Question
Title: Object is moving more than it should
I have the following code for Food:

```
exports.Food = function(x, y) {
this.MOVE_X_FROM_POSITION = 10;
this.ACCELERATION = 0.05
this.image;
this.firstX = x;
this.firstY = y;
this.x = x;
this.y = y;
this.width = 10;
this.height = 10;
this.velocity = {
  x: 0,
  y: 0
}
this.acceleration = {
  x: this.ACCELERATION,
  y: 0
};
this.render = function(ctx) {
  if (typeof this.image != undefined) ctx.drawImage(this.image, this.x - this.width / 2, this.y - this.height / 2);
  return this;
}
this.update = function() {
  this.velocity.x += this.acceleration.x;
  this.velocity.y += this.acceleration.y;
  this.x += this.velocity.x;
  this.y += this.velocity.y;
  if (this.x >= this.firstX + this.MOVE_X_FROM_POSITION) {
    this.acceleration.x = -this.ACCELERATION;
  } else if (this.x <= this.firstX - this.MOVE_X_FROM_POSITION) {
    this.acceleration.x = +this.ACCELERATION;
  }
}

```

... and so on

I want the food to move 10 steps from it's first location one side and 10 steps the other side. The problem is that if the script is running longer it becomes to move far more than 10 steps from it's original position. PS: update function is called in the loop every 30 times per second

Where could be the problem? Thank You in advance

**EDIT**

Here is actually a demonstration of my problem: https://jsfiddle.net/02jbmxnw/1/

# Answer
> 0 votes
You start in the middle, and move to the edge, until x \<= 80, at which point you flip the direction of acceleration. Then you move to the opposite edge, until x \>=100, and you flip the direction of acceleration.

The cause of the problem is this: In the first run, you move from the 10 units from the centre before reversing. That means you have a runway of 10 units over which you are accelerating, with very little overshoot.

Then, you accelerate in the other direction until you hit x\>=100, so you have a runway of 20 units over which you are accelerating. This means that when you hit X\>=100, you're moving faster, and risk overshooting in that frame by a greater amount

So, the total runway each time you reverse, after the first, is 20units + overshoot. Since the runway is increasing each time, the top speed is also increasing, and thus the overshoot is increasing. This is a vicious cycle.

So, thats the problem. The solution will depend on the behaviour you want. For a very simple solution, cap the velocity at a certain point:

```
requestAnimationFrame(function loop() {
    velocity += acceleration;

    if(Math.abs(velocity) > maxVelocity){
        velocity -= acceleration;
    }
...

```

https://jsfiddle.net/vm1zz62k/

# Answer
> 0 votes
When you hit the boundaries, you change the direction of the acceleration, but you do not set the velocity to 0. That means at the boundaries, the food will continue to move in the same direction, but slower and slower until it changes directions (when it's far past the original boundary).

I assume you want the swaying effect from acceleration, but if you don't, you can simply set the velocity to 0 as I've done here: https://jsfiddle.net/02jbmxnw/3/

If you do want the swaying effect from acceleration/deceleration, I recommend scaling the food's velocity from 100% to 0% (to -100%) based on the distance from it to a boundary (or its position between the boundaries).

Sorry if that was a bit confusing. Hope it helped though.

---
Tags: javascript
---


# Question
Title: Will Chartboost block my account for clicking my own ads?
I created a game in iOS and Android. Every day I manually click ads in it from my device.

Is this okay? Or can Chartboost block my account if I do this for a long time? I've been doing it for the last 15 days and haven't received an email from them about it yet.

# Answer
The Chartboost TOS says, in part:

> You will not, and will not allow any third party to... directly or indirectly generate queries, or impressions of or clicks on ads, including without limitation Online Services Ads, through any automated, deceptive, fraudulent or other invalid means (including, but not limited to, click spam, robots, macro Online Services, and Internet agents)

It is quite likely Chartboost would consider your manually clicking on your own ads every day to be deceptive or otherwise in violation of this agreement. That means they could terminate your account or otherwise serve you with legal action.

In general this sort of thing (regularly clicking your own ads to generate artificial impressions) is a bad idea and you should not do it. They can terminate your account without notifying you:

> If You violate this Agreement, Chartboost may in its sole discretion, without notice, terminate this Agreement, or suspend or terminate the participation of Your Online Services App in all or part of the Online Services.

Just because you have not yet been *caught* yet doesn't make it okay.
> 7 votes

---
Tags: android, ios
---


# Question
Title: Interactive Controls (switches, knobs, buttons) in Unity
I'm working on a puzzle aspect of a game, and wanted to make a section where players relay information to one another, and have to input the correct values.

At its most basic, its a few stored variables that exist only for this, and really don't do anything. i.e. "Turn on shields" would just be a bool. "Set phasers to 5" an int. etc.

I'm trying to figure out the best way for a player to interact with these variables. I've considered GUI elements placed on gameobjects, but I'm not entirely comfortable with Unity's GUI system.

Should i take the time and use the GUI system, or would setting up my own scripts to edit the controls (toggle boxes, sliders, knobs) be a more simple solution?

Thanks in advance!

# Answer
This question can be considered opinion based so I'm going to give you my opinion. If you have some sort of deadline then go with the approach you feel more comfy with. But if you do not have a deadline I suggest that you take your time and learn how to use the UI system. After version 4.6 they made it way better and easy to use. Eventually you will have to use it in a project and its better to learn new stuff now than when you actually need it. Besides the UI system is incredibly powerful, I've made entire mini-games with it.
> 0 votes

---
Tags: unity, gui, control
---


title: Zoom camera on player

text:
# Question
Title: Zoom camera on player
I am developing a simple side scrolling game. I want to target and zoom camera on player when he dies. But it rotates the screen, and I want to prevent it. I'm copying the snippet of code here :

```
IEnumerator ZoomIn()
{
    while (GameCamera.orthographicSize > 2) {
        yield return new WaitForSeconds (0.01f);
        GameCamera.orthographicSize -= 0.2f;
    }
}

public void ZoomCamera()
{
    CameraZoomSource.Play ();
    StartCoroutine (ZoomIn ());
}

public void TargetPlayer()
{
    transform.LookAt (PlayerTransform);
    GameCamera.orthographicSize = 3;
    GameCamera.transform.Rotate (0, 0, -2);
}

```

Should I change anything in this?

# Answer
I've solved a problem with a simple logic. Now, When player dies, camera position will be set exact to the player position, thus focusing the camera on player. And after that the orthographic size of the camera will reduced to give it zooming effect. Here is code snippet :

```
IEnumerator ZoomIn()
{
    while (GameCamera.orthographicSize > 2) {
        yield return new WaitForSeconds (0.01f);
        GameCamera.orthographicSize -= 0.2f;
    }
}

public void ZoomCamera()
{
    StartCoroutine (ZoomIn ());
}

public void TargetPlayer()
{
    Vector3 TempCameraPos = transform.position;
    TempCameraPos.x = PlayerTransform.position.x;
    TempCameraPos.y = PlayerTransform.position.y;
    transform.position = TempCameraPos;
}

```
> 1 votes

---
Tags: unity, camera
---


# Question
Title: Tire mesh rotates faster than wheelcollider in Unity
I have a car in Unity. Scripts are C#. I have noticed that my tire meshes' rotation is faster than whellcollider rotation. I am using this code for wheel rotation

```
 flWheel.localEulerAngles = new Vector3(flWheel.localEulerAngles.x, flWheelCollider.steerAngle - flWheel.localEulerAngles.z, flWheel.localEulerAngles.z);
 frWheel.localEulerAngles = new Vector3(frWheel.localEulerAngles.x, frWheelCollider.steerAngle - frWheel.localEulerAngles.z, frWheel.localEulerAngles.z);

 flWheel.Rotate(flWheelCollider.rpm / 60 * 360 * Time.deltaTime, 0, 0);
 frWheel.Rotate(frWheelCollider.rpm / 60 * 360 * Time.deltaTime, 0, 0);
 rlWheel.Rotate(rlWheelCollider.rpm / 60 * 360 * Time.deltaTime, 0, 0);
 rrWheel.Rotate(rrWheelCollider.rpm / 60 * 360 * Time.deltaTime, 0, 0);

```

I found this from here

Does anyone know how to fix this?

Edit:

Using AquaGeneral's answer I could able to solve rotation problem. But now front right tire position changed to rear left tire position and rear right tire rotated 180 on Y axis. need help

# Answer
The code you found is not the ideal way to go about this. Instead of figuring out exactly what is causing the issue for you, just use the builtin function: WheelCollider.GetWorldPose.

From the official Unity Wheel Collider Tutorial in the `ApplyLocalPositionToVisuals` function/method:

```
// Get the child of the wheel that has the mesh renderer
Transform visualWheel = collider.transform.GetChild(0);

Vector3 position;
Quaternion rotation;
collider.GetWorldPose(out position, out rotation);

visualWheel.transform.position = position;
visualWheel.transform.rotation = rotation;

```
> 2 votes

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


# Question
Title: Creating SurfaceView cause short screen blink
When I create `SurfaceView` for first time since app launch, the app screen blinks black for small time (about 1/4 second). It blinks over UI, so its really visible and doesn't look nice at all. I've tried to comment all of my code in `surfaceCreated`, but effect is same, so problem is not here. How do I remove or "hide" this screen blink?

In activity:

```
RelativeLayout layout = (RelativeLayout) findViewById(R.id.relative);
layout.addView(new Surface(getApplicationContext())); // causes short screen black blink

```

Surfaceview class:

```
public class Surface extends SurfaceView implements SurfaceHolder.Callback
{
        public Surface(Context context)
        {
            super(context);

            getHolder().addCallback(this);
            this.setZOrderOnTop(true);
            getHolder().setFormat(PixelFormat.TRANSPARENT);
            setFocusable(true);
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
        {
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder)
        {
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder)
        {
              ... stuff
        }
}

```

# Answer
Alright, after 2 hard-thinking days I've found quite a good workaround. Didn't fixed that blink, but it's hidden very well. Here's how to:

Create another Surfaceview class, for example FakeSurfaceview.java. Keep same options for it as I mentioned in SF class in main post. In surfaceCreated, add `this.setVisibility(GONE);`

In you main layout (first layout when your app launches), create `RelativeLayout` with width and height 0dp.

```
<RelativeLayout
        android:id="@+id/setupRelative"
        android:layout_width="0dp"
        android:layout_height="0dp">
</RelativeLayout>

```

At app start, after you set view to your main layout, create this fake Surfaceview:

```
RelativeLayout setupLayout = (RelativeLayout) findViewById(R.id.setupRelative);
setupLayout.addView(new FakeSurfaceview(getApplicationContext()));

```

That's it. Now, creating this `FakeSurfaceview` will blink, but nobody will notice it because it'll create durring app start (best with combination of startup black activity color!). Then, when you create anytime another `SurfaceView`, no blink will apear. That's it!
> 1 votes

---
Tags: java, android, view
---


title: Card game - creating card Listener

text:
# Question
Title: Card game - creating card Listener
I am making a card game where there are 21 cards on hand and 2 options from where user can draw cards to his hand and throw a card from hand.

**I am new** on game development and I'm following the principle of MVC. Till now in my game I have a `InputHandler` class that handel the input. `GameWorld` and `GameRender` are two class which controll the game logic and render the game respectively. Both of these class are called by `GameScreen` class which extends Screen.

My question is how should I implement the **touchListener to these cards.** They are now just `sprites` and I have used `texture Packer` to create a `spriteSheet`

Doing research i have found that `Stage` and `Actor` are the things that I am looking for. Reading on **wiki** I found that these are useful to create menus. I've also read that working with stage and Actor is complex for **creating game environment and follow the rule of MVC.**

So, please anyone could guide me a way from where should I need to move forward. This is the very basic move that I need to move but I know if I did wrong here, i have to pay much more later.

# Answer
> 0 votes
You can assign a listener to each of these cards if they are actors.

You can create and enum with each card:

```
public enum Cards{

     ACE_HEART("ACE_HEART.png"),
     2_HEART("2_HEART.png"),
     3_HEART("3_HEART.png");
     //etc

    private final String name;
    Cards(String name) { this.name = name; }
    public int getValue() { return name; }
}

```

and you can create a class:

```
public class Card extends Actor{
    float width, height;
    Sprite cardSprite;

    public Card(Cards cardType){
        cardSprite = new Sprite(new Texture(Gdx.files.internal(cardType.getValue())));
        this.width = cardSprite.getWidth();
        this.height = cardSprite.getHeight();
    }
}

```

For example we have a Set with these cards (so they're unique):

```
Set<Card> allCards = CREATE AND ADD ALL OF THE CARDS

//assign listeners
for(Card card : allCards)
    card.addListener(new ClickListener(){
        @Override
        public void clicked(InputEvent event, float x, float y) {
            Gdx.app.log("Clicked card at", x + "   " + y);
        }
    });

// now create a list for the player
Set<Card> playersHand = new SomeSet<>();

// we take 10 random cards to his hand:
while(playersHand.size() < 10)
    playersHand.add(allCards.get(new Random().nextInt(allCards.size() - 1));

public void render(){
    batch.begin();

    for(Card card : playersHand)
        card.draw(batch, posx, posy); // you can increment posX with each iteration
    batch.end();

}

```

# Answer
> 0 votes
I don't how you want to implement what I gonna say, but in most 2d game engines we have something called `TouchListener` (or in general term `EventListener`) which can assigned to your card sprite (and many things else) and tell how should your game card handle touches.

I can bring you a piece of code which is for a Game Card that I wrote in cocos2d-x engine. I hope it clarify your understanding.

```
auto gameCardTouchListener = EventListenerTouchOneByOne::create();
auto allCards = deckList->GetAllCards();
for(int i=0; i<  allCards.size(); i++) // Assign a copy of touch listener to each card
    addEventListenerWithSceneGraphPriority(gameCardTouchListener->clone(), allCards[i]);
///
gameCardTouchListener ->onTouchBegan = [this](Touch* touch, Event* event)
{
    // onTouchBegan Call for All touch listeners ( in some sequence) when
    // player start to touch screen.
    // Here we check which listener ( and It's related game card) handle it ?!
    auto myGameCard = static_cast<GameCard*>(event->getCurrentTarget());
    Point touchLocation = touch->getLocation();
    If ( /*Touch is over my card, I handle it*/ ) {
        ...
        return true; // I decide to capture this touch
    }
    return false; // Let some card else check this touch. Not mine;
}
///
gameCardTouchListener ->onTouchMoved= [this](Touch* touch, Event* event)
{
    // What should happen when touch is moving
    // Maybe I should move this card where player is touching
}
///
gameCardTouchListener ->onTouchEnded =
gameCardTouchListener ->onTouchCancelled = [this](Touch* touch, Event* event)
{
    // What should happen when touch is over
}

```

# Answer
> 0 votes
Don't know about touch listener, but I can help you with polling based input. Here's how I'd handle input for the sprites

```
// assuming you have the input touch co-ordinates
if((touchX>= sprite.getPosition.x) && (touchX<= sprite.getPosition.x+sprite.getWidth()) &&
   (touchY>= sprite.getPosition.y) && (touchY<= sprite.getPosition.y+sprite.getHeight()))
   {

    //  Handle input
  }

```

Basically you need to check whether the touch point falls on the sprite's bounding rectangle Based on the image above I might suggest you use a rectangle for a card's visible area and check for touches on that area

---
Tags: libgdx, sprites, touch
---


# Question
Title: How does a 4x4 matrix represent an object in space and matrix lore?
I have been following some tutorials on how Matrix maths works, with adding, dividing, scaling, etc, but I am struggling to understand how the 4x4 matrix represents an object's position in space.

There are 16 elements in the array but to my knowledge you only need to use 7 of them? (I am most likely, horribly wrong but please correct me) and they are:

* x, y, z
* scale
* pitch, roll and yaw.

Furthermore, what is the significance of a column major matrix over a row major one or vice versa? Is it just down to the framework you are using that determines which one you use? (i.e OpenGL or DirectX) What is the difference between them? Is it just the order the elements appear in?

# Answer
**How is Matrix Multiplication a Transformation?**
A matrix is just a big grid of numbers with rules that define how we can multiply it with other grids or lists of numbers.

In games, we usually want to construct a matrix so that, when multiplied with a list of numbers representing a source position (say, the position of a vertex in a mesh) we get a list of numbers representing a destination position (say, the position of that vertex in the game world, after applying the transformations of all its parent objects, or the position of the vertex projected on the screen by our camera)

Because of how matrix multiplication is defined, we can choose to write this in one of two ways, either: `DestinationColumnVector = Matrix * SourceColumnVector`

$$ \require{HTML} \style{display: inline-block; transform: rotate(-90deg)}{\begin{bmatrix} \text{vector}\end{bmatrix}} = \begin{bmatrix} \text{some big}\\ \text{squarish} \\ \text {matrix}\end{bmatrix} \times \require{HTML} \style{display: inline-block; transform: rotate(-90deg)}{\begin{bmatrix} \text{vector}\end{bmatrix}} $$

or `DestinationRowVector = SourceRowVector * Matrix`

$$ \begin{bmatrix} \text{destination row vector} \end{bmatrix} = \begin{bmatrix} \text{source row vector} \end{bmatrix} \times \begin{bmatrix} \text{some big}\\ \text{squarish} \\ \text {matrix}\end{bmatrix} $$

I'm most familiar with the first convention, so that's what I'll use for the examples below, with arrows to denote vectors (in code we usually don't distinguish a vector's row/column orientation) and blackboard bold to denote matrices.

$$\vec p\_\text{destination} = \Bbb M \times \vec p\_\text{source}$$

If your environment uses the opposite convention, just transpose all of the examples below (turn each column into a row)

**What Are We Transforming?**
The vectors we're transforming will typically look like this:

$$\begin{array}{cc} \vec p\_\text{source}=\begin{bmatrix} p\_x \\ p\_y \\ p\_z \\ 1 \\ \end{bmatrix} & \vec d\_\text{source}=\begin{bmatrix} d\_x \\ d\_y \\ d\_z \\ 0 \\ \end{bmatrix} \end{array}$$

Where \\$\vec p\_\text{source}\\$ is the source position we want to transform into a new coordinate space. The "w" coordinate of 1 means we're using homogeneous coordinates to apply translation.

If instead we're transforming a vector that represents an offset or direction \\$\vec d\_\text{source}\\$, not a position, then we want to ignore any translation in the matrix. (My right arm, outstretched to the side, forms an offset vector from my shoulder to my finger that always points to my right and never gets longer or shorter, no matter where I stand relative to the world origin point). We can do this by setting the "w" component to 0 instead of 1.

This is useful for things like surface normal vectors, but note that if you're applying scaling, then you'll want to use a different, related matrix called the "inverse transpose", \\$(\Bbb M^{-1})^T\\$, to ensure the normals flatten out correctly and stay perpendicular to the mesh surface as you squash or stretch the model.

**What Makes Up a Matrix?**
A typical object transform in games (not including camera projection), describing the relationship from our source coordinate system (local/model space) to our destination coordinate system (parent/world space) will look like this:

\\$\Bbb M=\begin{bmatrix} m\_{00} & m\_{01} & m\_{02} & m\_{03} \\ m\_{10} & m\_{11} & m\_{12} & m\_{13} \\ m\_{20} & m\_{21} & m\_{22} & m\_{23} \\ 0 & 0 & 0 & 1 \\ \end{bmatrix}= \Bbb T \times \Bbb R \times \Bbb S\\$

That is:
\\$\vec p\_\text{destination} = \Bbb M \times \vec p\_\text{source} = \Bbb T \times \Bbb R \times \Bbb S \times \vec p\_\text{source}\\$

Since we rarely deliberately introduce skew in object transformations, this matrix is generally the product of three distinct kinds of transformations, which we could look at as being three distinct matrices: a translation \\$\Bbb T\\$, a rotation \\$ \Bbb R\\$, and an axis-aligned scale \\$ \Bbb S\\$.

Looking at these in order of application from "most local" (applied directly to \\$\vec p\_\text{source}\\$ in its source space) to "most global" (applied as the last step to get to our final world space position \\$\vec p\_\text{destination}\\$, we have...

**Axis-Aligned Scale**
Scaling each of the x, y, and z axes of the source space by factors of \\$s\_x, s\_y, s\_z\\$ respectively:

\\$\Bbb S=\begin{bmatrix} s\_x & 0 & 0 & 0 \\ 0 & s\_y & 0 & 0 \\ 0 & 0 & s\_z & 0 \\ 0 & 0 & 0 & 1 \\ \end{bmatrix}\\$

Doing this first ensures that our scales are applied parallel to our local axes, rather than squishing the object diagonally when we rotate it.

You'll notice that if all three scale factors are 1 (100% normal size, no change), then this matrix is the "Identity matrix" with all 1s on the main diagonal and zeroes elsewhere. An identity represents "no transformation" / "source and destination spaces are identical" which is exactly what we expect when applying no scale, so this is a good sign that we got our math right so far. :)

**Rotation to a New Coordinate Basis**
Here we need to choose three unit vectors (length = 1) that are perpendicular to each other (orthogonal), to describe which way the object's right, up, and forward directions should point at the end of the rotation.

The exact names/interpretation we apply to each axis depends on the coordinate system conventions and handedness of the environment we're working in. For a concrete example, in Unity's left-handed coordinate system, we'd choose these vectors so that...

* Our local x direction rotates to point to our new "rightward" \\$\vec r = \begin{bmatrix} r\_x \\ r\_y \\ r\_z \\ 0 \end{bmatrix} = \Bbb R \times \begin{bmatrix} 1 \\ 0 \\ 0 \\ 0 \end{bmatrix}\\$
* Our local y direction rotates to point to our new "upward" \\$\vec u = \begin{bmatrix} u\_x \\ u\_y \\ u\_z \\ 0 \end{bmatrix} = \Bbb R \times \begin{bmatrix} 0 \\ 1 \\ 0 \\ 0 \end{bmatrix}\\$
* Our local z direction rotates to point to our new "forward" \\$\vec f = \begin{bmatrix} f\_x \\ f\_y \\ f\_z \\ 0 \end{bmatrix} = \Bbb R \times \begin{bmatrix} 0 \\ 0 \\ 1 \\ 0 \end{bmatrix}\\$

If we take a unit vector along each of the x, y, and z axes to these new cardinal directions, then every vector that's a combination of x, y, and z will be taken to the corresponding combination of \\$\vec r, \vec u, \vec f\\$, because matrix multiplication is a linear operation.

Now, storing 3 independent vectors is strictly redundant here (once you know \\$\vec r\\$ and \\$ \vec u\\$, there's only one choice for \\$\vec f = \vec r \times \vec u\\$, using the vector cross product) so in practice we'll usually store our rotations as either a quaternion or a trio of Euler/Tait-Bryan angles, and make the vectors on demand (using eg. quaternion multiplication or spherical coordinate formulae) when it's time to do matrix math with them.

Once we have our basis vectors, to make a matrix that rotates to face them, all we need to do is stuff these vectors in as the first three columns:

\\$R= \begin{bmatrix} \vec r & \vec u & \vec f & \begin{matrix}0\\0\\0\\1\end{matrix} \end{bmatrix} =\begin{bmatrix} r\_x & u\_x & f\_x & 0 \\ r\_y & u\_y & f\_y & 0 \\ r\_z & u\_z & f\_z & 0 \\ 0 & 0 & 0 & 1 \\ \end{bmatrix}\\$

Again, notice if our right vector is just the x+ direction (1, 0, 0, 0), and up is y+, and forward is z+, then this is just an identity matrix. "No rotation change"

One handy trick with rotation matrices like this: if you take the transpose, flipping the matrix along its main diagonal, so each row becomes a column and each column a row, then what you get is also a rotation matrix, one that exactly reverses the rotation we started with. Twist, and untwist. We say the transpose of a rotation matrix is also its inverse. :)

And lastly...

**Translation to a New Location in Space**
Now that we have the object in the shape/size and orientation we want, it's time to place it at the desired position in our scene. We do this last, because scaling and rotation both stretch/squash or rotate things around the origin. If we translated first, our pivot would change based on where we are in the world.

So far both the transformations we've used keep the origin the vector where it was (run (0,0,0,1) through both of the above: no matter how you choose \\$s\_x, s\_y, s\_z, \vec r, \vec u, \vec f\\$, you always get (0, 0, 0, 1) back out! This is another consequence of matrix multiplication being a linear operation. Zero has to map to zero. If we were using 3x3 matrices and 3-vectors, we'd be out of luck - there would be no way to use a matrix to shift the result off the origin.

But we really would like to be able to take a mesh centered at the origin, and use a matrix to move it to a new part of our scene. That's where this mysterious fourth row / "w" coordinate comes in, using a technique called "homogeneous coordinates"

By bumping up from 3 dimensions to 4 dimensions, we can place all of our content, including the center/pivot of our object, a little *away* from the origin - not at (0, 0, 0, 0), but at (0, 0, 0, 1). We're 1 unit away from the origin in the w dimension, and that lets use use a fourth column of our matrix to reposition everything - even our pivot point. It's effectively a 4-dimensional shear operation under the hood. But when we lop-off the w to get back to 3D, the effect is translation. :D

So, to translate (shift) our space by an offset vector \\$\vec t = \begin{bmatrix} t\_x \\ t\_y \\ t\_z \end{bmatrix}\\$,

we need a matrix \\$\Bbb T\\$ such that \\$ \begin{bmatrix} \vec t \\ 1 \end{bmatrix} = \Bbb T \times \begin{bmatrix} 0 \\ 0 \\ 0 \\ 1 \end{bmatrix}\\$.

Just like with the rotation case, we can get this by stuffing \\$ \vec t \\$ in as the fourth column of our matrix:

$$\Bbb T = \begin{bmatrix} \Bbb I\_\text{3x3} & \vec t \\ \vec 0\_3 & 1\end{bmatrix} = \begin{bmatrix} 1 & 0 & 0 & t\_x \\ 0 & 1 & 0 & t\_y \\ 0 & 0 & 1 & t\_z \\ 0 & 0 & 0 & 1 \\ \end{bmatrix}$$

Note again how if \\$\vec t = \vec 0\\$, ie. if we're applying no translation at all, then this again reverts to an identity matrix, leaving the space it's multiplied by unchanged.

**Bringing it All Together**
When we multiply all three of these component transformations together, we get:

$$\begin{align}\Bbb M &= \Bbb T \times \Bbb R \times \Bbb S\\ &= \begin{bmatrix} 1 & 0 & 0 & t\_x \\ 0 & 1 & 0 & t\_y \\ 0 & 0 & 1 & t\_z \\ 0 & 0 & 0 & 1 \\ \end{bmatrix} \begin{bmatrix} r\_x & u\_x & f\_x & 0 \\ r\_y & u\_y & f\_y & 0 \\ r\_z & u\_z & f\_z & 0 \\ 0 & 0 & 0 & 1 \\ \end{bmatrix} \begin{bmatrix} s\_x & 0 & 0 & 0 \\ 0 & s\_y & 0 & 0 \\ 0 & 0 & s\_z & 0 \\ 0 & 0 & 0 & 1 \\ \end{bmatrix}\\ &=\begin{bmatrix} s\_xr\_x & s\_yu\_x & s\_zf\_x & t\_x \\ s\_xr\_y & s\_yu\_y & s\_zf\_y & t\_y \\ s\_xr\_z & s\_yu\_z & s\_zf\_z & t\_z \\ 0 & 0 & 0 & 1 \\ \end{bmatrix} \end{align}$$

We've combined three different transformations into one, so now we can apply all three to a new vector for the cost of just one matrix multiplication. And this scales: if I have an object 10 levels deep in a transformation hierarchy, where each child inherits transformation from its parent and adds its own, I can compute a single matrix that combines all these transformations, to shortcut straight from local space to world space, without bubbling up one level at a time.

That's why we're so fond of using matrices to represent transformations: they're extremely flexible, and can collapse many complex operations down to just one straightforward mechanical process.

You'll notice through all that, the bottom row stayed constant. That's because we've been careful to keep to our homogeneous coordinate convention that all our content sits on the w=1 plane. In many math libraries, we'll even skip storing the 4th row in our vectors or matrices, and just pretend it's there by exposing separate methods to `TransformPoint` (simulate multiplication with a vector that has w=1) or `TransformDirection` (simulate multiplication with a vector that has w=0).

But this 4th row serves a whole different role once we get into rendering the scene with a camera: we can form a projection matrix that shoves depth information into the w coordinate, then divide by w to get a perspective projection, where things that are closer look bigger, and things that are further away get smaller. For those purposes, we'll typically store the whole 4 rows/components.

One last detail:

**Row-Major vs Column-Major Layout**
Using the conventions above, you can see vectors we care about often occur as columns in the matrix (eg. translation in the 4th column, direction vectors in the first three columns of the rotation matrix).

So, if we use a **column-major matrix representation** (where consecutive elements in a column are consecutive in memory storage order), this makes it convenient to set or read columns of the matrix (eg. `T[3] = (tx, ty, tz, 1)` to set the 4th column of a translation matrix).

A row-major representation would store consecutive elements in a row consecutively, making it easy to do operations on rows of the matrix at a time.

So, row-major vs column-major order is just about using the data representation that's most convenient for the matrix multiplication conventions used by your engine or programming environment.
> 18 votes

---
Tags: mathematics, matrix, geometry, transformation, linear-algebra
---


# Question
Title: How to set the position of objects in pixels on the scene editor
I created a camera of the size of 480x854 as the project is meant for Android but whenever I try to position objects on the scene editor, their positions dont seem to be in pixels. It is like -10 y on the top and 10 y on the bottom of the camera. So what I want is to see and position the objects on the scene editor in pixels.

Thanks in advance.

# Answer
In world space everything is measured in default meter unit. Terrain, gravity, sound etc depend on it.

In device display those world space coordinates are converted to screen space coordinates.

So you **can't place things in pixel**. It's a variable depends on device. And world space unit is meter, you have to place things in world space. It's proven best that way. You don't want to develop a game just for one device display.

tansform.position.x is floating point number represents one portion of a 2D/3D vector which is a position vector of an object. These are calculated in world space in meter and projected in display screen in pixels. (If your camera is positioned in the origin in world space it should look like the image).
> 1 votes

---
Tags: unity, 2d
---


# Question
Title: Box Collider center relative to GameObject
I'm trying to get the distance from the BoxCollider center of a gameobject to the bottom of that same BoxCollider. Note that the center of the collider is slighty modified.

So far, I have:

```
float halfHeightCollider = (bounds.size.y / 2);

```

I tried the following to take care of the slight modification:

```
float halfHeightCollider = bounds.center.y + (bounds.size.y / 2);

```

But seems like `bounds.center` give me the position of the center of the BoxCollider in the world, not relative to the gameobject, like in the inspector:

That value is the one I want. How can I get it?

# Answer
You can get the center in y-axis from `gameObject.GetComponent<BoxCollider>().center.y`.

You will get the total size in y-axis of the collider from `gameObject.GetComponent<BoxCollider>().size.y`.

Then take the y-size/2 and **subtract** center value in y-axis from it.
> 4 votes

---
Tags: unity
---


title: Unity 5 - Occlusion culling 2D error

text:
# Question
Title: Unity 5 - Occlusion culling 2D error
I'm trying to set a Occlusion culling on my topdown 2D game. I have made a sprite object with a Occlusion Area on it.Once I try to bake it, it gives me the following error:

No Renderers that are marked static were found in the scene. Please mark all renderers that will never move as static in the inspector. UnityEditor.DockArea:OnGUI()

What exactly does this mean?

I'm using V5.3.2

# Answer
You have to make the objects static which will be the part occlusion culling. The sprites/objects that will not move in runtime will have to be marked as static before baking. Make the objects static then system will get some renderer to work on. Then bake.

Occlusion culling is valid on only 3D mesh's. 2D sprites are not supported type. It's used on 3D objects. Usually 2D scenes doesn't require occlusion culling. **Or you have to have at least one static 3D object in the scene**
> 1 votes

---
Tags: c#, unity, culling, occlusion
---


# Question
Title: Unity - Loss of detailed shadows and shading marks on texture seams appearing after lightmap baking
I'm attempting to lightmap bake my scene and am running into the following problem -

With the lights set to realtime, the shadows have a nice amount of detail in them and the lighting on the models looks correct. However after a bake, all I end up with is a dull blob shadow underneath everything and nasty shading marks on my meshes, these shading marks are mostly appearing where the seams are on the UVs. The models are .blend files from Blender and 'Generate Lightmap UVs' is checked on the model Inspector panel.

All lights are set to static and 'Baked'

Lights are 3 x spotlights 1 x directional light

All models are set to static

Unity 5.3.3

PC standalone

Materials are using the standard shader with a diffuse and normal map on each.

I have attached screenshots of the problem and all my settings.

This is my first proper attempt at lightmapping, so I'm hoping it's just a simple oversight in my settings that someone more experienced can point out.

If anyone can suggest the cause of the problem, it would be much appreciated.

Thanks in advance

# Answer
> 2 votes
Increase atlas size to 4096. \[Lighting tab \>\> Baked GI \>\> Atlas size\]

Tested with your settings:

Increase **bounce intensity** of light. Also increase **indirect intensity** and **bounce boost** under General GI in Lighting tab. These should be satisfactory. If not put some bake only point lights where shading is not working good. Then bake.

---
Tags: unity, lightmap
---


# Question
Title: Need some advice on how to decide where to implement my enemy behaviours
I'm in the middle of writing a platformer game in Unity using C#. I have my character, if he presses the kick button his state switches to kicking. During this "kicking" state the character doesn't actually do anything, he only publicly exposes the kicking information such as kickForce etc.

The enemies however have a check in their update functions for the players isKicking value, if he is and the enemy lies within the range for being kicked by the player then the enemy has forces applied to itself and such. All this works fine but I've been thinking about future implementation of different enemy types, if I want to implement other types of enemies that do not behave the same this same script will not work.

To me this is inintutive, part of me thinks that the kicking behavior should be in the player class, he should retrieve all enemies within the area of kicking and run them through some sort of KickObject method. However this is my very issue, I am unsure of what the cleanest and most straightforward (and easily extendable) way of doing this is. I have this problem in general when it comes to implementing the structure of the game, i don't know the best answer and I feel that often when I am planning things they get much more complicated than I had originally planned for down the line and the structure i had in place starts to fall apart.

Any advice on this matter would be greatly appreciated.

TL:DR - For kicking enemies, should the behaviour be applied by the player or is the method of every enemy having its own "be kicked" code the better way to do this. General game development code structure questions.

# Answer
Why not use colliders and tags. When an enemy trigger/collider detects a player trigger/collider tagged say "Player kick" (child game object of the player) then that enemy executes his reaction with OnTriggerEnter(2D)/OnCollisionEnter(2D). Player just needs to enable and then disable its kick game object when kick is pressed.

The most important thing is that each object should only be responsible for his own actions/behavior. Player should only care to kick and nothing else. Enemies should only execute the consequences of being kicked.
> 2 votes

# Answer
The way I would handle this sort of scenario is to use some form of event messaging system. Each entity in your game world(and possibly the game world itself) should have the ability to send and receive messages.

A simple way to set this up would be to have a MessageTypeEnum that signals which type of message is being sent and then some way of sending the rest of the event data(i.e. use of dynamic to store a struct of data that the receiving entity can convert back to its original type, or through use of inheritance and extending a base message class with derived types for each message etc.).

You can then have a simple EventManager object that other entities can use to register for event types. When an event comes in to the manager it can then be dispatched off to the receiver method for each registered entity.

The main advantages of the above is that it is easily extendable and the sender object doesn't really care who the message is intended for. It just fires and forgets. This results in far less coupling in the code. It also allows for each entity to react differently if needs be to each message type.

For instance an EnemyDied message might result in the player handling it by adding some value to a score and the game world might handle it by removing the enemy from its update list.
> 0 votes

---
Tags: unity, c#, software-engineering, platformer
---


# Question
Title: How to create shockwave of objects in other shapes than circle?
Basically, I'm making a bullethell / I wanna be the guy inspired game for where I'm currently creating different methods of spawning bullets into the game. One of the few methods I've created is creating a shockwave of bullets with defined number of bullets in a circular shape. The method works excellently with a for-loop and is very simple to use.

```
for (double angle = (0 + rotation); angle < (Math.PI * 2 + rotation); angle += Math.PI / (numberOfBullets / 2))
{
     Bullet nextBullet = new Bullet(bulletDef, position, speed, acceleration, rotation, texturePriority, color, bulletID);
     nextBullet.speed.X = (float)Math.Cos(angle) * speed.X;
     nextBullet.speed.Y = (float)Math.Sin(angle) * speed.Y;
     nextBullet.acceleration.X = (float)Math.Cos(angle) * acceleration.X;
     nextBullet.acceleration.Y = (float)Math.Sin(angle) * acceleration.Y;
     nextBullet.position = position;
     nextBullet.isRemoved = false;
     Data.tempEntities.Add(nextBullet);
}

```

However, I wanted to extend this method a little further with the ability of creating shockwaves in other shapes, like Triangle, Square, Pentagon and Hexagon. I however have no specific idea of how to set this up with a for-loop.

The only lead I have so far of what I could do is calculate the amount of sides each shape have (they're all going to be equilateral as having differently long sides would be a waste of time to program) so we'll take a Triangle for example; has 3 sides. We'll decide that this triangular shockwave will shoot 6 bullets so we'll define what the first two bullets speed will be with these (probably wrongly written code).

```
int calculateBullets = (numberOfBullets / 3);
int divider = numberOfBullets % calculateBullets;

```

I tried using this in a for-loop, but it gave me OutOfMemory error without any explaination of what I did that was wrong. What would be the best way to approach this predicament? Should I still use a for-loop and how will I need to set it up? Or should I attempt to use something else?

# Answer
To maintain the shape while spreading, each bullet needs to have a different speed. Suppose you are going to create a "wave" of bullets originating from a centerpoint, what you need to do is to calculate the speed each bullet needs to have to maintain the contour of the shape. See below: the red bullet moves slower than the green bullet in order to enlarge the triangle.

So this is how one could do it:

* Define the shape as a bunch of lines.

Now there are two options:

1. For a radial distribution: Determine the intersect vector of the line from the origin to the edge of the shape (cast rays for each 2PI/numberbullets).
2. For an even distribution: Determine how many bullets per segment, evenly distribute (Lerp) between the endpoints of the segment.

Then based on the method (radial or evenly)

* Create the pattern.
* Spawn bullets at the directionVector multiplied by the speed you want the shape to grow.

If you set point a,b and c at distance=1 from the origin, bullets that travel towards a,b and c will have the vector lenght 1 and thus will travel at the speed you set. Other bullets will travel relative to that in order to maintain the shape.

If you define the shapes with lines you can create complex shapes such as stars, hearts or whatever you define.

I made some sample code to provide some insight how to do it:

**Step 1: Define the polygon in lines**

For now let's do simple polygons like triangles, squares and hexagons: /// /// Holds a linesegment /// private struct Linesegment { public Vector2 point1; public Vector2 point2; }

```
    /// <summary>
    ///  Creates a list of linesegments around (0,0) to create a polygon. The points generated have a distance of 1 from the center.
    /// </summary>
    /// <param name="segments">Number of linesegement that create the polygon, should be at least 3</param>
    /// <param name="offsetangle">Angle to rotate the generated polygon</param>
    /// <returns></returns>
    private List<Linesegment> CreateRadialPolygon(int segments, double offsetangle)
    {
        if (segments < 3)
            throw new Exception("Polgon should have at least 3 segments");

        List<Linesegment> result = new List<Linesegment>();
        double theta = (2 * Math.PI) / (double)segments;

        for(int i=0;i<segments;i++)
        {
            result.Add(new Linesegment()
            {
                point1 = new Vector2((float)Math.Cos(offsetangle + (i * theta)), (float)Math.Sin(offsetangle + (i * theta))),
                point2 = new Vector2((float)Math.Cos(offsetangle + ((i + 1) * theta)), (float)Math.Sin(offsetangle + ((i + 1) * theta)))
            });

        }
        return result;
    }

```

**Step 2, Radial distribution**

This is basic line intersection calculation. I altered it so it calculates the intersectionpoint of a segment with a ray spawning from the origin and a direction angle.

```
    /// <summary>
    /// The result of the intersection function.
    /// </summary>
    private struct IntersectionResult
    {
        public bool intersection;
        public bool coincident;
        public Vector2 intersectionPoint;
    }

    /// <summary>
    /// Find the intersectionpoint (if any) for a ray starting from a point in the direction of theta.
    /// </summary>
    /// <param name="point1">start of linesegment</param>
    /// <param name="point2">end of linesegment</param>
    /// <param name="origin">origin of the ray</param>
    /// <param name="theta">angle of the ray</param>
    /// <returns>an intersectionresult. If the ray intersects the line intersection is set to true, intersectionPoint contains the found intersection</returns>
    private IntersectionResult ProcessIntersection(Linesegment linesegment, Vector2 origin, double theta)
    {
        //since this is linesegment versus linesegment code; transform the ray into a point somewhere far away...
        Vector2 rayend = origin+new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta)) * 1000;

        float ua = (rayend.X - origin.X) * (linesegment.point1.Y - origin.Y) - (rayend.Y - origin.Y) * (linesegment.point1.X - origin.X);
        float ub = (linesegment.point2.X - linesegment.point1.X) * (linesegment.point1.Y - origin.Y) - (linesegment.point2.Y - linesegment.point1.Y) * (linesegment.point1.X - origin.X);
        float denominator = (rayend.Y - origin.Y) * (linesegment.point2.X - linesegment.point1.X) - (rayend.X - origin.X) * (linesegment.point2.Y - linesegment.point1.Y);

        IntersectionResult result = new IntersectionResult { intersection = false, coincident=false,intersectionPoint=Vector2.Zero };

        if (Math.Abs(denominator) <= 0.00001f) // epsilon, check if the point is on the line (within a very small distance for rounding errors).
        {
            if (Math.Abs(ua) <= 0.00001f && Math.Abs(ub) <= 0.00001f)
            {
                result.intersection = true;
                result.coincident = true;
                result.intersectionPoint = (linesegment.point1 + linesegment.point2) / 2;
            }
        }
        else
        {
            ua /= denominator;
            ub /= denominator;

            if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1)
            {
                result.intersection = true;
                result.intersectionPoint.X = linesegment.point1.X + ua * (linesegment.point2.X - linesegment.point1.X);
                result.intersectionPoint.Y = linesegment.point1.Y + ua * (linesegment.point2.Y - linesegment.point1.Y);
            }
        }
        return result;
    }

```

**Step 3, Radial distribution**

Tying this all together, in this part the pattern is generated; a shape with segments is made (using step 1) and the intersections are calculated (step 2). The result is an array of Vector2 that holds the directionvector of each bullet in the pattern.

```
    /// <summary>
    /// Creats a pattern of bullets in a polygon shape with 'segment' sides.
    /// </summary>
    /// <param name="segments">sides the polygon should have (must be >=3)</param>
    /// <param name="offset">rotation of the polygon</param>
    /// <param name="numberofbullets">number of bullets in this pattern</param>
    /// <returns></returns>
    private Vector2[] CreateBulletPattern(int segments, double offset, int numberofbullets)
    {
        List<Linesegment> polygon = CreateRadialPolygon(segments , offset);
        List<Vector2> bulletdirections = new List<Vector2>();

        double bulletangle = (2 * Math.PI) / numberofbullets;
        for(int i=0;i<numberofbullets;i++)
        {
            foreach(Linesegment l in polygon)
            {
                //do an intersection; if the line intersects add a bullet to the pattern.
                IntersectionResult r = ProcessIntersection(l, Vector2.Zero, i * bulletangle);
                if(r.intersection)
                {
                    //check if the intersectionpoint already is in the result-
                    //this may be if the intersectionpoint is one of the endpoints of the line segment.
                    if (!bulletdirections.Contains(r.intersectionPoint))
                        bulletdirections.Add(r.intersectionPoint);
                }
            }
        }
        return bulletdirections.ToArray();
    }

```

**Step 4, making it work it together**

Line intersections are relatively fast- you could do precalculations and store the vectors for a given shape and number of bullets for example in a Dictionary:

```
Dictionary<string, Vector2[]> _pattern = new Dictionary<string, Vector2[]>();

```

This enables you to fill it like this:

```
        _pattern.Add("triangle60", CreateBulletPattern(3, 0, 60));
        _pattern.Add("square80", CreateBulletPattern(4, 0, 80));
        _pattern.Add("hexagon30", CreateBulletPattern(6, 0, 30));

```

now each bullet can travel at a `speed` in the directionVector and the shape will remain the polygon you have defined. If an enemy spawns bullets in a pattern do something like this:

```
foreach(Vector2 directionvector in _pattern["triangle60"])
{
    SpawnBullet(startposition,directionvector,speed);
}

```

Improvements could be, change polygon code to create more complex shapes. Add delays to the bulletspawning code to have the pattern appear.

Using this code I produced this result (looks better when moving ofcourse):

**Evenly spaced option**

Another option is, to evenly space the bullets over the line segments. This does not require intersection calculations. By using code like this:

```
    /// <summary>
    /// Creats a pattern of bullets in a polygon shape with 'segment' sides.
    /// </summary>
    /// <param name="segments">sides the polygon should have (must be >=3)</param>
    /// <param name="offset">rotation of the polygon</param>
    /// <param name="numberofbullets">number of bullets in this pattern</param>
    /// <returns></returns>
    private Vector2[] CreateBulletPatternEvenlySpacedOverSegments(int segments, double offset, int numberofbullets)
    {
        List<Linesegment> polygon = CreateRadialPolygon(segments, offset);
        List<Vector2> bulletdirections = new List<Vector2>();

        int bulletspersegment = numberofbullets / polygon.Count;

        foreach(Linesegment l in polygon)
        {
            for(int i=0;i<bulletspersegment;i++)
            {
                bulletdirections.Add(Vector2.Lerp(l.point1, l.point2, (float)i / (float)bulletspersegment));
            }
        }

        return bulletdirections.ToArray();
    }

```

You generate the polygon in the same way as before, however the bullets are evenly spaced. This results in:

Both methods work; the outcome may look prettier for one shape than the other so you may want to experiment what looks best for you. If you create a tool to generate the shapes/linesegments you can create complex patterns.

Note that traditional bullethell type shooters often have pattern generators that spawn bullets based on angle, angle increments and delays. However since you wanted polygonlike shapes, this method suits your need.
> 11 votes

---
Tags: xna, monogame, bullet-physics
---


title: Sudoku generation doesn't finish

text:
# Question
Title: Sudoku generation doesn't finish
Heyho,

i got problems with my sudoku generator. First of all I generate some numbers between 1 and 9 and put them (according to the sudoku rules) into my game. After that I solve it using my second algorithm, but there's a problem with. It stops solving in the middle of the sudoku and says that there isn't a single solution for it, even if this sudoku has around 200 solutions.

```
private void generateSudoku()
{
//iSeed für den Random-Generator
iSeed = seeder.Next();
rnd = new Random(iSeed);

for(int i = 0; i < FIELDSIZE; i++)
{
    iContent[i] = 0;
    bEditable[i] = true;
}

switch(iDifficulty)
{
    case 0:  iNumbers = rnd.Next(30, 35);
        break;
    case 1:  iNumbers = rnd.Next(24, 29);
        break;
    case 2:  iNumbers = rnd.Next(18, 23);
        break;
    default: iNumbers = rnd.Next(24, 29);
        break;
}

for(int i = 0; i <= iNumbers; i++)
{
    int iValue = rnd.Next(1, 10);
    int iRow = rnd.Next(0, ROWSIZE);
    int iCol = rnd.Next(0, ROWSIZE);

    if(check(iRow, iCol, iValue) == 0)
    {
        iIndex = (ROWSIZE*iRow+iCol);
        iContent[iIndex] = iValue;
        bEditable[iIndex] = false;
    }else
    {
        i--;
    }
}

iSolutionCounter = 0;
solveSudoku(0);

Console.WriteLine("Solutions: " + iSolutionCounter);

if(iSolutionCounter != 1)
{
    //generateSudoku();
    //return;
}

for(int i = 0; i < FIELDSIZE; i++)
{
    if(bEditable[i] == true)
    {
        iSolution[i] = iContent[i];
        //iContent[i] = 0;
    }else
    {
        iSolution[i] = iContent[i];
    }
}

```

}

* FIELDSIZE = 81; The number of fields in complete sudoku (9x9)
* ROWSIZE = 9; The number of fields in a single row or column (9)
* iNumbers The amount of random generated startnumbers

And the solveSudoku(), which should solve the sudoku and sum up all solutions (but fails)

```
private bool solveSudoku(int iPos)
{
    int iCol = (iPos % ROWSIZE);
    int iRow = (int)(iPos / ROWSIZE);

    if(iPos >= FIELDSIZE)
    {
        iSolutionCounter++;
        return false;
    }

    if(iContent[iPos] >= 1)
    {
        return solveSudoku(iPos + 1);
    }
    for(int i = 1; i <= ROWSIZE; i++)
    {
        if(check(iRow, iCol, i) == 0)
        {
            iContent[iPos] = i;
            if(solveSudoku(iPos + 1))
            {
                return true;
            }
        }
    }

    return false;
}

```

That's what I mean (grey numbers are the ones, which are available at start, so you (or my algorithm) can't edit them:

# Answer
you should reassign 0 to the position at the end of the loop.

```
for(int i = 1; i <= ROWSIZE; i++)
{
    if(check(iRow, iCol, i) == 0)
    {
        iContent[iPos] = i;
        if(solveSudoku(iPos + 1))
        {
            return true;
        }
    }
}
iContent[iPos] = 0;
return false;

```

Otherwise the solver will think that the position is filled in when it's backtracking.

---

Your simple solver is a bit too simple for the job to be efficient. If the first guess it makes is wrong then it can take a long time for it to discover that and retry.

Sudoku solving is a constraint satisfaction problem so take some lessons out of the methods for resolving those. I suggest doing some kind of constraint propagation before going to guess.

Also instead of guessing in a fixed pattern you can guess a number in the square with the least number of options left. If that square has no options left then there is no solution.
> 2 votes

---
Tags: c#
---


title: What exactly is UV and UVW Mapping?

text:
# Question
Title: What exactly is UV and UVW Mapping?
Trying to understand some basic 3D concepts, at the moment I'm trying to figure out how textures actually work. I know that UV and UVW mapping are techniques that map 2D Textures to 3D Objects - Wikipedia told me as much. I googled for explanations but only found tutorials that assumed that I already know what it is.

From my understanding, each 3D Model is made out of Points, and several points create a face? Does each point or face have a secondary coordinate that maps to a x/y position in the 2D Texture? Or how does unwrapping manipulate the model?

Also, what does the W in UVW really do, what does it offer over UV? As I understand it, W maps to the Z coordinate, but in what situation would I have different textures for the same X/Y and different Z, wouldn't the Z part be invisible? Or am I completely misunderstanding this?

# Answer
> 30 votes
Your understanding is close. Each 3D model is made out of vertices. Each vertex usually defines the location of a point in space, a normal (used in lighting calculations) and 1 or more texture coordinates. These are generally designated as *u* for the horizontal part of the texture and *v* for the vertical.

When an object is textured, these coordinates are used to look up which texel or pixel to plot from the texture. I find it easiest to think of them as percentages or ratios between the left edge of texture (*u* = 0) and the right edge of the texture (*u* = 1.0) and from the top of the texture (*v* = 0) and the bottom of it (*v* = 1.0). They are interpolated between the vertices and looked up for each on-screen pixel that is rendered. They can be larger or smaller than these ranges and the render state that is set when the object is rendered specifies what happens. The options for this are CLAMP and REPEAT. Clamping limits the coordinate to either 0 or 1, causing the texture to smear where it is outside of the range. Repeat causes the texture to repeat when it is outside the range; it is effectively the same as grabbing just the decimal portion of the coordinate and using that in its place.

Before the texture coordinates are applied onto an object, they are multiplied by a texture matrix to apply some transformation to them (such as scaling, translation or rotation). This effect is sometimes animated in games to make it appear as though something is moving across an object without having to move the object itself... the texture is simply scrolling across it. When the texture matrix is multiplied by the texture coordinates, it produces 2 values that are used to look up the texel to plot (lets call them *s* and *t*). These are generated automatically from *u* and *v* even when the texture matrix is not set; it is the equivalent of multiplying *u* and *v* by an identity matrix.

This is where the *w* coordinate comes in, though it isn't used that often. It is an extra parameter to multiply the texture matrix against and is usually used when you want to take perspective into account (such as in Shadow Mapping). It works the same as when you transform a location in object-space to screen-space via a world-view-projection matrix. By multiplying the UVW with a projection transform, you end up with 2 coordinates, the *s* and *t* which are then mapped onto a 2D texture.

# Answer
> 9 votes
Think origami.

A UV map is like a flattened (unwrapped) 2D skin of your 3D mesh (shell).

If you were to cut out the map and fold it along the mesh lines, the result would be your 3d model.

The (U,V) floating point values range from (0,0) to (1,1) The upper left corner of the UV map is (0,0) The lower right corner is (1,1)

Each vertex in a mesh of polygons (tris/quads) has a (U,V) value that tells the renderer which part of the map to use.

In the GPU pipeline, vertex shaders calculate the 2D projections of each pixel in these 3D polygons, and then fragment shaders colour them in using the UV map.

This cannot be fully appreciated without a picture like this which makes it all obvious:

As the other commentators mentioned, the W component is used by the renderer for fancier effects like shadow mapping, but the UV map is the base for understanding.

Note that a vertex shader must call a fragment shader at least once for each and every pixel that needs to be coloured in. That is why GPUs are parallel processors with dozens of cores - the shader pipeline is very demanding.

Please also note that CPU-integrated GPUs are designed for mobile devices and are limited to less than one tenth the number cores than that of similar generation external GPUs. This because of mobile power and cooling constraints. Moore's Law seems to have slowed down, but performance is still improving (with the odd melt-down here and there ..)

UV-mapping billions of pixels at 240+ frames per second can cause a real hot mess!

# Answer
> 8 votes
Consider a triangle.

Each corner has a UV coordinate. You interpolate between these to get a set of UV coordinates for each pixel. (There's also perspective in play here but let's ignore that for the moment).

Then, you fetch a texel from the texture from the coordinates U and V. Which is to say, a pixel from the texture coordinate x,y - same thing, slightly different terminology since we're talking about textures.

If your texture is a truly 3-dimensional one, you'll also need a third coordinate, W.

One way to visualize this is to think of a block of wood. If you chop it somehow, you'll see that each plane inside the block contains a 2d texture of sorts.

3d textures are so rare that you can forget about them for the time being.

# Answer
> 1 votes
A uv map maps a point (x,y,z) in the mesh to a point (u,v) in the texture image. Since an image maps (u,v) to a color, the two maps can be chained, yielding a map from the mesh space to the color space.

```
         uv map       color map
 (x,y,z)   ->   (u,v)    ->     color
 mesh           Texture
 space          space

```

---
Tags: 3d, textures, uv-mapping
---