title: How to "port" Java2D code to LWJGL

text:
# Question
Title: How to "port" Java2D code to LWJGL
I've been following some game tutorials on youtube and developed a custom engine using Java (Graphics2D, BufferStrategy and such).

I have a class "Surface", which represents any 2D object (image, animation, sprite, text, graph, tiled map, height map, etc). All surfaces have some generic properties and a BufferedImage where the current state is drawn, and passed to the renderer when needed.

Everything works fine, but i wanted to try something "better" so now i have a new project using LWJGL 3 and... i'm totally lost. I know OpenGL and Graphics2D are parallel universes, but at this moment i just want to adapt the existing code to the new libraries.

How can i create a target surface for 2D drawing, which can receive pixels from different sources and drawing methods, using modern OpenGL/LWJGL?

# Answer
> 1 votes
Your best bet is to make a class that replicates Javas Graphics class in LWJGL.

For textures you can write your own LWJGL wrapper or use Slick 2D

---
Tags: opengl, java, rendering, lwjgl
---


title: Using my pathfinding more efficiently

text:
# Question
Title: Using my pathfinding more efficiently
I'm making a roguelike in C# with the Roguesharp libraries, in which the map can be as large as 200x200 cells. When I have an entity requiring pathfinding, I am using Roguesharp's built in pathfinding system (which I believe uses a variation on A\*, with Manhattan movement instead of orthogonal movement).

When I have an entity pathfinding every turn (to path to the player, which may constantly move) the framerate roughly halves, but the game is still playable. However, when I add in more entities the framerate drops greatly. 10 entities leaves the game running at less than 1 fps and completely unplayable.

Clearly I am doing something wrong, games like Dwarf Fortress manage to have hundreds of entities running around maps this size with little trouble. Does anyone have suggestions for how I can get better performance.

The way it currently works is: whenever the player takes his turn (attacks, moves, etc.) the game loops through every entity, does the pathfinding for that entity and moves them. Is there a more efficient way to do this when the player is moving every turn?

