# Question
Title: How can I determine the direction of the balls after collision in billiards game?
I'm making a billiard game and I have two questions:

How do I find the velocity of two balls when they collide with each other and how do I apply it to both balls?

I already know the angles that they're gonna move, I just need to find the velocity that they'll move in those directions.

My game is in 3D, and I'm using Unity. I don't want to use Unity's built-in physics to compute the result in this case, I'd like to know how to compute it myself.

# Answer
What you are attempting is non trivial and using the internal Physics system is going to be a ton less problematic.

That said, if you really want to eek it out by hand then you need to first detect intersections between the relevant balls, then you need to resolve these out, then you need to update the velocities.

1. To detect intersections between the balls

This is simply a sphere / sphere intersection test. Iterate through all pairs and check the distance. Distance = (sphere1.transform.position - sphere2.transform.position).Length()

If Length \< sphere1.radius + sphere2.radius then you have an intersection and you should resolve them

2. Resolution of intersection

You first calculate the normal of collision. This is simply

```
NormalOfCollision = sphere1.transform.position - sphere2.transform.position;
NormalOfCollision.Normalise();

```

You calculated the sphere distance in (1) so the resolutionDistance is totalRadius - sphereDistance. You then apply this to the bodies.

```
sphere1.transform.position += NormalOfCollision * resolutionDistance
sphere2.transform.position -= NormalOfCollision * resolutionDistance

```

If you are going to have spheres of different masses colliding then you should scale the impulse so that the smaller mass is moved more than the larger mass. I.e.

```
sphere1Impulse = sphere2Mass / (Sphere1Mass + Sphere2Mass);
sphere2Impulse = sphere1Mass / (sphere1Mass + Sphere2Mass);
sphere1.transform.position += NormalOfCollision * resolutionDistance * sphere1Impulse
sphere2.transform.position -= NormalOfCollision * resolutionDistance * sphere2Impulse

```
3. Calculation of velocity after impact

You need to use the conservation of linear momentumm law. The wikipedia page gives a worked example.

**NB**

1. The above is pseudo code, I've not run it, so I may have some of the +ve / -ve signs around the wrong way - butit's the right direction
2. This just handles the linear effects NOT angular (so won't simulate spin shots etc)
3. If you have larger time steps, or multiple balls interpenertating you should resolve until you have no more contacts (ObjectA may push ObjectB into ObjectC so you need to resolveagain)
4. There is no optimisation in this (islanding / broadphase collision etc)
5. There is no restitution in this with different objects being more bouncy than others
6. Using PhysX is going to be a ton easier than doing everything yourself
> 2 votes

# Answer
This question is more about an approach rather than the actual physics.

In this case all your balls should have or contain a component describing the relevant information that you require.

i.e.:

```
public class Balls
{
    public Vector3 Vector {get; private set;}
    public float Speed {get; private set;}
}

```

And when the balls meet you can then use this information to do whatever physics you need to perform. For example, depending on your implementation, you may choose to make each ball calculate its own trajectory after colliding with the other, in the `OnCollisionEnter` function.
> 0 votes

---
Tags: collision-detection, physics, billiards
---


# Question
Title: What causes seemingly random triangle artifacts in OpenGL?
When switching version of OpenGL from 4.5 to 4.4, I suddenly started seeing these weird random triangles flickering over my scene

They move around somewhat randomly and are always pointed towards `[0,0]`.

Given that this only appears in 4.4 and not in 4.5, my guess would be that I have some undefined behavior that manifests only in one version? I'm not using any advanced OpenGL, just drawing basic triangles with VBO buffers.

How should I go about debugging these sorts of issues, and what are the likely causes that manifest as artifacts? (The hexes and the white-ish path are what I inteded to draw, only the black/yellow/blue triangles are the artifacts)

# Answer
> 8 votes
There are a number things that could cause these problems. Here are some things to try:

* Bad vertex coordinates. One way to debug it is to print your coords to the console and check for things like NaN, Inf, etc. But it could also be that you're just uploading some wrong, but not obviously bad coordinates. One way to debug this is to bisect your data. Send only half to the card and see if it happens. If not, send the other half. Keep bisecting the data until you've figured out which vertices are the problem
* Bad near/far plane settings. If you make your near plane too close to the camera, depth testing can get wonky and produce odd artifacts like this. If the far plane is too far, then you might not have enough precision. You can debug it by checking your near and far settings and changing them to see if the problem goes away.
* Not clearing the frame buffer's color or depth attachment. If the framebuffer isn't cleared junk can be left in it. If you're drawing with blending on, the color results can be odd. If the depth buffer isn't clear, drawing may fail for a given fragment if it's depth is beyond the junk depth value already in the framebuffer. You can debug by checking that you're clearing things before drawing. Maybe look at the framebuffer both before and after drawing.
* An unexpected shader is active. A fragment shader can color things oddly. Maybe there's a case where you aren't calling glUseProgram() with a new program or clearing it? Debug by ensuring you're getting the program you think you are. You could replace the program you normally use with one that just outputs a solid color and see if it's getting used.
* Bad shadowing. Maybe your shadow maps are hosed? You could test by turning off your shadows and see if the problem goes away.
* As @glampert mentions, passing the wrong number of vertices or indices to calls like `glDrawArrays()`, `glDrawElements()`, etc. I often forget whether it's number vertices, number of triangles/quads/etc. and pass the wrong value at first. Or passing the wrong stride to one of the above calls. I often think in terms of triangles, but they often want the stride between vertices, not triangles. You can test by passing in a value that's half what you think it should be and see if the problem goes away. If so, add back 1/2 of what you took out and see if it still happens. Keep doing it until the problem returns, then figure out what the proper value is and why.

There are probably other potential issues, but those are the ones I can think of off the top of my head.

# Answer
> 1 votes
I was experiencing exactly the same problem in my application when showing DisplayList consisting of TRIANGLE\_STRIPs (grid of elevation data). They are extra triangles randomly flickering and moving around, always pointing to \[0,0\]. And here is my observation:

* It only happens on some graphics cards (e.g. Intel HD Graphics 4400 with OpenGL 4.0), it runs ok on others (OpenGL 4.5 or even OpenGL 2.1 and 1.4)
* It only happens if my grid is bigger than 200 x 200 vertices and more importantly:
* It only happens when I use TRIANGLE\_STRIPs to show the grid, if I use just simple separate TRIANGLES for the same data, it runs.
* What I also find interesting is that using TRIANGLES instead of TRIANGLE\_STRIPs has better performance

So I believe it is a problem of OpenGL implementation on some particular HW. I don't see the possibility of using wrong data or invalid pointers.

---
Tags: opengl
---


# Question
Title: Ashikhmin-Shirley model implementation: ugly result
I am trying to implement the Ashikhmin-Shirley model using these formulas:

This is the GLSL 1.2 fragment shader code:

```
uniform vec4 materialAmbient, materialDiffuse, materialSpecular;
uniform float materialShininess;
uniform vec4 lightAmbient, lightDiffuse, lightSpecular, lightPosition;

varying vec3 P,N;

float pi= 3.1415926535;

vec4 Fd(float NdotV, float NdotL) {
    vec4 fd= (28.0 * materialDiffuse * lightDiffuse) / (23.0 * pi) * (1.0 - materialSpecular * lightSpecular);
    fd*= 1.0 - pow(1.0-NdotV/2.0,5.0);
    fd*= 1.0 - pow(1.0-NdotL/2.0, 5.0);
    return fd;
}

vec4 Fr(float u, vec4 specular) {
    return specular + (1.0-specular) * pow(1.0 - u, 5.0);
}

// f= phi
vec4 Fs(float VdotH, float NdotH, float NdotL, float NdotV, float et, float eb, float f) {
    vec4 fs= Fr(VdotH, materialSpecular * lightSpecular);
    fs*= sqrt((et+1.0) * (eb+1.0)) / (8.0 * pi);
    fs*=  pow(NdotH, et*pow(cos(f),2.0) + eb*pow(sin(f),2.0)) / (VdotH * max(NdotL, NdotV));
    return fs;
}

void main(void) {
    vec3 L= normalize(vec3(lightPosition) - P);
    vec3 V= cameraPosition;
    vec3 H= normalize(L+V);
    float NdotL= max(dot(N,L),0.0);
    float NdotV= max(dot(N,V),0.0);
    float NdotH= max(dot(N,H),0.0);
    float VdotH= max(dot(V,H),0.0);
    gl_FragColor= Fd(NdotV, NdotL) + Fs(VdotH, NdotH, NdotL, NdotV, 128.0,128.0,1.0);
}

```

I already checked and it seems like all the uniforms and varying are passed in the right way, I pass P and N from the vertex shader. The variables are:

1. Light direction: L;
2. Surface normal: N;
3. Camera direction: V;
4. Half vector: H;
5. Fragment position: P.

The uniforms I pass are:

1. light{Specular | Diffuse | Ambient} : 0xffffff (converted to a rgba vector of course);
2. materialAmbient: 0x543807 ;
3. materialDiffuse: 0xc6901d;
4. materialSpecular: 0xfdefce;
5. materialShininess: 27.8974.

This is the result I get:

Which seems very strange to me, I've seen other images of Ashkhmin-Shirley implementations on the web, and they aren't similar. This is an example:

I want one like this !! Maybe I am using wrong values of phi and other values? Or there's something wrong in the formula?

# Answer
```
vec4 Fr(float u, vec4 specular) {
    return specular + (1.0-specular) * pow(1.0 - u, 5.0);
}

```

what's the specular in this function ? I think you specular is wrong,you can change

```
float Fr(float u) {
    float f = 0.125;
    float fresnelCoe = f + (1 - f)*pow(1 - u, 5);
}

```

f is a constant, different object has difference number
> 2 votes

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


title: Check if all gameobjects are destroyed

text:
# Question
Title: Check if all gameobjects are destroyed
I am making a shooting game, where I have a countdown as I destroy enemies. I want to implement logic when all the game objects are destroyed within the given time, and the countdown reaches zero.

How do I do that?

# Answer
You need to find a way of identifying all objects of interest. Do they have a particular script on them? You simply count them

```
if(GameObject.FindObjectOfType<EnemyScript>()==null)
{
    // Everything destroyed
}
else
{
    // Something survived
}

```
> -2 votes

# Answer
As mentioned, you could use `UnityEngine.GameObject.FindObjectOfType<>()` to find all available instances of a particular script, ideally the script that defines these game objects as enemies, in your game. This works, but it involves a lot of redundant work. You do not need to check if there is still an enemy alive in *every* frame. Instead, have your enemies notify us when they are destroyed.

---

## Creating an Objective Manager

Ideally, your main logic would be *aware* of the enemies, and the *enemies* would notify the main logic, when they are destroyed. I usually implement this behavior through a singleton objective manager class.

```
public class ObjectiveManager
{
    public static ObjectiveManager instance;

    void Awake()
    {
        if(instance == null)
        {
            instance = this;
        }
        else if(instance != this)
        {
            if(gameObject == null)
            {
                Destroy(this);
            }
            else
            {
                Destroy(gameObject);
            }
        }
    }
}

```

By being created in this way, we can always access our `ObjectiveManager` as an *instance*, even when we do not have a direct reference. That is because we have a *static* reference to our single instance: `ObjectiveManager.instance`. As an alternative to using a singleton and having a static reference to the objective manager, you could provide each enemy with a reference to `ObjectiveManager`.

---

## Creating a list of enemies..

### .. By searching all game objects

You have *two* fairly easy ways to find all the active enemies in your scene: by *tag* and by *script*. They both work fairly similar to eachother;

* **`FindObjectsOfType<Enemy>()`** will find *all* active instances of `Enemy`, and will retrieve a list of `Object` types.
* **`FindObjectsWithTag("Enemy")`** will find *any* active instance of a game object tagged with the string "Enemy". This allows you to specify specific `Enemy` instances to add to your count, and will retrieve a list of `GameObject` types.

Once you have decided how you wish to create your list, doing so is fairly simple. Note that you should only implement the code relating to the means in wish you wish to create your list.

```
public class ObjectiveManager
{
    public static ObjectiveManager instance;

    public int enemyCount;

    void Awake()
    {
        /* logic for setting up the instance reference */

        Object[] enemyList = GameObject.FindObjectsOfType<Enemy>();
        GameObject[] enemyList = GameObject.FindObjectsWithTag("Enemy");

        // Since the first element in an array is 0, we will
        // increment the initial count by 1 to correct the real count.
        enemyCount = (enemyList.Length() + 1);
    }

```

### .. By having your `Enemy` inform `ObjectiveManager` on `Awake()`

With a singleton objective manager, it is even easier to have the `Enemy` class inform `ObjectiveManager` that it needs to be added to the count. This is especially handy if you wish to add more `Enemy` game objects mid-game.

First, you would add a public method to `ObjectiveManager` to handle incrementing the count.

```
public class ObjectiveManager
{
    public static ObjectiveManager instance;
    public int enemyCount;

    public void AddEnemy()
    {
        enemyCount++;
    }
}

```

Then, on your enemy, add logic to the `Awake()` method to alert the `ObjectiveManager`.

```
public class Enemy
{
    void Awake()
    {
        ObjectiveManager.instance.AddEnemy();
    }
}

```

---

## Alerting `ObjectiveManager` when an enemy is destroyed

From there, you can use the `Enemy` objects `OnDestroy()` method to inform `ObjectiveManager` that it has to decrement `enemyCount` by 1. Assuming we have correctly counted the total enemies at the start, we know that when we kill the last enemy, `enemyCount == 0`.

```
public class Enemy
{
    void OnDestroy()
    {
        ObjectiveManager.instance.EnemyDestroyed();
    }
}

public class ObjectiveManager
{
    public static ObjectiveManager instance;
    public int enemyCount;

    public void EnemyDestroyed()
    {
        enemyCount --;

        if(enemyCount <= 0)
        {
            AllEnemiesDestroyed();
        }
    }

    public void AllEnemiesDestroyed()
    {
        // all enemies destroyed. Continue appropriate logic from here.
    }
}

```
> 2 votes

# Answer
There was a complaint that any alternatives to the currently accepted "Find" answer are "over-engineered," but this is not necessarily the case. We can get both good performance and simple code:

```
public class CountedObject : MonoBehaviour {

    public static int count { get; private set; }

    public static event System.Action AllObjectsDestroyed;

    void Start () {
        // Count every object as it's initialized.
        count++;
    }

    void OnDestroy () {
        // Decrement the count when objects are destroyed,
        // and optionally fire an event when the last one is gone.
        if (--count == 0 && AllObjectsDestroyed != null)
            AllObjectsDestroyed();
    }
}

```

Now scripts that are interested in how many objects are left can find out in two ways:

* By reading `CountedObject.count` whenever it needs
* By subscribing to the event `CountedObject.AllObjectsDestroyed += OnAllDestroyed;`

The cost for this is quite modest:

* Very few lines of code
* Constant time to initialize
* Constant time to read the current count

(for the Find method, this cost is linear in the number of objects in the scene)
* Constant time to destroy
* Constant time per subscriber to notify when the last object is destroyed, and this cost is incurred only when the final destruction happens

(for the Find method, this cost is linear in the number of objects in the scene *every update tick* that we check it)

This is not as full-featured and robust as an object manager that can track multiple separate object counts or expose more inspector control, but it gets a greater degree of both flexibility and performance than the accepted answer.

We should of course be wary of premature optimization leading us to excessive complexity, but that doesn't mean we should use code we already know is inefficient when there are much better-performing options available with similar code simplicity. In this day of mobile gaming, even if an inefficiency doesn't hit your framerate, it's still sapping the player's battery unnecessarily when there could be a simple way to let them play longer. ;)
> 2 votes

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


