title: Jump-through & drop-down platform

text:
# Question
Title: Jump-through & drop-down platform
I'm creating platforms in my game where the player can:

1) Jump through them from the bottom and land on top of them

2) While on top of them, drop down through them

I've been able to get #2 working just by disabling the contact using contact-\>SetEnabled(false) and this has worked fine. I'm mainly having some issues on the best way to handle #1. Here's the basic idea I have, though there's still some things that I need to concretely figure out. (Note: The logic below is very Box2D specific, but should apply to most physics engines):

* Add 4 sensor fixtures to the 4 sides of the main fixture that extends a small amount past the main fixture
* When the top, left, or right sensor fixtures make contact with a platform, disable the contact by using contact-\>SetEnabled(false) and set a boolean flag inside the Sprite object indicating that the Player is passing through the platform
* When the bottom fixture ends contact with the platform, disable the boolean flag

This would basically make the top, left, and right fixtures act as enablers for the pass through logic and the bottom fixture act as the disabler. So when the player is falling back down from their jump, the bottom fixture will make contact, but won't disable the contact.

This makes sense on paper, but I can think of a few corner-case issues that might arise from this. Before I start plugging down this path, does anyone have any suggestions that might make my plan better or even a completely different way of doing it?

# Answer
I was actually able to accomplish this by doing the following (there might be a better way than this, but it worked). This answer below is a bit specific to Box2D, as this was the original question's context. Here are the requirements we want

* When we make contact with the top of a platform, we want to enable the collision and stop the player
* If the player is trying to drop down and they are on top of a platform, disable the collision and let them fall
* The player should only be able to drop down through one platform at a time
* If the player is jumping upward into a platform, only enable the collision if the player ends up making it higher than the top of the platform

**Bullet-list steps:**

* Make a variable called **groundedPlatform** and a boolean flag called **isDroppingDown** on the player
* Add a sensor fixture to the player's bottom
* Add a sensor fixture to the platform's top
* In the player's Update method, check if the player is grounded and makes the action to drop down (Down button + Jump button for my game), set **isDroppingDown** to true
* In the BeginContact listener, if the two fixture's are the player's bottom sensor fixture and the platform's top sensor fixture AND the player's bottom is \< the platform's top, set **groundedPlatform** equal to that platform
* In the PreSolve listener, if the other fixture is part of a platform:
    + If isDroppingDown == true, contact-\>SetEnabled(false)
    + Else if the platform is **NOT** the same as **groundedPlatform**
        - If the player's bottom \< platform's top, set **groundedPlatform** equal to this platform
        - Else contact-\>SetEnabled(false);
* In the EndContact listener, if the other fixture is part of a platform AND the platform is the same as **groundedPlatform**, set **groundedPlatform** equal to null and isDroppingDown = false

**Psuedocode**:

```
Platform* groundedPlatform;
bool isDroppingDown;

Update() {
    if (player is grounded && player is pressing (Down key + jump key)) {
         isDroppingDown = true;
    }
}

BeginContact() {
    if ((player's bottom < platform's top) && (player's bottom sensor in contact) && (platform's top sensor is in contact))
        groundedPlatform = platform;
    }
}

PreSolve() {
    if (platform is other contact) {
        if (isDroppingDown) {
            contact->SetEnabled(false);
        }
        else if (groundedPlatform != platform) {
            if (player's bottom < platform's top) {
                groundedPlatform = platform;
            }
            else {
                contact->SetEnabled(false);
            }
        }
    }
}

EndContact() {
    if ((groundedPlatform is in contact))
        groundedPlatform = null;
        isDroppingDown = false;
    }
}

```
> 1 votes

# Answer
I'm pretty sure you can deal with this by ignoring the collision if the y-component of the velocity is positive (the player is moving upward).

Alternately you might be able to use the collision filtering flags. One-way floors are given their own contact group, and the player object can set/unset whether or not they collide with this group based on their vertical velocity.
> 2 votes

---
Tags: c++, box2d, platformer, physics-engine, jumping
---


# Question
Title: I need to find intersection point of a vector in an axis aligned rectangle
I need some help, I have one vector in a rectangle like following

(Ops, first A2 point on the top should be A1, assume it is A1)

Let's say the vector is like above It doesn't have intersection point actually, Basically, I need to find the point A1 and A2

I'm using cocos2d-x but framework specific solutions are not mandatory Thanks

# Answer
> 1 votes
The goal is to project the vector onto the correct sides of the rectangle. Using the tangens function we're already halfway done. The rest is basic trigonometry.

**Input data**
Depending on how you store the rectangle, we have to transform the input data first. This method expects a rectangle that is defined solely by it's size (width `w` and height `h`). It's top left corner lies on the origin \[0,0\]. The Y-axis of the coordinate system expands downwards (1).

We expect the point `p` to always be inside the rectangle. The angle is defined in radians.

```
#include <cmath>
#include <utility>
#include <iostream>

struct Vec2
{
    float x, y;
    Vec2() : x(0), y(0) {}
    Vec2(float X, float Y) : x(X), y(Y) {}
};

typedef std::pair<Vec2, Vec2> Result;

// a  d
// b  c
struct Rect
{
    Vec2 a, b, c, d;
};

void project(const Rect& rect, Vec2 p, float angle, Result& output)
{
    float tanA = tan(angle);

    // Avoid division by zero
    if(tanA == 0)
    {
        output.first.x  = rect.d.x;
        output.first.y  = p.y;
        output.second.x = rect.a.x;
        output.second.y = p.y;
    }
    else
    {
        // Transform input (make p relative to rectangle)
        p.x -= rect.a.x;
        p.y -= rect.a.y;

        float w = rect.d.x - rect.a.x;
        float h = rect.b.y - rect.a.y;
        calcProjection(w, h, p, tanA, output);

        // Transform result back to original coordinates
        output.first.x  += rect.a.x;
        output.first.y  += rect.a.y;
        output.second.x += rect.a.x;
        output.second.y += rect.a.y;
    }
}

int main()
{
    Rect rect {
        Vec2(400, 600), // Top left
        Vec2(400, 700), // Bottom left
        Vec2(600, 700), // Bottom right
        Vec2(600, 600)  // Top right
    };

    Vec2 p(550, 650);
    float angle = -M_PI_4;

    Result result;
    project(rect, p, angle, result);

    std::cout << "A1: x=" << result.first.x  << " y=" << result.first.y  << std::endl;
    std::cout << "A2: x=" << result.second.x << " y=" << result.second.y << std::endl;
}

```

**Projection Algorithm**
The basic idea is like this:

1. Use `tan()` and offsets to project `p` onto sides *CD* and *AB*. Result: `yCD` `yAB`
2. Check for boundaries.
3. If outside, project `yCD` and `yAB` onto *DA* or *BC* using trigonometry.

```
void calcProjection(float w, float h, const Vec2& p, float tanA, Result& output)
{
    float yCD = p.y - (tanA * (w - p.x));
    float yAB = p.y + (tanA * p.x);

    if(tanA < 0)
        tanA = -tanA;

    // First projection onto CD
    if(yCD < 0)
    {
        output.first.x = w + (yCD / tanA);
    }
    else if(yCD > h)
    {
        float opposite = yCD - h;
        output.first.x = w - (opposite / tanA);
        output.first.y = h;
    }
    else
    {
        output.first.x = w;
        output.first.y = yCD;
    }

    // Second projection onto AB
    if(yAB < 0)
    {
        output.second.x = -yAB / tanA;
    }
    else if(yAB > h)
    {
        float opposite  = yAB - h;
        output.second.x = opposite / tanA;
        output.second.y = h;
    }
    else
    {
        output.second.y = yAB;
    }
}

```

Note: The first result `A1` will always be on the right side of the rectangle. `A2` always on the left. If you want `A1` to be on the front and `A2` in the back of the vector, you can swap them when the following condition is true: `angle >= PI/2 || angle <= -PI/2`

I should also note that I haven't fully tested any of this.

(1) When using a coordinate system where the Y-axis expands upwards, simply negate the input angle: `angle = -angle`

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


# Question
Title: 2D top down RPG animation architecture problem
I have a problem with my sprite animations right now. I have different animations and sequences for each character so an specific archer might do a ranged attack in which he just plays one animation and shoots an arrow at the enemy. The other might be melee and has to move close to the enemy while having an animation for that and when he reaches the enemy do its attack animation and return back to its original position also having its own animation. And I could go on and on for maybe like bosses etc.

As you can see there are many possible animation sequences for quite a variety of characters. My question is what is the best way to program this into my game. Should I have a base class for the battler which has all the common methods and than inherent each character from that class with its own attack sequences? Because that is what I thought of first but I'm affraid its the wrong approach since I will have many classes doing the same kind of sequences. Or maybe should I create a sequence base class and each different animation sequence will inherent from that class. Than play the sequence on the base Battler class?

I'm developing the game in SFML C++ and here is a gif of the battle screen right now so you can get an idea of how a battle is in my game.

Battle scene of my game

# Answer
> 1 votes
The animations and logic for attacks can be broken down into individual logical units and then sequenced via data files. For example, you might have code like this:

```
AdvanceBehavior(entity, target, speed)
FallbackBehavior(entity, target, speed)
SoundBehavior(entity, sound_id)
AnimateBehavior(entity, anim_id, speed)

```

and then you can have a data file that specifies how attacks are sequenced:

```
{
  {
    'name': "fire arrow",
    'sequence': [
      {'id': 'sound', 'sound_id': 'twang.wav'},
      {'id': 'animate', 'anim_id': 'elf_fire_arrow.anim', 'speed': 1.0},
    ]
  },
  {
    'name': "fast strike",
    'sequence': [
      {'id': 'animate', 'anim_id': 'elf_jump.anim', 'speed': 2.0},
      {'id': 'sound', 'sound_id': 'jump.wav'},
      {'id': 'advance', 'speed': 5.0},
      {'id': 'animate', 'anim_id': 'elf_smack.anim', 'speed': 2.0},
      {'id': 'sound', 'sound_id': 'thwack.wav'},
      {'id': 'fallback', 'speed': 1.0},
      {'id': 'animate', 'anim_id': 'elf_jump.anim', 'speed': 1.0},
    ]
  }
}

```

Your code should contain logic. Your data should contain configuration.

# Answer
> 1 votes
> Should I have a base class for the battler which has all the common methods and than inherent each character from that class with its own attack sequences?

If you have a lot of battler types, I don't think you would necessarily want them all to be their separate class if they are very similar to each other otherwise. One approach would be to have them all be of a single type, Battler, with lists of abilities and animations and sprites and what-not attached to them after construction.

