# Question
Title: How to divide sprite sheet, but keeping the in same png?
first post here, but couldn't find an exact answer in your database, so guess I'll have to ask.

I want to know how it is possible to create a ".META" file for a .png so you can extract individual sprites in a spritesheet without having to save all the sprites in individual .png's.

I know it's possible since the developer in the tutorial HERE is using a spritesheet like that.

Thank you very much in advance.

# Answer
> 4 votes
# Sprite Sheets with a Uniform Grid

The easiest form of **sprite sheets**, are sheets that use a uniform grid to lay out the individual sprites of your object. Your sheet is essentially a grid with a certain number of rows and columns of cells. Each cell contains a single sprite.

Using a **uniform grid**, means that all cells have the exact same dimensions. Additionally, the alignment of the cells is always the same (this means the horizontal and vertical separation between cells is constant).

The image below shows a sheet with a uniform grid (property of pixel artist SmithyGCN)

---

# Required Metadata to Extract Sprites

As you correctly say, you need some metadata that describes the structure of the sprite sheet, in order to extract individual sprites from the sheet. I tend to use the following list of metadata myself (you can use this as an example, and add or remove metadata attributes as needed):

```
unsigned int m_SpriteWidth; // Width of an individual sprite
unsigned int m_SpriteHeight; // Height of an individual sprite
int m_SpriteOriginX; // Horizontal origin of the sprite
int m_SpriteOriginY; // Vertical origin of the sprite
unsigned int m_SheetWidth; // Width of the sprite sheet image
unsigned int m_SheetHeight; // Height of the sprite sheet image
unsigned int m_SheetColumns; // Number of columns in the sheet
unsigned int m_SheetRows; // Number of rows in the sheet
int m_SheetSeparationX; // Horizontal separation of cells
int m_SheetSeparationY; // Vertical separation of the cells
int m_SheetLeft; // Left position of the first cell
int m_SheetTop; // Top position of the first cell

```

These parameters will let you use a wide variety of sheets. Here's an explanation and motivation for the chosen parameters:

* The **sprite width** and **sprite height** describe how big an individual sprite is. You need this information to generate a quad of the appropriate size to draw on. Additionally, you need this value to calculate the UVs of the rectangular area you want to cut out of your sheet.
* The **sprite origin X** and **sprite origin Y** describe where a sprite is drawn when you specify a drawing location. For example, if you set the origin to be at the horizontal center, and vertical bottom of the sprite (14,27), the sprite will be drawn above and centered on the location of the object. This is typically what you want, as a ground-enemy should be drawn "just above" the ground and centered on it's position. Additionally, the origin is used as the center for scaling and rotating.
* The **sheet width** and **sheet height** describe the width and height (in pixels) of the complete sprite sheet. This information is needed when calculating the UVs of the rectangular area you want to cut out of the sheet. After all, you need to normalize your UVs to a value between 0.0f and 1.0f, so you'll need to convert your pixel coordinates to relative coordinates through a division by the width and height of the sheet respectively.
* The **sheet columns** and **sheet rows** values describe how many rows and columns of cells are within your sprite sheet. You need these to convert a sprite index (= which sprite you want to draw) to pixel coordinates. You'll want to number your sprites in scanline order (i.e. left-to-right, then top-to-bottom). You can then find the column of the sprite as *(index % m\_SheetColumns)* and the row of the sprite as *(index / m\_SheetColumns)*. This last calculation works because of the floor-rounding due to integer division. The number of rows can be used to prevent the index from overlowing outside of the sprite sheet range by doing *index = (index % (m\_SheetColumns* * *m\_SheetRows))* before using it to calculate the column and row.
* The **sheet separation X** and **sheet separation Y** values describe the spacing in between cells. In the case of the above sheet, both these values would be 2 (as there is a two pixel white border between cells, that makes up the grid of the sheet). If you tightly pack your individual sprites, this value would be zero. Having a small separation can be useful to make your sheets more clearer to the human eye.
* The **sheet left** and **sheet top** values indicate the starting position of the sheet. In the case of the above sheet, a 1 pixel white border was added around the entire sheet. This means that all pixel coordinates need to be shifted one pixel downward and one pixel to the right when calculating the rectangular cutout region. If your top-left cell starts at the very top-left of the sheet image fire (at coordinate (0,0)), this value would be (0,0).

---

In summary, you can back multiple sprite into one sprite sheet easily by aligning them on a uniform grid. As you said, you will need to metadata that describes the layout of the sheet. The above list contains some suggested attributes that will give you a lot of flexibility in the type of sheets you can employ in your game. Obviously, you can leave out or add new parameters as needed in your use-case.

---
Tags: unity, 2d, sprites, tilesets
---


title: interfacing WiiMote with Unity 5

text:
# Question
Title: interfacing WiiMote with Unity 5
I am looking for a guide on connecting WiiMote with Unity 5 as an Input device. I found this library here but I do not understand how to install it and what the prerequisites are for it to work.

# Answer
Although DMGregory's answer is a really thorough and good I have found a different solution and more robust that suit's my needs. I have found a dll (which I cannot find the link currently but will upload somewhere and edit my answer to encompass the link) and using DLLImport and these functions

```
[DllImport ("UniWii")]
private static extern void wiimote_start();
[DllImport ("UniWii")]
private static extern void wiimote_stop();
[DllImport ("UniWii")]
private static extern int wiimote_count();
[DllImport ("UniWii")]
private static extern byte wiimote_getAccX(int which);
[DllImport ("UniWii")]
private static extern byte wiimote_getAccY(int which);
[DllImport ("UniWii")]
private static extern byte wiimote_getAccZ(int which);
[DllImport ("UniWii")]
private static extern float wiimote_getIrX(int which);
[DllImport ("UniWii")]
private static extern float wiimote_getIrY(int which);
[DllImport ("UniWii")]
private static extern float wiimote_getRoll(int which);
[DllImport ("UniWii")]
private static extern float wiimote_getPitch(int which);
[DllImport ("UniWii")]
private static extern float wiimote_getYaw(int which);
[DllImport ("UniWii")]
private static extern bool wiimote_getButtonA(int which);
[DllImport ("UniWii")]
private static extern bool wiimote_getButtonB(int which);
[DllImport ("UniWii")]
private static extern bool wiimote_getButtonUp(int which);
[DllImport ("UniWii")]
private static extern bool wiimote_getButtonLeft(int which);
[DllImport ("UniWii")]
private static extern bool wiimote_getButtonRight(int which);
[DllImport ("UniWii")]
private static extern bool wiimote_getButtonDown(int which);
[DllImport ("UniWii")]
private static extern bool wiimote_getButton1(int which);
[DllImport ("UniWii")]
private static extern bool wiimote_getButton2(int which);
[DllImport ("UniWii")]
private static extern bool wiimote_getButtonPlus(int which);
[DllImport ("UniWii")]
private static extern bool wiimote_getButtonMinus(int which);
[DllImport ("UniWii")]
private static extern bool wiimote_getButtonHome(int which);
[DllImport ("UniWii")]
private static extern byte wiimote_getNunchuckStickX(int which);
[DllImport ("UniWii")]
private static extern byte wiimote_getNunchuckStickY(int which);
[DllImport ("UniWii")]
private static extern byte wiimote_getNunchuckAccX(int which);
[DllImport ("UniWii")]
private static extern byte wiimote_getNunchuckAccZ(int which);
[DllImport ("UniWii")]
private static extern bool wiimote_getButtonNunchuckC(int which);
[DllImport ("UniWii")]
private static extern bool wiimote_getButtonNunchuckZ(int which);

```

I managed to interface with the WiiMote and get the functionality I need.

The original publisher of the dll is no longer supporting it, or don't care any more. I emailed them about it and they still have not replied after a few months. I found it though in a project hosted in google code (here). It's a full project with examples and the .dll.

**EDIT** Also keep in mind if you are to use this dll for a commercial application you will have to contact the original publisher to get licenced (if you manage to get a response from them). And also I had some issues using this dll while building on a 64-bit machine using 64-bit Unity (if it was built on a 32-bit machine everything was ok and it ran perfectly on both 64-bit and 32-bit)
> 0 votes