title: How do I make a jetpack in Unity?

text:
# Question
Title: How do I make a jetpack in Unity?
I am trying to make a jetpack, in Unity, but I have a little problem. I can't make good flying controller.

There are two input options:

1. Control flying using a keyboard, and control movement using a vector, while always moving forward.
2. Control flying and movement using a keyboard, only.

Here's what I have planned, so far:

```
using System.Collections;
using UnityEngine;

public class JetScript : MonoBehaviour
{
    public float fuel = 60.0f;
    public float fuelUsing = 4.0f;
    public float maxFuel = 300.0f;
    public float gravity = 10.0f;
    public float JetForce = 5.0f;
    public float FlyingTime = 10000f;
    public Camera _camera;

    void Start()
    {
        GetComponent<Rigidbody>().freezeRotation = true;
        GetComponent<Rigidbody>().useGravity = false;
    }

    void FixedUpdate()
    {
        Vector3 velocity = GetComponent<Rigidbody>().velocity;

        if ((fuel >= 0) && (Input.GetKey(KeyCode.C)) && (FlyingTime >= 0))
        {
            GetComponent<Rigidbody>().AddForce(
                    new Vector3(_camera.transform.forward.x,  /* what goes here? */,
                    _camera.transform.forward.z), ForceMode.VelocityChange);

            FlyingTime -= Time.deltaTime;
        }

        GetComponent<Rigidbody>().AddForce(
                new Vector3(0, -gravity * GetComponent<Rigidbody>().mass, 0));
    }
}

```

How should I go about this?

# Answer
There are few things I notice when examining your code:

1. You get the rigidbody component twice every physics step (FixedUpdate).
2. Your implementation of gravity.
3. Difficulty calculating JetPack Force Direction.

Assuming you have a good reason for handling gravity on your own rather than letting the physics engine apply it, here are some tips:

**Problem 1: Getting a component**

In your start function, assign the rigidbody to a class variable. aka:

```
private Rigidbody rigid;
//...
void Start() {
    rigid = GetComponent<Rigidbody>()
    rigid.freezeRotation = true;
    rigid.useGravity = false;
    //etc
}

```

By doing so, your class only needs to get a reference to Rigidbody when it starts up. You can use rigid anywhere else without needing to have your script find it again. Conversely, you can make the rigid variable public and drag in the rigidbody component yourself from the inspector. This method wont require you to use GetComponent at all.

**Problem 2: Gravity Implementation**

The first red flag I see is that you are applying gravity * mass for your downward force. *This is incorrect* when mimicking real world physics. Google "Bowling ball vs feather" for reference. You should only apply the force of gravity, regardless of object mass.

**Problem 3: Jetpack direction**

Handling force and direction in a single vector can be difficult to comprehend at first. I calculate the force vector to apply by multiplying the force (JetForce) by the direction vector. In your case, the following code should help:

```
Vector3 forceToApply = JetForce * _camera.transform.up
rigid.AddForce(forceToApply, ForceMode.VelocityChange)

```

This hopefully will set you in the right direction for building your very first jetpack controller. I did not address smoothing out movement. For these tasks, you may want to consider a different ForceMode, along with clamping the velocity at a maximum speed. For the best results, I find that calculating a desiredVelocity and then using Vector3.SmoothDamp to smoothly achieve it is very effective. Select the method that is best for your game, whatever it may be!
> 2 votes

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


title: Implementing a camera on HTML5 canvas?

text:
# Question
Title: Implementing a camera on HTML5 canvas?
I am trying to work out the best way of implementing a camera in my simple 2d game.

The way it is structured at the moment is my game objects all have `draw` functions, which are passed a canvas instance to draw themselves to (at whatever position they are currently at).

I now need to add a camera to the mix, so that i can have a bigger world, but i'm not sure of the best way to implement it.

The way I see it, I can either translate the whole canvas and let the objects carry on drawing themselves at whatever position they are at, eg:

```
canvas.translate(camera.position);
player.draw(canvas);

```

This seems easy enough, but doesn't seem right somehow. Alternatively, I could pass the camera in to the objects with the canvas, and let the objects calculate a relative screen position before drawing, eg:

```
player.draw(canvas, camera);
// inside the draw function:
var position = this.position.subtract(camera.position);
canvas.drawStuff(stuff, position);

```

But that seems wrong too. How do other 2d engines handle this? Is there an established best way of doing it, or any pitfalls I should avoid?

# Answer
> 6 votes
I don't know what you think is wrong with those two approaches - both seem fine to me.

The only thing you have to watch out for is that you don't draw your whole world offscreen. Drawing offscreen is relatively cheap in most canvas implementations, but iterating completely through your data structure which stores the world data likely isn't. So before you draw a frame you should first determine the subset of objects and tiles which are actually in the viewport and only draw these. This means that you have to design your data structures in a way that you can determine these efficiently (without checking every single one, every single frame).