Instead of using separate child classes' constructors to then construct the different types of battlers, you could create simple functions that construct a suitable *battler* for you instead. For example:

```
Battler createBattlerType1()
    {
    Battler battler;

    //Add animations, abilities, etc.

    return battler;
    }

```

> Or maybe should I create a sequence base class and each different animation sequence will inherent from that class. Than play the sequence on the base Battler class?

To some extent, that sounds like a sensible thing to do to me, however, again I don't think you necessarily need to mix in inheritance at all. If a "sequence of animations" is simply a list of animations to be played one after another, you don't necessarily even need to create a new datatype for it: you could just store it in, say, an array or an std::vector. Then, each "battler" instance could have it's own list of animation sequences appointed to it.

---
Tags: 2d, architecture, animation, sprites, sfml
---


# Question
Title: How can I mark a pixel in the stencil buffer?
I never used the stencil buffer for anything until now, but I want to change this. I have an idea of how it should work: the gpu discards or keeps rasterized pixels before the pixel shader based on the stencil buffer value on the given position and some stencil operation.
What I don't know is how would I mark a pixel in the stencil buffer with a specific value. For example I draw my scene and want to mark everything which is drawn with a specific material (this material could be looked up from a texture so ideally I should mark the pixel in the pixel shader), so that later when I do some post processing on my scene I would only do it on the marked pixels. I didn't find anything on the internet besides how to set up a stencil buffer and explaining the different stencil operations. I was expecting to find some System-Value semantics like SV\_Depth to write to in the pixel shader (because the stencil buffer shares the same resource with the depth buffer in D3D11), but there is no such thing on MSDN. So how should I do this?
If I am misunderstanding something please help me clear that up.

# Answer
> 8 votes
There are two ways to set the stencil buffer value in Direct3D 11, one of which is only available in Direct3D 11.3 (and Direct3D 12). I will split this answer into two parts accordingly.

**Direct3D 11 General**

As part of the `D3D11_DEPTH_STENCIL_DESC` you specify what action to take on a stencil test pass and fail. These options boil down to:

* Keep the current value in the stencil buffer (`D3D11_STENCIL_OP_KEEP`)
* Set the current value in the stencil buffer to zero (`D3D11_STENCIL_OP_ZERO`)
* Increment the current value in the stencil buffer (`D3D11_STENCIL_OP_INCR/_SAT`)
* Decrement the current value in the stencil buffer (`D3D11_STENCIL_OP_DECR/_SAT`)
* Replace the current value in the stencil buffer with the reference value (`D3D11_STENCIL_OP_REPLACE`)

That last option is how you can explicitly set a stencil buffer index to a certain value.

The reference value is passed as the second parameter of the `OMSetDepthStencilState` method. Keep in mind that while the reference value argument takes in a `UINT` (32-bit), depth-stencil buffers typically allot only 8 bits to the stencil portion (`DXGI_FORMAT_D24_UNORM_S8_UINT`).

**Direct3D 11.3 and Direct3D 12**

In Direct3D 11.3, a new shader semantic called `SV_StencilRef` was introduced as a target for pixel shader output. With this you can explicitly set the stencil buffer value on a per-pixel basis (as opposed to changing the stencil reference value on a per-call basis).

Support for this feature can be queried via:

```
D3D11_FEATURE_DATA_D3D11_OPTIONS2 featuresDescr;
ZeroMemory(&featuresDescr, sizeof(D3D11_FEATURE_DATA_D3D11_OPTIONS2));

d3d11Device->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS2, &featuresDescr, sizeof(D3D11_FEATURE_DATA_D3D11_OPTIONS2));

if(featuresDescr.PSSpecifiedStencilRefSupported)
{
    // SV_StencilRef is supported
}

```

---
Tags: hlsl, directx11
---


# Question
Title: What's wrong with my animation trigger script?
So I am making an RPG and I am setting up the player. I am trying to trigger an attack animation by pressing a button. I wrote this down and I get an error that says `"Expressions in statements must only be executed for their side-effects"`. I don't know what that means, but it is an error that won't let me play the game without fixing it. I'm not sure where to go from here. How would I fix the error? EDIT: I'm not using Mecanim, nor am I planning on using it.

This is the script. It is in JavaScript (Unity3D).

```
#pragma strict

var anim: AnimationClip;

function Start()
{
    animation["Sword Slash"].layer = 4;
    animation["Sword Slash"].wrapMode.Once;
}

function Update ()
{

    if (Input.GetKeyDown ("c"))
    {
        animation.Play("Sword Slash");
    }
}

```

# Answer
The line `animation["Sword Slash"].wrapMode.Once` doesn't actually do anything, and that's why an error is generated, to help you. Maybe you meant to assign by calling `animation["Sword Slash"].wrapMode = WrapMode.Once`?
> 3 votes

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


title: Tank bullet shooting

text:
# Question
Title: Tank bullet shooting
Ok, I'm having a lot of trouble understanding using Matrices for Movement in a 2D game. I currently have a Tank object that has a Matrix3 globalTransform managing the direction Scale and Rotation. That Object is the Parent to a gun Object that rotates around the centre of the Tank.

That uses a localTransform that is multiplied by its parents globalTransform to get its own globalTransform. The Update Method is:

```
localTransform = localTransform * rotation;
globalTransform = tank->globalTransform * localTransform;

```

How would I go about implementing a bullet being shot from the Gun? Should I create a Bullet Object? What would be the math be to fire in a linear direction the way the gun is facing?

# Answer
> 0 votes
Yes, I would create a separate `Bullet` object in global coordinate space.

I guess you know how to transform a point from the gun's coordinate system to the global coordinate system. A simple way to get a global direction vector works like this:

```
// Coordinate system of the gun
Vec3 gunStart        = Vec3(1, 0, 1); // Local starting point of the bullet (tip of gun)
Vec3 gunTarget       = Vec3(2, 0, 1); // Local target vector

// Transform to global coordinates
Vec3 globalStart     = gun->globalTransform * gunStart;
Vec3 globalTarget    = gun->globalTransform * gunTarget;
Vec3 globalDirection = normalize(globalTarget - globalStart);

```

The bullet would spawn at `globalStart` and move in direction of `globalDirection`.

# Answer
> 0 votes
1. When you press key for the shot then create bullet object.
2. Of course. You need to create class for your bullet.
3. So you must to have two variables which will remember the direction of the bullet.

---
Tags: 2d, transformation
---


# Question
Title: How to Display hints to user when he is inactive for more than 5 sec in unity?
I have made a 2D Game using unity in which user has to select objects of similar color and now i want to display hint when user is unable to select the color for more than four seconds.

I want something similar to candy crush hint displaying system in which candy crush shows hint by highlighting the possible combination if user is not able to identify any combination himself.

I cannot figure out how to find if the user is inactive so that i can display hints.

I would really appreciate if someone can help me in figuring it out. Thanks in advance.

# Answer
Whenever an action counting as active interaction (tap/successful match) happens, capture current time to a variable in the hint showing script. In `Update()` method check if the difference is greater than delay(seconds).

```
public class HintController : MonoBehaviour {
  public float LastTime;
  public float HintDelay = 5.0f;

  void Start() {
     LastTime = Time.realtimeSinceStartup;
  }

  void Update() {
     if(Time.realtimeSinceStartup - LastTime > HintDelay)
        displayHint();
  }
}

//...when/where tap/match/whatever logic happens, save current time
//hc is reference to the HintController script
//you can assign it, for example, through designer variable or getComponent<> method
hc.LastTime = Time.realtimeSinceStartup;

```
> 3 votes

# Answer
Adding to wondra's solution, you can use OnMouseDown() in Unity to detect both mouse and tap events. So if you were to use:

```
void OnMouseDown()
{
    hc.LastTime = Time.realtimeSinceStartup;
}

```

Your timer would reset every time your user taps the screen or, on desktop, clicks the mouse. You can also add to this by adding a collider to the board (or whatever object is containing the *candies*) and using a Raycast to detect whether or not the tap/click is on the board. That way, any taps/clicks that are *NOT* on the board won't reset the hint timer.
> 2 votes

# Answer
Keep a Boolean if player is tapping or touching at the moment.Touch detection

If player is not touching the screen start a timer. Timer with Invoke or Timer with Coroutine

If timer goes to 5 seconds, enable the hint in a UI text object.
> 1 votes

---
Tags: unity, unityscript
---


title: Zoom in and switch scenes in unity

text:
# Question
Title: Zoom in and switch scenes in unity
I'm trying to zoom in as my game is like a map and I have to click on a certain country to zoom in and change the scene to this country. So I want to zoom the camera slowly and then change the scene from the map scene to the country scene.

# Answer
> 0 votes
Well, the title is *"Zoom In and Switch Scenes"*, so I'm gonna tell you how to do both of those.

In order to achieve a zoom effect, you'll need to modify the field of view of the camera, which I believe is simply called *camera.fieldOfView*.

To change scenes, you'll first need to make sure that you are

```
using UnityEngine.SceneManagement;

```

So that you can use the SceneManager class, then call:

```
SceneManager.LoadScene("insert name of your scene here");

```

To load a specific scene.

To do one and then the other, increment the field of view over several frames, either using Update() or with a Coroutine or some such, then, after the field of view has reached a certain value, load the new scene. So you zoom in over a number of frames, then load.

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


title: Multi-threading for rhythm game?

text:
# Question
Title: Multi-threading for rhythm game?
I'm trying to recreate a rhythm game. However trying to get the key-presses with SDL2 I ran into the problem, that you can only get an event every time a frame has been successfully rendered (I can't poll the events from another thread than the main thread). As you could separate game-logic from rendering, I thought I could run the game logic (including the polling of the events) for every 1ms and render the screen for every 16ms (60fps).

I read some articles stating that it doesn't make much sense to use multi-threading for that usage, but 16ms are quite a lot of latency for a rhythm game (which has about 30ms to determine a better rating for a better high-score). (The problem is also described here: Accuracy and frame-rate in a rhythm game)

EDIT: Here It's being said that multi-threading shouldn't be used:

What is the best way to handle event with SDL/C++

Now my question is:"Should I really not separate game-logic from render logic, as I don't need visual feedback for this kind of game and accuracy is more important"

# Answer
TL,DR: The SDL2 event/render system is not yet thread-safe, *but* you can overcome this limitation by using OpenGL to decouple the renderer system from your application (and then perform all rendering in a separate thread using only OpenGL functions). In this method, you still have a single event queue.