# Answer
I tried to look into the UniWii library linked in the question, but the Windows download page appears to be a broken link at the moment, and forum threads about it are mostly 4 years old. :(

The basic idea it uses, a native plugin DLL referenced from C# with \[DllImport\] mappings, is a good one. I've used this successfully for interfacing with the Kinect and Playstation Move controllers, so if you find a working download of an up-to-date version of this plugin, it's probably a better & more robust option that what I'm about to present below.

---

The method I've used to get Wii Remote information into Unity (or Flash) is to install an external program like GlovePIE on Windows or OSCulator on Mac. These programs do Programmable Input Emulation, effectively communicating with a wide variety of devices and giving you tools to control how they talk to each other.

Both expose the ability to send & receive data via Open Sound Control messages, which we'll listen for within Unity to read the data coming from the Wii Remote.

I'll describe the GlovePIE method because I'm most familiar with working on Windows.

1. Make sure your computer's Bluetooth adapter is on.
2. Run GlovePIE and fill a new script with something like this:

(You can save this as a new ".PIE" file to load it later)

```
var.port = 54934

debug = "On: " + Wiimote1.Exists + " Wiimote battery level: " + Wiimote1.Battery + " Rotation: " + Wiimote1.YawSpeed

SendOsc("localhost", var.port, "/wii/1/start", true)
SendOsc("localhost", var.port, "/wii/1/acceleration", tostring(Wiimote1.gx), tostring(Wiimote1.gy), tostring(Wiimote1.gz))
SendOsc("localhost", var.port, "/wii/1/rotationSpeed", tostring(Wiimote1.PitchSpeed in radians), tostring(-Wiimote1.YawSpeed in radians), tostring(Wiimote1.RollSpeed in radians))
SendOsc("localhost", var.port, "/wii/1/analog", tostring(Wiimote1.Nunchuk.JoyX), tostring(Wiimote1.Nunchuk.JoyY))
SendOsc("localhost", var.port, "/wii/1/buttonA", int(Wiimote1.A))
SendOsc("localhost", var.port, "/wii/1/buttonB", int(Wiimote1.B))
SendOsc("localhost", var.port, "/wii/1/buttonC", int(Wiimote1.Nunchuk.C))
SendOsc("localhost", var.port, "/wii/1/buttonZ", int(Wiimote1.Nunchuk.Z))
SendOsc("localhost", var.port, "/wii/1/button1", int(Wiimote1.One))
SendOsc("localhost", var.port, "/wii/1/done", true)

```
3. Click the "Run" button in GlovePIE. It's now scanning for Wii Remotes.
4. Set the Wii Remote on a flat surface (so the initial calibration is stable)
5. Press the 1 & 2 buttons on the Wii Remote at the same time.

All 4 lights on the remote should blink - the Wii Remote is scanning for receivers

6. Wait for Windows to do its "installing new hardware" nonsense.

You can ignore this, including any dialogs saying you need to restart (they lie).

7. Lights 1 & 4 should come on solid, lights 2 & 3 off.

GlovePIE has found the remote

8. Lights 2 & 3 should come on solid, lights 1 & 4 off.

GlovePIE is calibrating the sensors. Keep the remote still, or it will calibrate forever (which it sometimes does anyway).

9. Light 1 should come on solid, the rest off

The remote is registered as player 1 and is sending data over Open Sound Control messages.

The Debug box in GlovePIE should show that the remote exists, report its battery level, and show the current yaw rotation data. (That's the second line of the script above). If you're not getting yaw data when you rotate the controller, then you should power it off and try pairing it again.

10. You can stop & start your Unity game or PIE script as much as you want and the remote will "just work" until it's turned off.

Note that when you stop the script, the lights turn off, but the remote is still ON and draining the battery. If you're not using the remote for a while, hold the power button to turn it off. You'll have to start again from step 3 when you want to use it again.

Okay, so that's how to get the data into your computer. Now you can use a library like OSCuMote (download link) to read the OSC messages coming in on port 54934 and access the data in your Unity C# scripts.

I'll try to clean up the C# script I wrote for this in my last project and include it as part of this answer.
> 1 votes

---
Tags: unity, wii
---


# Question
Title: Unity - How to save variables for Android Game?
This is my current code, it only work into unity, when i test it in an Android Device it don't save the variable

```
public class Click : MonoBehaviour{

public UnityEngine.UI.Text proiettiliTotali;
public UnityEngine.UI.Text bpc;
public float proiettili = 0.00f;

void OnEnable(){
        proiettili = PlayerPrefs.GetFloat("Player Score");
}

// Update is called once per frame
void Update () {
    proiettiliTotali.text = ConvertiroreProiettili.Instance.GetCurrencyInString(proiettili, false, false);
    bpc.text = ConvertiroreProiettili.Instance.GetCurrencyInString (proiettiliOgniClick, false, true);
}

public void Clicked () {
    proiettili += proiettiliOgniClick;
}

void OnDisable(){

    PlayerPrefs.SetFloat("Player Score", proiettili);
    PlayerPrefs.Save ();
    Debug.Log (proiettili);
}

```

# Answer
PlayerPrefs creates on file on the disk of the device the app is used on, so it will not save between editor, and device. Other then that your code seems fine, I have noticed that if you build to your device on each test, that sometimes you lose your PlayerPrefs.
> 1 votes

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


# Question
Title: Resultant Vector Of Circle Line Collision
For my game I need to have a circle collide against a wall and bounce off in the appropriate direction. I've looked around for a while and haven't found a good solution to my problem. I have a diagram of what should happen below.

The problem is that I have the vector V, U, and P, but I am unable to calculate the new X and Y vectors after the collision. I have tried using Trig to find the angle of the intersection and get the new X and Y vectors from that but it gives massive numbers. How do I get the new X and Y vectors easily? Source code is posted below.

```
for (int i = 0; i < collisionList.size(); i++){
    Vec2<Integer> c = collisionList.get(i);
    int cx = c.getX();
    int cy = c.getY();
    if (distance(x, y, cx, cy) <= (r - (r / 2))){
        float mag = (float)Math.sqrt((Math.pow(x, 2) + Math.pow(y, 2)));
        float angleRad = (float)Math.atan(y / x);

        xVel = (float)(mag * Math.cos(angleRad));
        yVel = (float)(mag * Math.sin(angleRad));
    }
}

```

# Answer
> 1 votes
The way I handle these kinds of 2D physics is to process the X and Y components of the vector separately.

That way if a collision occurs, I know which direction the collider was moving along based on the sign and component of the velocity vector I am processing.

Then when a collision occurs, you can modify the velocity on the appropriate axis. Changing the sign simulates a perfectly elastic bounce, while multiplying it by a negative number (eg -0.5) can simluate a bounce where some energy is lost.

For your code

```
/*
   Move along X Axis
*/

for (int i = 0; i < collisionList.size(); i++){
    Vec2<Integer> c = collisionList.get(i);
    int cx = c.getX();
    int cy = c.getY();
    if (distance(x, y, cx, cy) <= (r - (r / 2))){
        xVel = -xVel;
    }
}

/*
   Move along Y Axis
*/

for (int i = 0; i < collisionList.size(); i++){
    Vec2<Integer> c = collisionList.get(i);
    int cx = c.getX();
    int cy = c.getY();
    if (distance(x, y, cx, cy) <= (r - (r / 2))){
        yVel = -yVel;
    }
}

```

---
Tags: java, collision-detection, vector
---


title: Touch through GameObject, best practice

text:
# Question
Title: Touch through GameObject, best practice
in the game I am doing atm you have an area with monsters. There are two modes to damage monsters :

1. tapping on them
2. casting spells on the ground

Tapping and damaging a monster works fine.

The problem : If I have selected a spell and want to cast it on the ground, the monster collider blocks my touch of the ground behind the monster.

My solution was to disable the monster collider when I want to cast a spell.

```
    GameObject[] toDisable = GameObject.FindGameObjectsWithTag ("Touch");

    foreach (GameObject g in toDisable) {
        g.GetComponent<Collider>().enabled = active;
    }

```

And ... it works.

Now my question is : Is this an adequate solution? They say GetComponent is slow, but I guess with 20 to 30 monsters running around it should be fine? Anything else that could be done? Maybe there is some Unity magic I am not aware of.

# Answer
> 1 votes
> The problem : If I have selected a spell and want to cast it on the ground, the monster collider blocks my touch of the ground behind the monster.

No need to disable `colliders`. Just assign different layers to monsters, spells and ground. Then use the collision matrix to specify that a spell doesn't collide with monsters.

(The same process, using `LayerMask` if you are using `RayCasting`)

> They say GetComponent is slow, but I guess with 20 to 30 monsters running around it should be fine?

It's slow because there's no caching of `Components` in the Mono side of the scripts. Every `GetComponent` is forwarded to the native code which iterates through all components attached to a given `GameObject`. More objects, more calls. More components more thing to iterate through.

Definitely an overkill in this specific context.

# Answer
> 1 votes
I think I have a solution: Set the LayerMask of the PhysicsRaycaster accordingly.

```
public LayerMask normal; //Everything
public LayerMask attack; //Floor
public PhysicsRaycaster rayCaster;

void Update() {

    attackAllowed = Input.GetKey (KeyCode.Space);

    rayCaster.eventMask = attackAllowed?attack:normal;

}

```

Works like a charm.

---
Tags: unity, touch
---


title: Hinting at Steganography

text:
# Question
Title: Hinting at Steganography
I'm working on an ARG which will be implemented mostly through a standard website. I'd like to give some of the images on the site steganographic content (hidden content stored in an image, e.g. an 8 color image of the same dimensions stored as even and odd color values in the pixels). Technologically, this is fairly easy to do. However, I'm having trouble figuring out a subtle way to hint at the presence of this content. The effect itself is invisible to the naked eye, and nobody just randomly checks for this kind of thing. What can I do to draw players' forensic attention to these images, while still maintaining an amount of subtlety (i.e. something that doesn't make it *glaringly* obvious)?

# Answer
One way is to "hide" an obvious message that then gets people looking for a more subtle one. Like a breadcrumb to lead them down the path.

For instance, pick a line or block somewhere in the image, and use the high bits in that patch to encode a short ascii string like "LOOK CLOSER" or a phrase significant to your game (like a name or date). This will be visible to the eye as a line or block of static.

While a naive viewer might assume it's a compression glitch or data corruption, someone familiar with ARGs/steganography will know to check whether the pattern of bright & dark pixels means something. They can do this by eye just by zooming in and entering the bits into a binary-to-ascii converter. The obvious message then confirms that they're on the right path, but can still go deeper, using image editing software to look for more subtly encoded information.

You can also try choosing the two images so that they have a "tell." If the overlying image has a patch that's all one flat colour, and the underlying image has some well-defined edges that cross this area, this will often be just barely noticeable - the eye is much better at spotting structure like edges than slight variations in dithering.

One more way would be to use more of the low bits, to increase the interference with the overlying image until it's noticeable. To keep the underlying image from being immediately visible, you can scramble it. Choose an underlying image width that's relatively prime to the overlying images's width, and encode each row one after another, wrapping around to the next line whenever you hit the edge of the main image. This scrambles the image so that pixels that should be adjacent vertically, aren't.

If the image and widths are chosen well, this should look like coloured static all over the main image - but static with too much repetition to be random, again cueing a sharp observer to look at the data. They then have an extra puzzle of figuring out the right stride to re-align thr rows of the hidden image.
> 5 votes

# Answer
The easiest way is to somehow implant a reference to your ARG in the image. A photo-shopped in poster on the wall with the logo for your game on it in a photo that otherwise shouldn't reference the game. But more subtle than that, make the picture somehow disconcerting. For reference look at paintings by Magritte and you'll know what I mean about disconcerting (you might want to be more mild than him though). Or look at pictures for the "When you see it.." meme for ideas on things that you'd glance over but disturb you if you noticed the details.

Even something like the size of the image can be a give away. When playing cryptographic games lots of people carefully go though the code of suspect web pages and they'll have in text the dimensions of an image. If say 31 is an important number and an image width turns out to be a multiple of that, people will look closer. Putting protection on the image so you can't just right click and save to download will also draw interest. Having very crisp graphics everywhere but then uploading one with higher compression all of a sudden will be suspicious. Fiddle with the metadata so if they download all the images on the site and compare them they'll notice some either have additional info or are stripped of it.

Replacing an image with something new will draw attention, especially if that image was part of the navigation for the site. Misspell something, screw up some grammar, leave off a period. Give conflicting information about an image eg, the time stamp says May 12th but it was posted on May 11th, or there's something going on that happened on the 13th, not the 12th.

These are just some suggestions. I'm not really sure who your target audience is, or what kind of feel you're going for, so it's hard to be more specific than general ideas about how one might go about something like this. But in all likeliness you won't need to hint much at all, just introduce your players to increasingly more complex puzzles and someone is bound to wonder if there's anything hidden in your image files.
> 1 votes

# Answer
One way I know is changing pixel colour to reflect a binary value.

Example 0 for an even coloured value and 1 for odd coloured value for every pixel. Changing images just one bit of it's coloured value tricks the eye if you use a multiple coloured picture/image.

The program then arranges the bit values taken from certain positions in the image to create a hidden message.

Example: A jpg picture for example can hold 256 color per pixel. If say the target pixel has value of 101 and you need to change it to odd number then you change it to 100. You may need to change 8 pixel to create 1 character cause 8 bits = 1 byte and 1 byte should be enough to reflect one ASCII character.
> -1 votes

---
Tags: game-design, puzzle
---


# Question
Title: Sprite Kit - keeping character level with the terrain 2d endless runner
I've been trying to figure this out exhaustively for the past few days and still haven't found an answer. I have an endless runner built using swift where the character is fixed and the terrain moves to the left. I have edge physics bodies on the terrain, and edge physics bodies that go up and down slopes.

The problem is, if I want my character to collide with the ground without being pushed back by it, since the only thing that can make contact with an edge is a dynamic volume.

My goal is to keep the character level with the terrain, (assuming they're not jumping). Even on slopes.

I've tried ray casting using enumeratebodiesalongraystart, but can't seem to figure out how to get coordinates of where it intersects with the ground. I've tried having an edge body that is vertical, that intersects with the ground(two edge bodies cannot make contact in sprite kit). I've tried dynamic volumes. I've tried Static volumes. Nothing works. I'm not posting code here since I'm really just looking for a general answer to sort of point me in the right direction, but I'm coding in swift. Thanks in advance. Also I have the character in a different bitmaskcatagory than the terrain catagory and they are set up to recognize each other, and do if one of them is a dynamic volume physics body.

# Answer
To keep a character level with a moving "ground" without its x position being affected by the physics engine, it would seem the best solution might be to place an SKConstraint on the character. Specifically:

```
character.constraints = [SKConstraint.positionX(SKRange(constantValue: 0.0))]

```

If you have any weird bugs from SpriteKit's physics engine, you might try placing a node with a physicsBody that's affect by gravity with that same constraint, and constraining the character to that node. You could place an additional rotational constraint on the character if you want the character to only rotate a certain angle while "climbing hills" or if you want your character to be "upright" constantly while not colliding with the ground.
> 0 votes

---
Tags: collision-detection, ios, physics, spritekit
---


title: Android - animating spritesheets

text:
# Question
Title: Android - animating spritesheets
I'm creating a basic endless runner game on Android using SurfaceView.

I have background that recreates itself constantly, which was simple enough.

One problem I've always had is getting my head around animating sprite-sheets, not just in Android but other platforms as well.

Based on the problem I'm stuck on right now.. I have a sprite sheet thats 9 images 2 rows, 5 columns, with an empty space at the end of the second row. All of which is one single running animation.

I've made a Sprite Class.

```
public class Sprite {
    GameView gameView;
    Bitmap bmp;
    private int x, y, width, height;
    private int spriteColumns 5, spriteRows= 2;
    private int currentAnim = 1;

    public Sprite(GameView gameView, Bitmap bmp) {
        this.gameView = gameView;
        this.bmp = bmp;
        this.width = bmp.getWidth() / spriteColumns;
        this.height = bmp.getHeight() / spriteRows;
    }

    public void update() {
       // do something here with currentAnim, x and y;
    }

    public void onDraw(Canvas c) {
       update();
       canvas.drawBitmap(bmp, x, y, null);
    }

}

```

How do I go about doing this? Am I on the right track so far?

# Answer
Create an arrays for each direction of running index. So, if there is one direction the player can move, all the player can do is either run or not run. You have a single array.

Say the that your animation requires 3 poses: both feet down, left leg up, right leg up. You place them in an array as indexes `0`,`1`,`2` respectively.

Then your run\_annimation array would be `[0,1,0,2]` because you want the player to breifly have both legs down when switching feet.

You keep a animation step variable that tells you where you are in the animation. When running stops, the step goes back to 0.

Here's some incomplete psudeo code to get you started.

```
Int animation[][]; // which bmp's are in each animation sequence
// [0][...] Idle aniation.
// [1][...] Run animation.
Bitmap bmp[];  // all the bmps sliced from the sprite sheet.
step = 0; // Where we are in the animation
Int whichAnim = 0; // Which animation we are playing.

public void animateRun() // Do the run animation.
{
  if(whichAnim != 1) // If we're not already doing the run animation.
  {
    whichAnim = 1; // Go to the run animation
    step = 0; // And start at the begining.
    return; // Done for now.
  }
  step++;  // Otherwise, we are already running.  Move to the next image in the animation.
  if(step > run_animation.length()) // If it past the end,
  {
    step = 0; // go back to the start of the animation and loop it.
  }
}

public void animationReset() // When we stop all animations...
{
  animation = 0; // Go to the idle animation
  step = 0;  // At the begining of the animation.
}

public void onDraw(Canvas c) // Your draw to take into account
{
  canvas.drawBitmap(bmp[ animation[whichAnim][step] ]);
}

```

Each time through the game loop, if the run key is pressed, before you move the sprite, you call `animateRun()`. You could simplfy the above by using a `setAnimation` and changing `animateRun` to just an general `animate` function. When the run key isn't pressed that time through the game loop, call `animateReset()`.

Hope that makes sense.
> 0 votes

---
Tags: android, sprites, spritesheet
---


# Question
Title: Help with Resolving Pixel Perfect Collision
Hi I'm having trouble resolving "Collision detection between axis-aligned bounding box and bitmap (pixel perfect) terrain on a Worms type game". (Read previous question to find more information about the game).

The player has got properties such as velocity, acceleration, gravity applied to it on its update method. I have controls that allow the player to "land" on a surface by detecting the pixel immediately below it and then stopping the velocity if that object is solid. I am having trouble with moving the character.

Currently when I move the character left or right the code should work in my head to move the character up, but it seams to still want to go into the ground. Could you help me to resolve the collisions for moving?

Below is the code I implement for Walking left or right. It is called immediately before the update method for sprite. This method is called from the Player class update method.

```
            boolean solidPixel;
            //Create a bitmask from top to bottom of the pixels
            for(int i=0;i<boundHeight;i++){
                //If true then collision
                solidPixel = TerrainObj.isPixelSolid(x+(getBound().halfWidth*direction),y-getBound().halfHeight+i);
                //if any of the pixels are solid then we've hit a wall
                //so act accordingly and exit the application
                if(solidPixel && i < getBound().halfHeight/4){
                    //
                    //Cannot move in the direction
                    velocity.x = 0;
                    break;
                }
                //if the bottom (left/right)quater of the sprite is
                //solid then its a slope
                if(solidPixel && i >= getBound().halfHeight/4){
                    //Position the item -(up) by the amount of pixels the
                    //gradient is
                    position.y+=(getBound().halfHeight*2)-i;
                    break;
                }
            }

```

Any help is much appreciated how I could approach the issue to stop the player ever moving into the ground to provide prefect collision detection.

Sorry for the long post, wanted to put as much information in as possible.

# Answer
> 2 votes
You can try calculating the surface normal using central finite differencing, and then colliding with a locally linear plane at the collision point.

```
Vector2 GetNormal(Grid grid, int x, int y)
{
    float dx = grid[x + 1, y] - grid[x - 1, y];
    float dy = grid[x, y + 1] - grid[x, y - 1];
    return Vector2(dx * 0.5f, dy * 0.5f);
}

```

When your grid is binary (1's and 0's) this normal will either point to the right, left, up, down, or at some 45 degree increment. You will get a better result if you first convert your map into a signed distance field instead.

After you find the normal of the surface, computing the collision between the plane and the bounding box should be easy. Essentially, just cancel out the velocity parallel to the plane normal.

# Answer
> 1 votes
I will give you a different approach you might wanna try.

How i would do this is I would use shapes for the objects. A rectangle for the terrain, a rectangle for the bottom half of the worm and a circle for the top half of the worm. So the worm is a combination of 2 shapes. Now, if the user `presses left worm gets a (-5,0) velocity` if the user `pressed up the worm gets a (0,-5) velocity`. After the velocity is applied, you check for collisions using trigonometry, and if any of the 2 shapes of the worm collide with the terrain, then you move it outside of the terrain, by moving the worm up. So you basically force it not to be inside the terrain. This velocity would have to be calculated according to the angle of the terrain, otherwise your worm would move very quickly on terrains placed at high angles.

For example, according to the image in your question, if the user pressed left, the worm would get a (-5,0) velocity applied to it, so it would move 5 pixels to the left. But then it would be inside the terrain, so we would have to force it outside of the terrain by moving it `k pixels` up. You will have to calculate `k` using Euclid theorem. So not only the worm will never be inside the terrain, but it will also move as a result of forcing it outside of the terrain.

So, basically the worm goes inside the terrain, and then the terrain pushes it `upwards (only)`. That way your worm is never drawn inside the terrain, and also it moves.

You will simply need `collision detection of rotated rectangle with a rectangle/circle`. Or instead of a "rectangle" you could check `collisions with 4 lines`. That way you would not only solve rectangle with an angle - rectangle/circle collision detection, but any given `polygon` \- circle/rectangle intersection, which you might need in the future. Because a polygon is nothing other than N lines. Now, the problem with that is that if your worm has a big velocity, your worm might pass right through the terrain, because lines are thin. For that to happen you worm would need to have a velocity of greater than 2\*radius of the circle, or greater than 2\*width of the rectangle (but in reality that is really unlikely, your worm would have to move like 50 pixels per frame for that to happen, which is too high for a worm anyway). The "circle" and "rectangle" i am talking about are the shapes of the worm. This problem is known as `continuous collision detection`.

Not that it is necessary, but if you had a physics engine with collision detection functions, you could check polygon collisions much easier. And probably a tiny bit more efficiently than any code you will write alone, unless you are familiar with mathematics.

---
Tags: java, android, collision-detection, collision-resolution
---


# Question
Title: Libgdx Drawing a triangle cannot resolve method "render "
I want to draw a triangle. I found a lot of code such as this.

I thiknk the code I found is old; if I use

```
mesh.render(GL20.GL_TRIANGLES, 0, 3);

```

Then the compiler cannot resolve method.

How can I draw a triangle or solve this problem?

# Answer
> 0 votes
Use ShapeRenderer http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/graphics/glutils/ShapeRenderer.html.

Note that it's pretty slow and you'd better just use triangle sprite for that.

---
Tags: libgdx, android
---


# Question
Title: What is an efficient method of collision detection for handling lots of objects?
In my game, I have plenty of objects that can collide. Literally, most of them can collide with each other. The problem I'm facing is that I can't come up with some good collision detection. How can I resolve collisions for lots of objects in such way that I don't end up with class that has more than 1000 lines of code with enormous conditional constructs like this?

```
    if (firstBodyUserData == "rocket"
            && secondBodyUserData == "car_body") {
        resolveRocketAndCarBodyCollision(firstBody, secondBody, contactData);
    } else if (firstBodyUserData == "rocket"
            && secondBodyUserData == "gas_tank")
        resolveRocketAndGasTankCollision(firstBody, secondBody, contactData);
    //...many more dumb lines of code for every particular object in my game

```

And don't forget about all these "resolving methods" after if statements.

To make question more specific, I use Box2D with its ContactListener and Artemis-odb entity-component-system framework so I don't really have classes for my entities and that kind of exacerbates the problem but main question is in resolving bunch of different types of collisions.

# Answer
What you want to do is register collision callbacks for each kind of body.

```
// You have a map from bodies to functions of bodies.
Map<BodyData, Function<BodyData> > collisionCallbacks;
// Invoke the function associated with that kind of body.
collisionCallbacks[firstBodyUserData].Invoke(secondBodyUserData);

// An example collision function
void resolveRocketCollision(BodyData data)
{
     // This is also really horrible. You don't want to be checking conditions
     // like this. Instead, you will want to indirect this one step further to
     // the *type* of the object, using virtual function calls.
     if(data == "car_body") ...
     else if(data == "gas_tank") ...

     // That is, it should look like this:
     if (data.HasProperty(Health))
          ...
     if (data.HasProperty(Explodes))
          ..
     ...
}

// Registering the function
collisionCallbacks["rocket"] = resolveRocketCollision;

```

## Avoiding function pointers

In Java, you don't have function pointers, so it might be better to have an interface with a "resolvecollision" method like this:

```
public interface CollisionResolver
{
    void Resolve(BodyData bodyData, CollisionData collision);
}

```

Then your map would be something like this:

```
Map<BodyData, CollisionResolver> collisionCallbacks;

```

And you invoke it like this:

```
collisionCallbacks[firstBodyUserData].Resolve(secondBodyData, collisionData);

```

## Avoiding a big static map

Obviously it's bad practice to carry around a big map of collision callbacks. You will have to use (drum roll) *object oriented programming*. Instead of storing strings as your user data, store the objects themselves. Then your function just becomes:

```
void ResolveCollision(BodyData body1, BodyData body2, CollisionData collisionData)
{
    body1.Resolve(body2, collisionData);
}

```

And, each of your bodies implements the `CollisionResolver` interface. For example, if you want a rocket to explode anything that has "health" you do this:

```
class Rocket implements CollisionResolver
{
   public void Resolve(BodyData otherBody, CollisionData collisionData)
   {
       if (otherBody.HasProperty(Health))
       {
           ExplodeRocket();
           otherBody.Die();
       }
   }
}

```
> 1 votes

---
Tags: collision-detection, box2d, physics
---


# Question
Title: Find distance from Vector2 to nearest point in Rectangle
I'm setting up collision detection and I have Walls which store their positions as rectangles. I need to figure out the distance from a Vector2 to the nearest side of a rectangle. If this was two Vector2's I could just do `Vector2.Distance()` but I can't find similar methods for Vector2s and Rectangles. Here is an image to illustrate what I need:

So the red dot would be my Vector2 and the blue would be my Rectagle, and I need to get the distance of the orange line. Once I have this I can check the distance for my collision detection.

# Answer
> 2 votes
# For arbitrary shapes

The basic algorithm goes like this:

```
// Gets the distance from a point to a shape made of line segments.
float GetDistance(Shape shape, Vector2 point):
    min_dist = float.max;
    foreach LineSegment line in shape:
         dist = GetDistance(line, point);
         min_dist = min(min_dist, dist);
    return min_dist;

// Gets the distance from a line segment to a point
float GetDistance(LineSegment, Vector2 point):
   ...

```

The distance from a line segment to a point is also pretty easy to find.

# For axis aligned rectangles

Axis aligned rectanges (ie, non-rotated) have the nice property that they're already rotated into the same coordinate frame as the point. This makes the problem a lot easier. Suppose the rectangle has the parameterization:

```
[min_x, min_y, max_x, max_y]

```

You can clamp to the nearest point in the rectangle, and find the distance to that point. The nearest point on the rectangle is given by:

```
nearest = [point.x, point.y];
if (point.x < min_x)
   nearest.x = min_x;
else if(point.x > max_x)
   nearest.x = max_x;

if(point.y < min_y)
    nearest.y = min_y;
else if(point.y > max_x)
    nearest.y = max_y;

```

And the distance is given by:

```
 (nearest - point).Length();

```

---
Tags: xna, c#, collision-detection
---


# Question
Title: How would I make a bullet shoot from my player to my mouse.
So far I've created an object called obj\_mouse. And my plan is whenever the player left clicks, it spawns a bullet from him toward where ever the mouse is pointing. I've got the concept down, but I'm struggling getting it to work.

Extra bits of code I'm messing around with to try and get it to work:

```
    bullet=instance_create(x,y,obj_bullet)
with (bullet) {
move_towards_point(mouse_x,mouse_y,5)
image_angle=direction
}

point_direction(obj_mouse,obj_mouse,obj_mouse,obj_mouse)
image_angle=direction

```

(In the above code, I havent attempted to specify to the program that I want the bullet to go in the direction of obj\_mouse, or rather, just the mouse. The above code works, and bullets do shoot, however the player must have the mouse on the players sprite for it to work.)

Thank you in advance for any advice given.

# Answer
> 1 votes
You need to use `Global Mouse` events.

Btw, your code

```
point_direction(obj_mouse,obj_mouse,obj_mouse,obj_mouse)

```

is very strange. You need store result, and you need use coords (not objects names)

```
direction = point_direction(x, y, obj_mouse.x, obj_mouse.y);

```

just for example

`Step End` event:

```
direction = point_deirection(x, y, mouse_x, mouse_y);
image_angle = direction;

```

`Mouse Global Left Pressed` event:

```
with (instance_create(x, y, obj_bullet))
{
    direction = other.direction;
    image_angle = direction;
    speed = 5;
}

```

---
Tags: game-maker
---


title: Why are 16×16 pixel tiles so common?

text:
# Question
Title: Why are 16×16 pixel tiles so common?
Is there any good reason for tiles (e.g. *Minecraft*'s) to be 16×16?

I have a feeling it has something to do with binary because 16 is `10000` in binary, but that might be a coincidence.

I want to know is because I want to make a game with terrain generation, and I want to know how big my tiles should be, or if it doesn't really matter.

# Answer
> 9 votes
Tiles and icons (even in UIs like window systems) are often in a size like 16x16 or 24x24 to make it easier to modify the tiles. Most times the tile size is a multiple of 8 because of the folowing reasons.

* It is relatively easy to shrink a tile with the size 32x32 to 16x16 by simply putting 4 pixels together (e.g. create the median/average of the 4 pixels). If you have a tile size like `17x17` you have difficulties to shrink the size.
* Most screen resolutions are also a multiple of 8, e.g. 1920x1200 (the typical HD resoltion for monitors) leads to a game field with 120x75 tiles (when using a tile size of 16x16).
* Calculations with 2 tiles (e.g. overlaying a terrain with a character) is easier in programming languages if the tile size is a multiple of 8. Often the exists some optimizations for such tile sizes.
* Historical reasons: Most earlier sprite engines (in home computers and game consoles) had limitation to force the tiles to be 8x8 or 16x16. *(added after comment from Code Clown)*

**TL;DR It is easier to handle tile sizes that are multipes of 8.**

So there are several reasons to use tile sizes like 16x16, 24x24 or 32x32.

---
Tags: sprites, tiles, data-structure, memory-efficiency
---


# Question
Title: Bullet Physics - Collision not working when moving btBvhTriangleMeshShape
I have a robot (btTriangleMeshShape for each component) and a chain of boxes used as a cable, which is anchored on two components of the robot. I want to rotate a robot component and when this happens, I want to twist/ roll the cable on that component. The problem is - when i rotate a robot component, collision does not work anymore with that component.

I cannot use btHullShape because of the lack of accuracy, neither btGimpact because of the complexity of computations (which gives a really unsatisfying performance). I couldn't improve enough any of these two shapes, so that is why I use btTriangleMeshShape and rotate it by code.

Also, I have replaced the btTriangleMeshShape of the rotating component with a simple static box and rotate the box. Using the box shape, collision is working with that box.

So the problem of collision not working is only when trying to rotate a (static) btTriangleMeshShape.

Here is the code I use to rotate the static body, although I don't think it's necessary (it works for box shape, not for triangle mesh shape):

```
   btTransform tr = m_dynamicsWorld->getCollisionObjectArray()[7]->getWorldTransform();
   static float angle = 0.f;
   angle += 0.1f;
   tr.setRotation(btQuaternion(btVector3(1, 0, 0), -angle));
   m_dynamicsWorld->getCollisionObjectArray()[7]->setWorldTransform(tr);

   m_dynamicsWorld->updateAabbs();
   m_dynamicsWorld->computeOverlappingPairs();

```

I have to mention that I've searched the web before and couldn't find any solution and also I'm a newbie on Bullet Physics and any graphic libraries.

Any help would by really apreciated,

# Answer
btTriangleMeshShape cannot be used as a dynamic objects as stated in the API documentation.

> The btBvhTriangleMeshShape is a static-triangle mesh shape, it can only be used for fixed/non-moving objects.

So your alternative is to represent the mesh using Collision Primitives or a collection of them.

## Single Primative

Using a singluar primitve is the easiest but loses accuraccy on complex models. For example:

You would rotate the collision box and then apply the rotation from bullet to your robot mesh.

## Multiple Primitives / Compound Collisions

The alternative is to use multiple collision primatives, choosing a base primative to rotate the mesh and to have all other primatives connected to. For example:
> 4 votes

---
Tags: c++, collision-detection, bullet-physics
---


# Question
Title: How can I tell a fragment shader to not write a particular pixel?
In a WebGL I'd like to send a screen space quad through that gets processed by a fragment shader, but have the fragment shader only write out a pixel under certain conditions (say... that it was within a circle, or that the pixel belonged to the positive side of a halfspace defined by a curve equation or something).

Is it possible within a fragment shader to say "don't write a pixel"?

I know this could be accomplished using various other methods like alpha blending, rendering this first and having it put the background color where it doesn't want to draw a pixel, or maybe doing some trick with the depth or stencil buffers. I also know i could create a bunch of geometry to match what it is that I want to render.

Is there a way though to make the fragment shader choose not to write a pixel at all?

# Answer
> 11 votes
Yes, you can `discard` in the fragment shader to avoid writing the pixel. Here's a random example I dug up from Google.

Note that this may not actually stop the fragment shader from processing (as the GPU tends to process fragments in blocks; only discarding from all fragments in a block will abandon the processing). But the fragment won't be written to the output, which is basically what you want.

You may be interested in this related question about the performance of `discard` and this one on SO.

I have no idea if this is supported in WebGL though. If it isn't, you'll need to fall back to one of your suggestions (like alpha blending; I think that would be the most straightforward).

# Answer
> 4 votes
The `discard` statement comes in handy.

You didn't say too much about your decision path, so I'll offer an example using a simple texture lookup:

```
void main() {
    gl_FragColor = texture2D(u_texture, v_uv) * u_color;
    if (gl_FragColor.a <= 0.0) discard;
}

```

(That's from some sample code I wrote before I learned about alpha blending.)

---
Tags: graphics, graphics-programming, webgl
---


# Question
Title: Unity3d Colliders not working on my characters
I have create 2 characters in maya and imported them in Unity3d. I am able to move and animate them in unity but the characters are not colliding with each others. I have tried all major colliders capsule, box and mesh. I am kind of stuck in it !

# Answer
> 1 votes
The problem while importing from maya was that the character is too big like 3x times the size of transformer robots. The collider was too small so collision was not detected correctly. Most important thing was to apply collider to the bones instead of just using on the mesh. That was the solution.

---
Tags: unity, maya, meshcollider
---


# Question
Title: Client-Server RTS networking with lockstep and lag
The peer to peer lockstep networking model would seem to indicate that everyone's input is delayed the same amount. And so this would indicate that everyone would feel the same lag in response to their input.

But in Warcraft 3 from playing many custom games it is clear that the creator of a custom game has much faster response time to their input. How can this be given the lockstep model?

# Answer
> 4 votes
I found the following comment on an article on lockstep, that should explain it http://gafferongames.com/networking-for-game-programmers/what-every-programmer-needs-to-know-about-game-networking/

> StarCraft don’t use peer-to-peer it uses client-server model with lockstep (at least warcraft 3 does so). It has the advantage what theoreticaly laggers will not affect gameplay/response latency at all (but to not let them fall behind server do timeouts so the lagger can catch up, also doing temporary local game speed increasing) and imo it’s the only and true way to do sync in RTS like games. (and for some reasons this technic isn’t good covered in the web) most articles are about FPS or peer-to-peer syncs

# Answer
> 0 votes
The server contains the actual running model of the game (the only source of truth).

Each player sends commands to be executed in the server's model, and when they see those actions take place, it's a result of the server accepting that command and echoing back the effect of it.

This echo is also broadcast to all other players in tandem.

If Player A is laggy (experiencing high latency), their actions take longer to reach the server, and their view of the game will be slightly behind the actual game.

If Player B is not laggy (fast connection, low latency), they may very well see the effects of Player A's actions before Player A can!

---

Now if we had no server, one of the player's must be the source of truth (or worse still a shared truth). This is where being laggy AND the server causes everyone else to be laggy regardless of how awesome their connection is. Being a laggy server is like being a bottleneck.

---
Tags: networking, multiplayer, rts, synchronization, packet
---


title: addChild does not work in Flash

text:
# Question
Title: addChild does not work in Flash
Have been trying to understand this problem for two weeks.

When I use addChild(movieclip) in the Main.as file, it works. When I try to use it in a function in a separate class file it does not work.

I've read about 40 different explanations, but all of them failed to explain it. I tried about 10 different suggestions, various code, but none of them worked.

Here is the code. This code is a separate file called Behavior. The main code is in Main.as.

package {

```
import flash.utils.Timer;
import flash.events.TimerEvent;
import Box2D.Common.Math.b2Vec2;
import flash.geom.Matrix;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.DisplayObject;
import flash.events.Event;
import flash.geom.Point;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
import flashx.textLayout.elements.ParagraphElement;
import flash.display.Loader;
import flash.display.Stage;

public class Behavior extends MovieClip {

    public function Behavior() {

       // didn't work. someone else's idea.
       Behavior._behavior=this;

    }

    static public function explodeOrb(explosion:MovieClip)
    {

        var myPoint:Point = new Point();
        myPoint.x = explosion.x;
        myPoint.y = explosion.y;

        explosion.parent.removeChild(explosion);

        Main._balls.push(new Ball(Main.createExplosion(myPoint.x, myPoint.y,   Constants.RADIUS_EXPLOSION), new Explosion(), Constants.WALL));
        var ballCurrent:Ball = Main._balls[Main._balls.length-1];

        //var obj:Behavior = new Behavior();
        addChild(ballCurrent);  // FAIL FAIL FAIL FAIL FAIL

    }

```

Of course it says addChild is not a property of blah blah, even though it just was able to removeChild from the same object and the object is defined.

I would just call the function from the main class with clip = Behavior.explodeOrb because then addChild DOES work.

The functions have to be static, since you can't call functions from other AS files. And I need to call them when I want them and not worry about a bunch of segregation and obfuscation.

# Answer
I'm not familiar with flash/as3.

This said, I fail to see what instance would be the parent to the child you're adding with `addChild` in a **`static`** method.

Here is the description from the documentation

> Adds a child DisplayObject instance to this DisplayObjectContainer **instance**. The child is added to the front (top) of all other children in **this DisplayObjectContainer instance**. (To add a child to a specific index position, use the addChildAt() method.)

*Your `addChild` does not work because you're in a static method, and there is no static version of the `addChild` method.*

To fix this issue I see this option: Pass in the object that should receive the new child (Main?) and call `addChild` on that object (`myObject.addChild(ballCurrent);`).

From what I understand from your question, this is a patch that could work for you. We're lacking a bit of information on what you're trying to achieve in there.
> 1 votes

---
Tags: sprites, flash, actionscript-3
---


# Question
Title: How can I generate a lightning bolt effect?
Is there an algorithm to generate a lightning bolt?

I would like an algorithm that generates a list of segment or point objects specifying where the bolt will land. The method would need a start point parameter, along with an endpoint. The bolt should have random branches coming off it, and zig-zag at random intervals. The result will be a random lightning effect that would look somewhat like this

(source: wikimedia.org)

If anyone knows of an algorithm that this may work for, help would be greatly appreciated!

# Answer
There's a fairly straightforward algorithm you can use to generate lighting bolts.

Start with a line segment between the bolt's origin (`O`) and end point (`E`)

Choose a point on that line (approximately or exactly in the middle), called `S` and split the segment into *two* line segments (`O->S` and `S->E`). Displace `S` away from the original line segment (along the segment's normal) by some small random amount. This gives you a single "bend" of lightning.

After you compute the bend, based on a small random chance you'll want to add a *third* line segment (usually an extension of the `O->S` segment). This is how you produce the "forks" in the lightning. You'll usually want to track information about the intensity of the bolt during this generation process, because you'll want the forks to be dimmer or have a more subtle blur:

Then, repeat the above process for all of the new line segments you have; you'll need to choose a repetition amount that produces shapes you like:

There's a fairly clear explanation of this technique at my friend's blog here (it's where I shamelessly stole the pictures from); it goes into additional depth about adding the glow effect as well.

Finally, there's also this NVIDIA paper that describes the same basic algorithm (also with more details).
> 33 votes

# Answer
I would recommend an alternative approach: the rapidly exploring random tree (RRT). One cool thing about it is you can get it to go around corners, or explode in all directions.

The algorithm is really basic:

```
// Returns a random tree containing the start and the goal.
// Grows the tree for a maximum number of iterations.
Tree RRT(Node start, Node goal, int maxIters)
{
    // Initialize a tree with a root as the start node.
    Tree t = new Tree();
    t.Root = start;

    bool reachedGoal = false;
    int iter = 0;

    // Keep growing the tree until it contains the goal and we've
    // grown for the required number of iterations.
    while (!reachedGoal || iter < maxIters)
    {
         // Get a random node somewhere near the goal
         Node random = RandomSample(goal);
         // Get the closest node in the tree to the sample.
         Node closest = t.GetClosestNode(random);
         // Create a new node between the closest node and the sample.
         Node extension = ExtendToward(closest, random);
         // If we managed to create a new node, add it to the tree.
         if (extension)
         {
             closest.AddChild(extension);

             // If we haven't yet reached the goal, and the new node
             // is very near the goal, add the goal to the tree.
             if(!reachedGoal && extension.IsNear(goal))
             {
                extension.AddChild(goal);
                reachedGoal = true;
             }
         }
         iter++;
    }
    return t;
}

```

By modifying the `RandomSample` and `ExtendToward` functions, you can get very different trees. If `RandomSample` just uniformly samples everywhere, the tree will grow uniformly in all directions. If its biased toward the goal, the tree will tend to grow towards the goal. If it always samples the goal, the tree will be a straight line from the start to the goal.

`ExtendToward` can allow you to do interesting things to the tree as well. For one thing, if you have obstacles (such as walls), you can get the tree to grow *around* them simply by rejecting extensions that collide with walls.

This is what it looks like when you don't bias the sampling toward the goal:

(source: uiuc.edu)

Some cool properties of the RRT once its finished:

* The RRT will *never cross itself*
* The RRT will eventually cover the entire space with smaller and smaller branches
* The path from the start to the goal can be completely random and weird.
> 14 votes

---
Tags: algorithm, graphic-effects
---


# Question
Title: Custom Editor - keep default look but add more
What I would like to know is if there is a easy way using OnInspectorGUI, to replace the inspector with one that includes just one or two additional fields (so that it looks identical to the non-custom editor, except for the addition of one or two fields at the end). It seems like such a bother to recreate every field manually when I just want to add one little thing - so perhaps this is already a thing.

Or is there any way to easily tell unity to do it's default drawing for a specific type of field? When I was playing with this before, I had to commit to exactly what was to be shown, and I would need to manually write each field out --- which is bothersome if the public fields in my class(s) change - and they do frequently during development.

tl;dr - is there any way to simulate the default behavior of the inspector in a custom editor?

# Answer
Call this function from inside OnInspectorGUI method to draw the automatic inspector. It is useful you don't want to redo the entire inspector, but you want to add a few buttons to it.

http://docs.unity3d.com/ScriptReference/Editor.DrawDefaultInspector.html

```
// This example shows a custom inspector for an
// object "MyPlayer", which has a variable speed.
using UnityEngine;
using UnityEditor;
using System.Collections;

[CustomEditor(typeof(MyPlayer))]
public class Example : Editor
{
    public override void OnInspectorGUI()
    {
        MyPlayer targetPlayer = (MyPlayer)target;
        EditorGUILayout.LabelField ("Some help", "Some other text");

        targetPlayer.speed = EditorGUILayout.Slider ("Speed", targetPlayer.speed, 0, 100);

        // Show default inspector property editor
        DrawDefaultInspector ();
    }
}

```
> 6 votes

---
Tags: unity, gui
---


# Question
Title: Spatial Partitioning - Objects larger than cell?
I'm developing a top down 2D tile based game. Recently I started working on collision detection and have gone down the route of simply using spatial partitioning.

Each object belongs in a cell and checks the neighbouring cells for collisions like this.

However, I realise I'm absolutely going to need to have some collision boxes that are bigger than a single cell.

Are there better algorithms for what I need or is there a simple work around I'm not seeing?

EDIT: multiple objects can be in a single cell at the same time.

# Answer
The way I handle this is each cell has a list of entities which inhabit it and each entity has a list of cells / tiles it inhabits.

This way a cell can contain multiple entities and an entity can inhabit many cells.

Whenever an entity moves it checks for collisions with other entities which inhabit the cells it is moving through.

Once it has finalised its position it removes itself from any cell lists, clears it own list of cells.

Then for every cell it currently inhaibts it adds itself to that cells list and the cell to its own list.

```
private void updateInhabitedTiles(){
    removeFromMap();

    MapTile bottomLeft = inhabitedTileMap.mapToTile(
            position.x,
            position.y
    );

    MapTile topRight = inhabitedTileMap.mapToTile(
            position.x + dimensions.x,
            position.y + dimensions.y
    );

    for(int x = bottomLeft.xPos; x <= topRight.xPos; x++){
        for(int y = bottomLeft.yPos; y <= topRight.yPos; y++){
            MapTile inhabitedTile = inhabitedTileMap.getTile(x, y);
            inhabitedTile.addEntity(this);
            inhabitedTiles.add(inhabitedTile);
        }
    }
}

private void removeFromMap(){
    for(MapTile mapTile : inhabitedTiles){
        mapTile.removeEntity(this);
    }
    inhabitedTiles.clear();
}

```

When stress testing this I had approximately 9000 colliders before I noticed any slowdown and the cell / tile resolution was 16 pixels.

I used a LinkedHashSet for my lists of Tile Inhabitants (for cells) and Inhabited tiles (for entities).
> 3 votes

# Answer
With the spatial-binning approach, there's a couple of ways to manage cell-size vs object-size.

* Make the cells big enough, so that cell edge \>= half the biggest object, and always check adjacent cells.
* Check more than 1 cell away. Radius 1 checks 9 cells, radius 2 would check 25 nearby cells, and so on.
* Put objects "into" more than one cell. When moving, you have to remove from stern-side and add to the bow-side of the motion. Or just always remove them all and re-add them.
* For non-moving objects (big walls) break them up into smaller pieces (same as "put into more than one cell," but extra easy if not moving).

I've been leaning towards "make cells big enough" for my current project.
> 1 votes

---
Tags: collision-detection, space-partitioning
---


# Question
Title: Unity Raycast shoots right through some objects
I made a melee combat system for my game. The code looks like this:

```
var hit:RaycastHit;
    if(Physics.Raycast(transform.position,transform.forward,hit)) {
        if(hit.distance<=2.0) {
            Debug.LogError("Hit!");
            Debug.LogError(hit.collider.tag);
            if(hit.collider.tag=="Enemy") {
                Instantiate(bloodFX,hit.transform.position,transform.rotation);
                hit.transform.SendMessage("ApplyDamage",25,SendMessageOptions.DontRequireReceiver);
            }
        }
    }

```

However, when an object with the tag "Enemy" stands in front of a "Tree" object, the log tells me that it's hitting the tree tag and not the enemy. What am I doing wrong here? The collision boxes are all correct.

Thanks!

P.S. This is for the ludum dare that ends in 4 1/2 hours so I have to fix this quickly.

# Answer
> 3 votes
Hope this may help : (from Physics.Raycast docu)

Notes: Raycasts will not detect colliders for which the raycast origin is inside the collider. If you move colliders from scripting or by animation, there needs to be at least one FixedUpdate executed so that the physics library can update it's data structures, before a Raycast will hit the collider at it's new position.

# Answer
> 1 votes
I suggest for a quick fix just implement your weapon using collision boxes with trigger assignments then go from there

```
void OnCollisionEnter(Collision col){
    if(col.collider.gameObject.name == "Enemy" /*or tag*/){
      //apply damage!
    }
}

```

P.S Thanks for helping me fix send message haha I hope this helps you!

# Answer
> 1 votes
Instead of `Physics.Raycast`, use `Physics.RaycastAll`.

I'm pretty sure I've run into this same problem and I don't see it in the documentation for `Raycast` but it's in `RaycastAll` that **order is not guaranteed**. I assume this carries over to `Raycast` as well. Even if it doesn't and this doesn't solve the issue for you it should be able to assist because it will give you a full list of everything that IS triggering a hit.

`RaycastAll` returns a `RaycastHit[]` you can simply iterate over, checking their distances.

Documentation: http://docs.unity3d.com/ScriptReference/Physics.RaycastAll.html

---
Tags: unity, javascript, raycasting, unityscript
---


# Question
Title: What are the steps for creating level in Libgdx with Box2d?
I have been trying to learn game programming for a week, although I have a good knowledge of programming.

I don't understand some steps of game design. I'm recently working to clone the iSlash game.I'm so confused about creating level like this one.

For example , this is a level of this game.

This crab or whatelse must be designed in tools like photoshop, am I right? There are objects which can move around, but inside this crab so I think, I can use Box2D.

Here is my temporary design this game.. I want to use a my own object and move balls inside this object,but the problem is here.I can't imagine that how I should do this? If I use mesh like below code,

```
mesh.setVertices(new float[] { -0.5f, -0.5f, 0,
                                        0.5f, -0.5f, 0,
                                        0, 0.5f, 0 });

```

I think , It's very very hard way to create a level and I don't know what my object's coordinate.It takes forever.

In brief, What should I do? What tools should I use? How do big games like Angry Bird or above game (iSlash) solve this? Can I use tiled map editor for this problem?

# Answer
> 1 votes
**Level designer is a full time job.**

Using an editor is really **mandatory** if you don't want to lose a lot of time. Most professional games like angry birds probably have teams that develops dedicated custom tools to ease their level designers job.

**Tiled :**

If i remember well, with Tiled Editor you can place shapes and manually set properties to them. You could use the xml output from tiled and write a custom loader to instantiate your physic objects with this data, it will faster and cleaner than to hardcode your objects in your code but i don't think this would be the most productive way to do it.

**Box 2D editors :**

There is several editors dedicated to create Box 2D game levels. I don't know them well enough to recommend one, but, if you google "Box2d Editor" or "Box2D Level Design tool", you should find plenty of them. Search for one that is easy to use & that can output a file format that you can easily parse with libgdx (json or xml).

So here is what i found :

**1 - RUBE :**

Seems like a really complete level design tool. Not free though, but affordable. So i'd recommend to test the trial and see if you can easily use the output for your libgdx game.

**2 - Physics Editor :**

I also found this other **tool**, seems interesting and complete. However it's doesn't seem to be free either, but there is a free trial.

**3 - Physics Body Editor :**

Here is also an interesting free tool to create box 2d shapes that even come with a loader for libgdx. It doesn't seem to be a complete level design tool, but i would try it if i were you, hopefully it will still work with the current libgdx version:

---
Tags: libgdx, game-design, box2d, assets
---


# Question
Title: Unity 2d - Destroying foreign object from script + seek explanation about destroying objects
I have simple emmiter which sending enemies toward player in center of screen. Player can shoot missile (also emmiter). I want to destroy enemy AND missile in same time.

Here is my code attached to Enemy

```
 public GameObject player;
 public GameObject missile;

 void OnTriggerEnter2D(Collider2D collider)
 {
     if (collider.gameObject.name == player.name)
     {
         Destroy(gameObject);
         Application.LoadLevel("Retry");
     }

     if (collider.gameObject.tag == missile.tag)
     {
         Destroy(gameObject);
         Destroy(missile.gameObject);
         Score.killed++;
     }
 }

```

But after missile hit enemy, error in unity occur

> Destroying assets is not permitted to avoid data loss.

Well... im programmer but new in unity. So my question is not that simple : i think im destroying object which is still in use. Am i right? How can i destroy both objects? When i can destroy GameObject? I tried to use this

```
GameObject mssle = Istantiate(missile,missile.transform.position,Quaternion.identity);
Destroy(mssle);

```

as was suggested by good people on unityanswers. Didnt work, missile is stil alive and my answer got rejected. Am i destroying whole prefab or what? This is little confusing for me

# Answer
I assume you assign a Prefab to `public GameObject missile` in the inspector. When you try to destroy `missile` inside of your `OnTriggerEnter2D` method, the error message does make sense, since you're trying to destroy a prefab and not an instance.

Instead of trying to destroy `missile`, you should destroy the object that collided with your GameObject.

So, replace: `Destroy(missile.gameObject);` with: `Destroy(collider.gameObject);` (you can be sure to destroy a collided missile here, since you already checked the matching tag in your if statement: `if (collider.gameObject.tag == missile.tag)`)
> 1 votes

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


# Question
Title: Why is the root of the character rig the pelvis?
When creating character rigs for video games we always set the root of the rig and all the kinematic chains to the pelvis of the character. Is their a specific reason that we do that or is it by convention?

What is the reasoning behind this?

# Answer
> 14 votes
As far as I know, this is because the humans centre of mass is near the pelvis. This is just a convention, but almost everyone does it. But it makes sense to choose a point that is at the middle (not a foot for example) and doesn't move too much.

Let's say you choose the foot as root. If you want to do a walk animation, you'll move the foot and everything moves with it. You have to move it back then. You won't have this situation that much, if you choose the pelvis.

---
Tags: animation, skeletal-animation, character, rigging
---


# Question
Title: Why value 1 in OrthographicCamera viewPort width?
So, I read that `camera = new OrthographicCamera(1, h/w);` creates a camera with an appropriate width and height for the field view.. However, I can't understand that value 1 for the viewport width, does a value 1 means full width?

# Answer
> 1 votes
You need to distinguish between the gl-viewport and the cameras viewport. The GL-viewport somehow defines the area on the Display, while the cameras viewport defines the area in the game world.

So a camera with a viewport of (1/1) can see 1 unit of your world in width and height and projects it to the gl-viewport.

For example: You have a Camera with a viewport of (16,9) and it's center is at (8, 4.5), the middle. Now you can see all objects form P(0,0) to P(16,9). Objects outside this area are not visible to you.

You may ask, which values you should use. That depends on the game, but to find a good value, you may think about them like meters. How many meters of your gameworld you want to see at once? For example if you have a 1m tall character. How much space should he take on screen? If it's 1/9 of the screen, your viewport hight should be 9.
One important note: You should definitly use Viewports, they have some additional functions, which are usefull in many cases.

---
Tags: libgdx, camera, viewport
---


# Question
Title: How to generate objects at specific intervals and make them move with same speed?
I'm creating an infinite runner where character has to jump on randomly generated pillars. The pillars are positioned with a gap between each of them. The gaps are dmin and dmax. In addition to this, i want the pillars to move to the left of screen with increasing velocity. But they all need to move with same velocity so that the gap in between them is maintained. I have the script as follows: pillar is a prefab.go is an empty gameobject which will later be used to Instantiate pillars. first is the first pillar, manually positioned in the scene.

```
using UnityEngine;
    using System.Collections;

    public class GM : MonoBehaviour {
        float tempx,dmin=1.3f,dmax=3.5f;
        GameObject[] bins;
        Vector2 speed,pos,tempvel;
        public GameObject pillar,go;
        public Transform first;

        // Use this for initialization
        void Start () {
            speed = new Vector2 (-0.005f,0);
            tempx = first.transform.position.x;
            tempvel = new Vector2 (0, 0);
        }

        void Update () {
            if ((Vector3.Distance (go.transform.position,transform.position)<40f)) {

                tempx+=Random.Range(dmin,dmax);

                pos=new Vector2(tempx,-2.22f);

                go=Instantiate(pillar,pos,Quaternion.identity) as GameObject;
            }

            bins = GameObject.FindGameObjectsWithTag("trash");

            tempvel += new Vector2 (-0.0005f, 0);
            foreach (GameObject bin in bins) {

                //bin.GetComponent<Rigidbody2D>().velocity+=new Vector2(Random.Range(-0.005f,-0.05f),0);

                bin.GetComponent<Rigidbody2D>().velocity+=tempvel;
            }

        }
    }

```

Problem is, the speed of pillars increases way too fast. They move to the left at nearly invisible speeds. Also, after a certain speed, the gap between the pillars increases. They become so far apart, one is in camera view, another is somewhere far away.

Is there a way to accomplish this?

# Answer
> 2 votes
Why don't you make the pillars children of some parent object and move that instead. You can use `Transform.SetParent` to achieve this, and then you only need to move the parent and the distance between the pillars will stay the same.

You can use the following to control the acceleration.

```
float addingrate = 0.5F;
float nextadd = 0.0F;

if (Time.time > nextadd)
{
    nextadd = Time.time + addingrate;
    bin.GetComponent<Rigidbody2D>().velocity += tempvel;
}

```

---
Tags: unity
---


title: Intersystem communication in a ECS game

text:
# Question
Title: Intersystem communication in a ECS game
Apologies if this question has been answered before, but after relentless searching I couldn't find anything.

As many, I've recently jumped on the ECS-bandwagon, and I am currently killing some time by making a modest ECS-game. The game is a somewhat simple 2D-platform game. It is programmed in plain JS.

The layout of the game is essentially as following:

The core of the game is the Engine, the Engine runs the game-loop and holds an EventManager, responsible for raising events, and an EntityManager, responsible for containing all components of all entities.

All logic is done by systems. The systems registers event-handlers (i.e. member-functions) with the EventHandler for specific EventTypes, which gets called when an event of that type is raised.

For example:

```
this.eventManager.registerHandler(EventType.EVENT_RENDER, this.render, null, this);

```

I recently switched from calling all systems relevant functions explicitly in the Engine to this pattern.

---

But over to my problem and question.

For rendering I have a RenderSystem. This system contains references to several type of drawable/animatable-components which it, you guessed it, renders.

Until recently, this system also contained a reference to **another system**, MapSystem, which spatially indexes all entities. The reason for this reference was to be able to call a function along the lines of

```
mapSystem.search(frame_bound);

```

effectively pruning away all entities not needing to be rendered.

So I have a couple of questions regarding this:

1. Is it very bad practice for systems to communicate directly? Something about it just doesn't smell right to me.

I see how it might severely complicate your code if you have say 100 systems, and each system holds references to many of the other systems. Hello O(n^2).
2. If I am not to hold inter-system references, how do I perform communication like described above?

---

My initial thoughts was to create an entity whose primary purpose were to hold the necessary information (i.e. all entities currently in the frame). Then let MapSystem write to and RenderSystem read from this entity.

But this also seems to be rather unclean to me. Especially as MapSystems search function might be useful to call in many different contexts. Creating an entity per calling-context doesn't really seem like a good way to go about it either.

---

TL;DR: Is it bad for systems in a ECS-game to communicate directly and hold references to each other?

# Answer
Basically speaking, your systems should not need to talk to each other. There may be cases where systems implicitly interact, but this interaction should not be explicit. If you **need** to have systems interact with each other, then you probably did not define the systems properly.

Before I dig into some examples to illustrate the point I want to define what kind of entity-component system I am talking about. You have entities that do nothing and components that define their behavior. Actual behavior is implemented in Systems. because that is the efficient thing to do. Entities have properties and events, which may be read, written or triggered by multiple components.

---

Let's assume that you are implementing a missile. The missile's basic behavior is controlled by a guidance component (a script), the actual motion is controlled by a rigid body physics component, detonation is controlled by a trigger component (a script), the visual representation is done through a visual mesh component and the sound is emitted through a point sound component. The guidance component sets the force vector property and the rigid body physics moves the entity and thus also sets position and orientation (among others). The trigger component listens to the collision event, so when a collision with an other entity happens it springs into action and ensures that mayhem happens.

To implement the missile, the graphic, sound, physics and scripting system are involved. Actual interaction is only happening though their components.

---

Let's assume you have a photo realistic game and the graphic system is the primary means to render the scene. You want a map as overlay. There are two ways to implement this, either you extend the graphic system to also draw maps (bad) or you add a mapping system (good). To access the actual graphic device the mapping system does not call the graphic system. You extract the graphic device (hardware abstraction) from the graphic system and then pass the mapping system and the graphic system the graphic device and they use it in turn.

---

Finally I find the notion that the graphic system asks the mapping system for a list of visible items odd. The graphic system should maintain a list of visible items, preferably stored in some specially optimized structure like a quad tree. You may get away with it in the context of a 2D game, but the moment you go 3D you get into real trouble.
> 4 votes

---
Tags: entity-system, entity
---


# Question
Title: Rectangles clear each other when moving on canvas
I am having this problem after moving rectangles, they seem to delete one another. Most probably it is a problem with clearRect(...) method. This is the clean function I am using:

```
clean: function(element){
        // All default values clean all the screen
        if(typeof element.x === 'undefined'){
            element.x = 0;
        }

        if(typeof element.y === 'undefined'){
            element.y = 0;
        }

        if(typeof element.width === 'undefined'){
            element.width = canvas.width;
        }

        if(typeof element.height === 'undefined'){
            element.height = canvas.height;
        }

        // In case values are entered
        if(element.type === 'rectangle'){
            ctx.clearRect(element.x,element.y,element.width,element.height);
        }
    }

```

This is the rendering

```
rect: function(element){
    // Check if color is defined
    if(typeof element.color === 'undefined'){
        element.color = 'black';
    }
    else{
        ctx.fillStyle = element.color;
    }

    // Draw the rectangle
    ctx.fillRect(element.x,element.y,element.width,element.height);
}

```

# Answer
Clearing the screen is only one half of the puzzle. I'm going to bet you also only re-draw the rectangles **if**/when they move. To confirm, you could make the red cube continue to move across the screen, I would expect there to be no graphical glitches.

**The solution:** Draw everything (on screen) every frame. There are fancier ways to deal with this, but they are not necessary for most, if not all, projects.
> 2 votes

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


# Question
Title: How to convert a number from one min\max set to another min\max set?
I'm doing terrain generation and I have a perlin library that is giving me random numbers between -1 and +1. I want to convert this to the scale of 0-255. What is the proper way to do this?

# Answer
Base formula is:

```
Result := ((Input - InputLow) / (InputHigh - InputLow))
          * (OutputHigh - OutputLow) + OutputLow;

```

Your case:

Result := ((**Input** \- **-1**) / (**1** \- **-1**) * (**255** \- **0**) + **0**;

From here you can optimize the conversion if your coefficients are static, but compiler will probably do it by itself as well.

Result := ((**Input** \- **-1**) / **2**) * **255** \+ **0**;

Result := **Input** * **127.5** \+ **127.5**;
> 31 votes

# Answer
The range `-1` to `1` is a total range of `2`. So you need to scale it appropriately to get to `255`. Something like this:

```
(randomPerlin + 1.0) * 127.5

```

So you first add `1`, to get to `0..2` then multiply with `127.5` to get a range of `0..255`
> 10 votes

# Answer
```
oldRange = oldMax - oldMin
newRange = newMax - newMin

newValue = ((oldValue - oldMin) * newRange / oldRange) + newMin

```

Hope this helps.
> 6 votes

# Answer
Through the power of scaling and bias.

From your value, subtract the minimum value of your range. That will give you a value in the range \[0..2\].

Divide that by the width of the source range, giving you a value in the range \[0..1\].

Multiply that by the width of the target range, giving you a value in the range \[0..255\].

Add the base of the target range to get a value in the target range, which for this case is the same as the previous step.

In summary:

```
            (v - (-1.0))
v' = 0 + ---------------- * (255 - 0)
          (1.0 - (-1.0))

```
> 3 votes

# Answer
Translate the input *range* so we get the min to zero by adding 1 (the negative value of the min input) -1 .. 1 -\> 0 .. 2

As the output range starts with zero, do nothing for that.

Scale the new input range so it fits the output range, this is easy as they now both starts at zero: multiply the value by 255/2 0..2 * 2/255 -\> 0..255

Done!

Example:

0.5 will go: (0.5 + 1) * 127.5 = 191.25 -0.5 will go: (-0.5 + 1) * 127.5 = 63.75
> 2 votes

# Answer
Lets say `x` is original input and `y` is expected output. We have at least **two points** (x,y) (-1, 0) (1, 255)

Since we want to do a **linear interpolation** we can look into the equation of form `y = m*x + c`

With above two points, we can solve for `m` and `c` Once that is done, you get the transform equation.

Note this method works for other types of equations too. e.g If you want a exponential or quadratic interpolation.
> 2 votes

---
Tags: mathematics
---


# Question
Title: Unity3D : Unity fails to detect null objects
im instantiating an object which is gonna play the background music for my game. On the Awake() function I check if there is a gameobject with the tag "MusicPlayer" on it, and if there isn't any I instantiate a prefab (the music player prefab with the tag "MusicPlayer" on it).

Now my issue is this :

It keeps instantiating the prefabs even if there is one or more music players(objects with the "MusicPlayer" tag on them). Why is this happening ?

Here is my code :

```
var musicPrefab : Transform;

function Awake()
{
    if(GameObject.FindWithTag("MusicPlayer") == null)
    {
        Instantiate(musicPrefab,transform.position,transform.rotation);
    }
}

```

I also have a script that makes the music player not be destroyed upon the level reload. This is the script :

```
function Start()
{
    DontDestroyOnLoad (gameObject);
}

```

Thank you for your time, I hope I was clear enough.

# Answer
Ehm...

I don't know whats going on but this is what I did to fix this :

```
var musicPrefab : GameObject;
var muter : GameObject;

function Awake()
{
    if(GameObject.FindWithTag("MusicPlayer") == null)
    {
        Instantiate(musicPrefab,transform.position,transform.rotation);
        DontDestroyOnLoad (musicPrefab);
        muter = GameObject.FindWithTag("MusicPlayer");
    }

    muter = musicPrefab;
}

```

You can compare the first script with this one. I don't know how I did it but it works.
> 0 votes

# Answer
The FindWithTag will throw an error if the Tag is not defined (or perhaps spelled wrong). I think that might have been why it did not work at first, but works now :)
> 1 votes

---
Tags: unity, unityscript
---


title: Libgdx box2d crashing

text:
# Question
Title: Libgdx box2d crashing
im making a game in libgdx which i having a bunch of circle bodies floating around in space and when the player's body crashes into another body, that body deletes and creates two smaller bodies around its location.

problem is that the game randomly crashes when i'm colliding with more than a few bodies. i tried limiting the amount of bodies in the scene to less than 10 but then it still crashes just after a long period. All the crashes happen on collision of the play body with a different body and when i comment out the code that generates the bodies the crashing stops.

I do my spawning and deleting before world.step. look:

```
@Override
public void render() {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    BlobAlien.CleanUpDeadBlobs(this);
    BlobAlien.BirthChildren(this); // crashing stops when i delete this line
    if(TimeUtils.timeSinceMillis(lastSpawn) > 5000) {
        BlobAlien.SpawnRandom(this);
        lastSpawn = TimeUtils.millis();
    }

    world.step(1 / 60f, 8, 3);
    renderer.render(world, camera.combined);

    batch.setProjectionMatrix(camera.combined);
    batch.begin();

        BlobAlien.RenderHorde(batch);
        ship.render(batch);

    batch.end();

}

```

and here are my static methods:

```
public static void RenderHorde(SpriteBatch batch) {
    for(BlobAlien blob : blobs)
        blob.render(batch);
}

public static void BirthChildren(App app) {
    if(birthQueqe.empty())
        return;

    while(!birthQueqe.empty()) {
        BlobAlien blob = birthQueqe.pop();
        if(totalWeight >= WEIGHT_LIMIT) {
            blob.CreateMe();
            blobs.add(blob);
        }
    }
}

public static void CleanUpDeadBlobs(App app) {
   killCount += deadQueqe.size();
   while(!deadQueqe.empty())
       app.world.destroyBody(deadQueqe.pop().body);
}

```

here are mt non static method

```
private void CreateMe() {
    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.DynamicBody;
    bodyDef.gravityScale = 0.5f;
    CircleShape ballShape = new CircleShape();
    ballShape.setRadius(size);
    totalWeight += weight;

    SetBody(app.world.createBody(bodyDef));
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = ballShape;
    fixtureDef.density = 1;
    fixtureDef.friction = 0;
    body.createFixture(fixtureDef);
    ballShape.dispose();

    body.setTransform(startPos, 45);
    sprite = new Sprite(app.blobImage);

    birthDay = TimeUtils.millis();
}

```

thanks for reading any explanation on how Box2d works and what makes it crash would be greatly appreciated. I'n not expecting too much from a physics engine I think it should be able to do a lot more than what I'm trying to do here if it has such reputation and is so widely used. correct me if I'm wrong.

BTW I'm running java 8 on manjaro linux 64 bit using intellij idea and I'm aiming for this game to run on android phones.

thanks again :)

*Edit*

this is the console output of the crash

```
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007ff5c0e0698b, pid=4700, tid=140693673539328
#
# JRE version: OpenJDK Runtime Environment (8.0_31-b13) (build 1.8.0_31-b13)
# Java VM: OpenJDK 64-Bit Server VM (25.31-b07 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C  [libgdx-box2d64.so+0x2198b]  b2BlockAllocator::Allocate(int)+0x4b
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /home/amit/Documents/blobmob/hs_err_pid4700.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

```

and this is the log file generated from the crash

http://pastebin.com/vCLYi98d

here is my collision listener

```
world.setContactListener(new ContactListener() {
        @Override
        public void beginContact(Contact contact) {
            GameObject a = (GameObject)contact.getFixtureA().getBody().getUserData();
            GameObject b = (GameObject)contact.getFixtureB().getBody().getUserData();
            if(a!=null && b!=null) {
                Vector2 contactPos = contact.getWorldManifold().getPoints()[0];
                Vector2 va = contact.getFixtureA().getBody().getLinearVelocityFromWorldPoint(contactPos);
                va.sub(contact.getFixtureB().getBody().getLinearVelocityFromWorldPoint(contactPos));
                float force1 = va.len();
                a.OnCollide(b, force1);
                b.OnCollide(a, force1);
            }
        }

        @Override
        public void endContact(Contact contact) {
            GameObject a = (GameObject)contact.getFixtureA().getBody().getUserData();
            GameObject b = (GameObject)contact.getFixtureB().getBody().getUserData();
            if(a!=null && b!=null) {
                a.OffCollide(b);
                b.OffCollide(a);
            }
        }

        @Override
        public void preSolve(Contact contact, Manifold oldManifold) {

        }

        @Override
        public void postSolve(Contact contact, ContactImpulse impulse) {
            Fixture fixtureA = contact.getFixtureA();
            Fixture fixtureB = contact.getFixtureB();

            GameObject a = (GameObject)contact.getFixtureA().getBody().getUserData();
            GameObject b = (GameObject)contact.getFixtureB().getBody().getUserData();
            if(a!=null && b!=null) {
                if ((a.name.contains("HammerShip") && b.name.contains("Blob"))
                        || (b.name.contains("HammerShip") && a.name.contains("Blob"))) {
                    if (impulse.getNormalImpulses()[0] < 1) {
                        StickyInfo si = new StickyInfo();
                        si.b = fixtureA.getBody();
                        si.a = fixtureB.getBody();
                        weldsToJoin.add(si);
                    } else if (impulse.getNormalImpulses()[0] < 1) {
                        StickyInfo si = new StickyInfo();
                        si.b = fixtureB.getBody();
                        si.a = fixtureA.getBody();
                        weldsToJoin.add(si);
                    }
                }
            }
        }
    });

```

# Answer
Had the same problem with the following code:

```
private void restart() {
    setScreen(new FooScreen);
}

```

Solved it simply by wrapping it in

```
private void restart() {
    Gdx.app.postRunnable(() -> {
        setScreen(screen);
    });
}

```

Hopefully that will help you.
> 0 votes

# Answer
That happens in native body creation, and in your code only these lines are directly connected with that:

```
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.gravityScale = 0.5f;

SetBody(app.world.createBody(bodyDef));

```

Box2d manual recommends to set body positions from the beginning, avoiding putting multiple bodies to the same point.

> Caution Do not create a body at the origin and then move it. If you create several bodies at the origin, then performance will suffer.

It speaks only of performance, not crashes, but since the problem is related to body creation, and I can't see any other problems with your code, why don't you add something like this:

```
  bodyDef.position.set(startPos)

```

and see if that fixes it.
> 0 votes

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


# Question
Title: Sample() returns (0, 0, 0) for normal map 90% of frames
I'm having some trouble reading the values from my Normal map in my lighting fragment shader.

The relevant part of the shader code is as follows:

```
Texture2D NormalGB : register(t0);
Texture2D DiffuseGB : register(t1);
Texture2D SpecularGB : register(t2);
Texture2D PositionGB : register(t3);

SamplerState NormalSampler : register(s0);

void GetGBValues(
    in int2 screenPosition,
    out float3 normal,
    out float3 diffuseAlbedo,
    out float3 specularAlbedo,
    out float specularPower,
    out float3 position)
{

    int3 screenPos3 = int3(screenPosition, 0);
    normal = normalize(NormalGB.Sample(NormalSampler, screenPosition).xyz); // HERE
    diffuseAlbedo = DiffuseGB.Load(screenPos3).xyz;
    float4 specularValues = SpecularGB.Load(screenPos3);
    specularAlbedo = specularValues.xyz;
    specularPower = specularValues.w * 50.0f;
    position = PositionGB.Load(screenPos3).xyz;
}

```

However, in 9 frames out of 10, normal is set to `{0. 0, 0}`. I've tried the code under the reference driver too, and get the same issue.

What's really weird is that if I change the line marked `// HERE` to a simple `.Load` call, the code works perfectly (except the obvious fact that I get no interpolation of normals). The sampler that is bound at time of the draw call (according to the graphics debugger) is:

```
D3D11 Sampler State (obj:18)
AddressU D3D11_TEXTURE_ADDRESS_WRAP
AddressV D3D11_TEXTURE_ADDRESS_WRAP
AddressW D3D11_TEXTURE_ADDRESS_WRAP
BorderColor (0.000f, 0.000f, 0.000f, 0.000f)
ComparisonFunc D3D11_COMPARISON_NEVER
Filter D3D11_FILTER_ANISOTROPIC
MaxAnisotropy 4
MaxLOD 340282346638528860000000000000000000000.000f
MinLOD 0.000f
MipLODBias 0.000f

Device obj:3

```

And finally, the normal-map (rendered to a texture by the previous pass):

# Answer
> 1 votes
`screenPosition` is not at the right scale for texture coordinate lookup. `Texture2D::Sample` expects texture coordinates (`0..1`) while `Texture2D::Load` expects *texel* coordinates (`0..[Width or Height]-1`). So you're probably sampling way off the edge of the texture and either hitting the border color, or clamping to the edge which happens to be black.

As a temporary solution, you can simply scale `screenPosition` by some fixed amount, e.g. `NormalGB.Sample(NormalSampler, screenPosition * 0.01f)`.

The right solution though is to add an additional `float2` texture coordinate input, usually associated with the `TEXCOORD` semantic name. This should be set in your vertex data to have values between 0 and 1, which are then interpolated in the pixel shader.

---
Tags: directx, directx11, hlsl, fragment-shader
---


# Question
Title: Can glsl main() have params or return a value?
I haven't ever seen anyone declare main as anything but void main() or void main(void) but I'm curious, is it possible to have a parameter or return value?

# Answer
No, glsl can't have parameters in the `main` function (as well as return values).

The doc says:

> Just like in C/C++, execution of a shader begins with the function main. **This function takes no parameters and returns no values.**
> 5 votes

---
Tags: glsl
---