For the tilemap, a two-dimensional array will do. When you draw a frame, first calculate the array indices of the outmost tiles in x and y direction and then iterate the arrays in two nested for-loops which only iterate between these coordinates.

For the objects, however, the issue becomes more complex because they can move between frames. There are several approaches to this issue.

One way to do it would be to build an auto-balancing 2d-tree data structure.

Another way would be to divide the game world into chunks of uniform size and make each chunk keep an own array of objects. Store the objects in a two-dimensional array just like the map tiles. When an object moves, check if it has passed a chunk border, and when it did, remove it from the old chunk and add it to the new one. When you draw a frame, only draw the objects on the object lists of the chunks which intersect the viewport.

# Answer
> 0 votes
I gave this answer as my proof of concept or method of creating a camera. You can also view it in it's repo

Long story short, you draw the World **once** with any static objects/sprites (e.g. walls), you then project it onto a viewport canvas as the player moves. All objects/sprites that move or animate are drawn onto the player canvas (a canvas that overlays the viewport canvas)

But yea, hope this helps as well. The answer is very detailed so I hope it's helpful.

---
Tags: 2d, camera, html-canvas
---


# Question
Title: Instantiating without the use of Resource Folder in Unity?
I am making a game which has around 25 prefabs. I want to generate these prefabs randomly one after another and also I am destroying the last prefab. One way is to make an array of gameobjects and then reference the prefabs to them. But this way a lot of memory is being used(around 190 MB) because of which my game crashes in android device. Another alternative is using the resources folder but I want to make asset bundle and I will not be able to make assetbundle of my resource folder. So is there any other way to Instantiate prefabs so that memory usage is also less and aset bundling is also possible.

# Answer
> 1 votes
The Resources folder is only needed *instead* of an asset bundle, not in addition to. If something is going in an asset bundle, then you load it from the bundle and it doesn't need to be in Resources.

# Answer
> 0 votes
You can load the asset bundle. Load a randomly selected object from that bundle and get a reference to it and then unload the asset bundle to conserve memory. This how ever means that you will have to load the asset bundle every time you have a new object. So a so called pooling system might be what you need. I will explain the steps.

1.Load the asset bundle

2.Load a chunk of the object in the bundle into a list(you will have to work out what number has good memory usage in your case)

3.Use that list to instantiate a randomly selected object. When you instantiate it you might want to keep a seperate list with something like object ID's to make sure we dont load/instantiate the same object twice.

4.Remove the object from the list when no longer needed.

5.When the list is empty repeat with step 1 and load another chunk of objects.

---
Tags: unity, scripting, resource-management
---


# Question
Title: Generate a random number of enemies to appear on screen
I am currently trying to create 2d shmups. I am trying to:

* Generate a random number of enemies to appear on screen
* Whatever number is generated will then be added to my List (the list is used to keep track of enemies). to load that number of textures.
* I would also like to keep a collection of Vectors to determine the positions the enemies will spawn randomly.

This is what I have done so far:

```
 List <Enemies> enemies = new List<Enemies>();
 Random rnd = new Random();
 int numberOfEnemies = rnd.Next(1,5); // I would like to generate between 1 and 5.
 if (enemies.count < numberOfEnemies){
     enemies.Add(new Enemy(Content.Load<Texture2D>("alienship");// one of the vectors from the collection of vectors will go here
 }

```

# Answer
> 1 votes
A few changes to your code are needed to achieve your objectives:

First, a caveat; most of what you are looking to do can be done using basic coding principles. If you're struggling to put this together, I'd recommend you look through the C# Programming Guide (https://msdn.microsoft.com/en-us/library/67ef8sbd.aspx). There's absolutely nothing wrong with attempting to learn the language, but making the jump straight into game development can be tricky.

Now then, the first thing you want to do is change your **if** clause to a **for** or **while** loop.

**While** loop:

```
List <Enemies> enemies = new List<Enemies>();
Random rnd = new Random();
int numberOfEnemies = rnd.Next(1,5) // I would like to generate between 1 and 5.
while (enemies.count < numberOfEnemies){
   enemies.Add(new Enemy(Content.Load<Texture2D>("alienship"),// one of the vectors from the collection of vectors will go here;
}

```

**For** loop:

```
List <Enemies> enemies = new List<Enemies>();
Random rnd = new Random();
int numberOfEnemies = rnd.Next(1,5) // I would like to generate between 1 and 5.
for(; enemies.count < numberOfEnemies; ){
   enemies.Add(new Enemy(Content.Load<Texture2D>("alienship"),// one of the vectors from the collection of vectors will go here;
}

```

Note that there are multiple ways to accomplish this, and while both are syntactically correct, the **while** loop is much cleaner in this case. In C#, and indeed most languages, changing your **if** clause to a loop (**for**,**while**) causes the code to repeatedly execute everything within the clause while a condition is met.

With this change made, you now have multiple enemies being created, however, none of them have a position initialized yet. To do this, we will extend the existing code.

```
List <Enemies> enemies = new List<Enemies>();
Random rnd = new Random();
int maxSpawnX = 800;
int maxSpawnY = 600;

int numberOfEnemies = rnd.Next(1,5);
while (enemies.count < numberOfEnemies){
   int x = rnd.Next(0, maxSpawnX);
   int y = rnd.Next(0, maxSpawnY);
   enemies.Add(new Enemy(Content.Load<Texture2D>("alienship"), new Vector2((float)x, (float)y)));
}

```

First, note that this assumes the constructor for your Enemy class looks something like

```
public Enemy(Texture2D texture, Vector2 location) { ... }

```

We've added two new variables to make life easier (maxSpawnX, maxSpawnY), and inside our loop we've created new *x* and *y* integers which hold the result of our random number operations. We insert those variables into a newly initialized Vector2, casting them to floats as we do so (using (float)).

With this done, the code now works and generates a random number of enemies in random locations. However, there are a few more details that need fixing.

The Random.Next(min,max) method provides a psuedo-random number within min(inclusive) and max(exclusive). That exclusive part is rather important here, as you state you want a random number between 1 and 5. However, as written in the code (rnd.Next(1,5)), you're actually generating a number between 1 and 4. To fix this, we need to increment that number by 1. We also have the same issue in our x and y variables, so those need fixed as well. (This code is not displayed as an exercise for the question-asker)

The only other issue I have with the code as it is now is your use of Content.Load for each enemy created. If each enemy in the loop were using a different texture, this could be an acceptable way to do this, and even as it is now, it works. However, it's likely not the most efficient way to do this as you're calling unneeded logic every time you create an enemy. A better way to do this is to move the Texture2D load outside of the scope of that loop, so the texture load is only called once.

```
List <Enemies> enemies = new List<Enemies>();
Random rnd = new Random();
int maxSpawnX = 800;
int maxSpawnY = 600;
Texture2D enemyTexture = Content.Load<Texture2D>("alienship");
int numberOfEnemies = rnd.Next(1,5);
while (enemies.count < numberOfEnemies){
   int x = rnd.Next(0, maxSpawnX);
   int y = rnd.Next(0, maxSpawnY);
   enemies.Add(new Enemy(enemyTexture, new Vector2((float)x, (float)y)));
}

```

With this done, you don't waste computing time looking up and possibly loading duplicate textures. (granted, I believe XNA is smart enough to recognize that this texture has already been loaded and just passes a reference to the existing object)

---
Tags: c#, xna, random
---


# Question
Title: How to connect circle nodes using arrows?
I'm trying to design a simple game where a series of numbered circles can be connected by arrows (like mobile phone pattern locks).

I have these circles designed here: https://jsfiddle.net/sarmadm/wq8fLphx/

As an example: The user starts from node (1) to any node (e.g node A), then from (A) to another node . I have designed the circle nodes but I can't workout how to connect them using arrows, how can I make these nodes connectable?

# Answer
I have rewritten your code so it uses objects to manage the circles. Try to understand all I have changed before continuing (Note that I have not changed the implementation of your drawing functions, they might need a review too):

```
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

function Circle(I) {
   I.radius = 30;

   I.draw = function() {
       context.beginPath();
       context.arc(I.x, I.y, I.radius, 0, 2 * Math.PI, false);
       context.fillStyle = 'white';
       context.fill();
       context.lineWidth = 2;
       context.strokeStyle = '#003300';
       context.stroke();
       context.font = '15pt Calibri';
       context.fillStyle = 'black';
       context.textAlign = 'center';
       context.fillText(I.label, I.x, I.y);
   }

   return I;
}

var circles = [];

circles.push(Circle({
    x: 369,
    y: 116,
    label: "A"
}));
circles.push(Circle({
    x: 231,
    y: 278,
    label: "1"
}));
// Do above for all your circles

function drawArrow(from, to) {
    var radians = Math.PI / 180;
    var headlen = 10;
    var angle = Math.atan(Math.abs(from.y - to.y) / Math.abs(from.x - to.x));
    var rise = from.radius * Math.sin(angle);
    var run = to.radius * Math.cos(angle);
    context.beginPath();
    if (from.x < to.x) {
        from.x += run;
        to.x -= run;
    } else {
        from.x -= run;
        to.x += run;
    }
    if (from.y < to.y) {
        from.y += rise;
        to.y -= rise;
    } else {
        from.y -= rise;
        to.y += rise;
    }
    context.moveTo(from.x, from.y);
    context.lineTo(to.x, to.y);
    context.stroke();
    context.lineTo(to.x - headlen * Math.cos(angle - Math.PI / 6), to.y - headlen * Math.sin(angle - Math.PI / 6));
    context.moveTo(to.x, to.y);
    context.lineTo(to.x - headlen * Math.cos(angle + Math.PI / 6), to.y - headlen * Math.sin(angle + Math.PI / 6));
    context.stroke();
}

circles.forEach(function(circle) {
    circle.draw();
});

drawArrow(circles[0], circles[1]);

```

I good improvment now is that it is really easy to move the cicles in the middle of the game : just change their x and y values. Same goes for radius, you can easily have circles with different radius.

Now if you want to make it into some kind of game where the user can select the circles to link them, you might want to add a few things :

1. A game loop
2. Get the user's mouse inputs and find which circles are clicked

Then if you know that the user pressed the mouse on circle B and released it on circle A, you can call the `drawArrow` function from B to A.
> 0 votes

