# Question
Title: RPG Damage Calculation Logartihm in Java
I'm trying to make a damage calculation formula for my RPG game, there are 12 levels for both the Player and the Enemy, I've come as far as making a Reverse Exponential formula, but I want the damage to go down from slow to faster as the Players level gets closer to the level of the Enemy.

```
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

public class DamageCalc {

    private static double defense;
    private static double dmg;
    private static String teststring;

    public static void main(String args[]) throws FileNotFoundException, UnsupportedEncodingException{
        for(int i = 1; i <= 12; ++i){
            for(int j = 1; j <= 12; ++j){
                defense = ((j * 3) * 2 + 11) * 2;
                dmg = i * 12;
                double totaldmg = getDamage(i,dmg,defense,j);
                teststring += "Player Level " + i + "\nMonster Level " + j + "\nTotal Damage " + totaldmg + "\n----------------------------------\n";
            }
        }
        PrintWriter test = new PrintWriter("testvalues.txt","UTF-8");
        test.println(teststring);
        test.close();
    }

    public static double getDamage(double level, double dmg, double defense, double enemy){
        double intdamage = (((2*level+10) / 128) * (dmg/defense) * 11 + 1) * 10;
        double damage = Math.ceil(Math.pow(intdamage,level/12) * 10);
        System.out.println(intdamage);
        return damage;
    }

}

```

The code just loops through the players level (int i) and the enemies level (int j), then returns the damage done. The difference in damage between level 1 and 2 is significantly higher than between 11 and 12, eventhough that should be the other way around.

EDIT: I'll explain it even further. The player starts with 12 for each stat, every level 12 get's added (dmg = level * 12). Every stat for the player has 128 points and monsters 128 points, so that's why the begin defense of a monster is 11. If the damage stat from the player is lower than the defense of the enemy, the damage will get a penalty, otherwise it will get a boost (double * (dmg/defense)).

I hope this explains it.

# Answer
Your given damage calculation (except for the inverse exponential) breaks down to:

```
intDamage = (1320/128) * (10 * lvl^2 + 50 * lvl)/(6 * enemyLvl + 11) + 10

```

The damage curve you appear to be looking for instead will wind up taking the form of:

```
1 / (enemyLvl - n) + m
                ^    ^
                |  push desired part of curve above origin
                |
      move desired part of curve to right of origin

```

Approximately in this case, `n = maxLvl + 1` and `m = 1`. Given that, we can figure out something that should approximate the curve, and damage levels you're looking for:

```
c = 1320 / 128
equalLvl = (((10 * lvl^2 + 50*lvl) / (6*lvl + 11)) + 10) * c
damage = equalLvl * ((1 / (enemyLvl - 13)) + 2);
finalDamage = Ceiling(damage/20 * lvl)

```

This gives a rough approximation of the desired curve with close to the desired damage values.

To get the damage falloff more to where you like it, primarily play around with the values of `n` and `m`.

**UPDATE**: To get an even closer approximation to the desired curve, we should scale the curve according to the player's level, and then handle what happens after the "knee" (where `enemy > player`).

So we can approximately adjust the formulae as follows:

```
if (enemyLvl > lvl)
    damage = equalLvl * ((1 / (enemyLvl - (lvl + 1)) + 2)
else
    damage = equalLvl * (lvl / enemyLvl) /*Deal with the Knee*/

```

The snippet below has been adjusted to use the new approximation.

```
var result = document.getElementById('result');

function pad(n, width, z) {
  z = z || '0';
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}

function getDmg(lvl, dmg, def, ene){
  var c = 1320/128;
  var cDamage = ((10*lvl*lvl+50*lvl)/(6*lvl+11) + 10) * c;
  var yDamage = cDamage * (1/(ene-(lvl + 1))+2);

  if (ene > lvl)
    yDamage = cDamage * (lvl / ene);

  var damage = Math.ceil(yDamage/20*lvl);
  return damage;
}

for (var pl = 1; pl <= 12; pl++){
  for (var ml = 1; ml <= 12; ml++){
    var def = ((ml*3)*2+11)*2;
    var dmg = pl*12;
    var totDmg = getDmg(pl, dmg, def, ml);

    var s = ml== 1? '*' + pad(pl, 5, ' ') : pad(pl, 6, ' ');
    s += ' ' + pad(ml, 7, ' ');
    s += ' ' + pad(totDmg, 6, ' ');

    result.textContent += s + '\n';
  }
}
```

```
<pre id='result'>Player Monster Damage
</pre>
```
> 2 votes

# Answer
There are a number of functions you can use to model this functionality.

We want to modify the player damage by 1x if the player\_level - monster\_level = 0, and we want the player damage modifier to increase exponentially as player\_level - monster\_level approaches infinity. Conversely we can have the player damage modifier decrease exponentially as player\_level - monster\_level approaches negative infinity. You should be able to use any function of the following form, f(x) = 1 + x^n where x = player\_level - monster\_level, and n is a natural number AND n is odd. This will give you an odd function which meets your criteria.

Graph these functions to see if they meet your requirements, f(x) = 1 + x^3, f(x) = 1 + x^5, and f(x) = 1 + x^9.
> 0 votes

---
Tags: java, mathematics, rpg
---


# Question
Title: When to use a blend tree vs state machine for animation
Im an experienced game dev hobbiest making my first game with 3d animated characters (in Unity) and am struggling to figure out when to use blend trees vs animation state machines. I understand both conceptually but have seen both blend trees and animation state machines used for character animation in a bunch of tutorials both from Unity and from other sources. I am not sure when / why one is better than the other am hoping someone can point me in the right direction.

My game is a 3rd person action rpg a'la WoW or KOTOR or Mass Effect (different systems I know but the perspectives and combat styles are kinda close at a high level). I have tons and tons of animations for attacks, blocks, feigns, deaths, walking, running, jumping, shooting etc but I am unclear on how to sequence them together naturally.

I have seen blend trees used for locomotion which makes sense to me when trying to keep character motion fluid, but I dont understand how to go from that blend tree to an attack state and nothing I have seen so far has gone past locomotion (no attacks etc). Do I need to make blend trees from my motion states to attack / death / dodge states? Do I have more control using just state machines? Im a little cautious of state machines because of the transition bloat that is so common with them and because I suspect there is greater potential for janky animation sequencing without blending.

I am planning to use the Unity character controller and write my own logic scripts to drive it. For the AI I will be using the built in nav mesh agents. Are character controller animations handled differently than the AI ones?

Any insights would be more than welcome!

Thanks

# Answer
I've worked quite a bit with Mecanim in Unity, and feel I have a quite good understanding of how it works.

Like you say, blend-trees are almost definitely the way to go for doing locomotion. Blend-trees are generally for when you want to *continously* blend animations to create the final output. Like give the player the control of how fast the avatar is running.

All *single actions* are likely better to keep as an individual state, which you can transition into. Depending on how intense your game is going to be, you may even consider using the **Any State** as a point of departure to quickly go to jump, attack etc., without having to wait for another animation to finish.

The key to blending from a blend-tree with running is to use **transitions**. There's no magic to make this look great, only careful planning, and tweaking while previewing the transition in Unity. A lot of the job relies on the animator for having the foundation for succesful transitions.

Something to keep in mind when doing transitions is to find the balance of them looking great, and giving the player the expected feedback. You may find that a quick transition works best for the game-feel, while a slower transition may look better but make your players want to throw away the controller.

Below is a somewhat simple setup, where arrows indicate how transitions go. Transitions are based on conditions for entering, and either exit when the animation finishes or a given condition is met. This also means that one state can go into various other states depending on different conditions.

What you probably notice is that this quickly can become a big pile of "spaghetti", and a way to avoid some of this mess is to utilize the **Any State** which is also included in the image above.

The **Any State** has the benefit of being able to transition into anything from any given time. Transitions can still be used to blend the animation, however, you're working a bit more in the dark as to how it will look. It is possible to preview from/to various states while setting it up.

Something you didn't mention is **Layers**, which can be extremely useful for making your character wounded or to override the upper body to carry different weapons while using the same animation for the legs for all weapons. **Layers** are also blended and can be adjusted gradually, so a character could be more or less wounded, for example. Another example would be to lift a characters arms in the air (if the character surrendered or something), while keeping all other animation the same.

But setting up a solid animation controller is not a 1-hour job. It takes some planning and I can only encourage you try setting up a simple state machine with two attacks, a jump, an idle and a walk/run blend-tree. You may also find the **Behaviours** introduced in Unity 5 extremely useful for controlling or interacting with scripts.

I am 99% sure that AI will behave in the same way as the player controller, given that it is parameters changed through scripts that controls how the animation goes from state to state.

### Summary

* **Blend-trees** for locomotion.
* **States** for single, defined actions or simple looping states.
* **Sub-states** for organising a series of states, like a jump.
* **Transitions** for blending/transitioning between different states (a state can also be a blend-tree).
* **Layers** for overriding or adding to the base animation.

So think of blend-trees as expanded states, which also act based on parameter values.

A bit of a long ramble, but I hope it shines some light on the subject :)
> 26 votes

---
Tags: unity, architecture, animation, ai
---


# Question
Title: Direct3D9: How to switch from one full-screen monitor to another?
I know how to display my game in full-screen on a specific monitor by specifying an adapter number when the D3D device is created.

However, I don't know how to *switch* from one monitor to another while the game is already running, without re-creating the D3D device from scratch. Is this even possible?

Thanks!

# Answer
Your statement in the question is correct. The recommended approach is that you recreate the d3d device object, you should already have an adapter reference and your creation settings from the first time you did this so do it again.

That said:

Switching from full screen to windowed mode then moving the window on the to the other screen and switching back to full screen may work if the driver is smart enough.
> 2 votes

# Answer
This is not actually possible. When you create the D3D device, it binds to the graphics adapter, which can't be changed on the fly.
> 2 votes

---
Tags: directx9
---