# Answer
> 3 votes
Graph-based pathfinding calculates an entire path (multiple turns' worth) and you're using only the first step, throwing away the rest, and recalculating every turn. This is wasteful. Keep following the path already computed until you think you need to recalculate it. If you're far away from the target, recalculate infrequently; if you're near it, recalculate frequently.

Also, RogueSharp's pathfinder isn't using A\*; it's using Dijkstra's Algorithm underneath, which is doing a lot of unnecessary work if all you want is a path from one location to another. (On your 200x200 = 40000 tile map, it finds a path from the source to *all* 40000 locations, then throws away all the paths other than the one it wants.)

However, your case has a better solution.

For the special case of many entities pathfinding to the same location, Dijkstra's Algorithm works better than A\*. For the special case of Dijkstra's where every step is weight 1, you can use Breadth First Search, which is even faster. Breadth First Search can be incredibly fast.

Dijkstra's and Breadth First Search find a path from one location to *all* other locations. You'll run pathfinding *once* to find a path between the player and all other locations. You'll get back a map of directions:

Then all the enemies look in that map to see which direction to move. The enemies don't have to run their own pathfinding.

I have a tutorial on this topic and some partial code in C#. Alternatively, it looks like Roguesharp includes a Dijkstra's Algorithm class so you could use that to find the paths from the player to all other locations.

# Answer
> 0 votes
You don't want to check for a path all at the same time for all of your entities. You could try to set a timer on each of your entities, and poll for a new path when the timer expires (instead of waiting for a move).

You can further refine this by only reducing the poll timer when the player changes positions (but this is really dependant on your specific game play).

Another thing to consider, is having a "Leader" and "Groups". The active leader of a group will poll for a path, while the remainder of that group would simply follow it's leader.

---
Tags: c#, path-finding, roguelikes
---


title: Cocos2d-x build failing on linux

text:
# Question
Title: Cocos2d-x build failing on linux
I was trying to compile cocos2d-x on my linux machine, because they do not provide a binary copy of the library. However, I received the following error during the build:

```
/home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/2d/CCActionCamera.cpp: In member function ‘virtual void cocos2d::OrbitCamera::startWithTarget(cocos2d::Node*)’:
/home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/2d/CCActionCamera.cpp:193:22: error: ‘isnan’ was not declared in this scope
     if( isnan(_radius) )
                      ^
/home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/2d/CCActionCamera.cpp:193:22: note: suggested alternative:
In file included from /usr/include/c++/4.9/random:38:0,
                 from /home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/base/ccRandom.h:29,
                 from /home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/base/ccMacros.h:73,
                 from /home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/math/CCGeometry.h:32,
                 from /home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/2d/CCAction.h:32,
                 from /home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/2d/CCActionInterval.h:33,
                 from /home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/2d/CCActionCamera.h:31,
                 from /home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/2d/CCActionCamera.cpp:28:
/usr/include/c++/4.9/cmath:641:5: note:   ‘std::isnan’
     isnan(_Tp __x)
     ^
/home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/2d/CCActionCamera.cpp:195:22: error: ‘isnan’ was not declared in this scope
     if( isnan(_angleZ) )
                      ^
/home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/2d/CCActionCamera.cpp:195:22: note: suggested alternative:
In file included from /usr/include/c++/4.9/random:38:0,
                 from /home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/base/ccRandom.h:29,
                 from /home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/base/ccMacros.h:73,
                 from /home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/math/CCGeometry.h:32,
                 from /home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/2d/CCAction.h:32,
                 from /home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/2d/CCActionInterval.h:33,
                 from /home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/2d/CCActionCamera.h:31,
                 from /home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/2d/CCActionCamera.cpp:28:
/usr/include/c++/4.9/cmath:641:5: note:   ‘std::isnan’
     isnan(_Tp __x)
     ^
/home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/2d/CCActionCamera.cpp:197:22: error: ‘isnan’ was not declared in this scope
     if( isnan(_angleX) )
                      ^
/home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/2d/CCActionCamera.cpp:197:22: note: suggested alternative:
In file included from /usr/include/c++/4.9/random:38:0,
                 from /home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/base/ccRandom.h:29,
                 from /home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/base/ccMacros.h:73,
                 from /home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/math/CCGeometry.h:32,
                 from /home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/2d/CCAction.h:32,
                 from /home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/2d/CCActionInterval.h:33,
                 from /home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/2d/CCActionCamera.h:31,
                 from /home/ryan/Downloads/cocos/cocos2d-x-3.11.1/cocos/2d/CCActionCamera.cpp:28:
/usr/include/c++/4.9/cmath:641:5: note:   ‘std::isnan’
     isnan(_Tp __x)
     ^
cocos/CMakeFiles/cocos2dInternal.dir/build.make:86: recipe for target 'cocos/CMakeFiles/cocos2dInternal.dir/2d/CCActionCamera.cpp.o' failed
make[2]: *** [cocos/CMakeFiles/cocos2dInternal.dir/2d/CCActionCamera.cpp.o] Error 1
CMakeFiles/Makefile2:463: recipe for target 'cocos/CMakeFiles/cocos2dInternal.dir/all' failed
make[1]: *** [cocos/CMakeFiles/cocos2dInternal.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

```

I have installed all of the dependencies, to my knowledge. Did I do something wrong or is this a known issue that I've encountered?

# Answer
While not having experience with Cocos2D, I'd guess that you'll need to replace `isnan` with `std::isnan`. If that works, it's a portability bug in Cocos2D because on some compilers/standard libraries some methods can be called without `std::`.
> 2 votes

---
Tags: c++, cocos2d-x
---


title: Unity using Animation and Ragdoll

text:
# Question
Title: Unity using Animation and Ragdoll
The question is simple, but I can't resolve it for a couple of days. I have an enemy model with ragdoll attached and also a couple of animations(e.g. idle, walk, run). It seems that ragdoll work only when animator is stopped and vice versa. What I want is when the animation is playing all the forces are applied too, e.g. when I shoot enemy he still walking by animation and and ragdoll corresponds with AddForce(). I tried to find appropriate tutorial for that, watched ton of youtube videos and read a lot of unity forums, but no success. Any help is appreciated. Thanks in advance.

# Answer
This link looks interesting and provides almost that what I need, maybe it can help somebody too http://forum.unity3d.com/threads/animfollow-active-ragdoll-is-now-free-to-download.220812/
> 2 votes

---
Tags: unity, physics, software-engineering
---


title: Receiving a "cannot find symbol" error

text:
# Question
Title: Receiving a "cannot find symbol" error
In my Java class, we're creating a connect 4 game. For now, we're just setting up the GUI. I am receiving the error on lines 13 and 14 " private ArrayListplayer; private Connect4Ui frame;"

and I'm receiving an error in the UI class on the GameListener line as well as the Panel line. I'm sure it's something simple, but this is our first few weeks of the intro course. Thanks a lot!

```
package connectfour;

import java.util.ArrayList;
import javax.swing.*;

/**
 *
 * @author j_ortiz9688
 */

// connect 4 main
public class ConnectFour {

    private ArrayList<Player>player;
    private Connect4Ui frame;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

    }

}

```

Ui Class

```
package userInterface;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

/**
 *
 * @author j_ortiz9688
 */
public class Connect4Ui extends JFrame {

    JMenuBar menuBar;
    JMenu gameMenu;
    JMenuItem playerPlayer;
    JMenuItem playerComputer;
    JMenuItem computerComputer;
    JMenuItem exit;
    GameListener gameListener;
    Connect4Panel boardPanel;

}

```

# Answer
You probably didn't import the classes Player and Connect4Ui. They seem to be in other packages, so you should write something like:

```
import userInterface.Connect4Ui;

```

at the beginning of your ConnectFour-File
> 0 votes

---
Tags: java
---


title: XNA - SoundEffect with SpeedOfSound

text:
# Question
Title: XNA - SoundEffect with SpeedOfSound
SoundEffect has SpeedOfSound property. I'm trying to use it, but it doesn't work:

```
SoundEffect.SpeedOfSound = 600.0f;
SoundEffectInstance soundEffectInstance = stepsSound.CreateInstance();
soundEffectInstance.Volume *= 0.5f;
soundEffectInstance.Play();

```

How to use it? How to set speed of sound?

# Answer
`SpeedOfSound` is the value for the speed of sound... that is, how fast sound waves propagate. It does not control the *playback speed* (or thus, effective duration) of an individual sound. Instead, it alters how the Doppler effect of 3D sounds is perceived.

What you probably want is to change the sound's `Pitch` property, although this has a limited range.

XNA does not natively support pitch-invariant time distortion of a sound, as far as I am aware.
> 0 votes

---
Tags: xna, monogame, sound-effects
---


# Question
Title: Dragging text element into Text variable unity 4.6
So I was trying to make a UI element to keep score in a unity (4.6) project and I'm having trouble assigning the 'Text' element to the Text variable.

So I have the text element with the script attached to it. At the moment the script is empty except from some variables being created, here it is:

```
using UnityEngine;
using UnityEngine.UI;

public class TextController : MonoBehaviour {

public Text text;
public int score1, score2;

// Use this for initialization
void Start () {
}

// Update is called once per frame
void Update () {
    //text.text = "a" + "";
}
}

```

In the unity UI the Text variable shows but it is empty, and it will not let me drag the 'Text' object from the hierarchy into the variable box. It shows the outline like its going to accept it but remaing 'None (Text)' when I release the click. I tried importing an already working UI from another project into this but when I added it to the hierarchy it removed the text element again (just for reference the text worked perfectly in the other project).

Also a screenshot of the hierarch just in case:

Is there a problem with the scipt or the prject or have I messed something else up?

Edit:

Clicking the circle next to the text variable brings up the window to select the element. Mine shows up without anything in it. I expect it to show the text object I have made.

# Answer
> 2 votes
So long as your 'Text' object contains a `Text` component, this will work as expected.

You may have replaced the `Text` component with your `TextController` script, or it was removed some other way.

Alternatively, you could change your script as follows:

```
using UnityEngine;
using UnityEngine.UI;

public class TextController : MonoBehaviour {

    public GameObject textObject;
    Text text;
    public int score1, score2;

    // Use this for initialization
    void Start () {
        if(textObject == null)
        {
            Debug.Log("You must set textObject to an UI component with a Text script");
            this.enabled = false;
            return;
        }
        text = textObject.GetComponent<Text>();
        if(text == null)
        {
            Debug.Log(textObject.name + " doesn't contain a Text component!");
            this.enabled = false;
            return;
        }
    }

    // Update is called once per frame
    void Update () {
        //text.text = "a" + "";
    }
}

```

This way, you can just drag the GameObject, and the script will retrieve the Text component on Start(). If the Text component is not available, the script will warn the developer and disable itself.

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


title: LibGDX, vertical group not displaying

text:
# Question
Title: LibGDX, vertical group not displaying
I'm having trouble showing a simple custom `VerticalGroup`.

Here's my `SideBar` class:

```
public class SideBar extends VerticalGroup {
    final GameManager gameManager = GameManager.instance;
    final Image nextBackground;
    final Image nextImage;
    final Image powerImage;
    final Image powerUp1Background;
    final Image powerUp2Background;
    final Image powerUp3Background;

    public SideBar() {
        super();
        nextBackground = new Image(gameManager.getTexture("bar.next.png"));
        addActor(nextBackground);
        nextImage = new Image(gameManager.getTexture("label.next.png"));
        addActor(nextImage);
        powerImage = new Image(gameManager.getTexture("label.power.png"));
        addActor(powerImage);
        powerUp1Background = new Image(gameManager.getTexture("powerup.bg.png"));
        addActor(powerUp1Background);
        powerUp2Background = new Image(gameManager.getTexture("powerup.bg.png"));
        addActor(powerUp2Background);
        powerUp3Background = new Image(gameManager.getTexture("powerup.bg.png"));
        addActor(powerUp3Background);
    }
}

```

And here's where I add it to my main `Stage`:

```
    TopBar topBar = new TopBar();
    topBar.setY(DonutsGame.WORLD_HEIGHT - topBar.getHeight());
    stage.addActor(topBar);

    SideBar sideBar = new SideBar();
    Gdx.app.log(TAG, "side bar - x,y: " + sideBar.getX() + "," + sideBar.getY() + ", w,h: " + sideBar.getWidth() + "," + sideBar.getHeight());
    stage.addActor(sideBar);

```

My `TopBar` class extends `Group` and is displaying correctly, so I'm not sure what I'm doing wrong with `SideBar` that's causing it to not show.

The `log` output shows that the position, and width/height are all 0, which seems incorrect to me according to the vertical group's documentation. Which states that the width/height should be based on the pref. width/height of the children (height based on sum).

I've tried calling `validate` and `layout` with no success.

# Answer
It seems that if the `VerticalGroup` is added to another layout, then it works. Looking at the code, this is due to `VerticalGroup` also being a `Layout`, and so it's `prefWidth`/`Height` are used instead of the `getWidth`/`Height` methods.

I got around this by manually setting the size to the pref. size.

```
setSize(getPrefWidth(), getPrefHeight());

```

Note, that you don't need to do this if you're putting the `VerticalGroup` in another `WidgetGroup` like `Table` or `ScrollPane` since they use `prefWidth`/`Height` anyway.
> 1 votes

---
Tags: libgdx, scene2d
---


# Question
Title: How to code a multi level isometric map?
I have already worked with isometric grids in the past, but in my current project I found an issue I am not sure on how to solve. I am trying to produce something similar to what's in the below screen:

What I am having trouble with is how to represent the tiles. With a flat 2d isometric grid all you need is an 2d array (even if you have elevation you can just have a z variable in there to track it and then render based on the z variable plus the z variable of nearby tiles). I am not sure how to proceed with this, however.

My plan was to have the map composed of 4-sided polygons that can be placed anywhere, and have a (x, y, z) position. Rendering is easy enough (start with lowest z tiles, go up to the next level, add any stairs that end on that level, keep repeating until all tiles are rendered).

However, how can I do collision checking? Checking if a point (a player) is inside the polygon is not too difficult, but how can I know whether he can move to another tile?

What would be best:

* Have tiles holding a pointer to neighbouring tiles? (Seems like a lot of trouble to code for the editor).
* Sort the array by Z-level, then search through the array for tiles that are close enough? (Seems slow)
* Something else entirely?

# Answer
> 3 votes
One approach to a multilayered map would be an array (or 2-dimensional array) of linked lists or vectors holding tile objects. So your tile struct would either hold a pointer to the next tile above it, or you would have "stacks" of tiles of varying heights spread across the grid. Essentially that creates a 3D array.

A nice, albeit old article on multilayered maps would be here: http://www-cs-students.stanford.edu/~amitp/Articles/Tiletech.html

So for example, your tile struct would look like something along these lines:

```
struct Tile
    {
    unsigned char type;
    Tile * next = NULL;
    };

```

The map it self, if for example it was a 2D grid, would look like this:

```
Tile tile_map[rows][cols];

```

To then get a tile at a certain point to check whether it collides or not, you would iterate through the list at that point until you reached the desired z position.

```
unsigned char getTileType(int x, int y, int z)
    {
    //Assuming 0 means an empty (air) tile
    unsigned char tile_type = 0;

    Tile * tile = &tile_map[x][y];

    //Iterate through the linked list of tiles  at this position
    int height = 0;
    while (height < z && tile)
        {
        tile = tile -> next;
        ++height;
        }

    if (tile)
        tile_type = tile -> type;

    return tile_type;
    }

```

---
Tags: collision-detection, architecture, software-engineering, tiles, isometric
---


# Question
Title: Creating laser redirection (eg. Portal 2 Cubes)?
Okay, so I asked this question about 2 years ago, and revisiting my project, I'm amazed I still can't think of a solution. I seemingly can write basic adventure game engines from scratch, but Unity's component-based programming stumps me.

So basically I have two cubes, SourceCube and RedirectCube. SourceCube is just a cube that fires a laser (for now a raycast).

A redirect cube is a cube that, when hit by a sourcecube laser, will fire its own laser.

My question is, how can I detect when one redirect cube's laser hits another redirect cube, causing the second redirect cube to fire its own laser (basically like the cubes in Portal 2)?

Below in the image, the blue-faced cube is my source cube. The pink ones are the redirect cubes.

Here's the code for the sourceCube (Unity, C#):

```
using UnityEngine;
using System.Collections;

public class OriginLaser : MonoBehaviour
{
    public RaycastHit sourceOut;

    void Update()
    {
        SourceShoot();
    }

    void SourceShoot()
    {
        if(Physics.Raycast(transform.position, -transform.forward, out sourceOut, Mathf.Infinity))
        {
            Debug.DrawRay(transform.position, -transform.forward * 20000, Color.red);

        }
    }
}

```

Pretty self-explanatory. Just draw a raycast.

Here's the code for the redirect Cube:

```
using UnityEngine;
using System.Collections;

public class RedirecCubetLaser : MonoBehaviour
{

    public RaycastHit redirectHit;
    public OriginLaser originRef;

    void Start()
    {
        originRef = GameObject.FindGameObjectWithTag("Source").GetComponent<OriginLaser>();

    }

    void Update()
    {
        Redirect();
    }

    void Redirect()
    {
        if (originRef.sourceOut.collider.name == this.gameObject.name)
        {
            if(Physics.Raycast(transform.position, -transform.forward, out redirectHit, Mathf.Infinity))
            {
                Debug.DrawRay(transform.position, -transform.forward * 20000, Color.green);

            }
        }
    }
}

```

And this works for detecting sourceCube rays. My question is, how can I get it to detect rays from another instance of the same object (these cubes will eventually become prefabs)?

Say we have two identical objects, RedirectCube1 and RedirectCube2. If sourceCube's ray activates RedirectCube1, how does RedirectCube1 activate RedirectCube2?

# Answer
Alright, thanks for the answers, but I found a decent solution. Honestly, I'm amazed I didn't think of this before. It seems ridiculously obvious. Anyway, the OriginLaser code remains untouched, here's the Redirect code:

```
using UnityEngine;
using System.Collections;

public class Redirect : MonoBehaviour
{
    public bool isActive;
    public OriginLaser sourceCube;
    public RaycastHit redirectHit;

    void Start()
    {
        isActive = false;
        sourceCube =  GameObject.FindGameObjectWithTag("Source").GetComponent<OriginLaser>();
    }

    void Update()
    {
        if (sourceCube.sourceOut.collider.gameObject == this.gameObject || isActive == true)
        {
            if(Physics.Raycast(transform.position, -transform.forward, out redirectHit, Mathf.Infinity))
            {
                Debug.DrawRay(transform.position, -transform.forward * 20000, Color.green);
            }

            if (redirectHit.collider.tag == "Redirect")
            {
                redirectHit.collider.gameObject.GetComponent<Redirect>().isActive = true;
            }
        }

    }
}

```

This line is key:

```
if (redirectHit.collider.tag == "Redirect")

```

Simply, if *this* specific redirect cube (that is already activated) detects another redirect cube, activate it. For any redirect cube, if activated, create a laser.

I tried something like this before, but did it the opposite, like with detecting the source cube (that is, the redirect cube object looks for source cube rays. Here the redirect cube object activates another redirect cube, rather than the second redirect cube looking for the first redirect cube's ray). Makes sense?

edit: this presents a minor bug with not being able to turn off the cubes when not being detected. ill post a fix later

edit2: here's the fixed version. definitely not a good solution, I repeat code and stuff, but whatever.

```
using UnityEngine;
using System.Collections;

public class Redirect : MonoBehaviour
{
    public bool isActive;
    public bool isFirst;
    public OriginLaser sourceCube;
    public Redirect otherCube;
    public RaycastHit redirectHit;

    void Start()
    {

        isActive = false;
        sourceCube =  GameObject.FindGameObjectWithTag("Source").GetComponent<OriginLaser>();
        otherCube = null;

    }

    void Update()
    {

        isFirst = (sourceCube.sourceOut.collider.gameObject == this.gameObject);

        if (isFirst || isActive)
        {
            if(Physics.Raycast(transform.position, -transform.forward, out redirectHit, Mathf.Infinity))
            {
                Debug.DrawRay(transform.position, -transform.forward * 20000, Color.green);
            }

            if ((redirectHit.collider.tag == "Redirect") && (!redirectHit.collider.gameObject.GetComponent<Redirect>().isActive && !redirectHit.collider.gameObject.GetComponent<Redirect>().isFirst))
            {

                if (otherCube != null && redirectHit.collider.gameObject != otherCube.gameObject && otherCube.isActive == true)
                {
                    otherCube.isActive = false;

                    if (otherCube.otherCube != null)
                    {
                        otherCube.otherCube.isActive = false;
                    }
                    otherCube = null;

                }

                otherCube = redirectHit.collider.gameObject.GetComponent<Redirect>();

                otherCube.isActive = true;

                }

            }

        }

        if (otherCube != null && ((redirectHit.collider.gameObject != otherCube.gameObject && otherCube.isActive) || (!isFirst && !isActive)))
        {

            otherCube.isActive = false;

            if (otherCube.otherCube != null)
            {
                    otherCube.otherCube.isActive = false;
            }

            otherCube = null;

        }

    }
}

```

edit3: awful solution above. last edit. Here's a better one. (3 scripts)

```
using UnityEngine;
using System.Collections;

public class CubeProperties : MonoBehaviour
{
    public bool isActive;
    public string cubeColor;
    public CubeProperties otherCube;

    public void Start()
    {
        isActive = false;
        cubeColor = "red";
        otherCube = null;
    }

}

```

-

```
using UnityEngine;
using System.Collections;

public class OriginLaser : CubeProperties
{
    public RaycastHit sourceOut;

    public LineRenderer line;

    void Start()
    {
        base.Start();

        line = GetComponent<LineRenderer>();
    }

    void Update()
    {
        SourceShoot();
    }

    void SourceShoot()
    {
        if(Physics.Raycast(transform.position, -transform.forward, out sourceOut, Mathf.Infinity))
        {
            line.SetVertexCount(2);
            line.SetPosition(0, transform.position);
            line.SetPosition(1, sourceOut.point);
        }

        if (otherCube != null && otherCube.isActive && sourceOut.collider.gameObject != otherCube.gameObject)
        {
            otherCube.isActive = false;
            otherCube = null;
        }

        if (sourceOut.collider.tag.Contains("Gamelogic") && !sourceOut.collider.gameObject.GetComponent<CubeProperties>().isActive)
        {
            otherCube = sourceOut.collider.gameObject.GetComponent<CubeProperties>();
            otherCube.isActive = true;
        }

    }
}

```

-

```
using UnityEngine;
using System.Collections;

public class Redirect : CubeProperties
{
    public RaycastHit redirectHit;
    public LineRenderer line;

    void Start()
    {
        base.Start();
        line = GetComponent<LineRenderer>();
    }

    void Update()
    {
        RedirectLaser();
    }

    void RedirectLaser()
    {

        if (otherCube != null && otherCube.isActive)
        {
            if ((redirectHit.collider.gameObject != otherCube.gameObject) || !isActive)
            {
                otherCube.isActive = false;
                otherCube = null;
            }
        }

        if (otherCube != null && otherCube.otherCube != null && otherCube.otherCube.gameObject == this.gameObject && otherCube.otherCube.isActive && isActive)
        {
            otherCube.isActive = false;
            otherCube.otherCube.isActive = false;
            otherCube = null;
        }

        if (isActive)
        {
            if(Physics.Raycast(transform.position, -transform.forward, out redirectHit, Mathf.Infinity))
            {
                line.SetVertexCount(2);
                line.SetPosition(0, transform.position);
                line.SetPosition(1, redirectHit.point);
            }

            if ((redirectHit.collider.tag.Contains("Gamelogic")) &&
                (!redirectHit.collider.gameObject.GetComponent<CubeProperties>().isActive) &&
                (cubeColor == redirectHit.collider.gameObject.GetComponent<CubeProperties>().cubeColor))
            {

                if (otherCube != null && otherCube.isActive && redirectHit.collider.gameObject != otherCube.gameObject)
                {
                    otherCube.isActive = false;
                }

                otherCube = redirectHit.collider.gameObject.GetComponent<CubeProperties>();
                otherCube.isActive = true;
            }
        }

        if (!isActive)
        {
            line.SetVertexCount(0);
        }

    }
}

```

The only reason I have a CubeProperties class is because I'm going to implement more cubes later, that shares some properties with Redirect. That is why I put Contains("Gamelogic"), so any redirect cube can detect any 'logic' cube, and vice-versa. I repeat code, but that can easily be changed by putting it into CubeProperties. I didn't do it yet because I want to create more cubes first. Oh, and ignore the "cubeColor" stuff. For the purpose of my game I'll have different colored cubes that can only activate other cubes.
> 0 votes

# Answer
I would make the laser a separate entity in this situation. Instead of the cube update redirecting the laser, the laser entity does all the tracking in one go:

Pseudocode:

```
Vector3 current_direction;
Vector3 current_location;
while (true) {
    RaycastHit hit;
    if (RaycastAgainstCubes(current_location, current_direction, out hit)) {
        // mark hit, update direction and location
    }
    else {
        // didn't hit another cube, done
        break;
    }
}

```

This isn't completely robust -- you may want to mark hit cubes and break if you hit the same cube again (to prevent an infinite loop), but the general concept should work.
> 2 votes

# Answer
It may be simpler to make the redirect cube a combined toggle-able laser source and laser detector. Where the source is active if the detector is hit.

That way the `SourceShoot` just sets the `detector.hit = true` and the redirect cube's shoot is only called `if(this.detector.hit)`
> 2 votes

---
Tags: unity
---


title: How my bullet can take HP from enemy?

text:
# Question
Title: How my bullet can take HP from enemy?
```
using UnityEngine;
using System.Collections;

public class GunScript : MonoBehaviour
{
    public Transform barrel;
    public float range = 0f;
    public Rigidbody myBullet;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Rigidbody bulletInstance; // reference
            //make the bullet apear out of the barrel
            bulletInstance = Instantiate(myBullet, barrel.position, barrel.rotation) as Rigidbody;
            bulletInstance.AddForce(barrel.forward * range); //give the bullet some force to move forward
        }
    }
    IEnumerator Fire()
    {
        RaycastHit hit;
        Ray ray = new Ray(barrel.position, transform.forward);
        // in don't know how write this iff
        if (Physics.Raycast(ray, out hit, range))
        {
            Enemy enemy = hit.collider.GetComponent<Enemy>();
            enemy.health -= 1;
        }
        //Debug.DrawRay(barrel.position, transform.forward * range);
        yield return null;
    }
}

```

I made an enemy class, my bullet is a prefab, but i don't understand what i need to do to lower HP points when the bullet hits.

# Answer
It looks like you have 2 halves to 2 different solutions for this, so I'll explain both possible solutions and let you choose the one that best suites your needs

**Solution 1**
*Initiate a bullet instance and remove the health from enemies the bullet hits*

In your GunScript fire a bullet when the mouse button is down (this is half the code you already have)

```
public class GunScript : MonoBehaviour {
   public Transform barrel;
   public float range = 0f;
   public GameObject myBullet;

   void Update()
   {
       if (Input.GetMouseButtonDown(0))
       {
           Rigidbody bulletInstance; // reference
           //make the bullet apear out of the barrel
           bulletInstance = Instantiate(myBullet, barrel.position, barrel.rotation) as GameObject;
           //give the bullet some force to move forward
           bulletInstance.GetComponent<RigidBody>().AddForce(barrel.forward * range);
       }
   }
}

```

Then, on your bullet pref you would detect collisions and remove health from your enemy class:

```
public class BulletScript : MonoBehaviour {
   void OnCollisionEnter(Collision collision) {
   {
       Enemy enemy = collision.gameObject.GetComponent<Enemy>();

       // If we hit an enemy, then reduce it's health
       if (enemy != null)
       {
           enemy.health -= 1;
       }

       // Remove the bullet from the scene, we don't need it any more
       Destroy(gameObject);
   }
}

```

Note that this approach is innefficient, as you're creating a new bullet for each shot fired. This may not be a problem for your game, but if, for example, your gun was a machine gun you'll find that your games performance will suffer as a result. If you need to show bullets, then I'd recomend an object pool

**Solution 2**
*Cast a ray for each bullet fired and remove enemy health if the ray hits*

In your GunScript, calculate a ray hit when the mouse button is down (this is the other half of the code you already have). No need for the Enumerable, or the Bullet prefab here. All the code is in the GunScript

```
public class GunScript : MonoBehaviour {
   public Transform barrel;
   public float range = 0f;

   void Update()
   {
       if (Input.GetMouseButtonDown(0))
       {
           RaycastHit hit;
           if (Physics.Raycast(barrel.position, transform.forward, out hit, range))
           {
               Enemy enemy = hit.collider.GetComponent<Enemy>();
               // Only take health if an enemy was hit
               if (enemy != null) {
                   enemy.health -= 1;
               }
           }
       }
   }
}

```

Note that with this approach you don't get a bullet flying across the screen, but that might be fine for your purposes, as you can mask this by just showing a muzzle flash and playing a gun sound. However, because the Raycast is efficient, and you're not instantiating and destroying multiple game objects, this approach is more suitable for firing multiple bullets in quick succession
> 4 votes

---
Tags: unity
---


# Question
Title: What is the difference of target frameworks for unity3d?
In `Visual Studio` in `properties` I can change `target framefork`.

I cannot find anywhere what means all of these magic titles.

What does it all mean (full, micro base, subset, web base)?

And...Can I use functionality of `.NET 4.6.1` ?

# Answer
Following Unity documentation at the moment this is the following supported .NET lib and their versions.

http://docs.unity3d.com/410/Documentation/ScriptReference/MonoCompatibility.html

it has been mentioned several times that once Unity5 gets stable they will start adding more compatibility with newer versions.
> 2 votes

---
Tags: unity, visual-studio
---


# Question
Title: Where can I find real-world map data for a game?
I want to build a game with a concept similar to Ingress, where the game map is overlaid on a real one.

Where can I find map data for an app like that? How (generally) do I integrate my own game objects into that map? Game objects need to move in real time, so having them as static markers on the map isn't sufficient.

I thought I could use Google Maps but as far as I can tell it would be impossible to create my own graphical style (like Ingress has done) with the official API provided by Google.

# Answer
You could use OpenStreetMap data.

It is liberally licensed. In particular, their wiki says:

> **3c. If I make something with OSM data, do I now have to apply your license to my whole work?**
>
> No. For example, if you have written a game or published an artistic map which includes OSM data, only the data is covered by the license. This is called a **Produced Work**.

The developer wiki explains how to import OSM data into a database for your own use.
> 13 votes

# Answer
I recommend Natural Earth Data as a source of public domain cultural and physical GIS data with global coverage. Vector data sets include landmasses, countries, populated places etc, while raster base layers are available with optional details like land elevation, climate, waterways and submarine elevation.

This data is intended for use with GIS software, but can be manipulated and then exported as something more "game friendly" (svg, png etc.) using tools like QGIS or indiemapper with no financial outlay.

The vector layers come with detailed attribute tables that might also be useful for simulations such as names, populations and GDP.

Here are a couple of quick mock-up produced with this data:
> 9 votes

# Answer
In some cases, you can use Google Static Maps API. This would let you to download sprites for specific locations one by one, and just use them as regular sprites/background in your game. However, you will need to deal with

* usage quota (depends on the API and use case, but probably 25000 requests per day for free)
* your game will be bound by Google Maps API T&C
* your users will be bound by Google T&C, and you will need to acquire their consent
* you will need to include a link to the Google Maps, I think.
* according to `10.5 (b)`, you cannot make derivative works from their images, but it's possible that overlaying their image with some filter (if you need to change hue/saturation), could still pass, as long as it doesn't obscure Google's copyright notice and logo. IANAL, though.
> 0 votes

---
Tags: maps, realtime
---


# Question
Title: Drawing on an image before drawing on screen in XNA using VB.NET
I'm programming a game in XNA, using VB.NET. I want to create an intro to the game that zooms in/out the whole screen and scaling each image to accomplish this is cumbersome at best. I like to be able to draw a lot of .PNG's (or parts of them) onto a whole image, to then be able to manipulate (scale, turn etc) that whole image, before drawing it with the spriteBatch. The examples I can find use something like:

```
dim bitmap as New Bitmap

```

or

```
dim image as New Image

```

but these codes highlights the "Bitmap" or "Image" as red, and I cannot use them. I'd be thankful for any help on this issue!

please note: I'm new to this, and self taught, so I prefer concrete examples if possible.

# Answer
So I've experimented with Petri Laarne's answer from StackOverflow and finally come up with a workable code (most examples online are using C#, and doesn't explain the entire process). Trying to explain it here:

In Public Class Game1:

```
Private WithEvents graphics As GraphicsDeviceManager
Private WithEvents spriteBatch, spriteBatch2 As SpriteBatch

```

In Loadcontent:

```
Public render2 As RenderTarget2D
spriteBatch2 = New SpriteBatch(GraphicsDevice)
spriteBatch = New SpriteBatch(GraphicsDevice)
render2 = New RenderTarget2D(GraphicsDevice, 1024, 768)

```

In Draw:

```
spriteBatch2.GraphicsDevice.SetRenderTarget(render2)
        GraphicsDevice.Clear(Color.Black)
        srcRect = New Rectangle(440, 0, 440, 440) : destRect = New Rectangle(100, 335, 440, 440)
        spriteBatch2.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend) : spriteBatch2.Draw(introNEWMirrorDecos, destRect, srcRect, Color.White) : spriteBatch2.End()
        destRect = New Rectangle(300, 335, 440, 440)
        spriteBatch2.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend) : spriteBatch2.Draw(introNEWMirrorDecos, destRect, srcRect, Color.White) : spriteBatch2.End()
        spriteBatch2.GraphicsDevice.SetRenderTarget(Nothing)
        GraphicsDevice.Clear(Color.Black)
        destRect = New Rectangle(512, 384, 1024, 768) : srcRect = New Rectangle(0, 0, 1024, 768)
        spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend) : spriteBatch.Draw(render2, destRect, srcRect, Color.White, PI / 12, New Vector2(512, 384), SpriteEffects.None, 0) : spriteBatch.End()

```

This is an example code from the actual game that worked like it was intended: drawing 2 things on the alternate rendering image and then drawing them as one single image (in this case being able to rotate it by pi/12).

Any comments on how to do this differently or more efficient is appreciated
> 0 votes

---
Tags: xna, image, vb.net
---


# Question
Title: How do I make a game over screen like Temple Run or Subway Surfer?
When you die in one of these 2 games I took screenshots of (Temple Run and Subway Surfers), what exactly comes up to say "Game Over" and posts your score and all-time high score?

Is it a different scene that is loaded after you die and says "Game Over" and has all of your stats?

Is it some sort of UI element that is enabled and becomes visible after the player dies and then it says "Game Over" and shows your stats (Just like the Game Over lesson on the Unity Survival Shooter tutorial)?

Or is something else entirely that I have no idea of? I'd like to implement a similar feature.

# Answer
If I would implement it in Unity I'd do a dedicated scene with a GUI to show whatever is needed.

So in the main scene I would have some script not destroyed on load of a new scene (with `DontDestryOnLoad(GameObject go)` method) which have all the infos you want to display at the Game Over stage.

You could also handle it in a whole scene with variables to control the game state and when it becomes GameOver then the GUI displays it properly.
> 2 votes

# Answer
While I don't know for sure what these two games do, this is how I would do it:

1. Have a Canvas set up with a child GameObject (which can be a prefab) holding all Game Over UI elements. This starts as disabled
2. In the UI GameObject have a script which listens to OnEnable and fills out the relevant info (stats etc)
3. Have a Game Controller that controls the state of your game (Paused, Running, Game Over etc) and holds a public reference to the Game Over UI Object
4. When the game is over enable the UI object

This is a little cheaper than loading a new scene (as you don't have the overhead of waiting for an additive scene load), but both are valid approaches. You can also use the same approach as above to control pause menus.

I addition, you may also be interested in Modal Windows, for when you need to ask a player a question (for example, 'Do you really want to start again?')
> 2 votes

---
Tags: unity, c#, architecture, game-mechanics, performance
---


# Question
Title: Imported Blender .fbx model appears transparent
I exported a model that i made in blender to a .fbx file. I imported it to Unity and, as you can see in the image, one arm of my character appears transparent.

I already have the normals pointing in the right direction, so i can't see what's causing this. I even tried to create a new arm from the other one, but the problem persisted.

What is causing this?

# Answer
Hard to know without more details like shader parameters. Could be a problem with alpha channel of either the texture or vertex color's alpha.
> 1 votes

---
Tags: unity, fbx, importing, 3d-modeling
---


# Question
Title: How can I resize SDL2 windows efficiently?
I guess resizable windows are not being optimized for in game development but still... The following piece of code demonstrates a problem I'm having: resizing the window is very slow. Basically the window trails after my mouse as I'm moving it:

```
#include <SDL2/SDL.h>
#include <iostream>

int main() {
    SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS);

    SDL_Window* window = SDL_CreateWindow("test", 10, 10, 800, 600, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);

    int count = 0;
    bool repaint = false;
    auto paint = [&](){
        if(!repaint) {
            return;
        }
        repaint = false;
        std::cout<<"Repaint "<<count++<<std::endl;
        SDL_Surface* surf = SDL_GetWindowSurface(window);
        int w, h;
        SDL_GetWindowSize(window, &w, &h);
        SDL_Rect rect = {0, 0, w, h};
        SDL_FillRect(surf, &rect, 0xff0000ff);
        SDL_UpdateWindowSurface(window);
    };
    SDL_Event event;
    bool run = true;
    while(run && SDL_WaitEvent(&event)){
        switch(event.type) {
        case  SDL_QUIT:
            run = false;
            break;
        case SDL_WINDOWEVENT:
            if(event.window.event == SDL_WINDOWEVENT_RESIZED) {
                repaint = true;
            }
            break;
        };
        paint();
    }
    SDL_Quit();
}

```

...is there some way for me to interfere with SDL's handling of window events that I am missing?

Platform is Linux (X11), have yet to test on windows.

# Answer
First, on Linux it appears to matter what Window Manager and Compositor you are using. WindowMaker with opaque windows enabled (not the default) was still fast, the wire windows are always fast because nothing has to repaint.

Second, there are a few things in your program that can be changed. The biggest issue is that you paint after every SDL\_WINDOWEVENT event. Some Window Managers are very spammy with these events, taking no long-running action until the spam has died down will resolve this issue.

Third, I modified your program (see below). I also changed it to paint for the first frame. Your Window Manager may be sending you SDL\_WINDOWEVENTs when the window is first created, but many Window Managers do not. (WindowMaker does not). I use SDL\_WaitEventTimeout() to help with corruption when another window covers, another way is to handle SDL\_VIDEOEXPOSE events and repaint on those too. If you wish you can go back to SDL\_WaitEvent() and handle the expose events.

```
#include <SDL2/SDL.h>
#include <iostream>

int main() {
    SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS);

    SDL_Window* window = SDL_CreateWindow("test", 10, 10, 800, 600, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);

    int count = 0;
    bool repaint = true; /* the screen has never been painted, we must paint */
    auto paint = [&](){
    if(!repaint) {
        return;
    }
    repaint = false;
    std::cout<<"Repaint "<<count++<<std::endl;
    SDL_Surface* surf = SDL_GetWindowSurface(window);
    int w, h;
    SDL_GetWindowSize(window, &w, &h);
    SDL_Rect rect = {0, 0, w, h};
    SDL_FillRect(surf, &rect, 0xff0000ff);
    SDL_UpdateWindowSurface(window);
    };
    paint(); /* paint once before events */
    SDL_Event event;
    bool run = true;
    const unsigned frame_wait = 10; /* anything less than 16 ms is good */
    while(run) {
    unsigned tries = 500; /* use UINT_MAX for no effective limit */
    if (SDL_WaitEventTimeout(&event, frame_wait)) {
        /* keep consuming events in a loop until there are no more,
         * or we run out of attempts. */
        do {
        switch(event.type) {
        case  SDL_QUIT:
            run = false;
            break;
        case SDL_WINDOWEVENT:
            if(event.window.event == SDL_WINDOWEVENT_RESIZED) {
            repaint = true;
            }
            break;
        };
        /* TODO: check time stamps to see if we've spent too much real
         * time processing events. Doing that would be more robust than
         * counting tries. */
        } while (tries-- && SDL_PollEvent(&event));
    }
    /* paint once we're done processing potentially spammy events */
    /* TODO: we could skip painting if we know the scene has not changed.
     * This would not likely happen in a game, due to animation.
     * In a utility that only reacts to user events, we'd want to change
     * this loop to use SDL_WaitEvent() instead.
     */
    paint();
    }
    SDL_Quit();
}

```

Unfortunately using a compositing window manager on Linux hides a lot of the funny behavior of X11. Trying with something like twm or fvwm as well as your favorite modern WM can narrow down issues like these.
> 3 votes

---
Tags: sdl2, linux
---


title: Unity 5 - custom lighting model

text:
# Question
Title: Unity 5 - custom lighting model
I have tried to use my own lighting model in surface shader in Unity. But there is a problem.

If I init my own lighting via

```
#pragma surface surf _SimpleSpecular

```

`Lighting_SimpleSpecular` method is executed. But, even if I return single color from it, my model has still applied texture (with the tint of my returned color). What I am doing wrong? I am using forward rendering.

If I switch to Standard and return single color, all is at it should be.

# Answer
How is your `surf` defined? In addition to lighting shader, you must modify it for material properties. Here's a modified example that uses red color instead of texture from http://docs.unity3d.com/Manual/SL-SurfaceShaderLightingExamples.html

```
Shader "Custom/CustomLight" {
        Properties {
            _MainTex ("Texture", 2D) = "white" {}
        }
        SubShader {
        Tags { "RenderType" = "Opaque" }
        CGPROGRAM
          #pragma surface surf SimpleLambert

          half4 LightingSimpleLambert (SurfaceOutput s, half3 lightDir, half atten) {
              half NdotL = dot (s.Normal, lightDir);
              half4 c;
              c.rgb = s.Albedo * _LightColor0.rgb * (NdotL * atten);
              c.a = s.Alpha;
              return c;
          }

        struct Input {
            float2 uv_MainTex;
        };

        sampler2D _MainTex;

        void surf (Input IN, inout SurfaceOutput o) {
            o.Albedo = float3(1,0,0);
        }
        ENDCG
        }
        Fallback "Diffuse"
    }

```
> 1 votes

---
Tags: shaders, unity
---


# Question
Title: Scene Graph: Does anybody have a real world example?
I'm trying to wrap my head around how scene graphs work, and how to apply that to my game, in the context of all my game objects, including assets, cameras, units, shaders, etc.

All I can find are massively simplified examples that include planets and rotations. What I'd like is a real world example of a well written scene graph, preferably in C++ and if possible with some form of graphical representation of at least a part of the graph.

Additional information: I am writing a real time strategy game using C++ and DirectX 11. Any other pointers for advice would be massively helpful. Wrapping my head around a scene graph and how that would relate to design patterns like data locality etc, and how to encapsulate it all in a standardised system is proving very difficult for me. I am extremely, extremely confused.

# Answer
> -1 votes
With a scene graph you can have child objects that move when parent moves. You can also make some states propagate to children, like hiding/showing groups of objects just by changing the state of the root of the hierarchy. Implementation could be done by game objects having a transform component that has a pointer to its parent.

---
Tags: c++, directx, directx11, rts, scene-graph
---


# Question
Title: With Unity and Mecanim, how do I trigger an effect animation?
We have a Mecanim animation. We'd like to play a particle effect on it at a certain frame in the animation.

Do we need to use an AnimationEvent and have it call a function that triggers the effect? Or is there some editor-only way to do it without script?

We're using Unity 5.3.5.

# Answer
Alternatively to SP's suggestion, you can also add events to the Mecanim animator now. Take a look here:

Then you can script it in, if you prefer this method. I have personally not used this feature yet, I just noticed it. There doesn't seem to be much information in the docs about it yet.
> 3 votes

# Answer
You can put the particle object as child to the main object and animate enable/disable the child in the animation tab. It's editor only.
> 3 votes

---
Tags: unity
---


# Question
Title: Setting up a custom cursor image in LWJGL 3
How can I load a **custom cursor image** with **LWJGL3**? It took me a while to figure this out. Here is how it is done for version 3.0.1. Hope this helps.

# Answer
```
    InputStream stream = new FileInputStream("C:\\path\\to\\image.png");
    BufferedImage image = ImageIO.read(stream);

    int width = image.getWidth();
    int height = image.getHeight();

    int[] pixels = new int[width * height];
    image.getRGB(0, 0, width, height, pixels, 0, width);

    // convert image to RGBA format
    ByteBuffer buffer = BufferUtils.createByteBuffer(width * height * 4);

    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            int pixel = pixels[y * width + x];

            buffer.put((byte) ((pixel >> 16) & 0xFF));  // red
            buffer.put((byte) ((pixel >> 8) & 0xFF));   // green
            buffer.put((byte) (pixel & 0xFF));          // blue
            buffer.put((byte) ((pixel >> 24) & 0xFF));  // alpha
        }
    }
    buffer.flip(); // this will flip the cursor image vertically

    // create a GLFWImage
    GLFWImage cursorImg= GLFWImage.create();
    cursorImg.width(width);     // set up image width
    cursorImg.height(height);   // set up image height
    cursorImg.pixels(buffer);   // pass image data

    // the hotspot indicates the displacement of the sprite to the
    // position where mouse clicks are registered (see image below)
    int hotspotX = 3;
    int hotspotY = 6;

    // create custom cursor and store its ID
    long cursorID = GLFW.glfwCreateCursor(cursorImg, hotspotX , hotspotY);

    // set current cursor
    glfwSetCursor(window, cursorID);

```
> 4 votes

---
Tags: mouse, lwjgl3
---


# Question
Title: Java Distance between two Vector positions never 0
I have a Player moving, but when the player reaching the destination it should stop. But problem is that distance never return 0.

It starts printing this: 0.9672514210000003

End by this and then start to raise back again: 0.0015875672000023044

```
// My position is 5.0 and toPosition is either +1 or -1
if (getDistance(getPosition(), toPosition) <= 0) {
    allowMovement = false;
}

public double getDistance (PositionVector pos1, PositionVector pos2) {
    double dx = pos1.x - pos2.x;
    double dy = pos1.y - pos2.y;
    return Math.sqrt(dx * dx + dy * dy);
}

```

Cheers.

# Answer
> 3 votes
Mathematically speaking, a distance is a value which is never lower than 0. You can see this thing in your `getDistance()` function implementation: the argument passed to the square root function is a sum between powers of 2. A power of 2 is always positive, their sum is positive as well, and the `sqrt()` function will always give back a positive value. So, no real reason to have your condition checking for a value smaller than 0.

The reason your distance check isn't going to evaluate to 0 is your player object's origin isn't aligned with the final position along any axis, so there will be only a minimum distance between they two:

You can fix this in two different ways, depending on your game:

**Higher minimum distance**
This approach is very simple, as you have a special area defined by a volume or just a distance radius, and events are performed when the player lies inside the area. To implement this tecnique, you can simply change the distance value in your code with a value higher than 0:

```
// Check if player is at hot position
int safeDistance = 30;  // Choose your desired value
if (getDistance(getPosition(), toPosition) <= safeDistance) {
    allowMovement = false;
}

```

**Axis distance**
Easier approach, instead of checking a distance to a point, you focus on one coordinate only. Works best with side-scrolling platformers, where you can move over a given horizontal coordinate from one way only, for example. Such x-axis coordinate may be the very end of the current level, like in Super Mario Bros. or similar.

In my opinion, the first one is the best one. This way you can force the player to get to a particular position in your level to progress during the game.

---
Tags: java, mathematics, vector
---


# Question
Title: Is drawing an entire game to a render target and then scaling it up a viable solution to a pixel-mismatching problem?
To clear up some possible confusion caused by my title, my game is meant to be pixelly. I currently achieve this by multiplying sprite sizes and locations by a constant called `World.Scale` (currently 8). This means every pixel is now 8x8 on screen, which is what I want.

However, I want an easier way to do game calculations without having to figure out where to fit `World.Scale` whenever I'm drawing or calculating something. Also, I'm currently having trouble with pixel-mismatching (see image).

To solve this, I thought about rendering everything in the game onto a render target, and then scale that render target up by `World.Scale` and draw it to the screen but I'm not sure how render targets work so I'm not sure about any possible performance implications of this.

Is it a good idea? Is there a better alternative?

# Answer
> 2 votes
Note that you can supply the `SpriteBatch.Begin` with a matrix parameter. Use your ingame "virtual screen" dimensions to calculate the scale factor. This way you can draw your game in the native "virtual" resolution and have the matrix do the heavy lifting for you.

For example:

```
float xscale = (float)ScreenWidth / VirtualscreenWidth;
float yscale = (float)ScreenHeight / VirtualscreenHeight;
Matrix transformmatrix = Matrix.CreateScale(xscale, yscale,1.0f);

spriteBatch.Begin(,,,transformmatrix); //supply parameters as usual but add the matrix.

```

You can make this better by calculating the matrix while respecting the aspect ratio (use pillarbox or letterbox).

I believe monogame.extended has an implementation using this method (and other useful stuff!)

---
Tags: c#, monogame, pixel, rendertargets
---


# Question
Title: Is there a way to determine Android physical screen size?
We're currently porting our games to Android, and would like to be able to release a universal build for tablets and phones. Is there a way to determine the actual screen size or DPI in order to adjust the size of interface elements accordingly? It took a fair bit of research.

Here's what we have tried:

```
using UnityEngine;

public class DisplayMetricsAndroid {

 // The logical density of the display
 public static float Density { get; protected set; }

 // The screen density expressed as dots-per-inch
 public static int DensityDPI { get; protected set; }

 // The absolute height of the display in pixels
 public static int HeightPixels { get; protected set; }

 // The absolute width of the display in pixels
 public static int WidthPixels { get; protected set; }

 // A scaling factor for fonts displayed on the display
 public static float ScaledDensity { get; protected set; }

 // The exact physical pixels per inch of the screen in the X dimension
 public static float XDPI { get; protected set; }

 // The exact physical pixels per inch of the screen in the Y dimension
 public static float YDPI { get; protected set; }

 static DisplayMetricsAndroid() {
     // Early out if we're not on an Android device
     if (Application.platform != RuntimePlatform.Android) {
         return;
     }

     // The following is equivalent to this Java code:
     //
     // metricsInstance = new DisplayMetrics();
     // UnityPlayer.currentActivity.getWindowManager().getDefaultDisplay().getMetrics(metricsInstance);
     //
     // ... which is pretty much equivalent to the code on this page:
     // http://developer.android.com/reference/android/util/DisplayMetrics.html

     using (
         AndroidJavaClass unityPlayerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"),
         metricsClass = new AndroidJavaClass("android.util.DisplayMetrics")
     ) {
         using (
             AndroidJavaObject metricsInstance = new AndroidJavaObject("android.util.DisplayMetrics"),
             activityInstance = unityPlayerClass.GetStatic<AndroidJavaObject>("currentActivity"),
             windowManagerInstance = activityInstance.Call<AndroidJavaObject>("getWindowManager"),
             displayInstance = windowManagerInstance.Call<AndroidJavaObject>("getDefaultDisplay")
         ) {
             displayInstance.Call("getMetrics", metricsInstance);
             Density = metricsInstance.Get<float>("density");
             DensityDPI = metricsInstance.Get<int>("densityDpi");
             HeightPixels = metricsInstance.Get<int>("heightPixels");
             WidthPixels = metricsInstance.Get<int>("widthPixels");
             ScaledDensity = metricsInstance.Get<float>("scaledDensity");
             XDPI = metricsInstance.Get<float>("xdpi");
             YDPI = metricsInstance.Get<float>("ydpi");
         }
      }
   }
}

```

# Answer
> 1 votes
I'm giving you how I did this in java before I switched to Unity. Perhaps you can use it in c# with small modifications:

So lately I did it this way:

```
screenWidth = getResources().getDisplayMetrics().widthPixels;
screenHeight = getResources().getDisplayMetrics().heightPixels;

```

But I used to do it this way too (probably deprecated):

```
Display display = getWindowManager().getDefaultDisplay();
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB_MR2){
            android.graphics.Point screenSize = new android.graphics.Point();
            display.getSize(screenSize);
            screenWidth = screenSize.x;
            screenHeight = screenSize.y;
        }else{
            screenWidth = display.getWidth();
            screenHeight = display.getHeight();
        }

```

---
Tags: android, unity
---


# Question
Title: Keep gravity velocity the same all the time
I have 2D rigidbodies that fall to the ground, however they speed up while falling. Also, when they freeze in the air and then unfreeze, the velocity is set to 0 and they gradually start speeding up again. How can I keep the velocity constant at all times, until they hit the ground?

# Answer
Fixed by setting `Linear Drag` in `RigidBody 2D` at 1.1 (value depends on gravity, etc), which damped the fall speed and now the objects don't accelerate with time when falling.

Rotation can also be damped by setting `Angular Drag` to the appropriate value.
> 1 votes

# Answer
Disable gravity for the object as you'll no longer be wanting it to interfere. Have some reference to the object's Rigidbody, as well as some way to determine whether the object/character is jumping - in which case you will probably apply some upward velocity for a short time. If it's not jumping, you can manually set the velocity of the body, applying the constant downward factor you're looking for.

```
void FixedUpdate()
{
    if(!jumping)
    {
        Vector2 currentVelocity = rigidbody.velocity;
        rigidbody.velocity = new Vector2(currentVelocity.x, -9.81f);
    }
}

```
> 0 votes

# Answer
Make a script that will check for the magnitude of the rigidbodies like so:

`if(GetComponent<RigidBody>().velocity.magnitude > MAX_SPEED){
 GetComponent<RigidBody>().useGravity = false;
}`

This will make sure that your rigidbodies can't have a speed higher than your preset value.
> 0 votes

---
Tags: unity, physics, rigid-body-dynamics
---


# Question
Title: How to use prefab only when in inventory game object?
I created an empty game object named "inventory", whenever I click on an object it transfers into that game object :

and I got this far with the script:

```
//Transforms
public Transform Knife; //will use the knife prefab
public Transform IceBlock; //will use the iceblock prefab
public Transform Bomb;//will use the bomb prefab
public Transform Chain;//will use the chain prefab
public Transform inventory;//will use the inventory gameobject
private bool knife;
private bool ice;
private bool bomb;
private bool chain;
void fInventory()
{
    if (inventory != null)
    {
        foreach (Transform child in inventory.transform) // child is a gameobject inside of the inventory gameobject
        {
            if (child.name == Knife.name)
            {
                knife = true;
            }
            else if (child.name == IceBlock.name) { ice = true; }
            else if (child.name == Bomb.name) { bomb = true; }
            else if (child.name == Chain.name) { chain = true; }
        }
    }
}
void Update() {
    fInventory();
    if (knife)
        //use knife
    if (ice)
       //use ice
    //........etc
}
}

```

but as you can see, it's pretty hardcoded. So what I want this to do is whenever I pick up an gameobject with the name example:"knife", I will be able to use the Knife Transform, and while this script works it really looks ugly and inefficient. Is there any other way to check if two tranform names are the same without using an if-else statement? Hope the question was clear enough, and please just point me in a direction!

# Answer
You can make a class of type InventoryObject. You can then create a Knife class that inherits from InventoryObject. Your inventory script can then call

```
InventoryObject newObjectComponent = newObject.GetComponent<InventoryObject>();

```

when you add a new object. Then you can test:

```
if(newObjectComponent is Knife)
  knife = true
else if(newObjectComponent is IceBlock)
  ...

```

Also, your foreach doesn't look right. I think what you want is something more like this:

```
foreach (Transform child in inventory.GetComponentsInChildren<Transform>())

```
> 1 votes

# Answer
you can use Switch statement.in switch statement you can compare experision with your object name then if it was match Do something

```
using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {
    public GameObject Inventory;

    // Update is called once per frame
    void Update () {
        for(int i =0;i<Inventory.transform.childCount;i++){
            switch(Inventory.transform.GetChild(i).name){
            case "Knife":
                print ("I found Knife // You can do something");break;
            case "Bomb":
                print ("I found Bomb// You can do something");break;
            case "chain":
                print ("I found chain// You can do something");break;
            }
        }
    }
}

```

instead of define public Transform Knife you can load them as prefab in array to shorten your script you can use Array for load prefabs

```
using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {
    public GameObject Inventory;
    public Object[] prefabs;

```

public GameObject knife,chain,bomb;

```
    // Use this for initialization
    void Start () {
        prefabs = Resources.LoadAll("Prefabs", typeof(Object));
        for(int i =0;i<Inventory.transform.childCount;i++){
            switch(Inventory.transform.GetChild(i).name){
            case knife.name:
                print ("I found knife // You can do something");break;
            case chain.name:
                print ("I found Bomb // You can do something");break;
            case bomb.name:
                print ("I found chain // You can do something");break;
            }
        }
    }
}

```
> 0 votes

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


title: Limit access to socket end point

text:
# Question
Title: Limit access to socket end point
I'm developing a multiplayer canvas game based on socket.io and box2d physics engine. Is there a way to limit connections to my socket endpoint and only allow connections from a specific domain?

```
window.socket = io.connect('http://mysite:8080');

```

I don't want people to be able to use my end point which is currently possible. They could just use the above code and then "manipulate" the clients logic based on the `emits` from the servers response.

# Answer
> 0 votes
After a bit of a research regarding Socket.io I realised you can control the origin that is connecting to your game (The Client) using the origin option, you can read about it over here - Socket.IO server API.

if I understood you correctly you wish to control the connections and you want to accept connections only from a specific uri (correct me if i'm wrong please), now if you dig into Socket.IO code you will find the following

```
 var origin = request.headers.origin || request.headers.referer
  , origins = this.get('origins');

...

var parts = url.parse(origin);
parts.port = parts.port || 80;
var ok =
  ~origins.indexOf(parts.hostname + ':' + parts.port) ||
  ~origins.indexOf(parts.hostname + ':*') ||
  ~origins.indexOf('*:' + parts.port);

```

which is checking your server.js file and looking for the following line

```
io.set('origins', 'www.mydomain.com:3000');

```

this is where you want to define the allowed domains.

# Answer
> 1 votes
If you have access to the box you're connecting to, couldn't you add a firewall policy to only allow a specific domain? If you don't have access to the box directly, perhaps whatever hosting service you're using allows some form of firewall control for access to your endpoint? As far as I know, that's the only way to truly prevent connections.

There are other solutions you could probably draw up with a little creativity. Authentication and disconnection of users who the server discovers are cheating is one potential way of approaching this. Usually with games involving a server, you want to make sure the server controls the actual game logic so that there's no way a hacked client can cheat.

# Answer
> 1 votes
The server receives the `connect` event when the client connects to the socket.io server.

At this point, you can implement a simple verification to make sure that the person connected is supposed to be using your application.

To do so, the next event the client **must** send is a `sign in` event with some credentials (a token, for example). You can then validate the token, and only if the user has been validated should the other `socket.on` events be allowed to properly run.

If the user doesn't verify himself, you will immediately disconnect the socket. (If you want to get fancy, grab the IP address and blacklist the user.)

I'm not sure why the restriction has to necessarily be tied to the domain--can't that be faked? If you're really focused on security, make the client provide data that only your server can possibly provide. Then validate this data and you will know that the client is legit.

---
Tags: box2d, html-canvas, websocket
---


title: Can't access properties of a class

text:
# Question
Title: Can't access properties of a class
Sorry for the bad title, but I couldn't think of a way to word my problem for a title.

So I have this script, with two classes:

```
using UnityEngine;
using System.Collections;

public class GameItem {

    public string ItemName { get; set; }

    public string ItemDesc { get; set; }

    public Item_Type ItemType { get; set; }

    public int ItemValue { get; set; }

    public int ItemID { get; set; }

    public GameItem() {

    }

    public GameItem(string name, string desc, Item_Type type, int value, int id) {
        this.ItemName = name;
        this.ItemDesc = desc;
        this.ItemType = type;
        this.ItemValue = value;
        this.ItemID = id;
    }
}

public class Weapon : GameItem {

    public string WeapEnch { get; set; }

    public float WeapEffic { get; set; }

    public Weapon() {

    }

    public Weapon(string name, string desc, string ench, float effic, int id) {
        this.ItemType = Item_Type.WEAPON;
        this.ItemName = name;
        this.ItemDesc = desc;
        this.WeapEnch = ench;
        this.WeapEffic = effic;
        this.ItemID = id;
    }

    public void Attack() {

    }
}

public enum Item_Type {
    APPAREL,
    WEAPON,
    TOOL,
    CONSUMABLE,
    BOOK,
    MISC
}

```

And then I have a script for adding items to a list using the constructors:

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

public class InventoryManager : MonoBehaviour {

    public List<GameItem> GameItems { get; set; }

    void Start () {
        GameItems.Add(new Weapon("Sword", "It's just a sword.", null, 5, 0));
    }

    void Update () {
        if(Input.GetButtonDown("Interact")) {
            Debug.Log(GameItems[0].ItemName);
        }
    }
}

```

So when I create a new Weapon in the list, I can access everything from the `GameItem` class, but nothing from the `Weapon` class, even though I used the Weapon constructor. So I can't use the `Attack ()` function, or access the Weapon's variables. How can I get around this problem?

# Answer
> 1 votes
The thing is that with your list you dont know if the element is a weapon or a apple. It's just a GameItem. To be able to use the weapon specific properties you need to retrieve the element and cast it back to a Weapon. For example the update in inventory manager will look like this.

```
 void Update()
    {
        if (Input.GetKeyDown("a"))
        {
            Debug.Log(GameItems[0].ItemName);
            Weapon currentWeapon =(Weapon)GameItems[0];
            Debug.Log(currentWeapon.ItemName);
            currentWeapon.Attack();
        }
    }

```

What you can do is add a virtual method `UseItem()` to your GameItem class if you dont want it to be abstract(I would say that it should be). Example :

```
 public virtual void UseItem()
    {

    }

```

Then your weapons class you can do this :

```
  public override void UseItem()
    {
        Attack();
    }

```

Now if you call UseItem on a elemet from your GameItems list and it was added as a weapon it go and call the Attack method from the Weapons class.

An alternative design is to use interfaces to specify different logical boundaries. For example

```
interface IItem
{

}
interface IWeapon : IItem
{

}
interface IFood : IItem
{

}
interface IRangedWeapon: IWeapon
{

}
void ProcessItems()
{
    foreach (var item in Items)
    {
        if (item is IWeapon) //do some logic
         if (item is IFood) //do some logic
                if (item is IRangedWeapon) //do some logic
    }
}

```

Note this is more or less a pseudo implementation. I also suggest you read up on Polymorphism. For a bit more in depth look and information check out this question

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


# Question
Title: Force Reload VS soution Explorer when adding new c# Script via Unity3d?
When I create C# script (`Create -> C# Script`) via `Unity3d` or delete it from `Unity3d` \- `Visual Studio` shows me the warning window.

it's annoying.

Is there any way to force "ReloadAll" in solution Explorer without the window?

# Answer
So, what we have.

Developer from the `VS Tools for Unity team` said that it is one of their most voted feature requests. And it's surprisingly not trivial to fix, they are working on it.

However, I found some script which can use.. I found it on russian unity community.

Great thanks to **DbIMok**. Also he posted this script yesterday on forum.unity3d.com

Need to create C# script named as `FileModDialogCloser.cs` and put it into the `Editor` folder. Here is the code:

```
using System;
using System.Runtime.InteropServices;
using UnityEditor;

[InitializeOnLoad]
public class FileModDialogCloser {

        [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
        static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);

        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        [DllImport("user32.dll")]
        static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);

        const string search = "File Modification Detected";
        static IntPtr hwnd;

        static void Check() {
                hwnd = FindWindowByCaption(IntPtr.Zero, search);
                if ((int)hwnd != 0) {
                        ShowWindow(hwnd, 5);
                        keybd_event(0x0D, 0, 0, 0);
                }
        }

        static FileModDialogCloser() {
                EditorApplication.update += Check;
        }
}

```

Wondering!

It works for creating and deleting C# scripts via Unity.

As you can see the code has a line `keybd_event(0x0D, 0, 0, 0);`. This is simulate pressing of `Enter` button. And that means *Reload* realization. if you need *ReloadAll* then you have to do like that:

```
keybd_event(0x09, 0, 0, 0);
keybd_event(0x0D, 0, 0, 0);

```

This is pressing of `Tab` button and then `Enter`.

*SMALL FAULT:* When you are creating/deleting script: confirm window opens, runs `keybd_event`, the window closes. It happen very fast, so you don't need to click any button. But you can see this window on few milliseconds anyway. I think, for now there is no better way to do that.

---

**ADDITIONALLY:**

You can create C# script **for Unity projects** (not just simple C# script) within `Visual Studio`. `Unity` will add the file automatically without confirmation window.

**The first method (simlple)**:

If I got it right: when you are using `Visual Studio Tools for Unity` \- that tool are integrating already templates for creating Unity C# scripts into the `VS`. So, right click on Solution and chose `Add -> NewItem`. You can see two templates for Unity:

However, these templates can contains a lot of unnecessary information, comments for example `// Use this for initialization`, `// Update is called once per frame` e.t.c. And, as @wondra in comments said: you can add own custom item template for unity scripts.

**The second method**:

* Creating file from anywhere.

* Adding whatever you want or delete smth., or example:

* Click `File -> ExportTemplate`
* Choose `ItemTemlate`

* Check your template in the list

* Click `Next`, `Next`
* Set name and description for template, click `Finish`

* Template will be added into the `c:\Users\YOUR_PROFILE\Documents\Visual Studio 2015\My Exported Templates\` folder, also into the `c:\Users\YOUR_PROFILE\Documents\Visual Studio 2015\Templates\ItemTemplates\`. After `VS` restart you can see this template in the list just as `VS Tools for Unity` templates:

Here is the video explanation.

---

Happy End!
> 3 votes

# Answer
You can add the new script directly on Visual Studio on your intended directory in Unity. In that case you will not need to reload.

But you will have to do something else. New script in Visual Studio will have some namespaces that used default. You may change or remove them. You will have to add `using UnityEngine;`at first for Unity related privileges. You will have to add `void Start()` or `void Update()` by yourself if you need. New Class should look like:
> 0 votes

---
Tags: unity, visual-studio
---


# Question
Title: Calculate the displacement of device in unity
I'm making a 3D game in unity where the object should move forward and backward as the android device moves/accelerates in the Z axes. ie. When the player moves the devise in the direction of the +ve Z axis, the object should move forward, and when the player moves the devise in the direction of the -ve Z axis, the object should move backward.

This game is a multiplayer game, and the players will move in a large football field.

My idea to do this is using the accelerometer to calculate the acceleration of the device, then integrate the data of acceleration to get the device speed in the Z axis. and use the speed to move the device.

Using this equation

> **V2=V1 \+ ΔA . ΔT**
> *Where*
> **V2** : final velocity.
> **V1** : initial velocity.
> **ΔA** : difference between the initial and final acceleration.
> **ΔT** : difference between the initial and final time.

At first I tried to use kinematic equations to calculate the final speed, but I realized then that it can be only used when acceleration is constant. So a friend of me who studies physics differentiated this equation for me to use it when acceleration is variable.

I know that there will be some error in calculating the accurate displacement, and that the error will increase after the integration of acceleration, but this small percentage of error is okay for my application; I thought at first in using GPS instead of accelerometer but I found that GPS accuracy will be less than the sensors.

I know also that the error will be incredibly high after some time, so I reset the values of acceleration and velocity every 10 seconds. I'm also using a low-pass filter to reduce the noise of the sensor.

```
public class scriptMove : MonoBehaviour
{
    const float kFilteringFactor = 0.1f;

    public Vector3 A1;
    public Vector3 A2;
    public Vector3 A2ramping; // for the low-pass filter
    public Vector3 V1;
    public Vector3 V2;

    public int SpeedFactor=1000; //this factor is for increasing acceleration to move in unity world

    void resetAll()
    {
        Input.gyro.enabled = true;
        A2 = Vector3.zero;
        V1 = Vector3.zero;
        V2 = Vector3.zero;
        A2ramping = Vector3.zero;
    }
    // Use this for initialization
    void Start()
    {
        InvokeRepeating("resetAll", 0, 10);
    }

    //http://stackoverflow.com/a/1736623
    Vector3 ramping(Vector3 A)
    {
        A2ramping = A * kFilteringFactor + A2ramping * (1.0f - kFilteringFactor);
        return A - A2ramping;
    }

    void getAcceleration(float deltaTime)
    {
        Input.gyro.enabled = true;

        A1 = A2;
        A2 = ramping(Input.gyro.userAcceleration) * SpeedFactor;

        V2 = V1 + (A2 - A1) * deltaTime;

        V1 = V2;
    }

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

        getAcceleration(Time.deltaTime);

        float distance = -1f;
        Vector3 newPos = transform.position;

        transform.Translate(Vector3.forward * Time.deltaTime * V2.z * distance);
    }
}

```

## The problem:

My code doesn't work always as expected when I move with the device;

* Sometimes when I move forward (in the +ve Z axis of the device) the object moves forward also, but sometimes it doesn't move at all.
* Sometimes when I'm still in my position the object moves alone by itself.
* Sometimes when I move forward and suddenly stop, the object does not stop.

# My questions:

* Are those strange behaviors because of the accuracy of the device, or is there something I'm missing in my code.
* If I'm missing something in my code, What is it?
* I searched a lot about methods to get the most accurate position of the device, and I found that I can integrate GPS with accelerometer, how can I do this with my code in unity?

# Answer
Well your code is very smart but Unity has already done those calculations for you and you can just use

```
void Update ()
{
    transform.Translate(0, 0, -Input.acceleration.z);
}

```

as it will take the device rotation in the world and translate it into Unity same way it behaves with WASD movement.

EDIT:

a simple example code,

```
public class DeviceMovement : MonoBehaviour {

public float speed = 10f;

  void start() {

  }

  void Update () {

  transform.Translate(0, 0,

  (-1 * Input.acceleration.z *speed * Time.deltaTime)); // adds movement on the Z axis alone.

  }

}

```
> 1 votes

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


# Question
Title: Should I slow down my animation with co-routines or update the animation state?
I want to

1. gradually stop the car animation as it collides with another car
2. gradually speed up the car animation as it exits the collider

I have two ways to achieve this.

1. Update
2. Co-routine

For co-routine I used this piece of code:

```
IEnumerator IncreaseSpeedGradually1(AnimationControlSpeed lastGOHitScript)
{
    //stop if decrease speed in progress
    StopCoroutine("DecreaseSpeedGradually");
    float decrementValue = ((lastHitVehicleSpeed / 2) * 2);
    while (lastGOHitScript.Speed <= lastHitVehicleSpeed)
    {
        lastGOHitScript.Speed += decrementValue * Time.deltaTime;
        yield return 0;
    }
    //setting speed to the last speed
    lastGOHitScript.Speed = lastGOHitScript.iniSpeeed;
}

```

and for the update-based approach I just added this criteria to the method:

```
if (carAnimState == carAnimationState.starting)
{
    carAnimState = carAnimationState.running;
}

if (carAnimState == carAnimationState.stoping)
{

    carAnimState = carAnimationState.running;
}

```

These are the two ways I thought about using. I wanted to ask which is right way to do this job? To slow down animation speed and hence get my objective? I guess co-routines can be problematic later in my game. Are there performance concerns for using one of the approaches?

# Answer
Why just slow down the animation? If you want a slow-mo effect, just slowing the animation means everything else is still going to move at normal speed around you. For that, I would recommend lowering Time.timeScale, which slows down time for everything, including the physics engine.

And to answer your question, neither. The best way is to use OnCollisionEnter() and OnCollisionExit(). These are events built into Unity for collision detection. So you would say:

```
void OnCollisionEnter(Collider other)
{
    if(// other collider is a car)
    {
        Time.timeScale = 0.1f; // One tenth the speed of realtime.
    }
}

void OnCollisionExit(Collider other)
{
    if(// other collider was a car)
    {
        Time.timeScale = 1.0f; // Back to realtime.
    }
}

```

So you attach that script to your player's car, and then whenever they collide with another car, time will slow down until they stop colliding with that other car, at which point time will speed up again back to normal. There would of course be occasions in which the player's car won't stop colliding with the other car, so you'd probably want to speed time up again after a set amount of time anyway.
> 1 votes

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


# Question
Title: How can I determine which Trigger is hit?
I have a GameObject. It has 3 BoxCollider2Ds:

1. Body Collider - Not a trigger - Determines if body is hit
2. Weapon Collider - Trigger - Determines if weapon is hit
3. Vision Collider - Trigger - Determines what the GameObject sees

I can tell the Body Collider apart from the other colliders, because it has a different method (OnCollisionEnter2D). However, I cannot tell the Weapon Collider and Vision Collider apart. They both access the same method (OnTriggerEnter2D), and pass in the collider they are hitting. I cannot determine which one is hit.

I could put each trigger on a separate child GameObject, and send a message to the parent, but this is very slow and feels messy to me. What is the best way I can determine which trigger I am hitting?

---

From the Unity Docs for reference:

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public bool characterInQuicksand;
    void OnTriggerEnter2D(Collider2D other) {
        characterInQuicksand = true;
    }
}

```

# Answer
> 4 votes
You might have some success checking the Collider2D.IsTouching method in your OnTriggerEnter.

```
void OnTriggerEnter2D(Collider2D col)
{
    if (weaponCollider.IsTouching(col)) { /* Weapon */ }
    if (sightCollider.IsTouching(col)) { /* Sight */ }
}

```

IsTouching is polled against the last physics update so it should be pretty light weight.

However, if your colliders overlap, it might be best to process the triggers during OnLateUpdate or keep tabs on the touching colliders separately.

```
HashSet<int> collidesWithWeapon;
void OnTriggerEnter2D(Collider2D col)
{
    if (weaponCollider.IsTouching(col)
       && !collidesWithWeapon.Contains(col.GetInstanceID()))
    {
       collidesWithWeapon.Add(col.GetInstanceID());
       // Weapon stuff
    }
}

void OnTriggerExit2D(Collider2D col)
{
    if (!weaponCollider.IsTouching(col)) collidesWithWeapon.Remove(col.GetInstanceID());
}

```

I'm pretty sure there are other curve balls along the way, but hope this helps forward. Adding the colliders to other GameObjects might help too, but I think trigger events cascade top to bottom or something similar. Can't remember what it was exactly, though... Whatever it was, I've made it a practice to check the `IsTouching()` if the hierarchy contains more than one collider.

# Answer
> 0 votes
I fail to see what your problem is with making child objects. Just make two objects as children of your "body" object, make a script saying:

```
public GameObject body;

OnTriggerEnter2D(Collider2D other)
{
    body.characterInQuicksand = true;
}

```

Attach it to whichever of the children is supposed to have it, assign the variable *body* in the inspector and you're done.

# Answer
> -1 votes
I think you can use `GetComponent<Collider2D>().name` to determine the current collider being used in OnTriggerEnter. I did a quick test with this `Debug.Log(other.name + "hit" + GetComponent<Collider>().name);` and it seemed to work ok as long as the triggers did not overlap.

# Answer
> -1 votes
Also, you can use CompareTag.

Firstly, you must to add tag your game objects.

Then: `public class PlayerClass : MonoBehaviour {
 void OnTriggerEnter2D(Collider2D other) {
 if (other.CompareTag("OtherGameObjectTagHere"))
 Destroy(other.gameObject);
 }
 }
}`

Please check this out https://docs.unity3d.com/ScriptReference/Component.CompareTag.html

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


# Question
Title: Combining lots of small polygons to one (some) big poly(s)
I am looking for algorithm to merge lots of relatively small 2d polygons to one or some big polygons. In case two small polygons are touching or overlapping, they should be merged to one polygon.

My big goal is to sufficiently decrease amount of points/lines required to describe collider. Resulting collider can include some polygons, btw.

Could you propose an algorithm or library to do this? (Finally I will implement solution in C# for Unity3d).

P.S. Here is one picture of task I need to solve. Look this http://epsiloncool.ru/i/E20160624-224050.png Green lines is a colliders. I need to merge them all to get one collider (or some)

# Answer
I've been proposed for using awesome Clipper library. It is exactly the thing I need.

"For constructing the union of 2D polygons you can use Clipper library."
> 0 votes

---
Tags: unity, 2d, algorithm, low-poly
---


# Question
Title: android game change background image at every level?
I want to be able to have a different background image at each level of my game. Presently I have only one. There is no layout folder shown in Android Studio and all info I have searched shows how to do it with the layout xml.

I have found this code in GameLayer.java of my game. Actually I am reskinning the game so everything is already there, I just need to know how to have different bg images now. Code:

```
// background
CCSprite bg = new CCSprite("game/game_bg.png");
bg.setPosition(G.displayCenter());
addChild(bg);

```

# Answer
This is actually pretty straight forward. Instead of loading up an image from a static path, you would want to store up (the implementation depends on how you store your levels) a path to the correct background for the level along the other level data. As you are loading and creating your game objects, you would load the path to the background image and set that to be rendered behind the other objects. I'll leave the detailed implementation to you, as it is very trivial and depends on the way you store your level data.

In pseudo-code you the implementation would look something like the following. First you would add the background data to the level file. This example adds it to an XML level description file:

```
<Level>
    <Background src="backgrounds/forest.png"/>
    <Objects>...</Objects>
</Level>

```

You would then load the level data as usual, and while doing that, find the background filepath, and load the instead.

```
for (XmlElement element : elements)
{
    if (element.Tag == "Background")
    {
        backgroundImage = new Image(element.Attributes.get("src"));
    }
    ...
}

```
> 1 votes

---
Tags: android, android-studio
---


title: How to make a visible area in unity3d

text:
# Question
Title: How to make a visible area in unity3d
the simple way to explain it is an image

I want to have a black background and to show only a small area around player. Which way I have to look? I have no clue where to start searching :)

Thanks.

# Answer
> 1 votes
An easy way is to use GUI. Have a big square about 16x times the size of the screen with a circle in the middle of it. This is so if your playing on the TV, you wont see the stuff behind the background.

---
Tags: unity
---


# Question
Title: How to find nearest gameobject on one side
Here is an example:

The left enemy robot is closer than the right enemy robot, but I want the character to attack the robot that is closest to him on his right side. I can't use `Physic.SphereCast` or anything of that sort because it will just find the closest enemy on both sides. How can I make this happen?

# Answer
The best way to do this depends on a few things. I'm going to assume the following - if any of these are incorrect, please let me know and I'll update my answer:

* You want the closest enemy that is anywhere to the right of the player within a certain range, even if it is at a different height
* You want true distance, not just the one that is closest in horizontal positioning (eg an enemy one unit to the right is closer than an enemy one unit to the right and one unit above)

Here's what I'd suggest as a solution:

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

public class YourBotClass : MonoBehaviour {

    float sightRange = 15;

    //
    // Your class code here
    //

    Collider2D GetClosestEnemy(bool facingRight) {
        Vector2 pos = transform.position;
        IEnumerable<Collider2D> validTargets;

        // Get all targets in range
        // Note:  You'll probably want to add a layermask to the OverlapCircleAll call
        var targets = Physics2D.OverlapCircleAll(pos, sightRange);

        if (facingRight) {
            // Filter results to only include targets to the right
            validTargets = targets.Where(coll => coll.transform.position.x >= pos.x);
        } else {
            // Filter results to only include targets to the left
            validTargets = targets.Where(coll => coll.transform.position.x <= pos.x);
        }

        // I've broken the return statement into multiple lines for easier readability
        return validTargets
            // Sort targets by distance
            .OrderBy(coll => Vector2.Distance(pos, coll.transform.position))
            // Return first result, or null if no valid targets
            .FirstOrDefault();

    }
}

```
> 5 votes

# Answer
All the left enemy are in lower value in x-axis position. Objects on right side are on higher value. Subtract main character's x value from enemy's. Positive results are for enemies at right side.
> 1 votes

# Answer
Made it work by assigning a "Left Side" tag to the enemies on the left and a "Right Side" tag to the enemies on the right.

After that I find the closest enemy on a particular side by checking the distance from the enemy to the player and returning the closest one:

```
 private GameObject FindClosestEnemy(string side) {
        GameObject[] enemies = GameObject.FindGameObjectsWithTag(side);
        GameObject closestEnemy = null;
        var distance = Mathf.Infinity;
        var playerPos = transform.position;

        foreach (var enemy in enemies) {
            var diff = enemy.transform.position - playerPos;
            var currDistance = diff.sqrMagnitude;

            if (currDistance < distance) {
                closestEnemy = enemy;
                distance = currDistance;
            }
        }

        return closestEnemy;
    }

```
> 1 votes

# Answer
Assuming your enemies all have colliders, could you not simply fire a 2D Raycast https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html in a straight line to the right of your player and return the GameObject of the first collider it hits?
> 0 votes

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