---
Tags: javascript, html-canvas
---


# Question
Title: Changing a direction Vector with Euler angles
It seems like an easy problem but I somehow didnt got to the solution. I need the Maths to change the Vector based on Euler angles.

Example Problem:

I have an direction Vector- for example: Showing Forward: (0,0,1)

I have 3 Euler Angles (X,Y,Z) for example like this: (0°,180°,0)

Which means: It rotates back -

Now if I add that to the direction Vector- I want my direction Vector to show Backward (0,0,-1)

I tried last night and did not came up to a solution how to do the maths for this.

Anyone here knows the math to solve this?

# Answer
The general solution is to unpack your angular representation to a transformation matrix or quaternion, then multiply your vector by that transformation.

The exact matrix math will depend on the conventions used for your angular representation. In games we often call any 3-angle representation "Euler" but often we really use roll-pitch-yaw or pitch-roll-yaw systems that aren't mathematically equivalent. For an example of how to derive this matrix for your rotation conventions, check this related answer. We won't be able to offer a more explicit answer without knowing what your angles represent in your environment's rotation conventions.

For special cases where the vector is aligned with one of the coordinate axes (like your `(0, 0, 1)` example), it suffices to compute just one column of the transformation matrix, and scale it by the nonzero component of your vector to generate its transformed version - so that can be a shortcut if you only care about one or two axes. Similarly, we can simplify the matrix math if you know in advance that one of your angles will always be zero or some other constant.
> 1 votes

---
Tags: vector, angles
---


# Question
Title: Wierd behaviour upon limiting rotation on Y-axis
Okay, this is the code that works for a FPS camera, except it allows the player to flip it over by going under/over -/+90° rotation on Y-axis:

```
transformation->rotateObjectFromRight(glm::radians(angleX), glm::tvec3<GLfloat>(0.0f, 1.0f, 0.0f));
transformation->rotateObjectFromLeft(glm::radians(angleY), glm::tvec3<GLfloat>(1.0f, 0.0f, 0.0f));

```

`transformation` object holds the data required to construct the view matrix, among others, a quaternion representing the rotation.

The functions called will construct the quaternion with the given data and then multiply it with the rotation quaternion either from the left (relative to global axes) or the right (relative to local axes) side.

`angleX` and `angleY` are mouse X and Y offsets representing the angles to rotate around.

The first line yaws the camera around local Y-axis, while the second then pitches it around global X-axis, creating the characteristic FPS camera movement.

Okay. So far so good. This is the code that should limit the pitch to never exceed the +/-90 boundaries:

```
transformation->rotateObjectFromRight(glm::radians(angleX), glm::tvec3<GLfloat>(0.0f, 1.0f, 0.0f));

glm::tvec3<GLfloat> forwardVector = glm::rotate(glm::inverse(transformation->getRotation()), glm::tvec3<GLfloat>(0.0f, 0.0f, 1.0f));
GLfloat pitchAngle = forwardVector.y * 90.0f;
angleY = glm::clamp(angleY, -(pitchAngle + 90.0f), -(pitchAngle - 90.0f));

transformation->rotateObjectFromLeft(glm::radians(angleY), glm::tvec3<GLfloat>(1.0f, 0.0f, 0.0f));

```

First and the last line are the same. What happens here?

First I get the unit vector that lies on the Z-axis and rotate it so that it represents the forward vector of the camera. I then take the Y component of that vector (ranging from -1 to 1) and multiply it with 90 to get the degrees. Then I clamp the angleY so that current rotation combined with the new one never exceeds the +/-90° boundary.

If the rotation was about to flip the camera overhead, it would change the new rotation angle so the camera looks straight up. Similar thing for underfoot flipping.

However, the camera acts weird. It's fastest at pitch angles close to 0°, but gets progressively slower as the pitch nears +/-90°. If I move my mouse slower, the camera is faster, if I move it faster, it's slower.

It's as though it's discarding the too large/small angleY values instead of clamping them to the appropriate values (but it's not, and I can confirm via the debugger - all the calculated values look alright and are correct).

What could be amiss here to cause such weird movement?

# Answer
> 0 votes
I was, interestingly enough, using radians instead of degrees. Usually it's the other way around.

---
Tags: opengl, c++, rotation, quaternion, glm
---


# Question
Title: Drawing in SFML outside of the main function (passing the window over to other fuctions) doesn't work
Why does the drawn Sprite only appear in the Window when drawn from the main-function, but not when drawn from an external function and how can I change this?

```
class Class {
private:
sf::Sprite sprite;

public:
Class()
    {
        sprite = initializeSprite(sprite);
    }
};

void Class::draw(sf::RenderWindow& win)
{
    win.draw(sprite);
}

int main(int argc, char* argv[])
{
    sf::RenderWindow window(sf::VideoMode(1920,1080), "Window");
    Class instance;
    while(window.isOpen())
    {
        window.clear();
        instance.draw(window);
        window.display();
    }

    return 0;
}

```

-\> Doesn't work.

```
int main(int argc, char* argv[])
{
    sf::RenderWindow window(sf::VideoMode(1920,1080), "Window");
    sf::Sprite sprite;
    sprite = initializeSprite(sprite);
    Class instance;
    while(window.isOpen())
    {
        window.clear();
        window.draw(sprite);
        window.display();
    }

    return 0;
}

```

-\>Works.

I'm using SFML-2.4.0. It also doesn't work when i use a pointer instead of a reference. What's wrong here?

# Answer
I tried out your code and it works quiet fine. How did you initialize your Sprite? One possible reason why it doesn't work is that your image isn't loaded correctly or your sprite is "to small" (that happens if you only says that the color should be red; there is no information about the size so it is 0x0 pixel).

Here is the code I tried (Copy + Paste + Correcting all formal errors):

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

using namespace std;

class Class {

private:

    sf::Sprite sprite;
    sf::Texture texture;

public:

    Class() {
        // Loading my test-image (128x128 px)
        texture.loadFromFile("player.png");
        sprite.setTexture(texture);
    }

    void draw(sf::RenderWindow& win) {
        win.draw(sprite);
    }

};

int main(int argc, char* argv[])
{
    sf::RenderWindow window(sf::VideoMode(640, 480), "Window");
    Class instance;

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

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

    return 0;
}

```
> 1 votes

---
Tags: architecture, graphics, sprites, sfml
---


# Question
Title: Untity Game Destroy all objects instead of one
I have two game objects with the same script.

In the PicUpSys script I have this code

```
using UnityEngine;
using System.Collections;

public class PicUpSys : MonoBehaviour
{

    public InvSys _InvSys;

    public bool SmallStone;
    public bool SmallTree;

    public GameObject ME;

    void Start()
    {
        ME = gameObject;
    }

    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            if (SmallStone == true)
            {
                if (_InvSys.SelectedSlot == "1")
                {
                    if (_InvSys.FirstSlotCont == "")
                    {
                        _InvSys.FirstSlotCont = "SmallStone (1)";
                        _InvSys.FirstSlotContN = 1;
                        _InvSys.Stone = _InvSys.Stone + 1;
                        Destroy(ME, 1);
                    }

                    else
                    {
                        _InvSys.FirstSlotCont = "SmallStone (" + _InvSys.FirstSlotContN + ")";
                        _InvSys.FirstSlotContN = 1;
                        _InvSys.Stone = _InvSys.Stone + 1;
                        Destroy(ME, 1);
                    }
                }

                else if (_InvSys.SelectedSlot == "2")
                {

                }

                else if (_InvSys.SelectedSlot == "3")
                {

                }
            }
        }
    }
}

```

When I start the game ME is automatically set to the current game object.

But when I click the SmallStone the script destroy SmallStone and SmallStone(1)

How I can do to only destroy SmallStone?

# Answer
> -1 votes
Try defining an object, in the code, as a variable. Then, go into the inspector, and set that game object to each stone as it's self. Finally, make the code destroy that game object variable.

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


# Question
Title: Unity C# GameObject Clones Sharing the Same Script When I Don't want them to
I've been having issues with a game I've been working on for a while. It's a pretty big project. I'm having some issues with two tree prefab game objects sharing code, where I don't want them to.

When the player presses `E` while facing them, they start searching the tree for items like apples. It was all working well, until I added another tree. Now, when I search one tree, it searches all trees in the scene. Obviously, I don't want that to happen.

I have provided my code, below. What am I doing wrong?

```
public class Search : MonoBehaviour
{
    public List<Item> items;
    public bool searched = false;
    public GameObject inventory;
    public Inventory inv;
    public Log log;
    public AudioSource takeSFX;
    public GameObject player;

    void Awake()
    {
        inventory = GameObject.Find("  Inventory Master");
        inv = inventory.GetComponent<Inventory>();
    }

    void Start()
    {
        log = GameObject.Find("  Game Master").GetComponent<Log>();
        AddItems();
        items = new List<Item>();
    }

    void Update()
    {
        SearchObject();
    }

    public void AddItems()
    {
        int rand = (int)Random.Range(0, 2);
        Debug.Log(rand);

        for (int i = 0; i < rand; i++)
        {
            items.Add(inv.database.FetchItemByID(0));
        }
    }

    public void SearchObject()
    {
        if (Input.GetButtonDown("Interact"))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit = new RaycastHit();
            Debug.Log("Raycasting");

            if (Physics.Raycast(ray, out hit, 10))
            {
                Debug.Log("Searching");

                if (!searched)
                {
                    this.takeSFX.Play();

                    if (items.Count >= -0)
                    {
                        for (int i = 0; i < items.Count; i++)
                        {
                            this.inv.AddItem(items[i].ID);
                        }
                    }

                    if (items.Count == 0)
                        log.UpdateLog("No items found in search.");
                    else if (items.Count == 1)
                        log.UpdateLog("1 item found in search.");
                    else
                        log.UpdateLog(items.Count + " items found in search.");
                    searched = true;
                }
            }
        }
    }
}