# Question
Title: Calculate speed of object for specific device
I have an object - player - which is moving X px ahead each update (updates based on device FPS). From my results, to get average same player speed on all devices, is to do calculation screenWidth / averageFPS. This should give me speed, that player reaches mobile screen width for one second (note my game is in landscape mode). But it doesn't, it was significaly faster on Z3 Compact (720x1280; avg. 60FPS) than on tablet A5600-F (800 x 1280; avg. 62FPS).

How to get correct speed?

# Answer
You should be working in world coordinates, not pixel coordinates.

For example, in a Unity project, I might have a world 100 units across, and the speed is 1 unit per second. It takes 100 seconds to cross the screen. The engine takes care of worrying how many pixels per frame that is.

On a related note, you don't move a certain distance per frame. You check the "delta time" of the current frame, and adjust the speed for how long the frame takes in order to keep the speed consistent regardless of the frame rate.
> 1 votes

---
Tags: java, android
---


title: Cannot clone game object in Unity C#

text:
# Question
Title: Cannot clone game object in Unity C#
I am having a bit of an issue with getting an empty bullet shell to clone every time a bullet is shot. The first empty shell appears and drops, but after the first empty shell, nothing is cloned.

I am struggling to figure out what the issue is. I am trying it on the first initial weapon before trying other weapons. My code is as follows:

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

public class RecoilScript : MonoBehaviour {
    public GameObject PistolRecoil;
    public GameObject RifleRecoil;
    public GameObject ShotgunRecoil;

    // Use this for initialization
    void Start () {
        PistolRecoil.SetActive(false);
        RifleRecoil.SetActive(false);
        ShotgunRecoil.SetActive(false);
    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKey(KeyCode.LeftControl) && SoldierController.canFire == true)
        {
            if (SoldierController.weaponType == 1)
            {
                PistolRecoil.SetActive(true);
                RifleRecoil.SetActive(false);
                ShotgunRecoil.SetActive(false);
                StartCoroutine(recoilClone());
            }
            else if (SoldierController.weaponType == 2)
            {
                PistolRecoil.SetActive(false);
                RifleRecoil.SetActive(true);
                ShotgunRecoil.SetActive(false);
            }
            else if (SoldierController.weaponType == 3)
            {
                PistolRecoil.SetActive(false);
                RifleRecoil.SetActive(false);
                ShotgunRecoil.SetActive(false);
            }
            else if (SoldierController.weaponType == 4)
            {
                PistolRecoil.SetActive(false);
                RifleRecoil.SetActive(false);
                ShotgunRecoil.SetActive(true);
            }
        }

    }

     IEnumerator recoilClone()
    {
        Instantiate(PistolRecoil, SoldierController.positionGun, transform.root.rotation);
        yield return new WaitForSeconds(0.5f);
        Destroy(PistolRecoil);

        //throw new NotImplementedException();
    }
}

```

# Answer
In these lines:

```
    Instantiate(PistolRecoil, SoldierController.positionGun, transform.root.rotation);
    yield return new WaitForSeconds(0.5f);
    Destroy(PistolRecoil);

```

you are not destroying the clone, you are destroying the original. Similarily, there is some code further above where you are manipulating the original, although you likely mean to manipulate the clone(s).

It appears you use the technique of creating a prefab, removing it from the scene, adding the prefab as a script variable of another game object in the scene and then using that as a template for instantiating clones. In that case your script usually does not meddle with the template at all. If you want the script to interact with the cloned objects, save the return value of `Instantiate` in a separate variable:

```
GameObject recoil = Instantiate(PistolRecoil, SoldierController.positionGun, transform.root.rotation) as GameObject;
yield return new WaitForSeconds(0.5f);
Destroy(recoil);

```

Oh, and a minor style advise: The disappearing is a part of the behavior of the *casing* not of the *soldier*, so I would rather implement it as a separate script attached to the PistolRecoil game object.
> 5 votes

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


# Question
Title: Transparency sorting in 3D world with different render types
I am rendering a world, object, and models from an older game format. The world is presented in a BSP tree so I can quickly iterate through. The opaque surfaces are rendered front to back. Then transparent surfaces are rendered back to front. For the world, that is all fine. I add the transparent pieces into a stack and pop them off one at a time and render.

Now I am realizing that characters that move in the world also support transparency and there is a possibility for error if I render them after the world and they happen to be overlapping with other semi transparent surfaces. Similarly, I have objects to handle.

The solution I have been kicking around in my head is to create a vector of containers that hold my current render structure and a distance from the camera. I would then sort these structures based on distance and then render them one by one.

As it stands now, my render call accepts a pretty generic object:

```
struct RenderCall
{
    GLuint textureID;
    int indexStart;
    int indexCount;
};

struct TransparentRenderCall
{
    float distanceToCamera;
    RenderCall call;
};

```

What do you think? Is there a more streamlined way to do this?

# Answer
> 1 votes
What you've described (Painter's Algorithm) is indeed the way it's usually done. There are however maybe a few things to consider in addition:

* If you're sorting by object, then there are some limitations. These might not be super important in your case, but if you have a lot of complex objects with transparency, your sort might break in situations like this, where A is the camera and B and C your transparent objects:
source
* Many of the objects in your scene may be outside of the viewport/frustum so there's no point in sorting those. Usually sorting is done after frustum culling on every render call, rather than every time an object moves or so. In other words, on rendering, you get the visible transparent objects, then sort them, then render them. You kind of get part of that for free anyway by storing in a BSP tree.
* There are alternative commutative blending methods that are rendering order independent. Those might be worth a look at. What you want to search is Order-independent Transparency.

---
Tags: opengl, graphics, algorithm, rendering, sorting
---


# Question
Title: 2D Game has very bad lag because of one script?
I am making somewhat of a flappy bird clone (mostly for practice) and everything works fine, but it is just really slow with a low FPS of 13 and a max FPS of 28. Why would this be?

So I ran a check with the unity profiler and it turns out that my MoveLeft script which I am using to reuse my obstacles is taking up 73% of the CPU. I have it attached to each of my 6 prefabs, which include 2 long obstacles and a token (to collect) in middle each. The game works by moving the prefabs along the camera, then moving them back after they pass the camera.

Here is the script:

```
using UnityEngine;
using System.Collections;

public class MoveLeft : MonoBehaviour
{

    [SerializeField]
    private float _speed = 5f;
    // Update is called once per frame
    void Update()
    {
         transform.Translate(Vector3.left * Time.deltaTime * _speed);
         if (transform.position.x < -15)
         {
             float randomYPosition = UnityEngine.Random.Range(-3, 3);
             transform.position = new Vector3(15, randomYPosition, 0);
         }
     }
}

```

I really want to fix the lag. What can I do? I am sure this is the script causing it, but without this script my game does not work. Thank you! All help is appreciated!

Hierarchy (objects that I am moving with MoveLeft script. Script only attached to tree parents)

And a scene view that displays colliders found in prefabs

Profiler with information regarding my MoveLeft script

# Answer
Performance problems are tricky to diagnose remotely, but the fact that your palm trees turn almost solid green when selected is a probable clue.

If you started with a nice high-resolution image, Unity probably generated PolygonCollider2D data like what you see on the left: trying to capture each frond in exacting detail.

But if you're making a flappy bird clone, that detail is wasted. If a player ever ends up between those fronds or below the crown they're screwed anyway, so you don't need pixel-perfect collisions there. You could manually tweak the points to get something like the one in the middle, or replace the PolygonCollider2D with a simple EdgeCollider2D chain like the example on the right, for virtually identical gameplay.

**Why does the polygon count matter so much?**

When it comes to physics and collision tests, checking against a mesh of polygons is one of the most expensive things you can do. Circles/spheres and other primitives like boxes are generally a lot faster than similarly-shaped meshes, so you'll want to avoid polygon meshes whenever you don't need vertex-for-vertex fidelity, or at least try to keep the number of polygons/edges as low as possible.

**But wait, why is the game even doing detailed collision calculations for these trees when the player is nowhere near them?**

Because of this line:

```
 transform.Translate(Vector3.left * Time.deltaTime * _speed);

```

Physics objects, including colliders, are happiest when they're moving using physics (like Rigidbody2D forces & velocities). That lets the physics engine make good predictions about where they're going and what they might hit along the way, so it only checks for the minimum number of collisions each step.

When you `Translate` a physics object like a `Collider`, from the perspective of the physics engine it's just teleported, and could potentially be anywhere in the scene, intersecting with any other body. So suddenly its predictions are out the window and it needs to do more exhaustive checks and updates to make sure it safely handles even the worst teleportation cases. Any clever acceleration structures it had for speeding up checks against this object are now invalid too and need to be rebuilt - **this is especially expensive for static colliders** (ones with no `Rigidbody`/`Rigidbody2D`) as the physics system assumes these will never move. All that work is what's spiking time in your update function.

This gets compounded if the trees are in a physics layer that's allowed to collide with itself - because now the engine has to check not just each tree against the player, but each tree against every other tree.

**So, your best bet fixes, with the biggest performance wins first:**

1. Don't move the trees every frame. Move the camera and the player avatar. Then you only need to reposition a tree when it scrolls off-screen, and then only one tree at a time. Huge win.
2. Simplify your colliders to the minimum of what you need for your gameplay, using EdgeCollider2D or simpler primitives if possible. If you need to depart from the visible shape, err toward the inside - players feel much better about living when it looked like they were going to die than they do about dying when it looked like they should've lived. ;)
3. If you need objects to move every frame, do it with a Rigidbody2D and velocity. That way the physics engine keeps control of their locations and has fewer surprises thrown its way, so it can work at peak efficiency. You can also set the body to Kinematic if you need to override the physics without incurring the cost of moving static colliders.
4. Keep the obstacles in a physics layer that only collides with the player. That lets the physics engine focus only on the collisions that could possibly matter for gameplay.
> 6 votes

# Answer
If I understand correctly, I believe the transform function calls a GetComponent with it every time, which could spike CPU in an Update function. Is it attached deep in a parented hierarchy on the prefabs? (i.e. a child, in a child, in a child and the scripts are attached there?)

Try something like this and see if it helps

```
Transform myTransform;
private float _speed = 5f;