Another way is to use multiple *processes* (e.g. using PySDL2 and Python's `multiprocessing` module, or a C/C++ program that launches two sub-processes), and follow the same dual-window method outlined below (where each window has it's own event queue, but one window is hidden and is only polled to check for user input). One process will handle drawing and the other input, and application state changes and events are communicated between both processes using a pipe or thread-safe queue.

---

It's generally not recommended to separate render/input/game logic into different threads since it greatly complicates things under the hood, and you need to ensure data concurrency and thread synchronization (although SDL2 does indeed provide what you need to accomplish this). That being said, if you do need to separate input/rendering - and in this case, I agree that would be the most logical thing to do - it *is* possible to do using SDL2 threads (as well as Python threads if you're using PySDL2) and OpenGL.

There are two approaches to accomplishing this, one with a single-window and another with a double-window.

With a single window, create your OpenGL context/window with SDL2, then pass the OpenGL context to a new thread that will perform *only* rendering. It needs to safely notify the main thread when to call SDL\_GL\_SwapWindow and block until it's done (you can still keep polling events for the window even if you don't call GL\_SwapWindow), but so long as you ensure only one thread is calling OpenGL functions at once, there is no problem doing this, even cross platform.

Using the double-window approach allows you to fully decouple all OpenGL API/rendering calls from the main loop, by using the main loop to create a hidden overlay window that captures the keyboard/mouse input, and continually polls for input/window events. This way you don't need to stop for *any* OpenGL calls, and so long as your application state is thread-safe, you can pass any relevant window events to the GL window in a queue.
> 3 votes

---
Tags: multithreading, events, frame-rate
---


title: How to use the zoom gesture in libgdx?

text:
# Question
Title: How to use the zoom gesture in libgdx?
I found the example code for the `GestureListener` class, but I don't understand the zoom method:

```
private float initialScale = 1;

public boolean zoom (float originalDistance, float currentDistance) {
    float ratio = originalDistance / currentDistance; //I get this
    camera.zoom = initialScale * ratio; //This doesn't make sense to me because it seems like every time you pinch to zoom, it resets to the original zoom which is 1. So basically it wouldn't 'save' the zoom right?
    System.out.println(camera.zoom); //Prints the camera zoom
    return false;
}

```

Am I not interpreting this right?

# Answer
> 1 votes
Each time you put your fingers on the screen the `originalDistance / currentDistance` will result in the value 1.

If you use this value directly the zoom would always start at zoom = 1.0f.

To solve this issue you should store the current zoom factor at the start of the zoom and multiply this with the new calculated ratio. So: on touchDown take the current zoom: `initialScale = Camara.zoom;`.

# Answer
> 0 votes
`initialScale` looks like a constant used to scale everything in the game.

`zoom` function calculates `originalDistance / currentDistance` value, applies it to Camera and prints it out.

It's hard to tell more without seeing other affected code.

---
Tags: java, libgdx
---


# Question
Title: Is game localization by external files protected by a patent?
http://www.google.ch/patents/US7930167

This patent explains loading game languages from external files. I'm pretty sure that has already been implemented in many games. I'm not sure if they violate the patent or not. What kind of localization would be allowed then?

# Answer
From the USPTO:

> A patent cannot be obtained upon a mere idea or suggestion...A complete description of the actual machine or other subject matter for which a patent is sought is required.

So no, the "idea" of "localization by external files" is not something a patent can be granted for. However, a specific process for localization via external files *is*, and that's what is described in US 7930167.

The patent is attempting to solve the problem whereby the set of languages supported by a game is hard-coded at build time, and requires a new build to add a new language. Specifically it describes a solution using:

* a library
* which can detect at runtime (dynamically) the availability of "language packs" (collections of localized resources)
* and load the most-appropriate of those based on machine settings
* and provide fallback resources in the event that a specific resource is not available in chosen localized pack
* which has the ability to retrieve new language packs from a network

While I am not a lawyer and you may want to consult one if you are concerned about infringing upon this patent, the crux of the issue seems to be the process for dynamically detecting and loading localizations such that you can drop new localizations without updating the game itself.

If you're simply loading localized strings from an external file which you choose based on a hard-coded list that's not *precisely* what this patent describes, so you may be safe.

Microsoft has issued "patent promises" concerning the free use of various patents it owns; they are generally related to standards, however, and as far I can tell this patent is not in the list. You can get in touch with Microsoft's patent department if you have further questions.
> 2 votes

# Answer
A patent is invalid when whatever it does has already been done by a different product before the patent was handed in. This is called *prior art*.

This patent is from 2008.

What you describe (loading localization from external files) has already been done by GNU gettext, first released in 1995. So when that would be the claim the patent covers, it would be invalid.

But as Josh Petrie pointed out, the patent claim goes far further into detail. And until your implementation covers **all** claims the patent makes, it isn't in violation.

But again, ask a real patent lawyer to be 100% sure.
> 2 votes

# Answer
The patent refers to the specific library they have developed to solve this problem not the idea of having such a system. You literally cant patent a idea. So if you code your own localization and don't steal that specific code you are good to go. I personally made a simple system that read a google doc, downloads it into XML form and then replace a bunch of string dependent on the selected language.

TLDR; The idea of doing localization this way can not be patented and you have nothing to worry about.
> 1 votes

---
Tags: legal, localization, patents
---


# Question
Title: Another app has the same name as mine on the appstore!
I am about to publish a game on the android playstore and the ios appstore. It is called "PairIt". I checked a while back to see if there were any other apps named PairIt on the playstore, and there were none. But I did not check on the appstore. Yesterday, when I tried publishing my app onto the appstore, it said the name was taken. After looking around on the appstore I saw someone else had an app named PairIt. So what I did was changed my app name to "PairIt!". Will this work? Could I get into any legal troubles for this?

# Answer
Names can be trademarked. If "PairIt" is already used or registered as a trademark by somebody else, then yes, it is possible you can get into legal trouble if they decide to defend that trademark.
> 1 votes

---
Tags: google-play, appstore, trademark
---


# Question
Title: How do you pack resources, in a game when you have too many of them?
I've recently made a basic Space Invaders clone, in C++, using the Allegro 5 framework. After I finished, I realized I had about 10 sprites, and 13MB worth of DLLs; some of the players didn't even have the mingW DLLs, which was making the game very confusing.

How do I pack all my resources in a way that I can easily add and remove data to my game, and to reduce the size taken by the resource, basically placing them in one spot? I'm using codeblocks.

# Answer
> 14 votes
It seems like there are two challenges you are facing here: distribution, and asset packaging.

***Distribution***

Package up your entire application into directories as you see fit, then place the top-level directory into a .zip file. Distribute that .zip file. When your users extract the zip, they will have a folder with everything they need ready to run the game.

How do you place your files?

* Your .dlls usually need to be in the same directory as the executable (there are exceptions, but for the sake of simplicity...)
* Your assets (images, audio) can be wherever you want them, though if you move them in reference to your executable you'll have to modify you resource-loading code to take this into account.

I usually do something like this:

```
MyGame\              // top level directory holds entire progrma
  bin\               // dlls go here along with the compiled exe
  res\               // game resources top level directory
    music\
    sound-effects\
    voice\
  cfg\               // default configuration files (user-configs go in user directory)
  MyGame.lnk         // shortcut to compiled exe

```

***Asset Packaging***

You can use some sort of compression library (zlib, lzo) to compress all of your game resources (the above res\ directory) into a single file. Then you need to use the same compression library to extract the contents of your resources, in real-time, in order to load your assets into your game.

Then what happens when you want to patch your assets? Then you have to either: compile a whole new assets file and distribute that to your users (so they are essentially re-downloading what they already have, plus the handful of additions), or you have to build an updater (another program to maintain) and deal with the fact that things can go wrong and your asset file will get corrupted...

Honestly, it's not exactly trivial to make that work and I don't see the pay-off in your situation. A simple directory should be enough to encapsulate your 10 sprites and it's a whole lot easier to add and patch things: just need to download them to the right directory and done.

***Building an Installer***

This is assuming you're targeting Windows... once you have the above down, you can work on building an installer for your game. I would avoid at all costs the ClickOnce methods that Visual Studio supports. It's **not** your typical Windows installer and comes with it's own set of quirks.

Take a look at this StackOverflow question \- it contains a set of helpful links to installer packages you can use. A lot of people these days seem to like WiX. I've never used it myself. In addition, AdvancedInstaller and InnoSetup are both popular choices.

# Answer
> 0 votes
You might be able to statically link some of the libraries instead of including the dll’s. If and how is different for every library though.

# Answer
> -1 votes
You could use a software like Enigma to pack your files and save them into a single .dat. You would need to change the folder of your launcher.

---
Tags: c++, assets
---


# Question
Title: rough texturing on edges of mechanical parts
How do major studios fake the effect of "wear & tear" on the edges of guns and other things? I've always wondered this, but today it got to the point where I figured, why not just ask you guys. I"ve tried painting a greyscale mask, where the edges show a rough concretelike texture (Painted white and use lerp in ue4) but for some reason I feel like There is something im missing. Then, today I noticed sometihng playing BO3 - the edges seemed to have some more specularity on guns. Is this my answer? What process would you go through to show roughed edges? What goes into that effect?

# Answer
Certainly when there is some kind of 'finish' worn off of a surface the albedo/diffuse texture changes, but what is also important is, as you note, the specular highlight as well as any glossiness or reflectivity. This is normally done with a grey-scale texture used as a mask to make the worn off sections look matte while the pristine areas remain glossy.
> 1 votes

# Answer
Edge effects are generally produced by using multiple surface materials (texture sets) and blending between them with hand-painted or generated edge textures. Note that these materials only exist in the artist's workflow, as they're rendered to a single set of textures for the game.

Textures that may contain edge information are curvature maps and ambient occlusion maps.

You can see how it's often done by artists in this video: https://www.youtube.com/watch?v=4fCF5HPc5\_c
> 0 votes

---
Tags: textures, geometry, unreal-4, 3d-modeling
---


# Question
Title: Anyway to change the property of a existing animation to another type?
The title pretty much says it all. Take this rather simple animation  I would like to reuse this same animation in a UI element but for that I have to animate the Image component and not the sprite. Is there a way to copy over the keys or edit the animation somehow so that the property is a Image.sprite ?

# Answer
> 2 votes
Ok, this is how I did it.

1. Set asset serialization mode to force text
2. Create a empty animation clip containing the Image.sprite property.
3. Open up the new and old animations and copy everything bellow `-curve:` and `pptrCurveMapping:` from the old one to the new one.
4. Enjoy your new animation that works with UI images.

---
Tags: animation, unity
---


# Question
Title: How can I test which of two gameobjects is closest to a third gameobject?
It would be nice if it was as simple as:

```
    public void Closest()
    {
        if (A.distance > B.distance) {}
    }

```

But any sort of workaround would be acceptable.

# Answer
It has been a while since I've touched Unity, but this should get you in the right direction. Assuming A, B, and C are objects, and we want to see if B or C are closer to A:

```
var BtoA = (B.position - A.position).magnitude;
var CtoA = (C.position - A.position).magnitude;

// Assume B should return if distances are equal
if(BtoA <= CtoA)
{
    // B is closer
}
else
{
    // C is closer
}

```
> 3 votes

# Answer
This is actually pretty easy in Unity, as Vector3 has a helper method called Distance

Assuming A, B, and C are all GameObjects, you're using C#, and measuring the distance to A, your method can then look something like this:

```
public GameObject Closest()
{
    float distToB = Vector3.Distance(A.transform.position, B.transform.position);
    float distToC = Vector3.Distance(A.transform.position, C.transform.position);

    // B is closest
    if (distToB < distToC) {
        return B;
    }

    // C is closest
    if (distToC < distToB) {
        return C;
    }

    // return null to indicate neither is closest, but you could return C or B, depending on your requirements
    return null;
}

```
> 0 votes

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


# Question
Title: Unity WheelCollider motorTorque acceleration with ps4 triggers
I'm fairly new to Unity and i'm struggling to find some answers. Every car script and wheelCollider tutorial I can find is based in the horizontal and vertical axis and that works great. But I'd like to move the car while holding a trigger and brake the car while holding another trigger (ps4 controller. Inputs are already mapped and working), but I need some help on that.

This is the part of the script that handles the acceleration:

```
 float motor = maxMotorTorque * Input.GetAxis("Vertical");
 foreach (AxleInfo axleInfo in axleInfos) {
     axleInfo.leftWheel.motorTorque  = motor;
     axleInfo.rightWheel.motorTorque = motor;
 }

```

Is there anyone that can point me in the right direction or possibly provide some example scripts?

Thanks in advance.

# Answer
> 1 votes
See the trigger pressing input. If it's pressing keep the value in a Boolean.

The code will be like:

```
if(pressing_trigger) //trigger values are [0-1] so pressing_trigger is true when trigger value is greater than 0 (zero).
{
//your acceleration code
}

```

Go to xbox/ps trigger setup

---
Tags: unity, playstation4
---


# Question
Title: What is a good practice for deciding when to use transforms instead of applying force?
I was making several games. I don't understand when I should use addTorque instead of rotate. AddForce instead of position

The latest game was a pinball game. I wasn't sure the best way to active the flippers.

# Answer
> 2 votes
When you are dealing with AddForce and AddTorque, you are simulating physics. You are utilizing the RigidBody component of your physics engine. Do you require a physics engine for your game? Or do you want to fake the physics yourself?

You cannot apply forces to a transform. You also don't need to have a RigidBody component on your gameobject in order to move it. If you are are moving your gameobject via its transform, then you are no longer simulating the physics. You will need to do a lot of the work yourself.

This depends entirely on your game. In your pinball example, it would make sense to put your paddles on a Hinge Joint and turning on the motor at a very high value in a burst, in order to swing it in the open position. Doing a pinball game without utilizing the available physics engine would be pretty silly in my opinion.

# Answer
> 1 votes
Adding force means you are simulating some degree of pysical movement.

Do not play with vector(force) if you do not need to simulate physical property in your game.

---
Tags: physics, unity, rotation, movement, transformation
---


# Question
Title: Modify texture of sepcific area of Terrain in unity
I am developing a farming simulator 3D game in unity. I have a crop field on terrain which is actually a texture paint in square to show a crop area, and i have to perform sowing (prepare field for seeding) in which process as tractor pass on that texture part its texture from plain soil which i had applied on it should change to more darker and rough texture. I have a idea to get that specific texture part from terrain data but i do not understand how to modify that specific area's texture at run time (through code). Any help would be helpful. Thanks in advance.

# Answer
First you have to get all the textures used for whole terrain. From those you can get the texture you want to modify or change.

Use `TerrainData.splatPrototypes`to get textures. Then change the color properties to give it a darker look or change the texture.
> 0 votes

---
Tags: textures, unity, terrain
---


# Question
Title: 2D Bounding box for collision detection - alternate shapes
I have objects in my game such as clouds and stars. I have given the bounds for them in rectangle format.

The images are not rectangular, although the collision boxes are. How can I implement a collision box that is exactly the shape of my character?

I'm suing overlap2D.

# Answer
If you want to setup a physics data for an object that is already on the screen, just right-click on it and select “Edit Physics” button from drop down menu, this will bring up the “Edit Physics” dialog.

There you can choose if your object is static or dynamic, set its mass, friction, density and so on, and draw the polygon mesh for its fixture shape.

You can also right-click on an asset inside the right panel, and select “Edit Physics”.

If done so, later every time you drop this asset to the stage you will have physics data copied with it. It is also important to notice that physics data is not saved unless you click “Save Physics Data” inside the edit physics dialog. If you just close it, data is lost.
> 1 votes

---
Tags: libgdx, overlap2d
---


# Question
Title: Is it bad practice to store inventory and scores in PlayerPrefs?
I'm building a mobile game for a client in Unity. To save time, we started with a template game from the Asset Store that had some of the features that the client wants.

The game includes a progression system and shop, so we save the user's scores, progress, in-game currency, inventory, etc. We currently have no plans to export the save data.

The template game uses PlayerPrefs to store *all* save data. Is this bad practice? Assuming we don't include a button that calls `PlayerPrefs.DeleteAll()`, is there any extra risk associated with using PlayerPrefs instead of external files to store the player's data?

# Answer
It is up to you, but on android at least it is very easy to reset these things on your phone. Most of the time it is best to save things that you do not want to lose externally so that the user cannot manipulate or delete it. I am not positive how easy it is to do on iOS, but on android all you have to do is go to the app in the application manager and clear the cache and it will remove all of those PlayerPrefs.

Overally it would not be a good option for things you need to hold on to. Especially things like in game currency as users can find ways to manipulate this data.
> 1 votes

# Answer
Yes, because PlayerPrefs are VERY unsecure. If you get into the habit of using PlayerPrefs to store data, even for games where it doesn't matter, then you'll run the risk of doing it when it does matter, such as with an online multiplayer game or some such game where cheating would make a big difference.

The reason it matters is because they are extremely easy to edit, due to them being pretty much plain text and not encrypted in any way, so the values can be directly edited.

If you want to keep your data, especially save data and everything safe, then serializing your data is the best way. You can create a function by which you save your data to a binary file, but Unity does have built-in tech for serializing data.

http://blogs.unity3d.com/2014/06/24/serialization-in-unity/

That link will tell you how Unity's own serialization works. It's not the best method or the easiest to use, but it does mean you don't have to go away and spend several hours/days making your own methods. The best approach is to make a centralised class that keeps track of all of the data at the same time. This makes serializing it a LOT easier.
> 2 votes

# Answer
I had issues with PlayerPrefs() on Tizen device. Same game Worked great on Android and iOS.

It's good practice using XmlSerializer or Binary Serialization. They have better control when dealing with lots of data like in your case.
> 2 votes

---
Tags: unity, savegame
---