```

# Answer
Your raycast is being cast for every tree in the scene. Every tree is checking if the raycast hit *something*, even if it's not that tree.

This is happening because you are getting the input event **inside** the tree object. You should centralize this Event Handler, adding it to inside your PlayerInput.
> 2 votes

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


# Question
Title: Procedural generation of heightmap for non rectangular surface
I'm working on procedural generation of terrain for a continent, meaning I need a wide range of hills, mountains and valleys generated around the continent. For mountains I've adopted Amit's algorithm for island generation, which produces quite good looking mountain with very clear ridges, slopes and everything else mountain tend to have. Now my problems is with some smoother hilly terrain.

Due to a hexagonic nature of my continent, the mesh is subdivided into triangles. Also due to needing multiple mountains/hills/valleys I also split my continent into sectors, which are then stitched together easily due to the fact the edges of the sectors always have zero elevation. So the constraints are the following:

* The surface is hexagonal, this actually is less of a problem, since I can still generate elevation for "square" grid and use bilinear interpolation on "real" hexagon verts.
* The surface is not a square, this I have absolutely no idea how to deal with.

Now most of the terrain generating algorithms always generate the terrain on a square surface, midpoint displacement, noise, you name it. Also they don't generate zero values on the edges, which is a strict requirement for me.

Now I would really like to adopt the double simplex noise approach, but once again, I need a way to force it to always generate zeroes outside of the bounds of my polygonal sector (which obviously varies), and smooth values inside the bounds, which would form nice hilly terrain. Question is... is it even possible, or should I be looking for a diferent approach?

# Answer
> 1 votes
I build an ISO surface from a volume texture so I do thing a bit different but I had to find away to make the edges of the volume to be at y=0.

I use a falloff texture to attenuate the volume texture so the edges blend down to 0, I'm sure you could do sort of the same.

then blend in the volume texture shader like this:

```
float blend = permTexture.Sample(samANISOTROPICWrap, input.TexCoord2 / 32);

nFinal = clamp(lerp(-1, nFinal, blend), -1, 1);

return   nFinal;

```

What the above is doing is:

taking the final pixel value from my noise generation and using lerp to blend between the final pixel value and -1 using the falloff texture as the lerp factor, I then clamp it to -1,1 just incase the falloff texture messes with the values.

My noise is in the -1 to 1 range and the falloff texture is in the 0 to 255 range but on the GPU all values are between 0 and 1 because I load it into an 8bpp texture2D so I remaps the values to 0 to 1 range.

Now if you are using the CPU then you will need to load it like a height map and sample the values as you would for height map terrain.

It would go something like this:

Keep in mind that this code will not just drop in and work, its here to give you an idea of how it should work.

VB.Net:

```
Public Class HeightFinder
Public HeightData As Single(,)
// the position of the heightmap's -x, -z corner, in worldspace.
Private heightmapPosition As Vector3
// the total width of the heightmap, including terrainscale.
Private heightmapWidth As Single
// the total height of the height map, including terrainscale.
Private heightmapHeight As Single
Private TerrainScale As Single = 32

Private Sub tex2Dlod_bilinear(image As Bitmap)
    HeightData = New Single(image.Width - 1, image.Height - 1) {}

    Dim texelSize As Single = 1.0F / image.Width

    For y As Integer = 0 To image.Height - 1
        For x As Integer = 0 To image.Width - 1

            Dim uv As New Vector2(x, y)

            Dim height00 As Single = image.GetPixel(uv.X, uv.Y).R

            HeightData(x, y) = height00
        Next
    Next
End Sub
Public Sub New(texturePath As String, _TerrainScale As Single)
    TerrainScale = _TerrainScale
    Dim image As Bitmap = Bitmap.FromFile(DirectXDevice.ContentPath & texturePath)
    tex2Dlod_bilinear(image)
    heightmapWidth = (HeightData.GetLength(0) - 1) * TerrainScale
    heightmapHeight = (HeightData.GetLength(1) - 1) * TerrainScale
    heightmapPosition.X = -(HeightData.GetLength(0) - 1) / 2.0F * TerrainScale
    heightmapPosition.Z = -(HeightData.GetLength(1) - 1) / 2.0F * TerrainScale
    //image.Dispose()
End Sub
    // This function takes in a position, and tells whether or not the position is
    // on the heightmap.
Public Function IsOnHeightmap(position As Vector3) As Boolean
    // first we'll figure out where on the heightmap "position" is...
    Dim positionOnHeightmap As Vector3 = position - heightmapPosition
   // ... and then check to see if that value goes outside the bounds of the
   // heightmap.
    Return (positionOnHeightmap.X > 0 AndAlso positionOnHeightmap.X < heightmapWidth AndAlso positionOnHeightmap.Z > 0 AndAlso positionOnHeightmap.Z < heightmapHeight)
End Function

//This function takes in a position, and has two out parameters: the
// heightmap's height and normal at that point. Be careful - this function will
// throw an IndexOutOfRangeException if position isn't on the heightmap!
Private Function GetHeight(position As Vector3) As Single

    If IsOnHeightmap(position) Then

        // the first thing we need to do is figure out where on the heightmap
        // "position" is. This'll make the math much simpler later.
        Dim positionOnHeightmap As Vector3 = position - heightmapPosition

        // we'll use integer division to figure out where in the "heights" array
        // positionOnHeightmap is. Remember that integer division always rounds
        // down, so that the result of these divisions is the indices of the "upper
        // left" of the 4 corners of that cell.
        Dim left As Integer, top As Integer
        left = CType(positionOnHeightmap.X, Integer) / CType(TerrainScale, Integer)
        top = CType(positionOnHeightmap.Z, Integer) / CType(TerrainScale, Integer)

        // next, we'll use modulus to find out how far away we are from the upper
        // left corner of the cell. Mod will give us a value from 0 to terrainScale,
        // which we then divide by terrainScale to normalize 0 to 1.
        Dim xNormalized As Single = (positionOnHeightmap.X Mod TerrainScale) / TerrainScale
        Dim zNormalized As Single = (positionOnHeightmap.Z Mod TerrainScale) / TerrainScale

        // Now that we've calculated the indices of the corners of our cell, and
        // where we are in that cell, we'll use bilinear interpolation to calculuate
        // our height. This process is best explained with a diagram, so please see
        // the accompanying doc for more information.
        // First, calculate the heights on the bottom and top edge of our cell by
        // interpolating from the left and right sides.
        Dim topHeight As Single = MathHelper.Lerp(HeightData(left, top), HeightData(left, top), xNormalized)

        Dim bottomHeight As Single = MathHelper.Lerp(HeightData(left, top), HeightData(left, top), xNormalized)

        // next, interpolate between those two values to calculate the height at our
        // position.
        Return MathHelper.Lerp(topHeight, bottomHeight, zNormalized)

    Else

        Return 0

    End If

End Function
End Class

```

The idea with this code is to load your falloff texture from a bitmap and then let you sample it with your cell\poly\whatever x and y values.

Once you have sampled the falloff texture you would use it like this:

noisevalue=lerp(0,noisevalue, GetHeight(cell.x,cell.y,cell.z)

will blend from 0 to noisevalue based on the falloff texture, the closer the falloff texture is to 1 the more of the noisevalue will be shown.

Ps. I haven't used this bit of code in a long time as I have changed my terrain to volumetexture based marching cube terrain.

---
Tags: procedural-generation, maps, terrain-rendering, heightmap, simplex-noise
---


title: How can i solve this artifact in CSM

text:
# Question
Title: How can i solve this artifact in CSM
I have the next issue when a object is suspended in the air far enough of the ground.

How the algorithm works:

* It checks if the coordinates in the light view matrix of this cascade are inside the the actual cascade's view (\[0,1\] interval).
* If it is inside, it checks the depth to see if it is in shadow and finish.
* If it is not, it checks the next cascade.

The coordinate that it is checking is actually inside this shadow cascade, but the cube lands just partially in this shadow cascade, and for this reason the surface is cut and you can see the floor that is at the other side of the cube, which is the floor that is checking to draw or not the shadow, producing this artifact.

Is it any way to solve it? I tried checking if the next cascade has lower depth but it cause other problems and artifacts that are even worse because of the glur effect and the lower precision of the next cascade.

It just happen with distant flying objects or high objects, anything else it works great.

# Answer
Looks like your near clip could be set wrong.

Alos the thing with shadows is that sometimes you cant see the object but it casts shadows so u need to handle the culling different.

So for normal rendering you want just whats in front of the camera but for shadows u need some of the objects that are behind the camera.

I use the lightview frustum from each cascade to cull the objects.

But after looking at you screen shot I really think its your near clip for the shadow camera and the shadow looks funny to me.... like its distorted.

I tried VSM for a while but I didn't like how they looked so I went back to PCF:

```
// Calculates the shadow term using PCF soft-shadowing
// sqrtSample is the filter size. I.e. 2 for 2x2 PCF, 3 for 3x3 PCF, etc.
float2 CalculateShadowTermSoftPCF(float2 texCoord, float ourdepth, Texture2D ShadowMap,uint sqrtSamples)
{
float shadowTerm = 0.0f;

float radius = (sqrtSamples - 1.0f) / 2;

float Depth = ShadowMap.Load(int3(texCoord, 0)).r;
for (float y = -radius; y <= radius; y++)
{
    for (float x = -radius; x <= radius; x++)
    {
        float2 offset = float2(x, y) / ShadowMapSize;
        float sampleDepth = ShadowMap.SampleCmpLevelZero(samShadow, texCoord + offset, ourdepth).r;

        // Edge tap smoothing
        float xWeight = 1;
        float yWeight = 1;

        if (x == -radius)
            xWeight = 1 - frac(texCoord.x * ShadowMapSize.x);
        else if (x == radius)
            xWeight = frac(texCoord.x * ShadowMapSize.x);

        if (y == -radius)
            yWeight = 1 - frac(texCoord.y * ShadowMapSize.y);
        else if (y == radius)
            yWeight = frac(texCoord.y * ShadowMapSize.y);

        shadowTerm += sampleDepth * xWeight * yWeight;

    }
}

shadowTerm /= ((sqrtSamples - 1.1) * (sqrtSamples - 1.1));
return float2(shadowTerm, Depth);
}