void Start()
    {
         myTransform = transform;
    }
void Update()
    {
         myTransform.Translate(Vector3.left * Time.deltaTime * _speed);
         if (myTransform.position.x < -15)
         {
             float randomYPosition = UnityEngine.Random.Range(-3, 3);
             myTransform.position = new Vector3(15, randomYPosition, 0);
         }
     }

```
> 0 votes

---
Tags: unity, c#, performance, lag
---


# Question
Title: How do I move the camera sideways in Libgdx?
I want to move the camera sideways (strafe). I had the following in mind, but it doesn't look like there are standard methods to achieve this in Libgdx.

If I want to move the camera sideways by x, I think I need to do the following:

1. Create a Matrix4 `mat`
2. Determine the orthogonal vector v between `camera.direction` and `camera.up`
3. Translate `mat` by `v*x`
4. Multiply `camera.position` by `mat`

Will this approach do what I think it does, and is it a good way to do it? And how can I do this in libgdx? I get "stuck" at step 2, as I have not found any standard method in Libgdx to calculate an orthogonal vector.

EDIT: I think I can use `camera.direction.crs(camera.up)` to find `v`. I'll try this approach tonight and see if it works.

EDIT2: I got it working and didn't need the matrix after all:

```
Vector3 right = camera.direction.cpy().crs(camera.up).nor();
camera.position.add(right.mul(x));

```

# Answer
> 2 votes
It'll do what you think it does. If you check the `Camera` class source code, you'll see that they're doing exactly what you suggest, plus they're normalizing the result:

```
93 final Vector3 right = new Vector3();
94
95 public void normalizeUp () {
96     right.set(direction).crs(up).nor();
97     (...)
98 }

```

The "standard" method of finding a vector orthogonal to two others is indeed to compute their cross product (in libgdx or anywhere).

There's an additional benefit of knowing this: if you're sure that `normalizeUp()` gets called in your case, you can just use `camera.right` directly, e.g.:

```
camera.position += camera.right * someFactor;

```

# Answer
> 0 votes
```
boolean forward = false;
boolean back = false;
boolean right = false;
boolean left = false;

// when WASD keys are pressed, turn booleans on/off
// call this on create()
// you didn't ask for but I also included the relation between mouse and cam
// if you have a camera controller, please delete mouse moved function.
// also don't forget to override other methods.
Gdx.input.setInputProcessor(new InputProcessor() {
        private int dragX, dragY;
        @Override
        public boolean keyDown(int keycode) {
            switch (keycode) {
            case (Input.Keys.W):
                forward = true;
                break;
            case (Input.Keys.A):
                left = true;
                break;
            case (Input.Keys.S):
                back = true;
                break;
            case (Input.Keys.D):
                right = true;
                break;
            }
            return true;
        }
        @Override
        public boolean keyUp(int keycode) {
            switch (keycode) {
            case (Input.Keys.W):
                forward = false;
                break;
            case (Input.Keys.A):
                left = false;
                break;
            case (Input.Keys.S):
                back = false;
                break;
            case (Input.Keys.D):
                right = false;
                break;
            }
            return true;
        }

        @Override
        public boolean mouseMoved(int screenX, int screenY) {
            Vector3 direction = cam.direction.cpy();

            float x = dragX -screenX;
            cam.rotate(Vector3.Y,x/5.0f);

            float y = dragY -screenY;
            cam.direction.y +=   Math.sin( y/180f) ;

            cam.update();
            dragX = screenX;
            dragY = screenY;
            return true;
        }

    });

// call on render() or anywhere you see fit.
public void walking () {
    if (forward) {
        Vector3 v = cam.direction.cpy();
        v.y=0f;
        cam.translate(v);
        cam.update();
    }
    if (back) {
        Vector3 v = cam.direction.cpy();
        v.y=0f;
        v.x = - v.x;
        v.z = - v.z;
        cam.translate(v);
        cam.update();
    }
    if (left) {
        Vector3 v = cam.direction.cpy();
        v.y=0f;
        v.rotate(Vector3.Y, 90);
        cam.translate(v);
        cam.update();
    }
    if (right) {
        Vector3 v = cam.direction.cpy();
        v.y=0f;
        v.rotate(Vector3.Y, -90);
        cam.translate(v);
        cam.update();
    }
}

```

In this case you need to multiply the `Vector3 v` with the value of x. You can multiply x, y, z one by one, right before the translation. One other thing, My up is Y axis but of course yours is probably dynamic. SO instead of using `Vector3.Y`, please use `cam.up`. I am not sure it will work, but please Experiment. And most importantly have a nice day.

---
Tags: camera, libgdx
---


# Question
Title: Creating or saving model (.fbx or .stl) file in XNA
I have drawn a 3-D Sphere in XNA with the help of vertices (without fbx file).

Now I want create a .fbx file or .stl file of this 3D sphere from XNA, is there any way to do this?

or how can I save this sphere to any format type file.

# Answer
When drawing the sphere perspective has no meaning, since the sphere looks like a circle from any angle. The most important part of drawing a sphere is showing its volume. You can do this by carefully examining the light, shades, the reflected light and highlights. To draw a good circle, you can first draw a square and then draw the circle inside it. Notice that the sphere's shade on the table has the shape of an ellipse.

While drawing, try to see the object as an image. Be bold with your lines and don't worry about making mistakes. You can always fix them later. Don't worry about the construction lines or smudges.
> 1 votes

---
Tags: 3d, xna-4.0
---


# Question
Title: How to replace tiles in Tiled in AndEngine?
in my Game I Create object layers and interpret the shapes in the engine as collision objects...now I want when Player collide with object, after a few seconds object falls...this works properly but not display correctly and tiles are fixed and do not fall... I want to tiles are considered as objects also fall(replace)...how to replace tiles? here's my code

TMX file

```
<?xml version="1.0" encoding="UTF-8"?>
<map version="1.0" orientation="orthogonal" renderorder="right-down" width="500" height="50" tilewidth="20" tileheight="20" nextobjectid="19">
<tileset firstgid="1" name="map_tiles" tilewidth="20" tileheight="20" tilecount="48">
<image source="gfx/game/map_tiles.png" width="128" height="160"/>
</tileset>
<layer name="Tile Layer 1" width="500" height="50">
<data encoding="base64" compression="gzip">
   H4sIAAAAAAAAC+3YsQ2AMAxFQcsDBfafDjcRrZEQidAV17v8zxkRCQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAsIlRjnJucAsAAACwjh8BAAAA3HQyANBlNwAAAMAzWhoAmOwCAAAAeE+ns7U4AAAAfE+PAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPzDBbVpn02ghgEA
</data>
</layer>
<objectgroup name="Object Layer 1" width="500" height="50">
<properties>
<property name="sp" value="true"/>
</properties>
<object id="1" x="19" y="280" width="61" height="20"/>
<object id="2" x="80" y="361" width="60" height="20"/>
<object id="3" x="180" y="419" width="60" height="21"/>
<object id="4" x="261" y="480" width="60" height="21"/>
<object id="5" x="361" y="520" width="58" height="20"/>
</objectgroup>
<objectgroup name="Object Layer 2" width="500" height="50">
<properties>
<property name="fa" value="true"/>
</properties>
<object id="6" x="441" y="479" width="59" height="21"/>
<object id="7" x="541" y="439" width="59" height="21"/>
<object id="8" x="600" y="379" width="61" height="23"/>
<object id="9" x="680" y="321" width="61" height="20"/>
</objectgroup>
<objectgroup name="Object Layer 3" width="500" height="50">
<properties>
<property name="plat1" value="true"/>
</properties>
<object id="18" x="20" y="279" width="60" height="20"/>
</objectgroup>
</map>