# Question
Title: How do I write to a text file in Update function of a script? [Unity|C#]
I have a Unity C# Script which updates a variable each time the Update function is called. I would like to know how to write to a file from the update function.

# Answer
Although I wholeheartedly agree with @Jon on this one I'm still going to answer your question. The following class will write to a file in the Update method. Have fun with it.

```
using UnityEngine;
using System.IO;
public class VeryBadIdea : MonoBehaviour {

    private string filename = "WeWLad.txt";
    private float some_variable;
    private string textToWrite = "Variables : ";
    // Update is called once per frame
    void Update () {
        some_variable += Time.deltaTime;//update the variable with something;
        textToWrite = textToWrite + " " + some_variable.ToString();//create a proper string so we can read the file afterwards
        File.AppendAllText(filename, textToWrite);//write to the file. No need to call Flush or Close. Note this does NOT overwrite the file every time you restart the game
    }
}

```

Alternatively this might be a better solution.

```
using System.IO;
using System.Collections.Generic;
using UnityEngine;
public class SlightlyBetterIdea : MonoBehaviour {
    List<SomeDataToWrite> listToHoldData;
    private float var1,var2 ;// Some variables to increment;
    private string filename = "WeWLad.txt";
    void Start()
    {
        listToHoldData = new List<SomeDataToWrite>();
    }
    // Update is called once per frame
    void Update () {
        //Increment the variables
        var1 += Time.deltaTime;
        var2 += Time.deltaTime;
        //Add them to our handy dandy list
        listToHoldData.Add(new SomeDataToWrite(var1, var2));
    }
    void OnApplicationQuit()//Now that we are quiting the application we can write our data to a file
    {
        string textToWrite="GLORIOUS DATA" +"\r\n";
        foreach(SomeDataToWrite data in listToHoldData)
        {
            textToWrite = textToWrite + " x:" + data.x + " y:" + data.y +"\r\n";
        }
        File.AppendAllText(filename, textToWrite);
    }
     internal class SomeDataToWrite
    {
        internal float x;
        internal float y;
        internal SomeDataToWrite(float x, float y)
        {
            this.x = x;
            this.y = y;
        }
    }
}

```
> 6 votes

# Answer
You do not want to write to a file inside of Update(). That is bad design, and ridiculous. Instead, you may want to consider writing to memory in your Update() function -- and then dumping this data to file at a reasonable opportunity.
> 4 votes

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


# Question
Title: Shifting values or tiles on a 2D grid (1D array)
I recently turned my practice project into a match3-type game.

The game uses a 6x10 grid, internally stored into a single array, with each item being a positive integer (0-based). I have a function to detect groups of the same type of a given size, but once the group has been deleted, the tiles above need to be shifted down.

The unordered index of each deleted tile is also stored into a separate array.

The language I'm working with is Linden Scripting Language (LSL), although language-specific answers aren't needed (but very helpful), so even general examples are welcome.

Edit: My recursive function so far:

```
shift(integer i) // i == index of Grid, COLS == columns/width (6)
{
    if( (integer)grid[i] != -1 ) return; // blocked by deleted value

    Grid[i] = (integer)Grid[i-COLS]; // copy value from above

    if(i >= COLS) // haven't reached upper limit of grid
    {
        shift(i-COLS); // recursive call up
    }
    else
    {
        Grid[i] = (integer)llFrand(TYPES); // reached top, randomize tile
                                           // TYPES == integer, maximum amount of types
    }
}

```

Improvements needed:

* Don't copy deleted values from above (skip over)
* Stop recursing early if multiple values were deleted vertically
* Move horizontally and find the lowest point to begin recursing from

Limitations of the environment:

* Limited to 64KB of memory (bytecode + stack/heap)
* Each call may potentially use 512 bytes of stack

# Answer
> 1 votes
What you should do, is store neighbor information in each of your Tile objects. This way, it makes things a heck of a lot easier when dealing with this type of game logic.

```
public class Tile {
    public Tile Left;
    public Tile Right;
    public Tile Top;
    public Tile Bottom;
}

```

Associate these neighbors in your initialization code somewhere, making sure you set the the links properly. You should be able to figure out how to do this, if not you will need to provide more information on your data, as I cannot guess how you are storing your level information.

Then you can easily do something like this:

```
for (int n = 0; n < Tiles.Count; n++)
{
    if (Tiles[n].Bottom != null) {
        if (Tiles[n].Bottom.Type == TileType.Empty) {
             Move(Tiles[n], Tiles[n].Bottom);
        }
    }
}

```

And your Move function would look like:

```
void Move(Tile tile, Tile position) {
    position = tile;
    tile.Clear();
}

```

---
Tags: scripting, grid
---


title: Libgdx Back button exit the app

text:
# Question
Title: Libgdx Back button exit the app
when I press back button on android, it exits the game although I ask it to go to other screen instead. It goes to the other screen for one or two seconds then it exits.:

```
if((Gdx.input.isKeyPressed(Input.Keys.BACK)))
    game.setScreen(new GameOverScreen(game,4));

```

# Answer
> 4 votes
More code would be helpful, but you likely need to put this in your show method.

```
public void show() {
    Gdx.input.setInputProcessor(yourInputProcessor);
    // This should keep it from exiting.
    Gdx.input.setCatchKey(Input.Keys.BACK, true);
    ...
}

```

# Answer
> 1 votes
in your update method you should add the below code.

```
    if (Gdx.input.isKeyPressed(Keys.BACK)) {
        game.setScreen(new MenuScreen(game));
    }

```

// and in your game Screen classes show method Add this code

```
        Gdx.input.setCatchBackKey(true);

```

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


# Question
Title: Should I have one asset manager and unload and load with different gamestates? Or should I have one for each gamestate?
I am working on a LibGDX game and I would like to find out the best way to manage assets. Should I have one AssetManager that is passed through to my GameState init() method to load from each level, then unload all of those resources in the dispose() method of the gamestate.

Or, should I have a separate AssetManager in each gamestate which is passed to each of the entities and components within the gamestate and clear + dispose the entire AssetManager in the dispose() method of the gamestate.

# Answer
> 0 votes
No, you don't have to keep seperate assetmanager for different game states . One Assetmanager is enough for all the states. Moreover adding multiple Assetmanager leads to increase the load of GPU. Which will effect your Game play. So better use only one Assetmanager to load the all Assets. And Assetmanager is one of the class which should be disposed manually .So try to implement the below classes .

```
    public class Assets implements Disposable, AssetErrorListener {
     }

```

So after implementing the Disposable interface you can access a "dispose" method (note:- only use,if ur making seperate class for dealing with the Assets). in that dispose method you can also write

```
 @Override
public void dispose() {
 assetManager.dispose();

}

```

So I'm prefering you to use only one assetmanager. and the above code is used to dispose the Assetmanager

# Answer
> 1 votes
Creating only one is probably better. If you have one object storing and managing the lifetime of assets that you share between all levels, that makes it trivial to share *assets* across each level (for example, common, always-loaded assets).

If you have one asset storage object per level, that does not naturally lend itself to sharing common assets (you could still make it work, depending on how complicated you wanted to make your asset management interface, but it comes almost for-free when you simply create one at startup and pass references to it to all your levels).

---
Tags: java, libgdx, asset-management
---


title: Unity and Thread for Reading UDP

text:
# Question
Title: Unity and Thread for Reading UDP
I have a GameObject that reads sensor data coming in over UDP (formatted as JSON).

What I am observing in that my handshake (dataReady) is getting cleared by the Update() cylcle fast enough, and I am logging "data overruns" (see the code below).

I have the GameLoop running at 150FPS (confirmed in the IDE) and messages are comming at 0.5 FPS (simulated). So I really am wondering about the thread interaction. (I tried an async UDP read earlier, and had the same issue, I figured this was safer.

For debug I tested to make sure that CarMover.moveme() is called. I can see that happening in VS2015.

What is **really** strange is that even though messages are only coming in at 0.5 Hz, and the game loop is running at 150FPS (which means update() should be clearling dataready all the time, it is not happening. Not even the first time. Really odd.

I am also now included the external blaster.cs code that I use to test the Unity, so you can try it yourself and see what is going on.

```
using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System;
using System.Text;
using System.Net;
using System.Threading;

public class CommScript : MonoBehaviour
{
    UdpClient client;
    IPEndPoint endPoint;
    public int port = 7777;
    public string hostName = "localhost";
    public static Packet message;
    public static bool dataReady = false;
    public GameObject car;
    public int stepNum;
    Thread listener;
    public int upDateLoop = 0;

    void Start()
    {
        endPoint = new IPEndPoint(Dns.GetHostAddresses(hostName)[0], port);
        client = new UdpClient(endPoint);
        dataReady = false;
        Tools.LogDebug(gameObject.name, "Listening for Data...");
        listener = new Thread(new ThreadStart(translater));
        listener.IsBackground = true;
        listener.Start();
    }
    void Update()
    {
        if (dataReady)
        {
            upDateLoop++;
            stepNum = message.step;
            car.GetComponent<CarMover>().moveMe(message);
            dataReady = false;
        }
    }

    void OnApplicationQuit()
    {
        client.Close();
    }

    void translater()
    {
        Byte[] data = new byte[0];
        while (true)
        {
            try
            {
                data = client.Receive(ref endPoint);
                if (dataReady)
                {
                    Tools.LogDebugThread("Comm.translater", "DataOverrun", -1, -1);
                    client.Close();
                    return;
                }
            }
            catch (Exception err)
            {
                Tools.LogDebugThread("Comm.translater", "recieve data error " + err, -1, -1);
                client.Close();
                return;
            }
            string json = Encoding.ASCII.GetString(data);
            message = Packet.Parse(json);
            dataReady = true;
            //Tools.LogDebugThread("Comm", "got message: " + message.ToString(), 0, 0);
        }
    }
}

```

**Blaster.cs**

```
using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Timers;

namespace Blaster
{
    class Blaster
    {
        UdpClient client;
        IPEndPoint endPoint;
        public int port = 7777;
        public string hostName = "localhost";
        public int stepNum = 0;
        const int rate = 2000;
        public Timer clock;

        static void Main(string[] args)
        {
            Blaster b = new Blaster();
            b.run();
        }
        Blaster()
        {
            client = new UdpClient();
            endPoint = new IPEndPoint(Dns.GetHostAddresses(hostName)[0], port);
        }
        void run()
        {
            this.stepNum = 0;
            Console.WriteLine("Press Enter to do a send loop...\n");
            Console.ReadLine();
            Console.WriteLine("started at {0:HH:mm:ss.fff}", DateTime.Now);
            start();
            Console.WriteLine("Press Enter to stop");
            Console.ReadLine();
            stop();
            client.Close();
        }
        void stop()
        {
            clock.Stop();
            clock.Dispose();
        }
        void start()
        {
            clock = new Timer(rate);
            clock.Elapsed += send;
            clock.AutoReset = true;
            clock.Enabled = true;
        }
        void send(Object source, ElapsedEventArgs e)
        {
            Console.WriteLine("sending: {0}", stepNum);
            Byte[] sendBytes = Encoding.ASCII.GetBytes(message());
            try
            {
                client.Send(sendBytes, sendBytes.Length, endPoint);
            }
            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
            }
        }
        string message()
        {
            Packet p = new Packet();
            p.id = "car";
            p.timestamp = DateTime.Now.ToString();
            p.x = 1.2f;
            p.y = 0.4f;
            p.z = 4.5f;
            p.step = stepNum++;
            string json = JsonConvert.SerializeObject(p);
            return json;
        }
    }
}

```

# Answer
Well, I stumped our local unity expert also, but we did a debug session in my office and after about an hour, we found out it is not the code. The Unity IDE will report console messages even focus is off the window. But our test program was an external exe (Blaster.exe) which is a console program. So it looked like the messages were arriving and the update was not running. That was not the case, it was just that the IDE lost focus. I cleaned up my code to use a Synchrhonized Queue, so now all should be very thread safe.

BTW: The problem with IDE stopping running when it loses focus can be solved by:

```
    Application.runInBackground = true;

```

...

```
using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System;
using System.Text;
using System.Net;
using System.Threading;

public class CommScript : MonoBehaviour
{
    UdpClient client;
    IPEndPoint endPoint;
    public int port = 7777;
    public string hostName = "localhost";
    public GameObject car;
    public int stepNum;
    Thread listener;
    Queue pQueue = Queue.Synchronized(new Queue()); // holds the packet queue

    void Start()
    {
        endPoint = new IPEndPoint(Dns.GetHostAddresses(hostName)[0], port);
        client = new UdpClient(endPoint);
        Tools.LogDebug(gameObject.name, "Listening for Data...");
        listener = new Thread(new ThreadStart(translater));
        listener.IsBackground = true;
        listener.Start();
    }
    void Update()
    {
        lock (pQueue.SyncRoot)
        {
            if (pQueue.Count > 0)
            {
                Packet p = (Packet)pQueue.Dequeue();
                stepNum = p.step;
                car.GetComponent<CarMover>().moveMe(p);
            }
        }
    }

    void OnApplicationQuit()
    {
        client.Close();
    }

    void translater()
    {
        Byte[] data = new byte[0];
        while (true)
        {
            try
            {
                data = client.Receive(ref endPoint);
            }
            catch (Exception err)
            {
                Tools.LogDebugThread("Comm.translater", "recieve data error " + err, -1, -1);
                client.Close();
                return;
            }
            string json = Encoding.ASCII.GetString(data);
            pQueue.Enqueue(Packet.Parse(json));
        }
    }
}

```
> 3 votes

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


title: Android game to iOS, go with an engine?

text:
# Question
Title: Android game to iOS, go with an engine?
I have developed a game on android using native coding. However I am being asked to port it to ios.

So I thought that I should bite the bullet and recode it in unity so I can go cross platform.

I am just upset that I have to recode everything in unity. Is there any other way or tool that at least will make me use half of my code or so thing? Basically what would you do.

Ps:I don't even know unity but I heard learning it is easy

# Answer
Libgdx is a free game library that supports java and can be deployed to Android and iOS. You will definitely be able to use a lot of your existing code and, depending on how you implemented your Android game, you may even be able to convert many of your draw calls to the Android canvas directly to draw calls in Libgdx.

Libgdx definitely has a steeper learning curve than Unity, but it has a pretty good community and a couple of good tutorials. Libgdx supports Desktop(Win/Mac/Linux), Android, iOS. It even kind of supports HTML5/JS, though its a bit of a pain to get everything working in the browser.
> 3 votes

# Answer
There is no simple way to convert your java code into Unity, unfortunately.

You are going to have to convert the entire code base into either C# or Javascript. Even the way you do your scenes are going to have to be updated.

There is no easy way around it, sorry to say.
> 4 votes

---
Tags: unity, android, ios, cross-platform
---


# Question
Title: Is there a way to make the boundary between materials wavy?
I have a sea trading game that I'm working on developing. Right now, my world looks like this:

There are 4 different "biomes", with more to be added. Internally, this is a large mesh which has 4 different types of materials added to it, to make it work. Each region has a material associated with it.

The problem that I'm trying to overcome is to make it look less squary, I believe the process is known as bitmasking. The traditional way to do so I believe is to use images to show the boundary between each one, having one for each possible curve. That doesn't work with my current mesh architecture so far as I can tell. What I'm wondering is if there is a way to make the edges of the mesh to be curvy instead of straight lines. I assume it would have to be a shader of some kind, but my mind isn't quite figuring out the specifics of how to make it work. Any tips? Thanks!

# Answer
> 0 votes
What I ultimately decided to do was to use a single material with all of the texture compiled together, and add a shader. The effect is as follows:

The shader code is below. I added a texture of some pre-generated noise to let it work.

```
Shader "Custom/Position Blur" {
    Properties{
        _MainTex("Main", 2D) = "white"{}
        _BumpMap("Bumpmap", 2D) = "bump" {}
        _Noise("Position Noise", 2D) = "gray"{}
        _Smoothness("Smoothness", Range(0,1)) = 0.5
        _Metallic("Metallic", Range(0,1)) = 0.5
        _WorldPosOffset("World Offset",Range(1,100)) = 10
        _MovementOffset("Local Offset",Range(1,100)) = 50
    }
        SubShader{
        Tags{ "RenderType" = "Opaque" }
        Cull Off
    CGPROGRAM
        #include "UnityPBSLighting.cginc"
        #pragma surface surf Standard

        struct Input {
            float2 uv_MainTex;
            float2 uv_BumpMap;
            float3 viewDir;
            float3 worldPos;
        };

        sampler2D _MainTex;
        sampler2D _Noise;
        sampler2D _BumpMap;
        float _Smoothness;
        float _Metallic;
        float _WorldPosOffset;
        float _MovementOffset;

        void surf(Input IN, inout SurfaceOutputStandard o) {
            float2 offset = float2(
                tex2D(_Noise, float2(IN.uv_MainTex.y / _WorldPosOffset, 0)).r-0.5,
                tex2D(_Noise, float2(0, IN.uv_MainTex.x / _WorldPosOffset)).r-0.5
                );
            o.Albedo = tex2D(_MainTex,IN.uv_MainTex+offset/ _MovementOffset);
            o.Normal = UnpackNormal(tex2D(_BumpMap, IN.uv_BumpMap));
            o.Smoothness = _Smoothness;
            o.Metallic = _Metallic;
        }
    ENDCG
    }
        Fallback "Diffuse"
}

```

# Answer
> 1 votes
You could interpolate and make the grid smaller. Basically the idea would be to take those large squares and make them smaller so that the edges are not so obvious.

I posted the algorithm here with an example and some pretty pictures:

Creating colour spectrum by light flux values

Essentially, you would have to take your generated map data array -- and then just stretch it out over a larger map array, making the edges look a lot smoother. This would be an alternative approach to utilizing bitmasking.

Considering you are already converting your map into a mesh, I would assume this wouldn't be much of a performance hit during gameplay, so as long as you pre-calculate it all during the map creation portion.

**Edit** Alternatively to this -- you could also just sample a larger dataset so that your world is larger to begin with.

---
Tags: shaders, maps, tile-bitmasking
---


title: Textures are not drawn separatley

text:
# Question
Title: Textures are not drawn separatley
I am trying to draw different textures of balloons and I want them to appear in different times about half second between each one, and move in the world. first balloons are rendered but after about half second the other balloons are rendered next to the previous ones, not in the initial place: this is code:

```
private Ballons ballons;
    private Ballons ballons2;
    private Ballons ballons3;
    private Ballons ballons4;

    private Texture background;
    public Celebration(Fruits game, float level)
    {
        this.game=game;
        this.level=level;
        gamecam=new OrthographicCamera();
        gameport=new StretchViewport(820/Fruits.PPM,580/Fruits.PPM,gamecam);
        stage=new Stage(gameport,((Fruits) game).batch);
        background=new Texture("Wining.jpg");
        gamecam.position.set(gameport.getWorldWidth()/2f,gameport.getWorldHeight()/2f,0);
        temp=0;
        counter=400;
        world=new World(new Vector2(0,0.5f),true);
        b2dr=new Box2DDebugRenderer();
        ballons=new Ballons(world,this,1,140);
        ballons4=new Ballons(world,this,2,290);
        ballons3=new Ballons(world,this,3,480);
        ballons2=new Ballons(world,this,4,650);

    }

    @Override
    public void show() {

    }
    public void handleinput(float dt)
    {
        if(Gdx.input.isTouched())
            game.setScreen(new GlobalWorld(game, 1));
    }
    public void update(float dt)
    {
        handleinput(dt);
        world.step(1 /60f, 6, 2);
        //player.update(dt);
        gamecam.update();
//        renderer.setView(gamecam);
        ballons.update(dt);
        ballons2.update(dt);
        ballons3.update(dt);
        ballons4.update(dt);
    }

    @Override
    public void render(float delta) {
        float level;
        update(delta);
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        counter--;
        b2dr.render(world, gamecam.combined);
        game.batch.setProjectionMatrix(gamecam.combined);

        game.batch.begin();

        game.batch.draw(background, 0, 0, gameport.getWorldWidth(), gameport.getWorldHeight());
        if (counter < 200) {
            ballons.draw(game.batch);
            ballons2.draw(game.batch);

        }
        if (counter < 100) {
            ballons3.draw(game.batch);
            ballons4.draw(game.batch);

        }
        game.batch.end();

    }

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

    }

}

```

# Answer
> 1 votes
It is a little bit difficult understanding your question, but I think your problem is caused by the fact that you update all ballons in the `update (float dt)` method even though you're not drawing them. This means that when 200 iterations has passed and you draw `ballons` and `ballons2` for the first time, they have already moved some distance.

# Answer
> 0 votes
The problem is that your update function is only fixing the position of the balloons to the Box2D body. Since the Box2D body is created and added to the world on creation, the body will still be moving even though it is not drawn.

You can disable the balloon's bodies until they are ready to be drawn, like so:

Balloons.java

```
public void defineCollector(float x) {
    BodyDef bdef=new BodyDef();
    bdef.position.set(x/Fruits.PPM,-20/Fruits.PPM);
    bdef.type=BodyDef.BodyType.DynamicBody;
    b2body=world.createBody(bdef);
    FixtureDef fdef=new FixtureDef();
    CircleShape shape=new CircleShape();
    shape.setRadius(15/Fruits.PPM);
    fdef.shape=shape;
    b2body.createFixture(fdef);

    b2body.setActive(false);
}

```

Celebration.java

```
public Celebration(Fruits game, float level) {
    ...

    stage.addAction(
        Actions.sequence(
            Actions.delay(0.5f),
            Actions.run(
                new Runnable() {
                    ballons.b2body.setActive(true);
                    ballons2.b2body.setActive(true);
                }
            ),
            Actions.delay(0.5f),
            Actions.run(
                new Runnable() {
                    ballons3.b2body.setActive(true);
                    ballons4.b2body.setActive(true);
                }
            )
        )
    );
}

public void update(float dt) {
    stage.act(dt);

    ...
}

@Override
public void render(float delta) {
    ...

    if (ballons.b2body.isActive()) {
        ballons.draw(game.batch);
    }
    if (ballons2.b2body.isActive()) {
        ballons2.draw(game.batch);
    }
    if (ballons3.b2body.isActive()) {
        ballons3.draw(game.batch);
    }
    if (ballons4.b2body.isActive()) {
        ballons4.draw(game.batch);
    }
}

```

I would recommend using Scene2D to handle your logic by changing your balloons to extend `Image` and adding your balloons to the stage like so: `stage.addActor(balloon)`. You can then handle your logic inside of the `act` method, and override `draw` to position the texture over the Box2D body.

https://stackoverflow.com/a/37971861/5468569

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


# Question
Title: How to make a windows installer for Monogame/F# game?
Alright, I have several questions that I haven't been able to find answers to yet. It looks like WiX and Inno Setup are pretty standard solutions for making the installer. WiX looks pretty intimidating and I got lost reading the tutorial on their site, so I'll probably use Inno Setup.

My questions:

* What are the dependencies for Monogame that I need to install? I couldn't find any official documentation on this. I found a few forums posts where people said you'll likely need DX 11 and .NET 4.0. My visual studio project says .NET 4.5, so I'm guessing that's actually the one I need?
* What things in my output directory need to be installed? I've got some .XML, .pdb, and .config files and I doubt I should be including them? Does MS have documentation on this?
* Are there any tools to help me make sure I've got everything? Maybe some Visual Studio automation for doing this stuff? It looks like there is a WiX template for XNA, but I have no idea if I can safely use that with monogame.
* Do I need a separate windows computer (including license) just to test the install? Or can I make a VM and use like a trial version of windows? It looks like windows 10 has a trial mode.
* Additional guides, tutorials, or documentation I should be reading?

Thanks!

Here are the files in my output directory for the **release** build (do I need all these?):

* font.xnb
* FSharp.Core.dll
* FSharp.Core.xml
* MonoGame.Framework.dll
* MonoGame.Framework.xml
* NVorbis.dll
* OpenTK.dll
* Pong.exe
* Pong.exe.config
* Pong.pdb
* Pong.XML
* pop.xnb

# Answer
Based on the `OpenTK.dll` you are using the OpenGL version of MonoGame. Therefore you don't have to care about DirectX, but you need to include and silently run the OpenAL installer during the installation. You should also link to the .NET 4.5+ installer for Windows Vista/7 users.

The XML files contain documentation comments and the PDB contains debug information. You should not include them. I'm not sure if the .config file is necessary either, it depends on your project.

Inno Setup is a good choice in my opinion. For such a small project, attempting to automate things any further might be an overkill. I'm not a lawyer, but a VM would be just perfect for testing the install.
> 1 votes

---
Tags: monogame, windows, installer
---


# Question
Title: object smooth orbital limit around another object depending on mouse drag
I am working in Unity.

I have special objects that can each be dragged freely around in 2d.

The objects cannot get too close to other objects (minimal Vector3.distance allowed is 1.5f).

I also have special connectors, which I can apply freely between 2 of any of these special objects. once 2 objects are connected, dragging them is further restricted.

The 2 objects cannot get too far between each other (max Vector3.distance allowed is 5f).

Both of these restrictions work, my issue is that once these restrictions occur, the objects are pretty much just stuck in place until dragged away from the restriction they tried to pass.

I want the object being dragged to orbit smoothly around the object it's connected to, once they reach any of the 2 restrictions.

The best example I can think of is the angry birds slingshot,

that once it reaches it's maximum pullback, you can just orbit along this max distance smoothly up or down depending on where you are trying to drag, this same smooth effect needs to occur both when too close and too far.

Hope I explained myself thoroughly I tried to find answers and try myself but could not reach any working solution.

The closest I think I got to a solution is with rays and the on point of ray function like in the video I provided below but I have no idea how could that be implemented in my sort of game.

thanks,

Remember the BBQ.

link to the sort of angry birds pulling mechanics I am talking about: https://unity3d.com/learn/tutorials/topics/physics/making-angry-birds-style-game-part-1

Image provided is very inaccurate to the boundaries of each restriction, just to make it seem more clear.

# Answer
If I understand your question correctly this can be done using a bit of vector math. I've created an example in Javascript so please keep in mind that many of the mathematical operations I'm doing here can be done in Unity really easily using the built-in classes and methods.

The ball will follow your mouse when you hover it over the window. I recommend you run it in Chrome if possible. Also once you click "Run Snippet" I recommed you click the "Full page" link, the reason for this is because the mouse coordinates don't account for the scrollbar, so if you scroll down the mouse coordinates will no longer be accurate.

The function called "mousemove" is where the magic happens.

Ask away if you need any clarification.

```
var OUTER_BOUNDS = 160;
var INNER_BOUNDS = 40;
var BALL_RADIUS = 16;

var canvas = document.getElementById("mainCanvas");
var ctx = canvas.getContext("2d");

canvas.addEventListener("mousemove", mousemove, false);

var centerPos = {
  x: (canvas.width / 2),
  y: (canvas.height / 2)
};

var ballPos = {
  x: -1000,
  y: -1000
};

function mousemove(event) {
  //This is where the good stuff happens.
  //Set the ball to be at the position of the mouse.
  ballPos.x = event.clientX;
  ballPos.y = event.clientY;

  //Calculate the distance from the center to the ball. This is simple linear algebra.
  var dX = ballPos.x - centerPos.x;
  var dY = ballPos.y - centerPos.y;
  var distance = Math.sqrt(Math.pow(dX, 2) + Math.pow(dY, 2));

  if (distance > 0) {
    //Calculate a unit vector that points from the center towards the ball. This is the same as normalizing the vector.
    var direction = {
      x: dX / distance,
      y: dY / distance
    };

    //If you square your inner and outer bounds you can perform this same comparison we're about to make without using the square root operation.
    if (distance > (OUTER_BOUNDS - BALL_RADIUS)) {
      //The ball is outside the outer bounds. We will calculate a new position for it using the unit vector above.
      ballPos.x = centerPos.x + (direction.x * (OUTER_BOUNDS - BALL_RADIUS));
      ballPos.y = centerPos.y + (direction.y * (OUTER_BOUNDS - BALL_RADIUS));
    } else if (distance < (INNER_BOUNDS + BALL_RADIUS)) {
      //The ball is too close to the center. We use the same method as above to calculate a new position for it.
      ballPos.x = centerPos.x + (direction.x * (INNER_BOUNDS + BALL_RADIUS));
      ballPos.y = centerPos.y + (direction.y * (INNER_BOUNDS + BALL_RADIUS));
    }
  }
};

function run() {
  window.requestAnimationFrame(run);
  draw();
}

function draw() {
  //Draw background.
  ctx.fillStyle = "#444444";
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  //Draw the center ball.
  fillCircle(centerPos.x, centerPos.y, BALL_RADIUS, "#000000");
  strokeCircle(centerPos.x, centerPos.y, OUTER_BOUNDS, "#FF0000");
  strokeCircle(centerPos.x, centerPos.y, INNER_BOUNDS, "#FF0000");

  //Draw the moveable ball.
  fillCircle(ballPos.x, ballPos.y, BALL_RADIUS, "#000000");
}

function fillCircle(x, y, radius, color) {
  ctx.fillStyle = color;
  ctx.beginPath();
  ctx.arc(x, y, radius, 0, Math.PI * 2);
  ctx.fill();
}

function strokeCircle(x, y, radius, color) {
  ctx.strokeStyle = color;
  ctx.lineWidth = 2;
  ctx.beginPath();
  ctx.arc(x, y, radius, 0, Math.PI * 2);
  ctx.stroke();
}

run();
```

```
html,
body {
  padding: 0;
  margin: 0;
}
```

```
<canvas id="mainCanvas" width="400" height="400"></canvas>
```
> 1 votes

# Answer
Instead of hard restrictions you can use opposing forces.

You want to simulate a rubber band between the two objects. That sort of force can be simulated by applying a push every frame that equals "distance to object" to the power of "your rubber band's springiness". If you want to increase the effective distance that object A can travel away from object B without being pulled back then you subtract a "distance constant" from that value and do a check at the end which sets any negative values for force to zero. At some other distance threshold you can set the rubber band to break.
> 0 votes

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


# Question
Title: How to achieve a hard edge at this geometrical intersection?
Im trying to make this edge appear smooth, soo that the faces on each side seem to meet up smoothly. But I want the green edges around this to be hard and sharp. I am using 3ds max, and this is the result.

# Answer
> 1 votes
Just apply a different smoothing group to the green polys

---
Tags: 3dsmax
---


title: How to handle user save games?

text:
# Question
Title: How to handle user save games?
I started on my first game; and now im confused how to handle the player SaveGames. I use google-play-services to persist the user's save games across devices, and I am keeping a local save too.

So the problem is how do I manage conflicts (server vs local). I have attached Save DateTime on he file and there is general data included.

So this is what im doing right now :

* I check the number of coins and gems, the level the player has and if all those are greater than or equal to the other save, i take the first save;
* In all other cases i ask the player what copy to keep; displaying the infos in each save file;

I would like to minimize asking the player which file to keep; (These problem arises only if the player uses multiple devices; Or sometimes he plays locally for a while; and signs in to his acc which already has a save file)

I think you get the idea. I would like to automate everything and dont want the user to go sad just because he misclicked on the local-copy when he had awesome stuff in the server-copy.

I need the idea please :)

# Answer
If you completely trust your client, or don't care if they mess around with the save file, simply keep some sort of **incrementing counter in the save file**. Then you can easily tell which save file is newer. Datetime seems like the right answer except it may break if your clients clocks are out of sync, if they set their clocks forward etc. Game variables that don't always increment, like gems or levels, is also bad - what if they don't increase, what if they *decrease*? The counter can be the turn number if your game is turn based, or a "game clock" that is incremented by the game, based on frames.

If you are worried about the client manipulating the save file, remember that the save file time/counter is not the only thing they could manipulate - anything from scores, levels, achievements - so check out this question: How can I protect my save data from casual hacking?

If you go the route of server-only saving, you need to guard against other kinds of cheating. Check out this question: How can I prevent false score reports to global highscore tables?

But keep in mind that, unless there is a multiplayer component like global high scores, or the game is monetised, requiring players have an online connection to save in a single player game is a very anti-player design.
> 1 votes

---
Tags: savegame, arcade
---


title: Traffic system in isometric game

text:
# Question
Title: Traffic system in isometric game
I would like to create a traffic system in my tile-based isometric game and I would like to ask for some good approaches because I don't have a clue how to begin.

Right now I have a tilemap and keep its data in an 2d array. I have... 1. tile objects (with properties like index, tile type etc.) 2. building objects (with properties like origin, size etc.).

I´ve already implemented a A\* algorithm which allows me to find the best/shortest path from one tile to another but now I have to realize the movement from start to end tile with features like stackable cars.

I though about setting up a property for my tile object which tells me if a tile contains a car but right now two cars fits on one tile in my game on each lane so this approach might be not the best solution.

Edit: i´ve added an image with lanes drawn on my tilemap. Having lane objects might be a good idea but I need to connect them to the tile objects somehow.

Have anyone implemented a traffic system in a tile-based game or have any ideas how to realize that and would share his/her knowledge with me? Would be great!

Thanks a lot!

# Answer
> 2 votes
The simple solution would be to just have each actor calculate the ideal path using A\* and then stick to it. Implement each lane of a road as a first-in-first-out queue. The edges in your A\* graph should be the lanes, not the tiles. When a car wants to move onto a lane but that lane is already occupied by the maximum number of cars, they simply wait until it is empty.

The result will be that there will be traffic jams even though there are alternative routes which are longer, but would still be faster because they are less frequented. You could let the player figure that problem out on their own. Or you could help them by taking congestion into account when calculating paths so the AI actors avoid high-traffic areas.

First you need to figure out which lanes are congested. You can calculate the congestion factor of a lane by counting the number of cars waiting to enter the lane each tick and calculating the average over multiple ticks. Then you can use that congestion factor to add an additional cost to this lane when calculating A\* routes. That way the AI actors will avoid highly frequented lanes and will distribute more evenly on alternative routes.

By the way, when you are looking for inspiration, you might take a look at Cities:Skylines. They have a really neat traffic simulation system.

# Answer
> 0 votes
I'm aware of two ways to do system simulations.

One is macro models. You create formulas that takes areas densities in account and evaluate likely traffic at various hours, and that gives you an "extensive variable" (in physics science terms). This technique is the fastest, and most controllable, but potentially less realistic and also boring.

The other is micro models. You create agents that live in the system, each with local laws and limited scope. "it's 8am I need to drive to this industrial site, A\* and follow route. along the route stop if vehicle in front of me, wait until way is free."
This is computationally heavy, but it will give you **emergent behaviors**. That is, stuff you never planned or thought about, will happen. It's the most interesting way of doing things.

On the realism side, it's hard to say, for example "crowd simulation" research showed that adding inertia to people movement created emergent vortices and clogging that were seen in videos of real life crowds too. Which means, the slightest change on your local laws can radically change the macro result.

Same with weather simulation, first models included only atmosphere, then it included ground albedo, then it included vegetation, and each time you put something in, you don't get more precise results, you get antipodal results. Even with everything we can know about the state of earth at some point in time, US weather simulation predicted that Caterina would not land, while EU simulators predicted it would.
That's the misfortune of agents, the macro result is uncontrollable.

Maybe you can invent an hybrid, where macro simulation would weight in agent decisions.

---
Tags: c#, tilemap, isometric
---


# Question
Title: LibGDX - Collision detection between all bullets and all enemies
I'm trying to make a collision detection system between the player's bullets and all the enemies on screen.

So far I had something like this:

```
for (Bullet bullet : hero.getPistols().getAllShotBullets()) {
        for (Enemy enemy : enemies) {
            if (!enemy.isDead()) {
                if (bullet.overlaps(bullet.getBounds(), enemy.getBounds())) {
                    enemy.die();
                }
            }
        }
    }

```

But after a while, the frame rate drastically drops - making the game unplayable, almost (which is understandable, as the nested for loop looks terrible for performance...). I've been looking around and found out that a common solution is to use Quad-Trees, but at the same time, I'm worried that the overhead brought by the use of that data structure will make it a bit of an overkill, if that makes sense.

**Are there any more solutions? Or should I use the Quad-Tree?**

Thanks in advance.

# Answer
> 1 votes
The algorithm you are using right now has a runtime of O( n^2 ). A tree structures can help you get that runtime lowered. Quadtrees have O( log(n) ) From that you can calculate if you will benefit from a quadtree.

# Answer
> -2 votes
A grid. Implementation is more simple and often times superior in performance.

Edit: Hu, why the downvotes? This was more of a follow up info to the accepted answer. The OP asked for alternatives. You can find grid vs. quadtree discussions everywhere. Bottom line is a quadtree doesn't deliver a better performance (often times it's slower) than a simple grid unless you have many objects of varying size.

---
Tags: java, 2d, collision-detection, libgdx
---


title: When should a VBO be unbind or not?

text:
# Question
Title: When should a VBO be unbind or not?
Searching about VAOs and VBOs I read here and here that I can optionally unbind them to avoid accidental modification so I gave it a try. The problem is that unbinding the VBO causes an access violation when calling glDrawElements and I don't understand why am I getting this behavior.

```
int main(int argc, char *argv[]) {
    if (!glfwInit()) {
        return -1;
    }

    GLFWwindow* window = glfwCreateWindow(800, 600, "OpenGL", nullptr, nullptr);
    glfwMakeContextCurrent(window);
    glewExperimental = GL_TRUE;

    if (glewInit() != GLEW_OK) {
        return -1;
    }

    GLfloat vertices[] = {
        -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, // Top-left
        0.5f, 0.5f, 0.0f, 1.0f, 0.0f, // Top-right
        0.5f, -0.5f, 0.0f, 0.0f, 1.0f, // Bottom-right
        -0.5f, -0.5f, 1.0f, 1.0f, 1.0f  // Bottom-left
    };

    // Create Vertex Array Object
    GLuint vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    //Vertex Buffer Object
    GLuint vbo;
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    // Index Buffer Object
    GLuint elements[] = {
        0, 1, 2,
        2, 3, 0
    };

    GLuint ibo;
    glGenBuffers(1, &ibo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);

    (...) // Shader-related stuff

    // Specify the layout of the vertex data
    GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
    glEnableVertexAttribArray(posAttrib);
    glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), 0);

    GLint colAttrib = glGetAttribLocation(shaderProgram, "color");
    glEnableVertexAttribArray(colAttrib);
    glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (void*)(2 * sizeof(GLfloat)));

    glBindVertexArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    glBindVertexArray(vao);
    while (!glfwWindowShouldClose(window)) {
        glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

        if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
            glfwSetWindowShouldClose(window, GL_TRUE);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    // Prepare to close the application
    glDeleteProgram(shaderProgram);
    glDeleteShader(fragmentShader);
    glDeleteShader(vertexShader);
    glDeleteBuffers(1, &vbo);
    glDeleteBuffers(1, &vao);
    glDeleteBuffers(1, &eab);

    return 0;
}

```

I'm getting the following error and it happens only when I unbind the VBO. Unbinding the VAO and the IBO doesn't throw any exception.

> Unhandled exception at 0x0282D434 (ig4icd32.dll) in main.exe: 0xC0000005: Access violation reading location 0x00000000.

Is there a problem with the way I did the unbinding?

# Answer
> 1 votes
Before *glfwCreateWindow()* call these functions:

```
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

```

And after *glfwMakeContextCurrent(window)* call:

```
printf("OpenGL version: %s\n", glGetString(GL_VERSION));

```

---
Tags: opengl, vbo, vao
---


title: Translation Matrix not working properly

text:
# Question
Title: Translation Matrix not working properly
Hello, I get this result when i try to scale and then translate a vec4 in my shader. I created a mat4x4 class on my own and some functions wich return some matrices for me, everything works, but not the translationfunction.

Currently, I use this Shader Codes:

```
GLchar* vertexShaderCode = {
"#version 330 core                              \n"
"layout(location=0) in vec3 position;           \n"
"uniform mat4 scale;                            \n"
"uniform mat4 translate;                        \n"
"out vec4 vertexColor;                          \n"
"void main()                                    \n"
"{                                              \n"
"   gl_Position = translate*scale*vec4(position,1.0); \n"
"   vertexColor = vec4(1.0f,0.5f,0.7f,1.0f);    \n"
"}                                              \n"

GLchar* fragmentShaderCode = {
"#version 330 core                              \n"
"in vec4 vertexColor;                           \n"
"out vec4 color;                                \n"
"void main()                                    \n"
"{                                              \n"
"   color = vertexColor;                        \n"
"}                                              \n"

```

The matrix setup looks like this:

```
program.use(true);
h3d::mat4x4 mat_scale,
            mat_translate;
mat_scale     = h3d::Math::scale(.5f, .5f, 0.f);
mat_translate = h3d::Math::translate(.5f, .5f, 0.0);

GLint location_scale       = program.Uniform.getLocation("scale");
GLint location_translation = program.Uniform.getLocation("translate");

program.use(true);
glUniformMatrix4fv(location_scale,      1, GL_TRUE,mat_scale.getRowWiseValues());
glUniformMatrix4fv(location_translation,1, GL_TRUE,mat_translate.getRowWiseValues());

```

So basically, the h3d::Math::scale(X,Y,Z) returns:

* X,0,0,0
* 0,Y,0,0
* 0,0,Z,0
* 0,0,0,1

And h3d::Math::translate(X,Y,Z) returns this:

* 1,0,0,X
* 0,1,0,Y
* 0,0,1,Z
* 0,0,0,1

The vertices are normal:

```
GLfloat vertices[] = {
    -1.0f, 1.0f, 0.f,
     1.0f, 1.0f, 0.f,
     1.0f,-1.0f, 0.f,
    -1.0f,-1.0f, 0.f,
};

```

What do I am doing wrong ? I really appreactiate your help ! All the other matrices are working (scale, rotate, perspective).

# Answer
> 1 votes
OpenGL uses column-major matrices, but as I understand from your code you pass row-major matrices. So in GLSL scale\[0\] is the first column of scale matrix.

---
Tags: opengl, c++, mathematics, matrix
---


# Question
Title: Best approach for destructible car in Unity
I'm developing a simple racing car game. I'm wondering what is the best approach to manage visually car destruction. For instance: i think one option (expensive) is to build car 3d model with 'separate' mesh, each for any component (bump, door, glass) and relative cooliders.. Other options ? Thanks

# Answer
If you just want bumps and scratches, you can do things like use effects and deform the vehicle mesh and you wouldn't need a large collection of objects.

Assuming you want to have bits fly off in a super realistic fashion and have it look awesome, then I think the easiest way is to do what you already suggested. Have a collection of objects that can detach away from the main body and be destroyed afterwards. Most 3D models you can download will come as a collection of parts anyway, though.

The only other approach I can think of is to make your own procedural destruction system, similar to the one CryEngine 3 uses. That would be a lot more work though.
> 2 votes

---
Tags: unity
---


# Question
Title: Will my "Block Buster" game infringe on the Blockbuster (movie rental) trademark?
I'm developing a small puzzle game called "Block Buster" and I was wondering if there will be any collision with already existing "Blockbuster" (movie rental company) registered trademark.

Does the space or case difference in the trademark mean something? Or is there any difference in that Blockbuster is a movie renting company and I will just be selling a game?

Do I really have to change the game's name?

# Answer
> 8 votes
I would say a programmer who has asked this exact question to his lawyer may be some help? I'm not a lawyer so take this as for what it is. blah blah blah

I asked this question about my IOS game which incidentally has the exact name as an album on iTunes. So it's not only the same name, it's the same name in the same store. Luckily my lawyer informed me that trademarks can only be enforced when there is a possibility of confusion of the two products or the names are the same in the same industry. In my case it was determined that a game is not a competitor or in the same industry as a song so I was given the OK. Granted my case is much more gray than yours.

I'm pretty sure nobody will confuse an indie developed block breaking game with the dying movie rental company. Just my thoughts.

# Answer
> 3 votes
You're unlikely to run into any trouble with Blockbuster the movie-rental folks, but might have (marginally) more issues being confused with Block Buster the Flash game, Blockbuster! the other Flash game, Block Buster the other other Flash game, or one of several games on the App Store, or possibly even Block Buster the arcade game.

(In other words, you're probably okay, but a more unusual name might be in order - especially if you want anyone to be able to search for your game without wading through several pages' worth of competing hits.)

# Answer
> 2 votes
If you don't want to take the risk of being taken to court then change the name. In reality it is unlikely you will be sued due to a game and a video rental store being in completely different markets. However, it's still possible thanks to the close resemblance in name.

# Answer
> 2 votes
I'm not a lawyer, etc.

Just pointing out that, even though the markets are very different, you could still have issues from over-zealous lawyers at Blockbuster (or any other similarly named company). See http://www.sparkfun.com/news/300 for an example in which SPARC, the mainframe server brand, sent a cease and desist to SparkFun, the hobby electronics online store, on the basis of a rather more tenuous link in trademark than Blockbuster/Block Buster.

# Answer
> -1 votes
No I have seen loads of Block Buster the arcade games on game distribution platforms and I can't see a problem with that. There are loads of Block Buster arcade games around.

---
Tags: legal
---