```

Random disk filter:

```
 float2 poissonDisk[24] =
 {
 float2(-0.4448907f, 0.7713736f),
 float2(-0.4675094f, 0.4431239f),
 float2(-0.1220913f, 0.5835819f),
 float2(-0.8736015f, 0.3635427f),
 float2(-0.2091058f, 0.0196037f),
 float2(-0.7448996f, 0.6206658f),
 float2(0.2112615f, 0.1990242f),
 float2(-0.572591f, -0.1135838f),
 float2(0.2162377f, 0.7406282f),
 float2(0.4967479f, 0.5918304f),
 float2(0.4943127f, -0.0736846f),
 float2(-0.461087f, -0.393838f),
 float2(-0.8604655f, -0.04897872f),
 float2(-0.09501296f, -0.808184f),
 float2(0.8711416f, 0.248008f),
 float2(0.07829998f, -0.1680121f),
 float2(0.4522456f, -0.5761201f),
 float2(0.6582519f, -0.3458804f),
 float2(-0.1601302f, -0.4334383f),
 float2(-0.3873517f, -0.7103282f),
 float2(0.2616926f, -0.8700755f),
 float2(-0.7656811f, -0.6018973f),
 float2(0.9460136f, -0.1249114f),
 float2(0.5343407f, 0.2145455f)
};

float poissonDiskFilter24Samples(float2 texCoord, float ourdepth, Texture2D ShadowMap)
{
// Get the current depth stored in the shadow map
float4 samples[24];

float shadow = 0;

float2 pixelSize = ShadowMapPixelSize * spread;

[unroll]
for (int i = 0; i < totalSamples; i++)
{
    samples[i] = ShadowMap.SampleCmp(samShadow, texCoord + poissonDisk[i] * pixelSize,ourdepth).r;
    shadow += samples[i];
}

// shadow /= totalSamples  * totalSamples ;
shadow /= ((totalSamples - 1.1) * (totalSamples - 1.1));

return totalSamples * shadow;
}

```
> 1 votes

---
Tags: shadow-mapping
---


# Question
Title: How do i define array in shader's constant buffer with C#?
I am using SharpDX to render 3D graphics and i cannot get to work constant buffer in my shader since it contains an array. Currently it looks like this:

```
cbuffer cb0 : register(b0)
{
    matrix mWorld;
    matrix mView;
    matrix mProj;
    float4 vLightDir[2];
    float4 vLightColor[2];
    float4 vOutputColor;
}

```

But how to define a struct in C#, which will be correctly marshalled to such constant buffer in shader? In C# we don't have "excplicit" array initialization, e.g. this line of code i used in C++ will not work in C#:

```
struct cb0
{
  // ...
  Vector4 twos[2];// C#: Vector4[] twos;
// ...
}

```

I always set StructLayout option Pack=16 for my structs for alignment, but HOW to define such struct with C#? i have tried to define struct like this:

```
struct cb0_t//pack=16
        {
            public Matrix mWorld;
            public Matrix mView;
            public Matrix mProj;
            public Vector4 vLightDir0;
            public Vector4 vLightDir1;
            public Vector4 vLightColor0;
            public Vector4 vLightColor1;
            public Vector4 vOutputColor;
        }

```

Yes, it works with this, but this IS NOT COOL. Thank you, sorry for my english...

# Answer
If you make a light structure and send that as an array it should work, also maybe use two constant buffers?

Looks something like this(HLSL):

```
struct Light
{
float4 vLightDir;
float4 vLightColor;
};
cbuffer Camera : register(b0)
{
matrix mWorld;
matrix mView;
matrix mProj;
}

cbuffer Lights : register(b1)
{
Light lights[];
}

```

C#

```
[StructLayout(LayoutKind.Sequential)]
public struct Light
{
public Vector4 LightDir;
public Vector4 LightColor;
}
[StructLayout(LayoutKind.Sequential)]
public struct Camera
{
public Matrix mWorld;
public Matrix mView;
public Matrix mProj;
}
private Light[] lights = new Light[2] { };
private Buffer LightCB;

public void updatelight(DirectXDevice _dev)
{
lights(0) = new light();
lights(0).LightDir = new vector4();
lights(0).LightColor = new vector4();
lights(1) = new light();
lights(1).LightDir = new vector4();
lights(1).LightColor = new vector4();
LightCB = _dev.CreateBuffer(BindFlags.ConstantBuffer, lights);
}

```
> 1 votes

# Answer
It looks like you can use the `MarshalAs` attribute like so

```
[StructLayout(LayoutKind.Sequential, Pack = 16)]
public struct cb0_t
{
    public Matrix mWorld;
    public Matrix mView;
    public Matrix mProj;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=2)]
    public Vector4[] vLightDir;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=2)]
    public Vector4[] vLightColor;
    public Vector4 vOutputColor;
}

```

You can take a look at this article, search for the heading Arrays.

Otherwise here's a shorter solution on StackOverflow.
> 0 votes

---
Tags: c#, hlsl, data-structure, sharpdx, slimdx
---


# Question
Title: How would you design a transformation matrix to project absolute coordinates to any orthographic projection desired?
I am attempting to make an RTS based on AoE II HD Edition. I want to have ease of control by designing a transformation matrix given any style of projection I want. This is a good example of what I mean. So, given each of those three angles, and any absolute x, y, and z, how can I design a transformation matrix to multiply the absolute position by to get the projected position on the screen? I just want full control, and I need to get better at matrices. I am about to graduate High School but I hardly learned anything related to matrices. Only a little in Physics and a little in Algebra II with Trig.

I just need to know *how* to create the matrix.

Also, after that, how would I convert a projected matrix back to the original position? Dividing it (Although, I know matrices can't divide - I mean multiply by the inverse)? Thanks so much for any help!

# Answer
I'm going to make some assumptions...

* Your 3D world coordinate system is left-handed, with the y axis pointing up in the world.
* You want to convert to camera space, where y is up on the screen, x is rightward on the screen, and z points into the screen. (From here projecting into normalized device coordinates is straightforward, so I'll skip that here so we can ignore things like aspect ratios and near/far planes)
* The world y axis will point directly up in the image plane and will be scaled by `scaleY`
* the world x axis will project to point in a direction `angleX` radians counter-clockwise from the projected y axis, and will be scaled by `scaleX`
* the world z axis will project to point in a direction `angleZ` radians counter-clockwise from the projected x axis, and will be scaled by `scaleZ`
* your matrix multiplication convention is `M * v` (ie. your vectors are treated as columns, multiplied on the right side of the matrix)

Using these assumptions, we can form various common projections:

* true isometric: `{angleX&Z = 2pi/3, scaleX&Y&Z = 1}`
* 2:1 dimetric `{angleX = atan(1/2) + pi/2, angleZ = 2* atan(2), scaleX&Z = sqrt(5)/2, scaleY = 1}` (this projection is often called "isometric" in games, although it's not quite)
* cavalier-45 `{angleX = pi/2, angleZ = 3pi/4, scaleX&Y&Z = 1}`
* plan `{angleX = pi/2, angleZ = pi/2, scaleX&Z = 1, scaleY = 0}`
* x-elevation `{angleX = pi/2, scaleX&Y = 1, scaleZ = 0}`

---

So with that in hand, we can use some handy facts about matrices. In general transformation matrices we use look like this:

```
 ┌                ┐
 | Xx  Yx  Zx  tx |
 | Xy  Yy  Zy  ty |
 | Xz  Yz  Zz  tz |
 |  0   0   0   1 |
 └                ┘

```

Here, the 3x3 block in the top-left represents the rotation, scale (including reflection) and skew applied to the 3D space - the linear components of the transformation.

The right-hand column represents the "affine" component, a translation vector (tx, ty, tz) representing how far the origin of the space is shifted.

And that bottom row (0, 0, 0, 1) lets us use homogeneous coordinates to accomplish the affine transformation above (otherwise we're limited to just the linear component). Often though, we'll just treat this as a given and not really store that row - we'll just multiply "as though" it's there. ;)

We can get more granular in that 3x3 block too. The left-most column `(Xx, Xy, Xz)` is exactly the direction & scale that will be applied to the unit vector along the x+ axis, `(1, 0, 0)` (and any vector parallel to it). The same goes for the middle column and the y+ axis, and for the remaining column and the z+ axis.

(This works for the multiplication convention v * M too, just exchange "columns" for "rows" above)

So, knowing this, if we figure out where we want each original axis to point in our image, we can assemble these three vectors to form our rotation/projection. Then we can adjust the translation to center whichever part of the image we want.

---

First, we'll construct the 2D image of the x+ unit vector `(1, 0, 0)` and z+ `(0, 0, 1)` after transforming to image space:

```
Vector2 xImage = Vector2(-sin(angleX), cos(angleX)) * scaleX;

Vector2 zImage = Vector2(-sin(angleX + angleZ), cos(angleX + angleZ)) * scaleZ;

```

This is just using the unit circle and basic trigonometry. The image of the y+ unit vector gets scaled to `(0, scaleY, 0)` according to the assumptions above.

And assuming we want some worldspace vector `lookPoint` to map to the center of the screen, we'll want to compute a pair of centering offsets...

```
float tx = -lookPoint.x * imageX.x - lookPoint.z * imageZ.x;
float ty = -lookPoint.y * imageX.y - scaleY * lookPoint.y - lookPoint.z * imageZ.y;

```

we can form a projection matrix:

```
                       ┌                                    ┐
Matrix4x4 projection = | imageX.x    0      imageZ.x   tx   |
                       | imageX.y  scaleY   imageZ.y   ty   |
                       |    0        0         0        0   |
                       |    0        0         0        1   |
                       └                                    ┘

```

This matrix isn't invertible, because we've flattened the z axis to zero. But it's also 2AM here and my faith in my math skills is faltering. ;) So, I'll come back and edit this answer to discuss how we extend this projection to have a sensible z vector so we can reverse the transformation a little later. Hopefully this is enough to get you started. :)

---

**Edit:** I still don't have a complete solution to offer, but I wanted to give some explanation of why it's a bit more complicated than it might appear.

If we only wanted to represent orthographic projections, we'd have an easier time. Each image vector would retain its original length, pointing in or out of the image plane to achieve the needed foreshortening, and the view direction (the z-axis of the camera space) would point perpendicular to the image plane in our original coordinate system.

But many of the projections we can form with the parameters above are not orthographic, like cavalier projections. These stretch & squash the axes to arbitrary lengths, which is equivalent to skewing the coordinate system - so the view direction runs diagonal to the image plane.

We actually have some wiggle room in how we choose which diagonal to use, which can impact how we sort objects like sprites that we might be rendering. So, it's important to pick a good diagonal - and that's where things get a bit tricky.

The basic idea is to find a linear combination of our image-space axes that sums to zero. ie.

```
a * xImage + b * (0, scaleY) + c * zImage = 0