```

GameScene:

```
if (group.getTMXObjectGroupProperties().containsTMXProperty(
                "sp", "true")) {

            for (final TMXObject object : group.getTMXObjects()) {
                final Rectangle rect = new Rectangle(object.getX()
                        + (5 * mapTileSize) / 3, mapHeight - mapTileSize
                        / 2 - object.getY(), object.getWidth(),
                        object.getHeight(), vbom);

                final Body body = PhysicsFactory.createBoxBody(
                        physicsWorld, rect, BodyType.StaticBody,
                        boxFixtureDef);
                rect.setVisible(true);
                this.attachChild(rect);
                body.setUserData("sp");
                physicsWorld.registerPhysicsConnector(new PhysicsConnector(
                        rect, body, true, false));
            }
        } else if (group.getTMXObjectGroupProperties().containsTMXProperty(
                "fa", "true")) {
            // This is our "wall" layer. Create the boxes from it
            for (final TMXObject object : group.getTMXObjects()) {
                final Rectangle rect = new Rectangle(object.getX()
                        + (5 * mapTileSize) / 3, mapHeight - mapTileSize
                        / 2 - object.getY(), object.getWidth(),
                        object.getHeight(), vbom);

                final Body body = PhysicsFactory.createBoxBody(
                        physicsWorld, rect, BodyType.StaticBody,
                        boxFixtureDef);
                rect.setVisible(true);
                this.attachChild(rect);
                body.setUserData("fa");
                physicsWorld.registerPhysicsConnector(new PhysicsConnector(
                        rect, body, true, false));
            }

```

contactListener:

```
if (x1.getBody().getUserData().equals("sp")
                        && x2.getBody().getUserData().equals("player")) {
                    engine.registerUpdateHandler(new TimerHandler(0.4f,
                            new ITimerCallback() {
                                public void onTimePassed(
                                        final TimerHandler pTimerHandler) {
                                    pTimerHandler.reset();
                                    engine.unregisterUpdateHandler(pTimerHandler);
                                    x1.getBody().setType(
                                            BodyType.DynamicBody);
                                }
                            }));

                }
                if (x1.getBody().getUserData().equals("fa")
                        && x2.getBody().getUserData().equals("player")) {
                    engine.registerUpdateHandler(new TimerHandler(0.2f,
                            new ITimerCallback() {
                                public void onTimePassed(
                                        final TimerHandler pTimerHandler) {
                                    pTimerHandler.reset();
                                    engine.unregisterUpdateHandler(pTimerHandler);
                                    x1.getBody().setType(
                                            BodyType.DynamicBody);
                                }
                            }));
                }

```

# Answer
There are a few things you can try that might work for you.

*Destroy the static body and create a new dynamic in it's place.* This is pretty much guaranteed to work but if you drop static bodies often it might incur a performance problem. Still, this is the approach I would try first.

*Manually toggle the **active** state on the body*. I seem to remember there being a bug in **Box2D** when changing body type where the previously *static* body wouldn't realize that it needed to be **active**.

```
if (x1.getBody().getUserData().equals("sp") && x2.getBody().getUserData().equals("player")) {
  x1.getBody().setType(BodyType.DynamicBody); // Change type first
  x1.getBody().setActive(false);
  engine.registerUpdateHandler(new TimerHandler(0.4f, new ITimerCallback() {
      public void onTimePassed(final TimerHandler pTimerHandler) {
      pTimerHandler.reset();
      engine.unregisterUpdateHandler(pTimerHandler);
      x1.getBody().setActive(true); // Then, when timer expires flip the active flag
    }
  }));
}

```

*Force the waking up of the body by transforming it and then transforming it back.* You can try moving the body temporarily to a place far away where it won't interfere with the rest of the world and then move it back.

```
if (x1.getBody().getUserData().equals("sp") && x2.getBody().getUserData().equals("player")) {
  engine.registerUpdateHandler(new TimerHandler(0.4f, new ITimerCallback() {
      public void onTimePassed(final TimerHandler pTimerHandler) {
      pTimerHandler.reset();
      engine.unregisterUpdateHandler(pTimerHandler);
      x1.getBody().setType(BodyType.DynamicBody);

      // Store current transform
      Vector2 position = x1.getBody().getPosition();
      float angle = x1.getBody().getAngle();

      // Set transform to place outside the actual world
      x1.getBody().setTransform(-1000, -1000, -1);

      // Restore transform
      x1.getBody().setTransform(position.x, position.y, angle);
    }
  }));
}

```

I'll see if I can dig out the original bug report that mentions this problem.
> 1 votes

---
Tags: java, andengine, tiled
---


# Question
Title: Converting normalized device coordinates to world space coordinates flipping my sprites
I'm trying to convert my game's camera system to use world space coordinates rather than OpenGL's default normalized device coordinates, however in doing so my sprites are being rendered improperly as you will see in the image below. Using GLM as my math library I have created a 4x4 orthographic matrix with the following code:

```
m_orthoMatrix = glm::ortho(0.0f, (float) m_screenWidth, (float) m_screenHeight, 0.0f);

```

I am then performing some translations (and scaling if by chance that is messing with anything) with the following code (m\_cameraMatrix is a 4x4 matrix)

```
vec3 translation(-m_position.x, -m_position.y, 0.0f);
    m_cameraMatrix = glm::translate(m_orthoMatrix, translation);
vec3 scale(m_scale, m_scale, 0.0f);
    m_cameraMatrix = glm::scale(mat4(1.0f), scale) * m_cameraMatrix;

```

m\_scale is a float currently with my testing at value 1.0f. m\_position is a vec2 where in the image, the sprite on the right has values (0, 0) and the sprite on the left as values (screen width / 2, 20).

The issue, as you will notice, is that the sprites are rendered upside down, and I can't seem to fix it without getting rid of my translation math and going back to normalized coordinates.

# Answer
Try this.

`m_orthoMatrix = glm::ortho(0.0f, (float) m_screenWidth, 0.0f, (float) m_screenHeight);`

Looking at the documentation it says glm::ortho takes left, right, bottom, top, in that order as it's parameters. You are saying that y-value m\_screenWidth should be at the bottom of the screen while 0.0f should be at the top. This has the effect of flipping the y-axis if you expect the coordinates to have their orgin (point 0,0) in the bottom left. The bottom left now have the coordinates (0, m\_screenWidth) instead.

If you want the origin to be top left however, then you are already doing it correctly. So then what you are probably doing wrong is either drawing the quad upside-down, have upside-down texture coordinates, or loading the image into a texture upside-down.
> 0 votes

---
Tags: opengl, c++, coordinates, glm, projection-matrix
---


title: How to code sprite sheets?

text:
# Question
Title: How to code sprite sheets?
First of all, the XNA Framework works on my computer, but I do not wish to use it for reasons. I am set with the task of coding my own sprite sheet class. I do not know if a class is the best way to do it, but I have tried my best. I am not an advanced C# user, but I know enough to have got this far with the class:

```
class Spritesheet
{
    //w: 50px h: 96px
    Bitmap sheet;
    int fWidth, fHeight;
    int framesPerRow, framesPerCol;
    int x, y;
    public Bitmap curState;

    public Spritesheet(string path, int width, int height)
    {
        sheet = new Bitmap(path);
        fWidth = width;
        fHeight = height;
        framesPerRow = sheet.Width / fWidth;
        framesPerCol = sheet.Height / fHeight;
        curState = new Bitmap(path);
    }

    public void playSprite(int frameSpeed, int endFrame, int row)
    {
        int curFrame = 0;
        int count = 0;
        bool play = true;

        while (play)
        {
            if (count == (frameSpeed - 1))
            {
                curFrame = curFrame++ % endFrame;
                Rectangle cloneRect = new Rectangle(row * fWidth, curFrame * fHeight, fWidth, fHeight);
                System.Drawing.Imaging.PixelFormat pFormat = sheet.PixelFormat;
                Bitmap curState = sheet.Clone(cloneRect, pFormat);
            }

            count = (count + 1) % frameSpeed;
        }
    }
}

```

I am aware that class variables should never be public, but this is just until I get it working. My Form1 looks like this:

```
public partial class Form1 : Form
{
    Spritesheet player = new Spritesheet("Content/Sprite/charzera.png", 700, 270);

    public Form1()
    {
        InitializeComponent();
        pb_char.Image = player.curState;
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        player.playSprite(5, 13, 0);
        pb_char.Image = player.curState;
    }

}

```

The form builds but doesn't launch now. I am just lost on where to go with this now. I want a spritesheet to be created for the main character, and from there I want to be able to pick a row based on what action is happening and then the game to run along the row animating the PictureBox that I am using for the character.

I've never done this before, so its probably completely wrong.

# Answer
> 1 votes
I'm not sure how to do this in C# as I haven't used it but the basic idea is to cut out each section of the sprite sheet when you need it and crop the rest. I have C++/SFML code for it but I will try to generalize it

```
enum Direction {Down, Left, Right, Up};

int source_x = 1;
int source_y = Down;

int loop = 0;

float frameCounter = 0, switchframe = 100, frameSpeed = 500;

Clock clock;

Sprite PlayerImage;
Texture PlayerT;

bool updateFrame = false;

if (!PlayerT.loadImage("Player.png"))
{
    std::cout << "Error Image could not load" << std::endl;
}

PlayerImage.setTexture(PlayerT);
while (window.isOpen())
{
    if (Keyboard::isKeyPressed(sf::Keyboard::W))
        {
            source_y = Up;
            PlayerImage.move(0, -0.05);
            updateFrame = true;
        }
    else if (Keyboard::isKeyPressed(sf::Keyboard::S))
        {
            source_y = Down;
            PlayerImage.move(0, 0.05);
            updateFrame = true;
        }
    else if (Keyboard::isKeyPressed(sf::Keyboard::D))
        {
            source_y = Right;
            PlayerImage.move(0.05, 0);
            updateFrame = true;
        }
    else if (Keyboard::isKeyPressed(sf::Keyboard::A))
        {
            source_y = Left;
            PlayerImage.move(-0.05, 0);
            updateFrame = true;
        }

    loop++;
    if (loop >= 3000)
    {
        loop = 0;
        updateFrame = false;
    }

    if (updateFrame)
    {
        frameCounter += frameSpeed * clock.restart().asSeconds();
    }
    else
    {
        frameCounter = 0;
    }

    if (frameCounter >= switchframe)
    {
        frameCounter = 0;
        source_x++;
        if (source_x * 32 >= PlayerT.getSize().x)
            source_x = 0;
    }

    window.clear();
    PlayerImage.setTextureRect(sf::IntRect(source_x * 32, source_y * 32, 32, 32));

    window.draw(PlayerImage);
    window.display();
}

```

I hope that this helps however it is for another language.

Also I found this thread over on Stack Overflow which could help: https://stackoverflow.com/questions/16112622/2d-sprite-animations-without-using-xna-or-other-third-party-libraries

---
Tags: c#, sprites, spritesheet
---


title: Different screen sizes? (landscape)

text:
# Question
Title: Different screen sizes? (landscape)
**I want to make a separate landscape layout for each size of my original layout**

I have `activity_main.xml`. I have adapted it to be able to fit multiple screen sizes:

Now, I want to create a landscape layout **for each different screen size**. The android docs and many (Many!) stack overflow pages suggest to do something like this to create a new landscape layout:

But after doing this, I create a landscape layout for **all of the activity\_main.xml's** I need a separate landscape for the large `activity_main`, the small `activity_main`, the xlarge `activity_main`, and the normal `activity_main`. By doing the method described everywhere, I end up with this:

And because this covers all of the `activity_main.xml`'s, I don't get the option to 'Create Landscape Variation`on my other versions of my`activity\_main\`.

So, how do I get separate landscape layouts for **each** already made variation of `activity_main`?

Thanks so much,

Ruchir

# Answer
> 1 votes
Instead of choosing 'Create Landscape Variation', try 'Create Other...' instead. Then you can make a new layout for whatever set of constraints you want. If you want a layout for xlarge screen and landscape. Then just choose size and orientation as your qualifiers and set them correctly to xlarge and landscape. This should create a new folder with a layout for you.

For more detailed explanation on how to create these folders in Android Studio, try looking at this answer. https://gamedev.stackexchange.com/a/112232/75055

Lastly, ask yourself this. Do you really need a separate layout for each possible screen size? Most apps would be fine with 1-2, one for phone sized screens and maybe one for xlarge/tablet sized screens.

---
Tags: java, 2d, android, game-design, textures
---


title: World Space Normals Are Black

text:
# Question
Title: World Space Normals Are Black
My world space normals appear fine for most of a mesh. However, some of the normals are black. I was wondering if anyone had any ideas why this is. This happens for any mesh, not just this sphere. I'm using a right-handed coordinate system with z up (+x = right, +y = forward, +z = up)

The following image is showing the mesh with no camera or object rotation and with the normals scaled from the \[-1,1\] to \[0,1\] range.

^^Green appears on the other side of the sphere (+y)

The Following Is The GBuffer Generation

Vertex Shader:

```
#version 430

////////////////////////////
//This Is A GBuffer Shader.
//GLSL 4.3
////////////////////////////

#define PLATFORM_WINDOWS_DESKTOP       //Define Windows Desktop Platform For SnAPI.ShaderLib.
#define SHADING_LANGUAGE_GLSL          //Define GLSL Shading Language For SnAPI.ShaderLib.
#pragma include "SnAPIShaderLibrary.h" //Include SnAPI's Shader Library (SnAPI.ShaderLib).

//This Shader Expects To Be Given These Attributes From The Application.
in vec3 In_VertPos;
in vec3 In_VertNormal;
in vec2 In_VertTexCoord;

//This Shader Expects To Be Given The Following Variabls From The Application.
uniform mat4 World;
uniform mat4 WorldView;
uniform mat4 WorldViewProjection;
uniform mat4 WorldInverseTranspose;
uniform mat4 NormalMatrix;

//This Shader Exports The Following Attributes To Be Consumed By The Next Shader.
layout(location = 0) out vec3 Out_VertPos;
layout(location = 1) out vec3 Out_VertNormal;
layout(location = 2) out vec2 Out_VertTexCoord;

//The Vertex Shader Entry Point.
void main()
{
    //Write Out The Vertex Position In Clip Space.
    gl_Position = WorldViewProjection * vec4(In_VertPos, 1);

    //Write Out The Vertex Position In Eye Space.
    //Out_VertPos = ObjectPositionToEyePosition( WorldView, In_VertPos );

    //Write Out The Vertex Position In Eye Space.
    Out_VertPos = ( World * vec4( In_VertPos, 1 ) ).xyz;

    //Write Out The Vertex Normal In Eye Space.
    //Out_VertNormal = ObjectNormalToEyeNormal( NormalMatrix, In_VertNormal );

    //Write Out The Normal Direction In World Space.
    Out_VertNormal = ( World * vec4( In_VertNormal, 0.0 ) ).xyz;

    //Write Out The Vertex Texture Coordinate.
    Out_VertTexCoord = In_VertTexCoord;
}

```

Fragment Shader:

```
#version 430

////////////////////////////
//This Is A GBuffer Shader.
//GLSL 4.3
////////////////////////////

//This Shader Expects To Be Given These Attributes From The Previous Shader.
layout(location = 0) in vec3 In_VertPos;
layout(location = 1) in vec3 In_VertNormal;
layout(location = 2) in vec2 In_VertTexCoord;

//This Shader Supports 1 Diffuse Texture.
uniform sampler2D DiffuseTexture;

//This Shader Expects The Following FragData To Be Exported.
layout(location = 0) out vec4 Out_Pos;
layout(location = 1) out vec4 Out_Normal;
layout(location = 2) out vec4 Out_TexCoord;
layout(location = 3) out vec4 Out_Diffuse;//Vertex Color

//Specifies Whether This Instance Has A Diffuse Texture.
bool bHasDiffuse = false;

//The Fragment Shader Entry Point.
void main()
{
    //Write Position Out To Texture.
    Out_Pos = vec4( In_VertPos, 1 );

    //Write Normal Out To Texture.
    Out_Normal = vec4( normalize( In_VertNormal ), 0 );

    //Write Texture Coord Out To Texture.
    Out_TexCoord = vec4( In_VertTexCoord, 1, 1 );

    //Write Diffuse Out To Texture.
    if( bHasDiffuse )
        Out_Diffuse = texture( DiffuseTexture, In_VertTexCoord );
    else
        Out_Diffuse = vec4( 0.4, 0.4, 0.4, 1 );//Dark Gray Color.
}

```

The Following Is The Full Screen Quad Rendering:

Vertex Shader:

```
#version 430

/////////////////////////////////////////
//This Is A Shading And Lighting Shader.
//GLSL 4.3
/////////////////////////////////////////

//This Shader Expects To Be Given These Attributes From The Application.
in vec3 In_VertPos;//The Clip-Space Vertex Position.
in vec2 In_VertTexCoord;

//This Shader Exports The Following Attributes To Be Consumed By The Next Shader.
layout(location = 0) out vec2 Out_VertTexCoord;

//The Vertex Shader Entry Point.
void main()
{
    //Write Out The Vertex Position.
    gl_Position = vec4( In_VertPos, 1 );

    //Write Out The Vertex Texture Coordinate.
    Out_VertTexCoord = In_VertTexCoord;
}

```

Fragment Shader:

```
#version 430

/////////////////////////////////////////
//This Is A Shading And Lighting Shader.
//GLSL 4.3
/////////////////////////////////////////

#define PLATFORM_WINDOWS_DESKTOP       //Define Windows Desktop Platform For SnAPI.ShaderLib.
#define SHADING_LANGUAGE_GLSL          //Define GLSL Shading Language For SnAPI.ShaderLib.
#pragma include "SnAPIShaderLibrary.h" //Include SnAPI's Shader Library (SnAPI.ShaderLib).

//This Shader Expects To Be Given These Attributes From The Previous Shader.
layout(location = 0) in vec2 In_VertTexCoord;

//This Shader Expects To Be Given The Following GBuffer Textures From The Application.
uniform sampler2D GPositionTexture;
uniform sampler2D GNormalTexture;
uniform sampler2D GDepthTexture;
uniform sampler2D GTexCoordTexture;
uniform sampler2D GDiffuseTexture;

//This Shader Expects The Following FragData To Be Exported.
layout(location = 0) out vec4 Out_FragColor;

//The Fragment Shader.
void main()
{
    //Pixel Albedo.
    vec4 Color = texture( GDiffuseTexture, In_VertTexCoord );

    //Pixel Position In World Space.
    vec3 PixelPos = texture( GPositionTexture, In_VertTexCoord ).xyz;

    //Pixel Normal In World Space
    vec3 Normal = normalize( texture( GNormalTexture, In_VertTexCoord ).xyz );

    //The Lighting Factor (The Ammount Of Lighting To Apply).
    float Lighting = dot( vec3( 1, 0, 0 ) /*Light Direction*/, Normal );

    //Clamp Lighting Factor Between 0-1.
    Lighting = max( Lighting, 0 );

    //Calculate Final Shading/Lighting.
    //Out_FragColor =  Lighting * Color;

    //Preview Normals.
    Out_FragColor =  vec4( Normal, 1 );
}

```

# Answer
> 1 votes
It seems to be working fine. I don't know where the x,y,z-axis is pointing, so I can't really tell. But if you apply no rotation before viewing the geometry it should be easier to determine if it's working correctly as the world space and eye space axis line up. Then the object should be red on the right side (positive x-axis), green on the up side (positive y-axis), and blue toward you/out of the screen (positive z-axis). I'm assuming you are using a right handed coordinate system.

The black is probably the result of all the values becoming less than 0, so no color. If you want it to always have color you could map the values \[-1, 1\] to \[0, 1\] before previewing them.

`Out_FragColor = vec4( 0.5*(Normal + vec3(1.0, 1.0, 1.0)), 1 )`

This should be doing this mapping operation x' = 0.5(x+1) for all x,y,z.

---
Tags: 3d, deferred-rendering, normals, deferred-shading
---


title: increase and decrease coin count

text:
# Question
Title: increase and decrease coin count
I am working in coin system. if the player get the coin it adding to +1 coin. after game over i want to store the coins. if the player again earn coin means the new coin want to add with existing coins. anyone please help. Here's the Code i have used.

```
private int iCoin =0;
private int itotalCoin =0;
String TotalCoinKey = "TotalCoin";

void start(){
itotalCoin=PlayerPrefs.getInt(totalCoinKey,0);
}

void Update(){
playerprefs.Setint(TotalCoinKey, iCoin);
playerprefs.save();
}

public void Death(){
debug.log("current Level Coins = " +iCoin); //Show Coins earn in current level.
}

```

i want to save the earned coin and increment the coins.

# Answer
```
void Update(){
  playerprefs.Setint(TotalCoinKey, iCoin);
  playerprefs.save();
}

```

what that is doing is, it is setting total coins value to the number of coins the player has earned so far this session.

Instead, use trigger for collision detection do detect when player collides with a coin. Using `OnTrigger` method, you can increment the iCoin every time player collides with a coin.

Then, when player dies,

```
public void Death()
{
  itotalCoin=PlayerPrefs.getInt(totalCoinKey,0);
  itotalCoin+=iCoin;
  playerprefs.Setint(TotalCoinKey, itotalCoin);
  playerprefs.save();
}

```

**Update** : How to determine whether to increase or decrease count.

All Collision methods can take optional parameter to identify the collided object and perform necessary action. In this case, you add tags to your coins e.g: tag inc for positive coins and tag neg for negative coins. Then, in `OnTrigger` method,

```
void OnTrigger(Collider col)
{
  if(col.gameObject.tag=="inc")
    iCoin++;
  else
    iCoin--;
}

```

I would also strongly advice to go through Unity documentation and tutorials to get a thorough understanding of methods. Also, note that there are two different physics available : Physics and Physics2D. Please refer docs and tutorials to efficiently use the one you need.
> 4 votes

---
Tags: monogame, unity, unityscript
---


title: Everything is a Scene Node?

text:
# Question
Title: Everything is a Scene Node?
My perception of scene nodes is that they are just containers for Mesh objects with transformations.

After viewing some open sources graphics APIs (e.g Irrlicht), I noticed they call many not-to-be-rendered related objects (such as LightSceneNode, CameraSceneNode, etc) scene nodes, having them inherit SceneNode properties as well. Why is that?

Also, why in Irrlicht is it possible to call `sceneNode->setMaterialTexture()` and other material related methods? I thought that materials are property of Mesh objects and not SceneNode objects.

# Answer
In most game engines today the typical design is that a scene is a graph / tree of components some of which may be renderable.

In a sense you are correct, every object is basically a node in a tree of things.

You may have heard the expression "Entity Component System" and the expression "Component Composition" in relation to game engines and more specifically scene based objects.

These 2 terms refer to a mechanism for maintaining a hierarchy of objects that are part of a renderable scene not all of which may contain a renderer.

Component Composition is particularly useful for games because it refers to the mechanism of using composition to dynamically bolt bits of objects together in order to achieve something useful where each bit would be function / behavior of the object I am bolting to.

For example:

In unity (arguably one of the most popular engines for indie developers today) we can create an object in our scene which is in itself just a container. I can then add child objects to that object which are also just containers.

I can then add things like renderers and mesh information about materials behavior like input control or other behaviors like gravity to an object.

So I could say "this is a terrain object", and this child of that terrain is a character object, which has a controller component to allow the user to feed input to the character.

So to put this back in to terms that match your question ...

Your scene node object would contain a mesh component and a renderer component for rendering that mesh. The renderer would use the mesh and a material to draw the object in our virtual world each frame.

Also:

Other things that might be scene nodes / objects would be a camera, audio source, a light source, none of this as such would typically be renderable but arguably have an impact on the scene, it is the job of the engine to determine how to interpret your defined scene graph / tree.
> 3 votes

# Answer
I don't know about Irrlicht but materials can be represented in some systems like a scene graph where state (texture properties, tint color etc.) is propagated into children.

Scene graphs don't have to contain renderable objects in general, they can be also used for audio positioning etc.
> 1 votes

---
Tags: scene-graph
---


# Question
Title: MSAA/ CSAA / FXAA How to set the mode in OpenGL?
I'm learning OpenGL and something I am stuck with is AA. Specially when I want to turn it on and off at runtime. I know that I can set the samplecount when I create a FBO and blit it over to the final window. When I want to change the mode I switch the FBO and everything is fine. The question I am completely stuck with is, how do I change the mode and also important, how do I query the modes that the card supports. With mode I mean CSAA,MSAA,.. .I can't find a lot. At least I know that it is vendor specific. Hope anyone can point me in the right direction. Thanks

# Answer
Multisampling is a property of the framebuffer. You enable multisampling by rendering to a multisampled framebuffer while `GL_MULTISAMPLING` is enabled. If `GL_MULTISAMPLING` is not enabled when you render to a multisample framebuffer, the pixels covered by that rendering operation replicate their data across all covered samples.

To make a framebuffer object a multisampled framebuffer, you attach multisampled images to it. They will all need to use the same sample count, and all images in the framebuffer must be multisample.

To make the default framebuffer multisampled, you must create your context with multiple samples. This requires the use of the WGL/GLX\_ARB\_multisample extension, as appropriate to your platform.

Nowadays, the general pattern is to leave the default framebuffer non-multisampled and create your own multisample FBO images. Then, you blit from your multisample FBO to the default framebuffer's back buffer to display the multisampled data.

CSAA is an NVIDIA thing, with an extension to govern its use.

FXAA is not a piece of hardware; it's an algorithm. Some drivers have control panel settings that back-door it in. That's generally a bad idea, since they can't tell when you're rendering the UI (something that shouldn't use the FXAA algorithm). So it's generally up to you to implement it.
> 6 votes

# Answer
FXAA doesn't come with OpenGL implementations, you have to find and use a shader that implements it.

CSAA can be used on NVIDIA GPUs using `GL_NV_framebuffer_multisample_coverage`.
> 1 votes

---
Tags: opengl, antialiasing
---


# Question
Title: How to prevent accelerating along wall during 2d sliding collision response
I'm writing a simple 2d physics system using a circle colliding with edges. When the user presses a key the circle's velocity is incremented by some amount in the direction they pressed. There is currently no friction, although that shouldn't be relevant (for example if a character is jumping there's often no friction until landing but walls should still work correctly). There is also a limit to the magnitude of the velocity vector.

When the circle collides with an edge its velocity is projected along the surface of the edge. This allows the circle to slide along the walls, however it causes the circle to accelerate along the surface instead of move at the expected constant speed. Here's a diagram to demonstrate this:

On the left is the first iteration where the red vector represents the velocity and the green vector represents the amount added to the velocity from user input. This combined vector is projected on the wall to produce the blue vector.

On the right is the second iteration where the same green vector as before is added to the current velocity (the same projected velocity from the first iteration), and this resultant vector is projected along the surface to produce the new purple velocity vector.

As you can see the purple vector is larger than the blue one meaning that the circle is moving faster on the second iteration than the first and therefore is accelerating along the wall. The character will continue to accelerate on consecutive iterations along the wall until reaching the maximum speed.

I understand *why* this happens, however I'm struggling to figure out how to change the logic so that it'll behave in the way games typically handle this. Typically characters accelerate more slowly and have a smaller apparent speed cap the more perpendicular they are moving relative to the wall's surface.

# Answer
> 1 votes
I believe this occurs in your example because the user input is used to define the acceleration of the object. (As in your example you show that the velocity is increased based on user input).

**Limiting the Maximum Velocity**

What you could do is have a maximum velocity which scales depending on the angle with which the player attempts to move 'into' the wall,

```
vel_max = vel_max0 * abs(dot(player_input, wall_vector))

```

where `player_input` is the vector for the acceleration added by the player,`wall vector` is the vector parallel to the wall and `dot` is the dot product of the two vectors.

This would mean that a player who tries to go directly into the wall will have a maximum speed of zero and only players who move along the wall will reach the maximum speed `vel_max0`. Note you need to normalise the `player_input` before inserting into the dot product.

**Limiting the acceleration**

In similar way you could limit the acceleration of the player by multiplying by `dot(player_input, wall_vector)` achieving the result you desire.

Edit: As the comments have mentioned this behaviour is not entirely physical but it will 'appear' to behaviour better as per your requests.

---
Tags: physics, collision-resolution, character
---


# Question
Title: Where do you put the game window in fullscreen mode?
My game, like most games, supports running in fullscreen exclusive mode. And I'd like to give my players the choice of which monitor the game will display on.

In order to prevent the player from clicking through to the desktop, I need to position my game window to exactly cover the entire monitor's area.

My game works fine when displaying on adapter 0. I simply set the window's location to 0,0 and its size to the fullscreen resolution.

However, this doesn't work if the player chooses a different monitor. The game will render on the correct monitor, but the window will still be located on the primary monitor.

How do I determine the location for my window when the player chooses a monitor other than 0?

# Answer
> 0 votes
Okay, I believe I have figured it out:

First, call GetAdapterMonitor to get an `HMONITOR` handle from the adapter index you passed in when creating the D3D device. Then use that handle to call GetMonitorInfo, which gives you a MONITORINFO structure. The `rcMonitor` field of that structure contains the location and size of that monitor.

---
Tags: c++, directx9, windows
---


# Question
Title: In a shader, why does substituting a variable with the expression producing it cause different behaviour?
I have this correctly-working OpenGL shader producing Perlin noise:

```
 float left = lerp(fade(v),  downleft,  topleft);
 float right = lerp(fade(v), downright, topright);
 float result = lerp(fade(u), left, right);

```

Then I tried plugging the definitions of `right` and `left` into `result`:

```
float result = lerp(fade(u),
                    lerp(fade(v), downleft,  topleft),
                    lerp(fade(v), downright, topright));

```

Surprisingly, this behaves completely differently, giving visible edges in my Perlin noise. Below are both results:

My whole 30-line shader is here.

What is the difference between those?

# Answer
> 1 votes
It seems like the processing system is loosing floating point precision because you're not declaring memory for the variable. Normally this isn't a problem, however it seems that your lerp function requires a good bit of precision. Imagine this: computers cannot know irrational numbers. So if X is the square root of 5, and Y is the square root of 3. Saying X + Y is different than sqrt(5) + sqrt(3)

This is because on the lower level the data in the first operation goes

data \> memory \> cpu \> memory

And in the second operation it's more like

Data \> cpu \> memory

While faster, this operation results in precision loss, especially in 32 bit systems.

---
Tags: opengl, shaders
---


# Question
Title: Implementing attack animation in four direction movement
The way the program is supposed to run is basically, a character can be running/idle and if spacebar is pressed, all movement stops and movement controls are locked through the bool "canMove". The integer shockwave is a 1-4, directly correlating to the direction 1-4 (1 = north, 2 = east, 3 = south, 4 = west). Then, the animation plays and when it is over the controls are unlocked and you can move freely.

The problem I have encountered is, I can find no way to specifically tell when the animation is ending inside of a blend tree. I cannot find a way to allow the animation to play, and then continue to unlock the controls.

Since this site won't let me post more than three links, I will have to describe the animator window. Basically I have four idle states (N, E, S, W). Each motion is a blend tree, and each state is connected with a transition purely based off of int direction.

This is where I tried adding another motion to the blend tree called shockwave, based on threshold speed (-1). This worked up until the point that I realized I would not be able to add anymore attacks or states, and that I could not tell when the animation had finished in order to unlock the controls.

```
void Update (){

    if (Input.GetKey (KeyCode.Space)){

        canMove = false;
        direction = animator.GetInteger ("Direction");
        animator.SetFloat ("Speed", 0.0f);

        if (direction == 1){
            animator.SetInteger("Shockwave", 1);
            animator.SetFloat ("Speed", -1.0f);

            //find a way to detect that the attack animation is done.
            //continue and allow movement
            canMove = true;

                }
            }

        else if (direction == 2){
            animator.SetInteger ("Shockwave", 2);
            //if(!anim.IsPlaying ("character_shockwave_2")){
                //canMove = true;
            //}
        }
        else if (direction == 3){
            animator.SetInteger ("Shockwave", 3);
            //if(!anim.IsPlaying("character_shockwave_3")){
            //  canMove = true;
            //}
        }
        else if (direction == 4){
            animator.SetInteger ("Shockwave", 4);
            //if(!anim.IsPlaying("character_shockwave_4")){
                //canMove = true;
            //}
        }

```

Attempted solutions:

I have tried to use waitforseconds(x), and just wait for the attack animation to finish, and then after that amount of seconds I would set the canMove bool to true. For whatever reason, I cannot get this to work.

I have also tried to directly find if the animation is done playing through a few different ways, but I learned that the blend tree does not allow this.

The only solution I have thought might work is actually manually playing all animations through code alone. (Would require re writing the entire program).

If any further code is needed, I can supply it.

# Answer
Have you tried hooking into the Unity OnStateExit?

https://unity3d.com/learn/tutorials/modules/beginner/5-pre-order-beta/state-machine-behaviours

This will allow your state machine to execute code every time you exit a state.
> 1 votes

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


# Question
Title: Async loading in libGDX to set the screen
I would like to bring up a loading screen, for this would make the load async. How can I do this? I looked on the libGDX website but I do not understand very well, maybe because of my poor English.

Here's the code :

```
public void show() {
        stage = new Stage();

        Gdx.input.setInputProcessor(stage);

        loading = new com.badlogic.gdx.scenes.scene2d.ui.Image(new TextureRegion(new Texture(Gdx.files.internal("loading.png"))));
        loading.setPosition(Gdx.graphics.getWidth() / 2 - loading.getWidth() / 2, Gdx.graphics.getHeight() / 2 - loading.getHeight() / 2);
        loading.setOrigin(loading.getWidth() / 2, loading.getHeight() / 2);
        loading.setZIndex(1);

        loading.addAction(rotateTo(1440, 20));

        stage.addActor(loading);

        game.setScreen(game.gameScreen);
    }

```

What I would do is an async method like this:

```
asyncmethod()

public asyncmethod()
{
     game.setScreen(game.gameScreen);
}

public void show() {
        stage = new Stage();

        Gdx.input.setInputProcessor(stage);

        loading = new com.badlogic.gdx.scenes.scene2d.ui.Image(new TextureRegion(new Texture(Gdx.files.internal("loading.png"))));
        loading.setPosition(Gdx.graphics.getWidth() / 2 - loading.getWidth() / 2, Gdx.graphics.getHeight() / 2 - loading.getHeight() / 2);
        loading.setOrigin(loading.getWidth() / 2, loading.getHeight() / 2);
        loading.setZIndex(1);

        loading.addAction(rotateTo(1440, 20));

        stage.addActor(loading);

        asyncmethod();
    }

```

# Answer
> 3 votes
In a nutshell you should use power of AssetManager instead of async thread.

```

public static AssetManager manager = new AssetManager();

public MyAppListener implements ApplicationListener {

    public void create()
    {
        loading = new com.badlogic.gdx.scenes.scene2d.ui.Image(new TextureRegion(new Texture(Gdx.files.internal("loading.png"))));
        loading.setPosition(Gdx.graphics.getWidth() / 2 - loading.getWidth() / 2, Gdx.graphics.getHeight() / 2 - loading.getHeight() / 2);
        loading.setOrigin(loading.getWidth() / 2, loading.getHeight() / 2);
        loading.setZIndex(1);

        loading.addAction(rotateTo(1440, 20));

        stage.addActor(loading);

        // add assets to queue (will be loaded later)
        manager.load("data/mytexture.png", Texture.class);
        manager.load("data/myfont.fnt", BitmapFont.class);
        manager.load("data/mymusic.ogg", Music.class);
    }

    public void render() {

        // loads a part of assets step by step and let you show your loading screen
        if(manager.update()) {
            // we are done loading, let's move to another screen!
            game.setScreen(game.gameScreen);
            return;
        }

        // display loading information
        super.render();
    }
}

```

Here is the wiki page - https://github.com/libgdx/libgdx/wiki/Managing-your-assets

# Answer
> 1 votes
If you wish for your loading screen to be visible whenever an asynchronous process is taking place instead of just regarding asset management, you could always make use the the com.badlogic.gdx.utils.async classes

```
public class MyAppListener extends Game {

AsyncExecutor asyncExecutor = new AsyncExecutor(10);

AsyncResult<Void> task;

Stage stage;

public void asyncMethod() {
     //do stuff
     setScreen(gameScreen);
}

public void create()
{
    stage = new Stage();

    loading = new Image(new TextureRegion(new Texture(Gdx.files.internal("loading.png"))));
    loading.setPosition(stage.getWidth()/2f, stage.getHeight()/2f, Align.center);
    loading.setOrigin(Align.center);
    loading.setZIndex(1);

    loading.addAction(rotateTo(1440, 20));

    stage.addActor(loading);

    //create our async task that runs our async method
    task = asyncExecutor.submit(new AsyncTask<Void>() {
        public Void call() {
            asyncMethod();
            return null;
        }
    });
}

public void render() {

    // checks to see if the task is done.  If not draw the load screen
    if(!task.isDone()) {
        stage.act();
        stage.draw();
        return;
    }

    // display the game's current screen
    super.render();
}
}

```

It's useful to put your load screen within your application listener instead of in a separate Screen object. If you have your load screen as a Screen and change to it, then change it back to the original screen when the task is done, you might enter into an infinite loop as you'll keep going into show and hide methods of each Screen.

The only downside of having the loading screen in your application listener is that it'll always be in memory. However, it's such a small object that having it in memory at all times is a non-issue.

---
Tags: libgdx, multithreading
---


title: Java 2d topdown collision

text:
# Question
Title: Java 2d topdown collision
Im making a game and Im working on the collision. First Ill tell you what I want (Ill put in pictures), then Ill leave the code.

**What I want:** I want the player to stop exactly before its collision box (a rectangle) intersects with a wall collision box. Right now this only happens sometimes, sometimes it doesnt go all the way to the wall, that is probably because the velocity is too big I guess. Here are the pictures:

*Left:* it works good, it goes all the way to the wall (btw the red square is the collision box).

*Right:* The player only goes down that much and leaves a gap inbetween it and the wall (the circle shows the gap) and you can not go down to go all the way to the wall.

*The movment code:*

```
if(canMove){
    move(xVol, yVol);
    xVol = yVol = 0f; // resets the velotcity
}

public void move(float xv, float yv){
    if(!collisionv(yv)){
        y += yv; // moves the player on its y
        for(Entity e : PlayState.e){
            if(e.getID() == ID.Player){
                e.getCollisionRect().setY(y); // moves the collision box
            }
        }
    }

    if(!collisionh(xv)){
        x += xv; // moves the player on its x
        for(Entity e : PlayState.e){
            if(e.getID() == ID.Player){
                e.getCollisionRect().setX(x); // moves the collision box
            }
        }
    }

}

public boolean collisionv(float yv){
// Vertical collision checking
    boolean ret = false;
// makes a rectangle that represends the players collision rect after it moved to check if it will be colliding with anything
    Rectangle p = new Rectangle(x, y + yv, getCollisionRect().getWidth(), getCollisionRect().getHeight());

    for(Entity e:PlayState.e){

        if(e.getID() != ID.Player && c.trueCollision(p, e.getCollisionRect())){
    // This true collision method just returns if the rectangles are intersecting
            ret = true;
        }
    }
    return ret;
}

public boolean collisionh(float xv){
// Horizontal collision checking
    boolean ret = false;
    // makes a rectangle that represends the players collision rect after it moved to check if it will be colliding with anything
    Rectangle p = new Rectangle(x + xv, y, getCollisionRect().getWidth(), getCollisionRect().getHeight());

    for(Entity e:PlayState.e){
        if(e.getID() != ID.Player && c.trueCollision(p, e.getCollisionRect())){
            ret = true;
        }
    }
    return ret;
}

```

**My question: How do I make it move all the way to the wall, never leaving a gap inbetween the player and the wall?**

# Answer
Check out my answer: Platformer collision problems (C++)

Maybe it doesn't seem so simple to implement with your codes but that collision system would be the best choice for you (I think).
> 1 votes

---
Tags: java, collision-detection, slick
---


title: Sprite orbiting on a point

text:
# Question
Title: Sprite orbiting on a point
I was wondering how to make a Sprite do an orbit on a determinated point in SpriteKit. I tried to set the `anchorPoint` of the Sprite orbiting with the center point but it doesn't work. Please can someone help me?

# Answer
> 1 votes
Use the parenting to your advantage. From the SKNode Class Reference:

> When a node’s coordinate system is scaled or rotated, this transformation is applied both to the node’s own content and to that of its descendants.

First, create an `SKNode` (your center node) and set its position to the center of the orbit. Next, add the `SKSpriteNode` that should be orbiting as child to the center node. Set the child node's position to the radius of the orbit ((0, 50) for a radius of 50).

When you rotate the center node, the child will "orbit" around it.

---
Tags: ios, spritekit
---


# Question
Title: Drawing a lines radiating from every angle using Bresenham line algorithm
I am trying to recreate a image like this

... or just each point

Using Bresenham line algorithm, but can't seem to able to do so.. The point i receive from my computation doesn't look like a like, and output from the different angles don't make sense for instance.

I start from the center (3,3), and want to draw with a certain angle with a given radius..

```
angle: 1
13,19
bressenham:
mark: 3,3
mark: 3,3
mark: 4,4
mark: 4,4
mark: 5,5
mark: 5,5
mark: 6,6
mark: 6,6
mark: 7,7
mark: 7,7
mark: 8,8
mark: 8,8
mark: 9,9
mark: 9,9
mark: 10,10
mark: 10,10
mark: 11,11
mark: 11,11
mark: 12,12
mark: 12,12
1319
angle: 2
-5,21
bressenham:
mark: -5,3
mark: -5,3
mark: -5,4
mark: -4,5
mark: -4,5
mark: -4,6
mark: -3,7
mark: -3,7
mark: -3,8
mark: -2,9
mark: -2,9
mark: -2,10
mark: -1,11
mark: -1,11
mark: -1,12
mark: 0,13
mark: 0,13
mark: 0,14
mark: 1,15
mark: 1,15
mark: 1,16
mark: 2,17
mark: 2,17
mark: 2,18
-521

```

For angle 1 =\> the angle is set to one.. (13,19) is the position of the endpoint located at the given length. and all the mark: are those pixels which are being marked by the algorithm.. That one makes sense, but, when i do the same for angle = 2.. something messes up.. I don't know why, but it would be very helpful if any of you could help me solve this problem.

Here is the code i used to compute these output.

```
#include <iostream>
#include <math.h>
using namespace std;

int sign(double x ){ return (x > 0) ? 1 : ((x < 0) ? -1 : 0); }

std::pair<int,int> endpoint(double angle, int x1 , int y1, int lenght)
{

    if(angle == 90)
    {
        double y2 = y1+lenght;
        return std::make_pair(x1, -y2);
    }
    if(angle == 180)
    {
        double x2 = x1+lenght;
        return std::make_pair(-x2, y1);
    }
    if(angle == 270)
    {
        double y2 = y1+lenght;
        return std::make_pair(x1, y2);
    }

    double x2 = x1 + (lenght * cos(angle));
    double y2 = y1 + (lenght * sin(angle));
    return std::make_pair(x2,y2);
}

void bresenham(int x0, int y0, int x1, int y1)
{
    int dx = x1-x0;
    int dy = y1 - y0;
    if (abs(dx) > abs(dy))
    {
        // x-axis
        int j = y0;
        double e = dy - dx;

        for (int i = x0; i<x1; i++)
        {
            std::cout << "marked: " << i << ","<< j << std::endl;
            if( e >= 0)
            {
                j += 1;
                e -= dx;
            }
            e += dy;

        }
    }
    else if(abs(dx)<abs(dy))
    {
        // y-axis

        int j = x0;
        double e = dx - dy;

        for (int i = y0; i<y1; i++)
        {
            std::cout << "marked: " << j<< ","<< i << std::endl;
            if( e >= 0)
            {
                j += 1;
                e -= dy;
            }
            e += dx;

        }

    }

}

void line(int x0, int y0, int x1, int y1)
{

    if(x1 < x0)
    {
        swap(x1, x0);
    }

    if(y1 < y0)
    {
        swap(y1, y0);
    }

    int dx = x1-x0;
    int dy = y1-y0;
    double e = 0;
    if(dx == 0)
    {
        if (sign(dy) == -1)
        {
            cout << "new" << endl;
            for (int y = y0; y != y1; y--)
            {
                cout << "mark" << x1 << "," << y << endl;
            }

        }
        else
        {
            for (int y = y0; y != y1; y++)
            {
                cout << "mark" << x1 << "," << y << endl;
            }
        }
        return;
    }

    else if(dy == 0)
    {

        if (sign(dx) == -1)
        {
            cout << "new" << endl;

            for (int x = x0; x != x1; x--)
            {
                cout << "mark" << x << "," << y1 << endl;
            }

        }
        else
        {
            for (int y = y0; y != y1; y++)
            {
                cout << "mark" << x1 << "," << y << endl;
            }
        }
        return;
    }
    cout << "bressenham: " << endl;
    double de = abs(dy/dx);
    int y = y0;
    for (int x = x0; x != x1; x++)
    {
        cout << "mark: " << x << "," << y << endl;
        e = e + de;
        while (e >= 0.5)
        {
            cout << "mark: " << x << "," << y << endl;
            y = y + sign(y1-y0);
            e = e -1;
        }
    }

}

int main(int argc, const char * argv[])
{
    for (int angle = 0; angle < 180; angle++)
    {
        cout << "angle: " << angle << endl;
        pair<int, int> end = endpoint(angle, 3, 3, 20);
        cout << end.first << end.second << endl;
        line(3, 3, end.first, end.second);
        cout << end.first << end.second << endl;

    }
    return 0;
}

```

# Answer
> 2 votes
This might not be your only issue but I noticed you're using `sin` and `cos` with degrees. You must first convert your angles to radians for those functions to work properly (read "Parameters" here):

```
#define PI 3.14159265

std::pair<int,int> endpoint(double angle, int x1 , int y1, int length)
{
    // ...
    double x2 = x1 + (length * cos(angle * PI / 180.0 ));
    double y2 = y1 + (length * sin(angle * PI / 180.0 ));
    return std::make_pair(x2,y2);
}

```

Also, you spelt "length" wrong ;b

---
Tags: c++, angles, trigonometry, lines, rasterization
---


title: Display mesh in front of camera

text:
# Question
Title: Display mesh in front of camera
Im trying to display a mesh in front of the camera and **FACING** the camera ( I'm developing an small editor in wpf using helix3d).

Pretty much something like this question

I load my mesh into a `ModelVisual3D` and I set it 20 units in front of the camera with this code:

```
var camera = ((PerspectiveCamera) viewport.Camera);
var distanceFromCamera = 20;

var direction = camera.LookDirection;
direction.Normalize();
direction = direction * distanceFromCamera;

var meshPosition = camera.Position + direction;

 var compositeTransform = new Transform3DGroup();

 compositeTransform.Children.Add(new RotationTransform(???));
 compositeTransform.Children.Add(new TranslateTransform3D(meshPosition));

ModelVisual3D mesh = LoadMesh(...);
mesh.Transform = compositeTransform

```

It already shows correctly in front of the camera, but I'm missing the rotation, how can I extract the rotation of the camera and set it to my mesh so is facing the camera?

**Edit**

I tried to use the following function to get the rotation matrix but is not working either:

```
    static Matrix3D CalculateLookAt(Vector3D eye, Vector3D at, Vector3D up)
    {
        if (Math.Abs(up.Length - 0.0) < double.Epsilon) up = new Vector3D(0, 1, 0);
        var zaxis = (at - eye);
        zaxis.Normalize();
        var xaxis = Vector3D.CrossProduct(up, zaxis);
        xaxis.Normalize();
        var yaxis = Vector3D.CrossProduct(zaxis, xaxis);

        return new Matrix3D(
            xaxis.X, yaxis.X, zaxis.X, 0,
            xaxis.Y, yaxis.Y, zaxis.Y, 0,
            xaxis.Z, yaxis.Z, zaxis.Z, 0,
            Vector3D.DotProduct(xaxis, -eye), Vector3D.DotProduct(yaxis, -eye), Vector3D.DotProduct(zaxis, -eye), 1
            );
    }

```

# Answer
> 1 votes
I had to ask a friend that is good at 3D graphics this is what he did to make it right:

```
 ProjectionCamera camera = (ProjectionCamera) viewport.Camera;

Vector3D ax1 = camera.LookDirection.Normalized();
Vector3D ax2 = Vector3D.CrossProduct(ax1, camera.UpDirection).Normalized() * -1;
Vector3D ax3 = camera.UpDirection.Normalized();

Vector3D translation = (ax1*20 + camera.Position).ToVector3D();
Quaternion rotation = new Quaternion(ax3, -90) * QuaternionUtils.CreateFromRotationAxes(ax1,ax2,ax3);

Transform3DGroup transformGroup = new Transform3DGroup();

transformGroup.Children.Add(new RotateTransform3D(new QuaternionRotation3D(rotation)));
transformGroup.Children.Add(new TranslateTransform3D(translation));

mesh.Transform = transformGroup;

```

---
Tags: c#, 3d, transformation, linear-algebra, wpf
---


title: Unity procedural textures

text:
# Question
Title: Unity procedural textures
I'm wanting to have an object that does random animation in Unity, within the object. Basically, I want a floor that has lights that go through it. I'm trying to figure out exactly what is the best way to make that happen. I know there is such a thing as "Procedural Textures" in Unity, but I'm struggling to understand exactly how to make these textures. There are two basic ideas which I have:

1. Attach a script to the object that I want to place the texture on. That class should manage the texture in all senses of the word. This seems clunky, because it won't show up in the scene mode. This texture would then be assigned in the Start() function for said script.
2. There exists tools that make these procedural textures, such as Substance. Currently I don't have much of a budget for game development, so I'd like to stay away from anything with a cost (This is more of a hobby for me right now).

Is this the correct way to think about things, or am I missing something fundamental? There seems to be procedural materials that I can't quite understand how they work. Am I missing something else? Thanks!

EDIT:

What I'm trying to do is to have moving lights go across a floor, either as a part of the floor, or even as contained within the floor. I'm considering using some kind of particle system for it, but I've heard about these procedural textures and I thought it was worth a shot to see if they do something similar. I'm also considering using a randomly generated star skybox using a similar method. Specifically, I'm picturing moving lights going across the floor in this image.

# Answer
It turns out that the trick was to simplify. @Phillip provided me with a trick, that the easiest thing to do was to create a series of small moving lights, that only rendered on the floor. This creates the moving lights that I was looking for. This shows what I was looking for.

How I achieved this:

1. Create a game object that periodically creates small light sources that move just above the floor.
2. The floor was already on it's own render layer. I specified the light to only affect that layer. I might change my mind on this later, but for now, I like the effect.
3. Apply a slight velocity to the objects, some random color, and away they go!

The code looks something like this:

```
    GameObject obj = new GameObject();
    obj.transform.position = startLocation;

    Light light = obj.AddComponent<Light>();
    light.type = LightType.Point;
    light.intensity = Random.Range(probeMinIntensity, probeMaxIntensity);
    light.cullingMask = 0x1;
    light.bounceIntensity = 0f;

    Rigidbody rigid = obj.AddComponent<Rigidbody>();
    rigid.useGravity = false;
    rigid.velocity = new Vector3(0, 0, 1);

```

Of course, there's still more work to do, but this was more than enough to get me over the hurdle. Thanks!
> 1 votes

---
Tags: unity, textures, procedural
---