```

That's a system of linear equations with two equations and three unknowns, meaning it's under-determined. But we can arbitrarily choose some solution where a, b, and c are not all equal to zero, and normalize that into a vector:

```
n = (a, b, c)/sqrt(a*a + b*b + c*c)

```

Then our z+ axis can be either n or -n (one will render our scene as desired, the other will flip it backwards - we should be able to tell which one to use based on the angles between the axes in our image, but I haven't worked that bit out yet)

Once we finally have this, we can write our matrix as:

```
float tz = focalDepth - dot(n, lookPoint);

                       ┌                                   ┐
Matrix4x4 Invertible = | imageX.x    0      imageZ.x  tx   |
                       | imageX.y  scaleY   imageZ.y  ty   |
                       |    n.x      n.y       n.z    tz   |
                       |    0        0         0       1   |
                       └                                   ┘

```

Where `focalDepth` is the depth you want your `lookPoint` to sit at (generally you'll want this to be some distance in front of the camera so you can still render objects that are in front of what you're looking at)

This matrix is invertible, so you can use this to both map from worldspace to camera space, and back to worldspace.
> 3 votes

---
Tags: matrix, isometric, projection
---


# Question
Title: Android: How to prevent player(drag/drop touch input) from moving through non-moving objects?
My player is moved around the screen by touch user input. The user touches the character and drags him to another position. (implemented in `touchevent`: `actionmove` and `actiondown`). I want the touch-movement to stop, as soon as the character reaches an object. So I don't want the character to pass through the object.

I used `rect.intersect(player,object)` to detect a collision between the player and the non-moving object. As soon as a collision is detected, I have to move the character back from the object, so that both don't overlap. I used this minkowski-algorithm (Which Side Was Hit?) to find out on which side the collision occured. According to which side it is, I set back the player's position so it doesn't overlap with the non-moving object. Example for one side:

```
player.setPositionx(barrier.getCollision().left - player.getImage().getWidth());

```

or

```
 player.setPositiony(barrier.getCollision().bottom);

```

This is not working smoothly. When I move the player by touch really fast over the object, it still passes through and appears on the other side of the non-moving object (probably because the code for the other side is then being executed). When I move the player along the left side, it suddenly appears on top of the non-moving object. When I move it on the bottom of the object, it may suddenly appear on the right or left side. (corners not smoothly) How can I make sure that I can move the player (by touch input) around the object smoothly?

# Answer
> 1 votes
Consider using a swept collision test instead of just an intersect/overlap test.

When doing a swept test, the area traveled is also considered for the collision test, not just the final position/destination for the object in that frame.

Essentially it's about (for the AABB case at least) extending the corners of the AABB in the direction of travel by the velocity, and calculating if and when the intersection with the obstacle occurs. The article linked covers this in detail for AABBs along a linear path, the solution for more complex shapes with non-linear movement is a bit trickier.

---
Tags: android, collision-detection, touch
---


# Question
Title: unable to send or update data into my mysql database using unity
I am trying to save user scores into my data base so i have deveoped backend on php and mysql datbase. All the things are complete but having issues to send or receive data through my unity WWW class.

Here is my C# code to get and send data to php and then DB:

```
using UnityEngine;
using System.Collections;

public class Scripts : MonoBehaviour {
    string dataSubmitURL = "http://localhost/HighScore/AddScore.php?";
    string dataGetURL = "http://localhost/HighScore/GetScore.php";
    // Use this for initialization
    void Start () {
        StartCoroutine(GetScores());
        //StartCoroutine(PostScores("faizan",100));
    }

    // Update is called once per frame
    void Update () {

    }

    IEnumerator PostScores(string playerName, int score) {
        string submitURL = dataSubmitURL + "name="+ playerName + "&score=" + score;
        print(submitURL);
        WWW submitData = new WWW(submitURL);
        yield return submitData;
        if (submitData.error != null)
        {
            Debug.LogError("Error occur when Submitting data : " + submitData.error);
            Debug.LogError("Error occur when Submitting data : " + submitData.text);
            Debug.LogError("Error occur when Submitting data : " + submitData.responseHeaders);
            //submitData.text
        }
        else {
            print(" Submitted");
        }
    }

    IEnumerator GetScores() {
        WWW getData = new WWW(dataGetURL);
        yield return getData;
        if (getData.error != null)
        {
            Debug.LogError("There was an error getting the high score: " + getData.error);
        }
        else {
            print(getData.text);
        }
    }
}

```

If i directly run my urls into browser

```
string dataGetURL = "http://localhost/HighScore/GetScore.php";

```

then it is working perfectly and giving me data but same thing when i trying through my c# www(above code) then it reply.

```
There was an error getting the high score: Empty reply from server

```

# Answer
> 0 votes
I just change local host to my IP address and it works

```
 string dataSubmitURL = "http://Your IP Address /HighScore/AddScore.php?";
    string dataGetURL = "http://Your IP Address /HighScore/GetScore.php";

```

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


title: Multiplayer camera for each player

text:
# Question
Title: Multiplayer camera for each player
I followed the Official Unity guide for a Multiplayer game, and now I want a camera for each player.

For this reason, I have set the camera as a child of the player, but it is only showing one player camera for all players. How can I make separate cameras for each player in a multiplayer game?

I have also added this to my child camera but nothing worked

```
[RequireComponent(typeof(NetworkView))]
public class PlayerCamera : MonoBehaviour {

    void Start () {
        NetworkView objNetworkView = GetComponent<NetworkView>();
        if (objNetworkView.isMine)
        {
            GetComponent<Camera>().enabled = true;
        }
        else {
            GetComponent<Camera>().enabled = false;
        }
    }

}

```

# Answer
> 0 votes
I have manage all players camera by using single camera as @Jhocking mentioned

> In a networked multiplayer game, each player has their own copy of the game running.

So on Local Player Game Copy Side: I make Main camera child to my local player. Here is the code snippet

```
void Start() {

        if (isLocalPlayer)
        {
                GameObject.Find("Main Camera").gameObject.transform.parent = this.transform;
            }
        }

```

# Answer
> 3 votes
In a networked multiplayer game, each player has their own copy of the game running. So the game only needs one camera, and each player would see their own view.

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


# Question
Title: How do you create dots in a shape of a letter and make them interact-able for a user to connect them?
I am making a game where the user is given a letter on screen such as the below image

The user then uses the mouse to draw from one point to another until the shape is drawn.

I wanted to know what is the best way for the program to create these points so that they appear on screen for the user to interact with them?

I have a canvas and the mouse is able to draw on the screen the problem is I don't know how to make the points interact-able with the mouse, so that when the mouse draws on or over the dots that it connects them together to form the letter.

# Answer
*Following answer is not targeting Java/Swing especially, it a general process.*

1. Best way to create the points :

I would personnaly use an array of points for each letter, the points having as coordinates the local position starting at the top-left of the letter. You can then draw a whole word by defining the global position of each letter.

2. How to make the mouse interact with the points :

You should register whenever the user presses the mouse, get the x and y coordinates of the mouse click, and check if this point is inside one of your dots.
> 1 votes

---
Tags: java, swing
---


title: Realistic 3D Lighting in Unity

text:
# Question
Title: Realistic 3D Lighting in Unity
The game I am working on is in 3D, and I need to create a realistic looking recessed ceiling light, preferably without any 3rd party plugins or tools, as I am on a school computer.

What is the best way to go about doing this in Unity?

I am using a point light at the moment, but they are hard on memory, and I would like this game to run smoothly on mobile devices.

# Answer
Have you ever heard this sentence "Camera, Light, Action"?. Off course you know about it but what does it mean? It means that Light is another big, wide and great area of gaming and it is not a small topic. So basically you have to learn the lighting your self no one can ever define it to you in this single post. You can ask speicfic issue about lighting here but your rest of the part question require an answer that you want to run your mobile game smoothly. So you can consider bakingLightmaps in unity in perspective of Lights.

For further reading

1. lightmapping-in-unity-5
2. Unity-5-lighting-and-rendering
3. Practical Guide to Optimization for Mobiles
4. What is baking lights in Unity3d
> 1 votes

---
Tags: unity, 3d, lighting
---


title: Specify the center of rotation in Unity

text:
# Question
Title: Specify the center of rotation in Unity
I want to rotate my game object around a point in the space instead of the origin, so how can I do it ?

# Answer
> 1 votes
Create a new cube object that has the object you want to rotate as a child (or set your object's parent to this object with `this.parent = object`) and its point of origin as the point you want to rotate around. Any details on parents can be found on the Unity Scripting page. Essentially do this:

Now rotating the cube will rotate your object around the middle point of your cube. Of course, you don't want this cube to be seen so remember to remove the mesh renderer. When you're done, disconnect the sphere from the cube (`this.parent=null`) then remove the cube that you added (name it something like RotationCube so that you can easily find it or maybe from a tag).

In this test "turnturn" script has the line and as the invisible cube turns, the sphere turns around its origin:

```
Update(){
transform.Rotate(Vector3.left * Time.deltaTime*15);
}

```

# Answer
> 1 votes
Your question is very short and I don't know if I'm getting it correctly, but you should check RotateAround and then do something like:

```
transform.RotateAround(targetTransform.position, Vector3.up, speed * Time.deltaTime);

```

# Answer
> 0 votes
The basic theory is to translate your object to the world origin, perform your rotation as usual, then translate it back to the same position it was before.

# Answer
> 0 votes
Make your object the child of an empty GameObject that is located at your desired center of rotation. Then, rotate the new object instead of your existing (visible) object.

You can get fancy and do this in script, but this approach maintains the scene graph and keeps everything nice and editor-friendly.

---
Tags: unity, game-design, rotation
---


title: Libgdx Image doesn't fit the Screen

text:
# Question
Title: Libgdx Image doesn't fit the Screen
I am Trying to show Image as background, but it doesn't fit to the screen. When I use this class as the start screen it fit the screen properly but when I call this class after winning the level, the image becomes bigger than the device screen and only part of it is shown but when I divide the width and height on 2 the image is becomes smaller than the screen :`game.batch.draw(background, 0, 0, Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight()/2);` this is the code :

```
public class Celebration  implements Screen {
    private Fruits game;
    private OrthographicCamera gamecam;
    private Viewport gameport;

    private Stage stage;
    private World world;
    private static float temp;
    private float level;
    private Texture background;
    private Texture start;
    private Texture loading;
    private float counter;

    public Celebration(Fruits game, float level)
    {
        this.game=game;
        this.level=level;
        gamecam=new OrthographicCamera();
        gameport=new StretchViewport(820/Fruits.PPM,580/Fruits.PPM,gamecam);
        stage=new Stage(gameport,((Fruits) game).batch);
        background=new Texture("Wining.jpg");

        gamecam.position.set(gameport.getWorldWidth() , gameport.getWorldHeight() , 0);
        temp=0;

        counter=100;
        world=new World(new Vector2(0,-10),true);
    }
    @Override
    public void show() {

    }
    public void handleinput(float dt)
    {
        if (counter<0)
        {
            game.setScreen(new PlayScreen(game,level));
        }
    }
    public void update(float dt)
    {
        handleinput(dt);
        world.step(1 / 60f, 6, 2);

        gamecam.update();
    }
    @Override
    public void render(float delta) {
        float level;
        update(delta);
        Gdx.gl.glClearColor(0, 0, 0, 0);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        counter--;
        game.batch.begin();
        game.batch.draw(background, 0, 0, Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight()/2);

        game.batch.end();

    }

    @Override
    public void resize(int width, int height) {
        gameport.update(width, height);

    }

}

```

# Answer
> 3 votes
```
     texture = new Texture(
            Gdx.files.internal("Menubckgrnd/MenuScreen.png"));
    texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);

```

// here 2048 and 1238 is the actul width and height of the image . so replace these values with your images height and width

```
    TextureRegion region = new TextureRegion(texture, 0, 0, 2048, 1238);

    sprite = new Sprite(region);
    sprite.setSize(1f, 1.12f * sprite.getHeight() / sprite.getWidth());
    sprite.setOrigin(sprite.getWidth() / 2, sprite.getHeight() / 2);
    sprite.setPosition(-sprite.getWidth() / 2, -sprite.getHeight() / 2);

```

Try this code . it will defenitly works

# Answer
> 2 votes
Try this. In `create` method

```
texture = new Texture(Gdx.files.internal("myBackground.png"));
mainBackground = new TextureRegion(texture, 0, 0, 2826, 1590);
batch = new SpriteBatch();

```

2826 and 1590 is the image width and height respectively.

In `render` method

```
batch.begin();
batch.draw(mainBackground, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
//...
batch.end()

```

Don't forget to declare it first.

---
Tags: java, android, libgdx
---


# Question
Title: Can ARToolKit be used for color detection?
I'm trying to make an app that will show an object from different sides, but the target will be too small for any real marker detection.

Think of a cube with one or two centimeter sides. The camera distance is not a problem but it has to be at least ten centimeters out or what I'm trying to do won't work.

I was wondering whether it was possible to color one side of the cube differently than others and make ARToolKit recognize the color to know which side it's looking at. Is this possible or just not in the range of things ARToolKit can do? If so, is there any kind of AR that can do this.

# Answer
Short answer: Theoretically, yes this is possible.

Long answer: ARToolKit has a feature called Natural Feature Tracking (NFT). This is what is used to have ARToolKit recognize images, rather than its usual QR code-looking things. However, ARToolKit converts all images to greyscale and then uses the **changes in color** of that grey image to track the image. Thus, it *should* be possible to track just one side of the cube by using the NFT feature, however, it will need to be a color that is still to the other faces of the cube even when converted to greyscale. Remember, though, that unless there is some variation within that face of the cube (i.e. not just one solid color), ARToolKit won't track very well.

I would suggest having each side of the cube be an image unique from the others but all following the same template. For example:

And then use ARToolKit's NFT feature for every face. This will allow each face to be recognized differently from the others.
> 1 votes

---
Tags: unity, color, artoolkit
---


# Question
Title: What should I do with global high scores when the game has a major update?
I have a game that people have been playing for several years now. The game has a global high score list, and there has been some fierce battles among the players for the top positions.

I now want to make a major update to the game, but the changes I have in mind will bring the maximum theoretical score down to about 80% of what it currently is. This is just an estimate, of course, I haven't gotten very far into the update, but it will definitely come down. I should also note that this game has no logical, absolute maximum score because it is based on things like time and resources used as well as kills.

So the question is, what do I do with the current high scores when I release the update? It doesn't seem right to leave it because no one will ever be able to take the high spots, and new scores won't really compare to old ones. I don't think I should wipe it because a lot of people worked really hard to get there. Any suggestions?

Edit to add:

I also don't think I can adjust the current score values because they are a sum of many small games, and the user can replay those to get an increase to the total. An adjustment would make a confusing mismatch.

# Answer
When you change your game mechanics in a way that the old scores can no longer be compared to the new ones, then it doesn't make sense to have a scoreboard which does. So start a new scoreboard.

But the moment you do it, save the old high-scores and keep them available as a static website for everyone to look up. That way those who are currently leading won't be disappointed that their scores are deleted but honored that their awesomeness will be remembered for all times.
> 7 votes

---
Tags: leaderboards, scoring
---


# Question
Title: Is attribution sufficient for CC BY-SA 3.0-licenced music in a commercial mobile game?
I am in the process of developing a mobile game that I intend to sell on Google Play. I want to include a music licensed as:

> Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0)

If I attribute the author/contributor of the music, am I allowed to sell my game **without** the same license?

I would like to get opinions from people who have had experience in this situation.

# Answer
> 5 votes
The text of the licence states:

> **Share Alike**—If you alter, transform, or build upon this work, you may distribute the resulting work only under the same, similar or a compatible license.

and in more detail...

> 1.a **"Adaptation"** means a work based upon the Work, or upon the Work and other pre-existing works, such as a translation, adaptation, derivative work, arrangement of music or other alterations of a literary or artistic work, or phonogram or performance and includes cinematographic adaptations or any other form in which the Work may be recast, transformed, or adapted including in any form recognizably derived from the original, except that a work that constitutes a Collection will not be considered an Adaptation for the purpose of this License. For the avoidance of doubt, where the Work is a musical work, performance or phonogram, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered an Adaptation for the purpose of this License.

...

> 4.b You may Distribute or Publicly Perform an Adaptation only under the terms of: (i) this License; (ii) a later version of this License with the same License Elements as this License; (iii) a Creative Commons jurisdiction license (either this or a later license version) that contains the same License Elements as this License (e.g., Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons Compatible License....

So, if your inclusion of the music in your game counts as an "Adaptation" then you may distribute it only under a similarly free & open licence.

Synchronizing a video to an unmodified music track is explicitly called out as an example of an adaptation of that musical work, so I would strongly suspect that use of music in a game - where it is triggered in synch with changing game states and layered with other audio in the game - would also count as an adaptation. By that reasoning, your game itself would need to be distributed under a similar licence.

**I am not a lawyer, so when in doubt I'd recommend seeking professional legal advice.**

For instance, another recent answer suggests that games would be considered "collective work" rather than "derivative work" or "adaptations" and that the share-alike provision might not apply in this case. I don't have the legal knowledge to say with authority which interpretation is correct, so consulting a lawyer is likely your best bet.

You do also have another option available, which is to **contact the original author of the content you wish to use** and ask for their permission. As the copyright holder, they can give you licence to use and distribute the work in any particular adaptation, even if the base licence would not permit that use.

---
Tags: android, legal, google-play
---


# Question
Title: How to create a line renderer with end point as the mouse position, but with a fixed direction
I have two objects with a line going from one to the other, like this:

I want to create another line with a starting point one of the objects and an end point the mouse position, however still facing the second object, which will look like the first line is filling up to where the mouse is.

For example, I want to connect the blue shape with the green shape, so I move my mouse from one to the other. The game finds the nearest white line from the cursor and creates another line on top of it that follows my cursor, like this:

The current script is this. It draws a line from the origin shape to the mouse position, but it doesn't stay on only one direction and instead moves where my mouse goes:

```
public class SelectionLine : MonoBehaviour {
private LineRenderer lineRenderer;

private void Awake() {
    lineRenderer = GetComponent<LineRenderer>();
}

private void Update() {
    if (ShapeSelection.instance.selectedShape != null && ShapeSelection.instance.draggingFinger != null) {
        var originPosition = ShapeSelection.instance.selectedShape.transform.position;
        var destinationPosition = ShapeSelection.instance.draggingFinger.ScreenPosition;

        lineRenderer.SetPosition(0, new Vector2(originPosition.x, originPosition.y));
        lineRenderer.SetPosition(1, new Vector3(ShapeSelection.instance.draggingFinger.GetWorldPosition(1f).x, ShapeSelection.instance.draggingFinger.GetWorldPosition(1f).y, 0));
    }
}

```

}

There is no way (as far as I know) to set a direction of a line renderer in Unity, so how can I achieve this?

# Answer
It seems to me like it is a trigonometry question. Length of B = (length of A) * cos(alpha). To get alpha you can refer to: http://answers.unity3d.com/questions/317648/angle-between-two-vectors.html
> 0 votes

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


# Question
Title: Homing Fireball - Seiken Densetsu 3 style
I'd like to reproduce the fireball spell of Seiken Densetsu 3. The Fireballs don't follow the target directly, but encircle it more or less until they hit the target.

I have no idea how to reproduce this encircling. I tried using the Forward Vector of my Fireball and adding it to the velocity. At the same time, the Rotation is slowly interpolated.

But no matter how I tweak the values, my fireballs mostly miss the target due to too slow rotation or the fireballs go straight to the target due to too fast rotation.

Does someone have a formula/ can point me into the right direction? Here's a video on how the Fireballs in SD3 work:
https://youtu.be/PxtHGny88DM

Note how sometimes a fireball misses and encircles the target before it hits.

# Answer
> 1 votes
That looks similar to gravitational orbit.

Basically, you make the fireball accelerate toward the target, and give it an initial speed in a direction perpendicular to the target.

Then you play around with the acceleration parameter and initial speed parameter until you get the effect you want. In your case, you probably want a higher value for acceleration.

Hope that helps!

---
Tags: architecture, algorithm
---