title: Simple mouseray picking in openGL

text:
# Question
Title: Simple mouseray picking in openGL
Ive been looking at tutorials and trying to figure out how to do basic ray-picking. But I'm stuck at figuring out what space to do the distance calculations in. What space does `glm::unproject()` lead to exactly?

This is what I'm doing:

first I get the mouse unprojected, like so

```
//mouse ray start
vec3 m_uproj = glm::unProject(
    vec3(mouse_xy .x*glutGet(GLUT_WINDOW_WIDTH), mouse_xy .y*glutGet(GLUT_WINDOW_HEIGHT),0.0f),
    workshop.access_gui()->view_mat(),
    workshop.access_gui()->proj_mat(),
    glm::ivec4(0, 0, glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)));

//end of ray
vec3 m_uproj2 = glm::unProject(
    vec3(mouse_xy.x*glutGet(GLUT_WINDOW_WIDTH), mouse_xy.y*glutGet(GLUT_WINDOW_HEIGHT), 1.0f),
    workshop.access_gui()->view_mat(),
    workshop.access_gui()->proj_mat(),
    ivec4(0, 0, glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)));

```

Then I find its direction, mray, like so

```
vec3 mouse_ray = normalize(m_uproj2 - m_uproj); //get mray direction

```

And Im expecting to find the closest point to `some_object` by using this calculation:

```
vec3 closest_point = mouse_ray * glm::dot(locations[i], mouse_ray); //closest point;

```

But locations seems to be in the wrong space? Or am I thinking about this the wrong way? Ive been looking around, but I cant find anywhere that explains just this part that I must be misunderstanding.

the idea is to compare the distance between closest point and locations\[i\], but the results are incorrect. Im getting something like this:

Where it should be red only if the cursor is over the square.

What space does `glm::unproj()` put my ray in anyway? And in what space should I put the objects that I want to pick/highlight?

# Answer
> 2 votes
The solution is this:

```
//world space, notice z=0.0f
vec3 mouse_world_nearplane = glm::unProject(
    vec3(mouse.x*glutGet(GLUT_WINDOW_WIDTH), mouse.y*glutGet(GLUT_WINDOW_HEIGHT), 0.0f),
    workshop.access<_gui>()->view_mat(), //view matrix
    workshop.access<_gui>()->proj_mat(),
    ivec4(0, 0, glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)));

//world space, notice z=1.0f
vec3 mouse_world_farplane = glm::unProject(
    vec3(mouse.x*glutGet(GLUT_WINDOW_WIDTH), mouse.y*glutGet(GLUT_WINDOW_HEIGHT), 1.0f),
    workshop.access<_gui>()->view_mat(), //view matrix
    workshop.access<_gui>()->proj_mat(),
    ivec4(0, 0, glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)));

```

glm::unproject() takes:

```
a vec3 xy width/height and z, with z being plane/depth (0=close, 1=infinite)
your view_matrix (as given by glm::lookat)
your projection_matrix (as given by glm::perspective)
a viewport 0,0,width,height

```

And returns xyz as they would be in `world space`. World space is the same space that you would normally think in, where you get your object after applying the 3 initial transformations: `[translate|rotate|scale]` making up the objects identity matrix.

Meaning, the values returned by by `glm::unproj()` returns values that should be thought of in world space. So the solution is simple:

```
vec3 closest_point = glm::closestPointOnLine(
    locations[i],
    mouse_world_nearplane,
    mouse_world_farplane);

if (glm::distance(locations[i], closest_point) < 0.1f)colors[i] = vec4(0.5f);
else colors[i] = vec4(1.0f);

```

---
Tags: opengl, c++, picking
---


# Question
Title: Unity: From "Normal mode" to "VR mode" back to "Normal mode"
I want to change my unity application per runtime to a "Vr-Mode" and then switch it back. Since the VR-Mode changed the camera behaviour and messes with the system i want to use i can not start my program with "project settings" where VR is not active.

Is this even possible?

Is there some kind of a "magic bool" somewhere which toggles the vr on / off?

# Answer
You have to use these lib at first

```
using UnityEngine.VR;

```

and then in

`void Start () {
 VRSettings.enabled = false;
 }`

it will work for unity5.6 and further versions as well.
> 1 votes

---
Tags: unity, virtual-reality
---


# Question
Title: Impact of increasing physics simulation rate
I am working one **Mini Golf** game development using Scenekit (iOS). To fix one of the problem with Scenekit, I have to increase the **physics simulation rate** by **4 times**.

**Questions:**

1. What is the impact on the **CPU** requirements?
2. What are the common **advantages** and **disadvantages** of changing the physics simulation rate?
3. What are the expected **problems/issues** with such increase in the physics simulation rate?

I would appreciate any suggestion on this topic. Thank you.

# Answer
> 2 votes
It's pretty straight forward really.

When you increase the rate you increase the time it needed to calculate each in-game second by the same rate.

One of the issue you can run into when increasing the simulation rate too much is that the delta per timestap can become too small and get rounded away. Increasing by a factor of 4 means it's only 2 bits but it can add up if you are not careful.

# Answer
> 1 votes
The simulation rate is essentially as follows: how many times per second are you calculating and updating your objects?

If you're simulation rate is 10 times per second, you're taking all of your objects, updating their position by their velocty/10, and dealing with any forces and collisions. If you up that to 40 times per second, you're moving each object a smaller each time, but you're doing more updates. If everything works properly, a higher simulation rate means more precise physics. Your accelerations will be smoother, and your collisions will be calculated closer to when they should occur. A lower rate means less precise physics (and you might find bounces and accelerations not working as intended)

If you're completing all the calculations in less than 1/40th of a second, a simulation rate of 40 would mean you can display the objects in real-time (ignoring the time it takes to draw them for the purpose of answering this question). The load on your CPU per second would be equal to 40\*the time it takes to calculate your physics.

However, if it exceeds your CPU's capabilities, you've got two options: not render in real time (save the locations from each frame), or drop frames. This can potentially wreak havoc (pardon the pun) on the simulation itself as it could miss collisions or not properly calculate accelerations.

So in short, if you need precision, try upping it, but if you find that it's impacting CPU usage, consider dialing it back a bit.

---
Tags: physics, simulations, scenekit
---


title: Method to size game content

text:
# Question
Title: Method to size game content
I'm developing a game with quite a rich story. I'm not sure if I'll have enough time or money to make a level for each part of this story.

Is there a common method among designer to manage this problem ? Should I write the entire story first and then cut some parts to fit it in my time/money budget ?

# Answer
> 15 votes
I think you pretty much answered your own question there yeah. Depending on how important the story is to the game and especially the gameplay, you write the entire thing first, then cut out the things that are least relevant until you have something you CAN do. Or if you know what you're doing, you drop stuff before you even write it.

If you're making a game where the main focus is the story, however, I wouldn't recommend it, as the game is pretty much just a vessel for the story. In that case you want as much of the story as possible. This is the case in visual novels for example.

tl;dr: Really critically think for yourself how important the story is to your game as a whole, then decide if you should cut parts, or leave it.

You could also (if possible) split up the game into episodes like how Telltale approaches their games and continue development with the funds you gain from that.

One important piece of advice I would like to give you, write the beginning and ending first. Make those two things the best parts of your story. Then the players will be enticed by the beginning to continue and satisfied at the end because of the good ending. If you run out of time while writing the stuff in-between, that's fine, you can still link it up.

# Answer
> 3 votes
The "design first, cut later" principle can be fun at first because it doesn't impede creativity too much with concerns of what you can realize. But it leads to frustration later when you realize just how much you have to cut to stay within your budget. The result might be just an empty husk of your ambitious original idea which lacks everything which was interesting about it.

But you can of course also approach the problem from the other side. Eyeball what content you can create with your resources, and then think of a game concept which can be realized with that amount and quality of content. This might seem restrictive, but those restrictions can also be creative fuel. When you try to solve design problems with minimal resources, you might come up with unique design solutions the AAA studios would never consider.

When you have a small budget, then you can't compete with mainstream games on quality or quantity of your content. Your only hope is to **be unique**. And a lot of unique design solutions can result from having to work with what you got.

# Answer
> 3 votes
One approach is to go with at it in a hierarchical fashion.

Write a simple outline for the whole story. Put only the important stuff, the things that affect the rest.

Then, dig down into one part of it. Flesh out one level for this part. This will force you do design the settings, the characters, the motivations, what happened before that you must state, what might happen later that you allude to. A prototype there will/may convince you/inverstors that the whole is of interest.

Then just go back to the high-level story, improve it a bit, and budget allowing, dig down into another part.

That way, you avoid useless work, you remain agile, allowing you to adapt to inevitable discoveries (this character doesn't work, I need this type of location/setting, people would rather see xyz).

Best of luck with the project!

---
Tags: game-design, project-management
---


title: Implementing distance joint

text:
# Question
Title: Implementing distance joint
I would like to implement something that behaves much like a distance joint / revolute joint in Box2D, however I do not want to throw a whole physics engine at this problem. I'm curious where I might start research to implementing such a thing.

Currently I only know them by their Box2D names, so googling that leads of course back to Box2D, so even that would be helpful.

# Answer
> 1 votes
The complexity of doing this in a physics solver comes from trying to do it in a way that is both numerically stable (doesn't freak out and send your rigid bodies flying) and that conserves energy.

Erin Catto (the author of Box2d) has several GDC presentations that show how to do this with impulses so you wouldn't need an entire physics solver to make it happen.

http://code.google.com/p/box2d/downloads/list

# Answer
> 3 votes
Implementing any constraint in an impulse/velocity solver comes down to finding the relative velocity between the two connected bodies that you want to remove.

In the case of the distance constraint, this relative velocity is always in the direction between the constraint anchor points.

If you get the relative velocity of the two bodies, project it onto the normalised vector between the anchor points, you'll have the velocity that you want to remove.

Then, all you'll need is an equation which lets you remove velocity by calculating an impulse. Plug in the velocity to remove and out pops an impulse which you can then apply equally and opposite to both rigid bodies.

If you'd like to read more about this process, I wrote an article a while back which covers designing a constraint in a impulse/velocity solver:

http://www.wildbunny.co.uk/blog/2011/04/06/physics-engines-for-dummies/

Hope it helps!

# Answer
> 1 votes
Why don't you take a look at the Box2D Source. In there you'll be able to see how the distance joint works. It might be a bit complex, but the part I would start with is "solveVelocityConstraints" in the b2DistanceJoint.

If all you are looking for is a very simplistic implementation then you could try this;

* Find the distance between ObjectA and ObjectB
* Find the difference the distance and the desired rest distance.
* Apply a force, proportional to this difference value, to each body, in the direction of the other body.

It might look similar to the following for a basic implementation (disclaimer, I don't have the ability to test this right now).

```
Vec3 dir = ObjectB.position - ObjectA.position;
float mag = (dir.length - targetLength) * 0.5f;
dir.normalise();
ObjectA.velocity += dir * -diff;
ObjectB.velocity += dir * diff;

```

Keep in mind this is a very simplistic implementation and is potentially unstable. Also keep in mind that this would never let the body "rest", so the two objects would be constantly moving towards and then away from each other, although it might be too small to see. This is why you would be best either using box2D or working out how it works and then replicating it.

# Answer
> 0 votes
There are a couple things you can do shorthand that do not require an entire physics solver.

See example. https://youtu.be/UDkccb5fRwY

The only real code in the solver for a distance joint is to propagate the change. What you need to do is find the current distance of that object, assume the object is pulled and figure where it's new position should be. Then figure the pull of that change and propagate it down the line.

My code for the example is:

```
public void tugEvent(LayerIndex index, double toX, double toY) {
        double newX, newY;
        int posPost;
        if (index == null) return;
        if (!index.isValid()) return;
        PointSeries points = index.getLayer().getPointSeries();
        newX = toX;
        newY = toY;
        posPost = index.pointIndex;
        for (int pose = points.size() - 1; posPost < pose; posPost++) {
            Point c = points.getPoint(posPost);
            Point n = points.getPoint(posPost + 1);
            double originalDistance = Geometry2D.distance(c.getX(), c.getY(), n.getX(), n.getY());
            invalidate((float) c.getX(), (float) c.getY());
            if (posPost != index.pointIndex) {
                c.setLocation(newX, newY);
            }
            double newDistance = Geometry2D.distance(newX, newY, n.getX(), n.getY());
            double direction = Geometry2D.angleR(n.getX(), n.getY(), newX, newY);
            double difference = newDistance - originalDistance;
            if (Math.abs(difference) <= 0.1d) {
                break;
            }
            newX = n.getX() + (Math.cos(direction) * difference);
            newY = n.getY() + (Math.sin(direction) * difference);
            if (posPost + 1 >= pose) {
                n.setLocation(newX, newY);
                break;
            }
        }
        newX = toX;
        newY = toY;
        int posPrior;
        posPrior = index.pointIndex;
        for (int pose = 0; posPrior > pose; posPrior--) {
            Point c = points.getPoint(posPrior);
            Point n = points.getPoint(posPrior - 1);
            double originalDistance = Geometry2D.distance(c.getX(), c.getY(), n.getX(), n.getY());
            if (posPrior != index.pointIndex) {
                c.setLocation(newX, newY);
            }
            double newDistance = Geometry2D.distance(newX, newY, n.getX(), n.getY());
            double direction = Geometry2D.angleR(n.getX(), n.getY(), newX, newY);
            double difference = newDistance - originalDistance;
            if (Math.abs(difference) <= 0.1d) {
                break;
            }
            newX = n.getX() + (Math.cos(direction) * difference);
            newY = n.getY() + (Math.sin(direction) * difference);
            if (posPrior - 1 <= 0) {
                n.setLocation(newX, newY);
                break;
            }
        }
        invalidateRange(index.getLayer().getPointSeries(), posPrior, posPost);
    }

```

It does it in both directions (hence the duplicate code block, but descending) so I can pull any point and abort when it gets a pull below a certain threshold. That's all you actually need. How does the change in location tug the next point down the line, and when you apply that vector to it, calculate it for the next attached values.

---
Tags: physics
---


title: Transform.Rotate micro stutter?

text:
# Question
Title: Transform.Rotate micro stutter?
Hey all I have a quick question.

I am new and obviously still learning the basics of programming/scripting. However I am confused by the result of a simple script.

The goal is to have a Start Menu with a 3d background.The camera is attached to an Empty Object, which has a script that is meant to constantly rotate.

My confusion, is whether I am live testing in Unity, or a built executable. When the empty object is rotating, it will have a pause or a few milliseconds, and then continue with its rotation. Almost like a planned micro stutter. Regardless of where it is in its cycle. How can I make the rotation as perfectly smooth as possible?

Below is the script for rotating the empty object that the camera is attached to.

public class cameraAnchor : MonoBehaviour {

```
public float speed = 5f;

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

    //rotate camera anchor around y axis
    transform.Rotate(Vector3.down, speed * Time.deltaTime);
}

```

}

# Answer
The problem was hardware related rather than software. I had a hardware malfunction that caused the issue.

If anyone is experiencing a "lag" in your computers processing speed it could be software, virus, or hardware related. Perform a thorough diagnostic before assuming anything.
> 1 votes

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


title: Texture does not fit the screen

text:
# Question
Title: Texture does not fit the screen
Hi guys I am really new in OpenGL-ES and I am developing a simple android application with NDK, and I just want to ask why the image is not fit after I set the width and height of it.

this is my `width` and `height`

```
const int FIXED_WIDTH = 320;
const int FIXED_HEIGHT = 568;

```

and this is how I set my `Matrix`

```
glViewport(0, 0, width, height);

// Create a new perspective projection matrix. The height will stay the same
// while the width will vary as per aspect ratio.
float left = FIXED_WIDTH;
float right = 0.0f;
float bottom = FIXED_HEIGHT;
float top = 0.0f;
float near = 1.0f;
float far = 50.0f;

mProjectionMatrix = Matrix::newFrustum(left, right, bottom, top, near, far);

// Position the eye in front of the origin.
float eyeX = 0.0f;
float eyeY = 0.0f;
float eyeZ = 1.0f;

// We are looking at the origin
float centerX = 0.0f;
float centerY = 0.0f;
float centerZ = 0.0f;

// Set our up vector.
float upX = 0.0f;
float upY = 1.0f;
float upZ = 0.0f;

// Set the view matrix.
mViewMatrix = Matrix::newLookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ);

// model * view * projection
mMVPMatrix->multiply(*mProjectionMatrix, *mViewMatrix);

```

After setting the `Matrix` I thought that my point 0.0 will start at the **top right** corner of the device (This is my understanding of **matrix**). as you shown in the image.

and this is how I setup my `texture`

```
TextureGenerator* textureGenerator = new TextureGenerator();
textureGenerator->setSize(320.0f, 568.0f); // width and height
textureGenerator->setTranslate(0.0f, 0.0f); // X and Y
textureGenerator->setTextureId(GLUtils::loadTexture("bg.jpg"));
mTextureCollection.push_back(textureGenerator);

```

then after I add some `texture` this is the result.

This is the actual picture, size 320x568.

as you can see to the result of my doing, I don't know if my point 0.0 is starting at the center. Please someone help and explain to me why the texture is not fit, and if my `matrix` is correctly set or not. Thank you.

# Answer
> 1 votes
You are very right about your guess that the "point 0.0 is starting at the center" - simply looking at the screenshot you can see it is the bottom left corner of your texture.
The provided code example only confirms the suspicion:

```
// We are looking at the origin
float centerX = 0.0f;
float centerY = 0.0f;
float centerZ = 0.0f;

```

which is setting the view *center* to `[0,0,0]`. Adjusting either the quad position or the eye+center position by `[-w/2, h/2]` should do the trick. Suggested further reading:
Understanding glm::lookAt()
Getting started with OpenGL coordinate system
Viewing and Transformations

---
Tags: android, textures, matrix, opengl-es, ndk
---


title: Using std::threads to optimize drawing

text:
# Question
Title: Using std::threads to optimize drawing
I'm currently developing a 3D game with its own engine. I have some performance issues in the function that orders all the draw events and sends them to the GPU. I've heard about threads, and I thought that it could be nice if I could pass that code to another thread. The structure is something like:

## Global function that receives all events and calls OpenGL to draw

```
void DrawAll(float dt, vector<draw_events>)

```

## Function inside the EventSystem, that calls the previous function

Events passed by copy, that have pointers to objects in the scene (scene is in main thread)

```
void ModuleEventSystem::PostUpdate(float dt)
{
   DrawAll(dt, draw_events);
}

```

This has been tested, and has worked well.

Now I have inside:

```
std::thread draw_thread;
void ModuleEventSystem::PostUpdate(float dt)
{
   if(draw_thread.IsJoinable())
         draw_thread.Join();

   draw_thread = std::thread(DrawAll, dt, events_to_draw);
}

```

The problem: not only the performance as become worse, objects in scene doesn't draw at all. I have never worked on threads before, so I don't know if the issue is having a thread with OpenGl calls and pointers pointing to objects in the main thread, or is the bad structure of code... Or even if this kind of optimization is not possible at all. Thank all of you.

# Answer
On the note of multithreaded rendering:

General it is inadvisable, due to the GL context being thread specific. In order to render on another thread, you have to make the context current on that particular thread. Besides the cost of making a context current, you should be aware that only one thread can have a current context at any one time, therefore you cannot actually perform parallel rendering. Which leads me to the next point.

On the point of multithreading in general:

There are two main ideas concerning multithreading. The first is the parallel data model, which takes a set of data, and processes it in parallel. This is analogous to your situation, in which you wish to perform some kind of processing on a set of data on multiple threads. This is how a GPU performs rendering, e.g. Each core in the GPU processes the colour of a pixel, or fragment in parallel with other cores. This model is not suitable for your needs, due to the aforementioned problems inherent with OpenGL contexts.

The second method is the parallel task model, which is far more suited to your needs, but would require a non-trivial amount of refactoring to achieve. The basic idea is to separate your tasks into groups, e.g. rendering, physics, game logic etc, and run these tasks on complete data sets in parallel, such as rendering on the main thread, with an additional thread performing physics processing and game logic on yet another thread. In the way, each task only operates on the latest version of the data involved. The benefit of this is that only minimal thread synchronisation is required, which allows maximum performance benefit.

I would recommend reading this post by Intel to understand this more fully.
> 0 votes

# Answer
From the OpenGL wiki on OpenGL contexts:

> The current context is a thread-local variable, so a single process can have several threads, each of which has its own current context. However, a single context cannot be current in multiple threads at the same time.

Your new rendering thread doesn't have a current OpenGL context selected yet so it renders to nothing and you'll need to release that context from your main app thread before selecting it in your rendering thread.

---

However if ordering your render call is where the bottleneck is I recommend ditching the multi-threaded sort approach and rather keep all your rendering objects sorted between render calls and insert-sort those that change using, for example, a persistent `std::multimap<order_value, draw_event*>` container.

Before changing the order value you remove its entry from the multimap and insert it back in the new position after changing the order value.

Rendered objects generally keep their render order between frames.

The fastest sort function is the one you don't call.
> 1 votes

---
Tags: opengl, optimization, multithreading
---


# Question
Title: Game AI move towards player while avoiding an obstacle
I'm trying to move enemy towards player, while enemy also tries to avoid an obstacle if it's in its path. Here's a simple illustration of what I want to do:

What I've tried:

* Making circular collision around the obstacle. It works but that makes the enemy impossible to hit.
* I think going with an A\* pathfinding algorithm might be a bit overkill especially since it's designed for multiple obstacles, where in my case there is only the mouse and wall collision concerned.
* Moving the enemy towards the player, while also moving away from the obstacle at a slower speed. This works better because you can actually hit the enemy, but also slows down enemy if obstacle if it's in its path.

My questions:

1. Is there a better way to go about doing this?
2. Anything you would've done differently with my code to either improve or optimize?

Here's the code I have currently in my game logic and a fully-working example on jsFiddle.

```
// Calculate vector between player and target
var toPlayerX = playerPosX - enemyPosX;
var toPlayerY = playerPosY - enemyPosY;

// Calculate vector between mouse and target
var toMouseX = mousePosX - enemyPosX;
var toMouseY = mousePosY - enemyPosY;

// Calculate distance between player and enemy, mouse and enemy
var toPlayerLength = Math.sqrt(toPlayerX * toPlayerX + toPlayerY * toPlayerY);
var toMouseLength = Math.sqrt(toMouseX * toMouseX + toMouseY * toMouseY);

// Normalize vector player
toPlayerX = toPlayerX / toPlayerLength;
toPlayerY = toPlayerY / toPlayerLength;

// Normalize vector mouse
toMouseX = toMouseX / toMouseLength;
toMouseY = toMouseY / toMouseLength;

// Move enemy torwards player
enemyPosX += toPlayerX * speed;
enemyPosY += toPlayerY * speed;

// Move enemy away from obstacle (a bit slower than towards player)
enemyPosX -= toMouseX * (speed * 0.4);
enemyPosY -= toMouseY * (speed * 0.4);

```

# Answer
> 2 votes
There's a few questions that are very relevant to the potential answer given.

**What is the desired behavior?**

It's clear you want the enemy to avoid the obstacle/mouse, but how? Is it a zombie ambling towards a human? A fast moving jet flying towards a location? Is it an abstract shape moving towards another abstract shape? Is it a ghost avoiding a proton-pack-style beam?

The nature of the enemy and the obstacle matters when determining how it avoids the obstacle. An animal or zombie might stop or even reverse direction. A trained soldier might make attempts to dodge or predict pathing. A jet, car, or other entity with velocity could only make course corrections. A ghost might be able to simply disappear or teleport. A normal person might try moving/dodging or retreating, but be more sluggish than others (utilizing JibbSmart's idea)

The *kind* of entity it is determines the method by which it would avoid the obstacle.

**What is the desired difficulty?**

You could easily make an entity that could, quite literally, never be touched with the mouse. You could also make an entity that merely bee-lined and didn't avoid the mouse at all. It's clear you want something in the middle, but the level of difficulty matters.

Can the enemy speed up? Does the enemy have knowledge of past obstacle location? Can the enemy predict future locations? If this is a very simple entity with no ability to predict or alter tactics, are there other planned means to introduce varying levels of difficulty? Is it a possibility to have different "types" of enemies that utilize different methods of obstacle avoidance?

This information is important because, with no ability to predict the obstacle or alter speed, it will inevitably be slower when avoiding the obstacle/mouse than it would be moving directly towards the player. There's no way to avoid an obstacle slowing the enemy down.

**The solution**

If, however, *all* you want to do is merely avoid the obstacle with present-state knowledge, but do so in a reasonable way that provides difficulty but not impossibility, you do not want to simply add an "away from mouse" vector to the "towards player" vector. Rather, what you want is to change the angle of approach.

To do this, you'll need to do the following:

1. Calculate the angle to the goal/player
2. Calculate the angle and distance to the obstacle/mouse
3. Determine if the angle and distance to the obstacle is in the enemy's "danger zone" (is it a threat?)
4. If the obstacle is a threat, steer away from it in whichever direction is closer to the angle to the goal/player

The angle and distance of the "danger zone" and the angle chosen to steer around the obstacle are going to be determined when you are balancing difficulty.

The math goes something like this:

```
angleToPlayer = atan(toPlayerY, toPlayerX)
angleToMouse = atan(toMouseY, toMouseX)
angleToMove = angleToPlayer

if obstacleIsADanger {
  angleToMove += courseCorrectionAngle
}

enemyPosX += cos(enemyAngle) * speed
enemyPosY += sin(enemyAngle) * speed

```

Arctangent helps you find the angle to the relevant objects using the x and y coordinates Cosine determines the normalized x distance to travel, while Sine determines the normalized y distance to travel

# Answer
> 1 votes
One thing that makes shooting moving targets really interesting is that we as humans have slow reaction times. When we hit a moving target, it's because we've successfully estimated where that target will be after the span of our reaction time has passed and met the target there with our aimer.

For this enemy to avoid the mouse but still be hittable, you could give it a delayed reaction time. Have it pathfind through (or perform collision with) an old version of the current state.

If you keep a ring buffer of recent states (it doesn't have to be every frame if that's too much -- it could interpolate between a few states), you can have the enemy look back in time say half a second (or whatever works best for the difficulty you're going for) and give it circular collision with that old state. This'll require the player to quickly move over the enemy and fire where they anticipate the enemy will be in order to beat its reaction time.

Also, you could have the invisible collision circle around the mouse shrink when it moves quickly or changes direction, and grow over time back to full size when it's relatively still or moving consistently. This might have the enemy appear to keep a wide berth from the mouse when its position is obvious, but force it to make only small moves to avoid it when the mouse moves quickly.

---
Tags: javascript, ai, game-mechanics, path-finding
---


# Question
Title: Do multiplayer games use common server frameworks?
I mean, does each game company develop its own chat server? Login server?

I'm not sure how massive multiplayer games work, I believe they each have a login/lobby server and game servers, which the login server puts players in until they fill up and then continues to the next one (I'll call this "scaling"). Does each company develop its own scaling algorithm?

\*I'm not sure which tags I should put on, please help me with this.

# Answer
> 0 votes
Let's use World of Warcraft (wow) as an example:

The game client's first point of contact is the login server. This server processes your username and password, and interfaces with some form of use database, and handles privileges for certain users such as admins.

Once logged in, a list of available game servers, and player counts for each server is populated and presented to the user.

Once a game server is selected, the list of characters for the selected server is displayed (if any), and the option to join the server with the selected character, or create a new one.

When a group of character decides to run a dungeon or raid, another "lobby" server is joined which creates an instance of a smaller game server, in which the self contained dungeon exists. The players are then joined to this server to play the instance. When complete and all players leave, after a designated amount of time, the instance of that server is destroyed, unless it is a raid, in which case the progress (which bosses have been defeated) are saved to a database, along with the character names, game server name, and all participating players is saved to a database.

Later, if players rejoin that raid, the raid server is queried based on dungeon type/name, server name and character name. If an entry is found, an instance is created with the appropriate settings (defeated bosses missing). If not, a new instance is created and the players join as normal.

That about sums it up. Pretty much every multiplayer game uses this same basic architecture, though with differences specific to the type of game.

Even with smaller multiplayer environments on Steam, this principle still applies. Steam servers provide the framework for logins, but the developers will provide a lobby, which provides a list of available game servers. This precludes the need for "scaling".

Scaling, when necessary, is done rather naively, with performance/stress testing dictating the maximum number of players, which is then provided as configuration data as an upper limit. If the maximum number of players is reached in a login, or lobby server, players is placed in a queue, and informed to wait or try later.

---
Tags: networking, multiplayer, mmo
---


title: Create lamp shade material

text:
# Question
Title: Create lamp shade material
How would one go about creating a lamp shade material that lets light through from a light inside the object. I have read that turning of shadow casting for that object should work, however I have turned off `Cast Shadows` but it doesn't work.

Here are some pictures:

**Light off:**

**Light on:**

The lampshade remains dark. How can I fix this?

# Answer
You need a Shader that supports Translucency. The free pack from the unity asset store Lux Personal has a good solution. You can download it and start from there. Also here is a translucent shader from the web :

```
Shader "Custom/Translucent" {
    Properties {
        _MainTex ("Base (RGB)", 2D) = "white" {}
        _BumpMap ("Normal (Normal)", 2D) = "bump" {}
        _Color ("Main Color", Color) = (1,1,1,1)
        _SpecColor ("Specular Color", Color) = (0.5, 0.5, 0.5, 1)
        _Shininess ("Shininess", Range (0.03, 1)) = 0.078125

        //_Thickness = Thickness texture (invert normals, bake AO).
        //_Power = "Sharpness" of translucent glow.
        //_Distortion = Subsurface distortion, shifts surface normal, effectively a refractive index.
        //_Scale = Multiplier for translucent glow - should be per-light, really.
        //_SubColor = Subsurface colour.
        _Thickness ("Thickness (R)", 2D) = "bump" {}
        _Power ("Subsurface Power", Float) = 1.0
        _Distortion ("Subsurface Distortion", Float) = 0.0
        _Scale ("Subsurface Scale", Float) = 0.5
        _SubColor ("Subsurface Color", Color) = (1.0, 1.0, 1.0, 1.0)
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        #pragma surface surf Translucent
        #pragma exclude_renderers flash

        sampler2D _MainTex, _BumpMap, _Thickness;
        float _Scale, _Power, _Distortion;
        fixed4 _Color, _SubColor;
        half _Shininess;

        struct Input {
            float2 uv_MainTex;
        };

        void surf (Input IN, inout SurfaceOutput o) {
            fixed4 tex = tex2D(_MainTex, IN.uv_MainTex);
            o.Albedo = tex.rgb * _Color.rgb;
            o.Alpha = tex2D(_Thickness, IN.uv_MainTex).r;
            o.Gloss = tex.a;
            o.Specular = _Shininess;
            o.Normal = UnpackNormal(tex2D(_BumpMap, IN.uv_MainTex));
        }

        inline fixed4 LightingTranslucent (SurfaceOutput s, fixed3 lightDir, fixed3 viewDir, fixed atten)
        {
            // You can remove these two lines,
            // to save some instructions. They're just
            // here for visual fidelity.
            viewDir = normalize ( viewDir );
            lightDir = normalize ( lightDir );

            // Translucency.
            half3 transLightDir = lightDir + s.Normal * _Distortion;
            float transDot = pow ( max (0, dot ( viewDir, -transLightDir ) ), _Power ) * _Scale;
            fixed3 transLight = (atten * 2) * ( transDot ) * s.Alpha * _SubColor.rgb;
            fixed3 transAlbedo = s.Albedo * _LightColor0.rgb * transLight;

            // Regular BlinnPhong.
            half3 h = normalize (lightDir + viewDir);
            fixed diff = max (0, dot (s.Normal, lightDir));
            float nh = max (0, dot (s.Normal, h));
            float spec = pow (nh, s.Specular*128.0) * s.Gloss;
            fixed3 diffAlbedo = (s.Albedo * _LightColor0.rgb * diff + _LightColor0.rgb * _SpecColor.rgb * spec) * (atten * 2);

            // Add the two together.
            fixed4 c;
            c.rgb = diffAlbedo + transAlbedo;
            c.a = _LightColor0.a * _SpecColor.a * spec * atten;
            return c;
        }

        ENDCG
    }
    FallBack "Bumped Diffuse"
}

```
> 0 votes

---
Tags: unity, c#, lighting, materials
---


# Question
Title: Is it still possible for one person to make a complete game?
Is it still possible for one person to design and develop a complete game with all audio/visual/game mechanics aspects in place (complete package). I have some interest in game development, but don’t want to hire anyone... but wondering if it’s even feasible anymore to go solo.

# Answer
> 4 votes
Short answer: Yes.

Long answer: It depends on the scope of your game. It's entirely possible for one person to create a decent game, but if you want it to be profitable, you will have to wear a lot of hats: designer, programmer, artist, audio engineer, marketing exec, and tester. Not only that, you will have to plan and manage your own project.

You also have to consider the timescales involved. Every feature will require new code, testing, potentially new assets, and will need to be designed in such a way as to be maintainable. All this takes time, so you have to decide how much time you have to devote to your project.

So to summarise:

You can totally do games as a solo developer, but don't expect to be able to produce a AAA game any time soon. Hobby/web games are totally doable within reasonable timescales and cost.

# Answer
> 2 votes
Yes it is possible, if you have the motivation needed to do it, it won't be easy I can tell you, but if you work hard at it you will succeed. And another important thing, think simple don't try to do the biggest game of your career, make something simple.

# Answer
> 2 votes
It depends on the scale of your game. Monsters like "Call of Duty" require thousands of person-years. You don't have that long. OTOH, if you start with the right tools (which you already know how to use), a new game can be done in day (if it's simple enough).

You should also consider your actual goal. If making the game is an end in itself, it's a very different thing than if you want thousands of happy users.

---
Tags: development-speed
---


# Question
Title: What is the difference between Character Modeling and Level Design?
I'm thinking of either focusing on character modeling or level design, but I'm not sure what the differences are. Do companies consider them as separate jobs because I don't know that either.

My background: *Currently I'm in an associates program for Game Programming, but over the last semester due to my work schedule there was no programming class available for me to take so instead I decided to take 3D Modeling. But as I'm reaching the end of the class I noticed I'm enjoying the 3D Modeling a lot more than programming, so I decided to stick with the art side. However, due to unforeseen circumstances, I'm going to have to move soon and transfer to a new university. Now this new university that I'm going to be attending how the program is set up so that you're required to pick a particular area to focus on. But I'm not sure what to do.*

# Answer
> 2 votes
A character modeller is a 3D artist responsible for creating the polygon meshes for characters in the game. Depending on the team they might also do some or all of the texturing of those models, or that might be handled by dedicated texture artists. The rigging & weighting of the model for animation is typically done by a technical artist or rigger, but on small teams those hats might all be worn by the same artist.

A level designer is responsible for the layout of game environments and the sequencing and setup of gameplay events and triggers within them. In a large team they might do the initial greyblock pass, roughing out the volumes and hierarchy to figure out how to tell the right story through space and support the right gameplay, and work with specialized level artists to fill in the rendered detail. Designers also work on placing and tuning interactivity in the space — triggers for special events, resources and navigation elements the player can use, etc. Level designers will often participate in encounter & mission/quest design, setting up the challenges and opportunities players face, though again this can be its own specialized role in larger teams.

---
Tags: 3d, level-design, 3d-modeling
---


# Question
Title: Zooming versus panning in a 3D FPS fly camera
Imagine you have a strategy game, and it's rendered in openGL, in 3D. You have an overview of the map and the camera is currently looking at the direction of the ground at some angle (but is not limited to this angle). Like the standard view in the CIV games.

You now do one of the two actions:

A) You move the camera along its line of sight towards the ground (forward). B) You scale the whole scene by a factor \>1.

If I understand these actions correctly, both situations should have exactly the same visual result, zooming in. The player shouldn't really be able to tell which of the two has happened.

My questions is, firstly, am I right to assume this?

If no, what is the observable difference? If yes, which mechanic should be used?

Note that I am thinking about this in regards of use in a level editor.

Thinking about it a little further, the difference should become visible if player moves the camera after the action - the camera in the scaled version would move at an apparently slower speed, right?

Would there be any other side effects? Which behavior would be expected by the player/user?

If you assume an FPS fly camera (one that yaws and tilts, but does not roll), is there any scenario where the scaling method would be preferred?

# Answer
> 1 votes
In a **zoom shot**, the subject gets bigger within the frame, the spatial relationship between the subject and the objects or people around the subject will not change. However, **when there is a movement of the camera**, the relative position of everything within the frame changes constantly.If it is an **orthographic shot** then you can fake it by scaling. Panning creates a sense of speed around a moving object by combining shutter speed with camera motion.

---
Tags: camera, movement
---


# Question
Title: Why don't my generated instances update when I change their prefab?
I’m making an Editor tool -- a ScriptableWizard -- that instantiates a prefab on a grid. But I find that when I update the prefab, the instances don’t update.

When I instantiate prefabs interactively in the Editor by dragging them from the Project panel to the Scene or Hierarchy, then updates to the prefab affect the instances as expected.

I see another difference between my scripted instances and the ones created when I drag the prefab into the scene: when I do it interactively, the instance in the hierarchy is listed in blue. But the instances I create from script using the same prefab are listed in black, similar to objects created directly in the scene.

Here’s the hierarchy; the “JitterPrefab” was dragged into the scene, and the ones under “gridParent” were instances of the JitterPrefab generated from my script:

Here’s how I’m generating the instances:

```
public GameObject prefab; ...

void OnWizardCreate() { ...
  Transform instance = Instantiate (prefab.transform, pos, rot, parent.transform);
  instance.name = string.Format ("L{0:D2}-R{1:D2}-C{2:D2}", l, r, c);
  ...
}

```

When I make a change on the prefab, e.g. change the radius of the Jitter script from 0.025 to 0.25, the manually created instance updates:

But the script-generated instances do not:

What am I doing wrong? Why are my scripted instances no longer connected to the original prefab? And, separately, how to I tell in the editor (or in script) whether an object in the scene is an instance of a prefab or not?

# Answer
Instantiate creates it as a game object thus loosing the prefab link. You want to use PrefabUtility.InstantiatePrefab() in order to spawn the object in the scene and maintain the prefab link.
> 4 votes

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


title: How do I add a "pointer" to my UI menu?

text:
# Question
Title: How do I add a "pointer" to my UI menu?
I'm sure there has to be a simple answer to this, but frankly I cannot find anything about it anywhere on the internet, so I'm asking here. How do I add a pointer like this hand to the side of the currently selected UI button in my game?

I tried using Unity's built in UI system to do this, using the "sprite swap" feature that changes sprites based on whether or not the button is currently selected. I made an image for my "Play" button, and then an image for when the play button was selected that included a pointer as part of the image, but the image would either resize when the button was selected, or the image was moved to the right to accommodate Unity's centering mechanic on the UI. Perhaps this wasn't so wrong, and I'm just not using the UI system correctly.

Does a feature like this have to be hard coded into the UI design?

# Answer
> 2 votes
I would write a small script that takes the currently selected button and has a fuction that gets called from a event that changes the position of the hand to the position of the selected button + an offset so that it is to the side.

# Answer
> 1 votes
It is absolutely doable with the built in UI. Find a way yo store the hands all possible positions in a List or Array. I.e:
-you can just subtract the distance from your UI buttons positions to the hand positions, and then store the new positions.
Then find a way to change your sprites position based on user input i.e:
-declare an index variable, and increment, decrement, and clamp it according to user input and your design, i.e:

In your start or wherever you need to declare them:

```
GameObject handPrefab=//YourHandPrefab added in editor, etc
Vector3[] handPositions=//hand positions

```

In your update:

```
if(yourUpButtonPressed){

  handPositionIndex++;
  handPositionIndex=handPositionIndex%handPositions.Length; //this jumps back to 0 if Length reached
  handPosition.transform.position=handPositions[handPositionIndex];

}

```

Obviously, you gotta do all these for your directions, you are going to use.

Or if you going an event driven way:
Declare your event in start or where you want it and add a lambda expression that matches the signature.

```
public event YourUIDelegate OnUIMenuNavigate;

OnUIMenuNavigate+=(int x)=>{

 handPositionIndex+=x;
 handPositionIndex=handPositionIndex%handPositions.Length; //this jumps back to 0 if Length reached
 handPosition.transform.position=handPositions[handPositionIndex];

};

```

Call your OnUIMenuNavigate where you deal with the logic of navigation in the UI.

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


# Question
Title: Why when rotating object 360 degrees on the x, it rotates once then stops?
```
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class MeshGenerator : MonoBehaviour
{
    public GameObject meshPrefab;
    public Vector3[] newVertices;
    public Vector2[] newUV;
    public int[] newTriangles;

    private List<Vector3> verticesList = new List<Vector3>();
    private List<Vector2> uvsList = new List<Vector2>();
    private List<int> trianglesList = new List<int>();
    private GameObject go;

    private void Start()
    {
        Mesh meshprefab = meshPrefab.GetComponent<MeshFilter>().sharedMesh;
        newVertices = meshprefab.vertices;
        newTriangles = meshprefab.triangles;

        for (int i = 0; i < newVertices.Length - 2; i++)
        {
            DrawLine(newVertices[i], newVertices[i + 1], Color.red);
            DrawLine(newVertices[i + 1], newVertices[i + 2], Color.red);
            DrawLine(newVertices[i + 2], newVertices[i], Color.red);
        }
    }

    void DrawLine(Vector3 start, Vector3 end, Color color, float duration = 0.2f)
    {
        go = GameObject.Find("Lines");
        GameObject myLine = new GameObject();
        myLine.transform.parent = go.transform;
        myLine.transform.position = start;
        myLine.AddComponent<LineRenderer>();
        LineRenderer lr = myLine.GetComponent<LineRenderer>();
        lr.material = new Material(Shader.Find("Particles/Alpha Blended Premultiply"));
        lr.startColor = color;
        lr.endColor = color;
        lr.startWidth = 0.05f;
        lr.endWidth = 0.05f;
        lr.useWorldSpace = false;
        lr.SetPosition(0, start);
        lr.SetPosition(1, end);
    }

    private void Update()
    {
        var p = go.transform.eulerAngles;
        p.x += 1;
        go.transform.eulerAngles = p;
    }
}

```

This is the rotation part:

```
private void Update()
    {
        var p = go.transform.eulerAngles;
        p.x += 1;
        go.transform.eulerAngles = p;
    }

```

It's rotating 360 degrees once, then it stops rotating but keeps shaking like it's trying to keep rotating but something keeps it from continue.

# Answer
Euler angles are used to print a human-readable description of the object's orientation in the Inspector, but they're not the underlying model that Unity uses.

That means that when you set an orientation in Euler angles, Unity transforms that description into its internal representation (likely a quaternion). When you then ask for Euler angles in the next frame, it calculated new Euler angles from that internal model.

Because each orientation has many possible Euler angle representations (eg. add or remove a multiple of 360 on any axis and you get the same orientation), Unity has to have a policy about which one to return - and you're not guaranteed to get back the same one you put in. There have to be wrap-around points somewhere, where the angles you get back are very different from those you put in.

In this case, as you reach (91, 0, 0), Unity will return this orientation as (89, 180, 180) - an equivalent way to describe that orientation, with |x| \<= 90.

But there's one crucial difference:

* near (90, 0, 0), increasing x causes the object to pitch downward
* near (90, 180, 180), increasing x causes the object to pitch upward

That's because order of rotations matters, and in Unity's angle system, the y rotation is applied first. So the object rotates 180 degrees around y, flipping the local x axis around to the other side, then rotates about the x axis, then finally rotates around the z axis to undo the earlier flip. But by that time it's already applied the pitch in the opposite direction to what you were expecting.

This flip in pitch direction means in one frame your object pitches down to (90+e, 0, 0), then in the next frame it starts from (90-e, 180, 180) and the +1 takes it back the other way to (89+e, 0, 0). So it sits there vibrating, constantly bouncing between the two orientations.

For this reason, you should be very careful when trying to calculate an orientation by doing math on Euler angles. It's rarely what you really want.

Instead, if you want to rotate 1 degree on the local x axis, don't try to calculate the Euler angles yourself, just tell Unity you want to rotate 1 degree on the local x axis:

```
transform.Rotate(1, 0, 0); // Equivalently, transform.Rotate(Vector3.right, 1);

```

Fewer lines, and actually does the right thing.

Don't forget to correct for framerate though, so you probably want instead:

```
transform.Rotate(pitchSpeed * Time.deltaTime, 0 , 0);

```
> 4 votes

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


# Question
Title: How to find asset by it's number? Don't know what this number means
I need to find the asset that is displayed by this number inside my project. I guess this number means "GUID" but it's hard for me to understand what is it. Can you help me guys?

# Answer
> 1 votes
Inside your Assets folder, look for files with a `.meta` extension. These are hidden by default, so you may need to show hidden files to see them.

These are how Unity manages references between files in your project, as well as storing import settings for assets. The part before the `.meta` extension is the name of the file or folder for which this file provides metadata information.

For example, here's a snippet of the meta file for a texture asset:

```
fileFormatVersion: 2
guid: b16e813e7d26abe4bbbb349009f631be
timeCreated: 1519570387
licenseType: Free
TextureImporter:
    fileIDToRecycleName: {}
    externalObjects: {}
    serializedVersion: 4
    mipmaps:
        mipMapMode: 0
        enableMipMap: 1
        sRGBTexture: 1
        linearTexture: 0
        fadeOut: 0
        borderMipMap: 0
        mipMapsPreserveCoverage: 0
        alphaTestReferenceValue: 0.5
        mipMapFadeDistanceStart: 1
        mipMapFadeDistanceEnd: 3

```

The second line `guid:` shows the unique ID associated with this object. You can use something like Notepad++'s "Find in Files" to search your project folder for a meta file containing a particular GUID string.

---
Tags: unity, assets
---


title: What is a Linker Map Address ()

text:
# Question
Title: What is a Linker Map Address ()
I need to know how to execute a linker map address and use a draw method in xna 4.0 to for example in c#

My subfolder has this in it

textures models sounds ui scripts shaders linker map address

```
public void Draw()

{

// I need to execute my assets with the linker map address.

}

```

# Answer
So looking at your other post on the subject, it looks like this is relating to doom. Doom uses maps with the extension .map. However, many programs use the .map extension. What you are seeing is Visual studio thinks that that file is a file it knows.

If you want info on loading/using Doom maps, see

Given that there are only so many 3 letter combinations, something as common as .map will get reused by different programs for different things. Windows will not necessarily give you the right answer as to what that file is
> 1 votes

---
Tags: c#, xna-4.0, windows, visual-studio, microsoft
---


# Question
Title: How to use RSSetScissorRects with multiple rects?
I try this and work only first rect.

```
D3D11_RECT rc[2];
rc[0] = {0, 0, 16, 16};
rc[1] = {32, 32, 64, 64};

m_d3d11DevCon->RSSetScissorRects( 2, rc );

```

# Answer
Documentation link: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476478(v=vs.85).aspx

> Which scissor rectangle to use is determined by the SV\_ViewportArrayIndex semantic output by a geometry shader (see shader semantic syntax). If a geometry shader does not make use of the SV\_ViewportArrayIndex semantic then Direct3D will use the first scissor rectangle in the array.
>
> Each scissor rectangle in the array corresponds to a viewport in an array of viewports (see ID3D11DeviceContext::RSSetViewports).

The conditions for being able to use multiple scissor rectangles are therefore:

* You must also be using an array of viewports.
* Each scissor rect needs a corresponding viewport.
* the geometry shader stage must be active.
* The geometry shader must write to SV\_ViewportArrayIndex which determines both the viewport and scissor rect to use.

Otherwise the behaviour is that only the first scissor rect is used.
> 1 votes

---
Tags: directx11
---


# Question
Title: Instantiate a sprite using json data value (C# Unity)
Here is my code :

**BetBoard\_Test.cs**

```
 //Scoreboard
[SerializeField] protected GameObject prefab_big_road = null;

[SerializeField] Transform pos_big_road = null;

string jsonString = "[1, 1, 1, 2, 1, 1, 1, 2, 1, 2, 1, 1, 1, 2, 1, 1]"; //sample data

private void Start()
{

    ExampleClass dataParser = new ExampleClass();
    dataParser.dataToParse = jsonString;

    //Convert to Json
    string exampleClassToJson = JsonUtility.ToJson(dataParser);
    Debug.Log(exampleClassToJson);

    ExampleClass obj = JsonUtility.FromJson<ExampleClass>(exampleClassToJson);
    //Loop over it
    for (int i = 1; i < obj.dataToParse.Length - 1; i += 3)
    {
        char indivisualChar = obj.dataToParse[i];

        Debug.Log(indivisualChar);
    }

    WinLog();
}

IEnumerator WinLog_big_road()
{
    DeleteChildrens(pos_big_road);

    yield return new WaitForEndOfFrame();

    int[] array_big_road = tzPlayInfo.Instance._BIG_ROAD_;

    for (int i = 0; i < rh.Const._HISTORY_COUNT_ * rh.Const._HISTORY_HEIGHT_; i++)
    {
        if (array_big_road[i] == 0) continue;

        int x = i % rh.Const._HISTORY_COUNT_;
        int y = i / rh.Const._HISTORY_COUNT_;
        float xl = 9.0f;
        float yl = -8.0f;

        GameObject o = Instantiate(prefab_big_road) as GameObject;
        o.transform.SetParent(pos_big_road);
        o.transform.localScale = Vector3.one; //(1,1,1)

        o.transform.localPosition = new Vector3(x * xl, y * yl, 0f);
        o.GetComponent<UISprite>().spriteName = array_big_road[i] == 1 ? "layout_player_bigline-01" : "layout_banker_bigline-01";

        NGUITools.SetActive(o, true);
        yield return new WaitForEndOfFrame();
    }
    yield break;
}

    void DeleteChildrens(Transform t)
    {
        NGUITools.DestroyChildren(t);
    }

    public void WinLog()
    {
        StopCoroutine("WinLog_big_road");
        StartCoroutine("WinLog_big_road");
    }
}

[Serializable]
public class ExampleClass
{
    public string dataToParse;
}

```

**ConstantValue.cs**

```
public const int _HISTORY_COUNT_ = 70;
public const int _HISTORY_HEIGHT_ = 6;

```

**PlayInfo.cs**

```
public int[] _BIG_ROAD_ = new int[Const._HISTORY_COUNT_ * Const._HISTORY_HEIGHT_ ];

```

What i am trying to achieve here is that *see image*

my `jsonString="[1, 1, 2, 2, 1, 1, 1, 2, 1, 2, 1, 1, 1, 2, 1, 1]";` that is converted into json format needs to do it something like this for example

```
1 = blue circle
2 = red circle

```

just like that in the picture every value on my json data needs to be instantiated with the sprite that is equivalent to 1 and 2 which is i have this condition `o.GetComponent<UISprite>().spriteName = array_big_road[i] == 1 ? "layout_player_bigline-01" : "layout_banker_bigline-01";`

PS: I am very sorry if i couldn't explain it very well because english is not my native so i provided a picture. I am very sorry.

I did it like this but the problem is that it's not getting what i want all the red which is `2` is the only appearing on the board

```
 for (int i = 1; i < obj.dataToParse.Length - 1; i += 3)
    {
        char indivisualChar = obj.dataToParse[i];
        int j = 0;

        if(j < rh.Const._HISTORY_COUNT_ * rh.Const._HISTORY_HEIGHT_)
        {
            //lets increment it
            j++;
            //instantiate the sprite
            GameObject o = Instantiate(prefab_big_road) as GameObject;
            o.transform.SetParent(pos_big_road);
            o.transform.localScale = Vector3.one; //(1,1,1)
            int x = j % rh.Const._HISTORY_COUNT_;
            int y = j / rh.Const._HISTORY_COUNT_;
            float xl = 9.0f;
            float yl = -8.0f;
            o.transform.localPosition = new Vector3(x * xl, y * yl, 0f);
            //o.GetComponent<UISprite>().spriteName = indivisualChar == 1 ? "layout_player_bigline-01" : "layout_banker_bigline-01";
            if (indivisualChar == 1)
            {
                o.GetComponent<UISprite>().spriteName = "layout_player_bigline-01";
                NGUITools.SetActive(o, true);
            }
            else
            {
                o.GetComponent<UISprite>().spriteName = "layout_banker_bigline-01";
                NGUITools.SetActive(o, true);
            }
        }
       //Debug.Log(indivisualChar);
    }

```

More information:

It just give me this

All of the sprites are in one place and the second problem of that is all the prefab that is cloned is always **red** (`2`) which is `1` is for blue and `2` is for red.

# Answer
> 0 votes
I solved it . This is how i solved it

`o.GetComponent<UISprite>().spriteName = array_big_road[i] == '1' ? "layout_player_bigline-01" : "layout_banker_bigline-01";`

---
Tags: unity, c#, sprites, json
---


# Question
Title: How can I send Android notifications from my Unity game?
I'm want to send local notification on Android with Unity3D but I don't know how to do it. Any suggestions?

# Answer
It can be done using FCM (Firebase Cloud Messaging)

https://firebase.google.com/docs/cloud-messaging/unity/client
> 0 votes

# Answer
If you're looking for an easy way to implement it, there's this free asset: https://assetstore.unity.com/packages/tools/integration/simple-android-notifications-free-68626

If you want to make it yourself (if you for some reason need a more complex system), you can read this discussion: https://forum.unity.com/threads/push-notifications-on-unity-android.126528/

In case the forum or the linked post shuts down, here's a general overview of the information contained within:

* There is no native Unity support for it.
* It's really difficult to build it yourself, so it is recommended you don't because there are plugins that people have already made for it.
* If you want to do it yourself, you'll have to go into the Android documentations and figure out how to communicate to it from within Unity.

Then there are a few people trying to sell their own solutions on the asset store.

So **tl;dr:** *Use the free assets, it saves you time, money and frustration.*

Good luck!
> 2 votes

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


# Question
Title: Implementation details of Command Pattern in conjunction with Entity Component System
I have implemented an ECS where more or less an Entity is just an ID, a Component is just a wrapper for data, and a System holds the logic on operating over different components. There is an Engine that has a list of the entities, a table of the components and a list of the different types of systems (update and draw systems).

I was working on handling input when I reached a conflict: how I would resolve opposing inputs (for example, pressing left and right at the same time). So I decided to try and implement the Command Pattern to work with the ECS.

But I'm stumped. I'm not sure how to create a command, let's say moveLeftCommand, without knowing the intimate details about each entity that would effect. Also, since all my logic is in the systems, (if I understand the Command Pattern) it should have an execute function which will carry out the command. How do I populate the execute command if there isn't any logic that "belongs" to an entity?

Thanks for any help!

# Answer
> How do I populate the execute command if there isn't any logic that "belongs" to an entity?

But there ***is*** a mechanism for applying logic to an entity: Systems. In ECS, Systems map behavior to entities that have a specific set of components (e.g. apply "move" logic to all entities that have a `Transform` and `Velocity` component). So in your case you would:

1. Create a `MoveCommand` component with a direction.
2. Create a `MoveSystem` that iterates over all entities with a `MoveCommand` component and a `Position` component (or its equivalent).
3. In the `MoveSystem` modify the `Position` based on the direction in the `MoveCommand` and remove the component.
> 3 votes

# Answer
I hope this will be of some help.

I'm not sure it really matter if two keys are pressed at the same time because if I press forward and left then I move at diagonal left, forward and back does nothing because they cancel each other out its the same with left and right because they both have the same speed value they cancel each other out.

this is how I do my input handling:

```
 If Device.KeyBoredState.IsPressed(SharpDX.DirectInput.Key.A) Then
            _position.Z += _speed * CSng(Math.Sin(MathHelper.ToRadians(_yaw))) * _gametime.ElapsedGameTime.Milliseconds
            _position.X -= _speed * CSng(Math.Cos(MathHelper.ToRadians(_yaw))) * _gametime.ElapsedGameTime.Milliseconds

        End If
        If Device.KeyBoredState.IsPressed(SharpDX.DirectInput.Key.D) Then
            _position.Z -= _speed * CSng(Math.Sin(MathHelper.ToRadians(_yaw))) * _gametime.ElapsedGameTime.Milliseconds
            _position.X += _speed * CSng(Math.Cos(MathHelper.ToRadians(_yaw))) * _gametime.ElapsedGameTime.Milliseconds
        End If

        If Device.KeyBoredState.IsPressed(SharpDX.DirectInput.Key.W) Then
            _position.Z -= _speed * CSng(Math.Cos(MathHelper.ToRadians(_yaw))) * _gametime.ElapsedGameTime.Milliseconds
            _position.X -= _speed * CSng(Math.Sin(MathHelper.ToRadians(_yaw))) * _gametime.ElapsedGameTime.Milliseconds

        End If
        If Device.KeyBoredState.IsPressed(SharpDX.DirectInput.Key.S) Then
            _position.Z += _speed * CSng(Math.Cos(MathHelper.ToRadians(_yaw))) * _gametime.ElapsedGameTime.Milliseconds
            _position.X += _speed * CSng(Math.Sin(MathHelper.ToRadians(_yaw))) * _gametime.ElapsedGameTime.Milliseconds
        End If

```
> 0 votes

---
Tags: entity-system, design-patterns, lua, entity-component
---


# Question
Title: Why does the object not move correctly when I press the right mouse button?
**2D Game in UNITY C#**

I have an object BULLET .

After pressing the left mouse on my object (BULLET), the script allows me to rotate object according to the mouse's direction, in four directions :

**-up right**

**-down right**

**-down left**

**-up left**

I would like to add a movement so that the object starts moving in face direction after pressing the right mouse button.

I did it, but the object doesn't move freely in face direction and doesn't bounce off the walls, it just follows the mouse.

But I just want to fire my bullet.

I don't want the object to follow the mouse, just fire in face direction.

**You know, like an arrow from a bow.**

I press the left mouse button and I start rotate the object - **THEN I press the right mouse button and the object flies without stopping in face direction, and began to bounce off the walls.**

I show what's wrong on video (link below): enter link description here

This is my code:

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

    public class TestFollow : MonoBehaviour {

    private Transform _bullet;
    private Vector2 _screenSize;
    private float _interval = 10;
    public Sprite sp1,sp2;
    SpriteRenderer sr;
    bool mouseClicked = false;
    public float moveSpeed = 10f;
    public float speed;
    bool rightClicked = false;

    // Use this for initialization

    void Start ()
    {
        sr = gameObject.GetComponent<SpriteRenderer> ();

        if (sr.sprite == null) // if the sprite on spriteRenderer is null then
            sr.sprite = sp1; // set the sprite to sprite1

        _bullet = transform;
        _screenSize = new Vector2(Screen.width, Screen.height);

    }

    public void Update ()
{

    transform.position = Vector2.Lerp (transform.position, Camera.main.ScreenToWorldPoint (Input.mousePosition), moveSpeed);

    Vector3 difference = Camera.main.ScreenToWorldPoint (Input.mousePosition) - transform.position;
    difference.Normalize ();

    {
        if (Input.GetMouseButtonDown (0)) {
            Debug.Log ("Left Mouse Button was pressed");
            moveSpeed = 0f;
            if (sr.sprite == sp1) { // if the spriteRenderer sprite = sprite1 then change to sprite2
                sr.sprite = sp2;

            }
            mouseClicked = true; //register that the mouse has been clicked and the sprite is changed to sprite2
        }
    }

    if (mouseClicked) {        //checks if sprite has already been changed

        // Check for every 10 frames, reduce _interval if you want to check more often.
        if (Time.frameCount % _interval == 0) {
            // Use debug to learn mouse position, you can disable this if you want.
            Debug.Log (Input.mousePosition);

            // Mouse on Top Right screen
            _bullet.localEulerAngles = Vector3.zero;

            // Mouse on Bottom Right, else Mouse on Bottom Left else Mouse on Top Left
            if (Input.mousePosition.x > _screenSize.x / 2 && Input.mousePosition.y < _screenSize.y / 2)
                _bullet.Rotate (Vector3.forward, -90, Space.Self);
            else if (Input.mousePosition.x < _screenSize.x / 2 && Input.mousePosition.y < _screenSize.y / 2)
                _bullet.Rotate (Vector3.forward, -180, Space.Self);
            else if (Input.mousePosition.x < _screenSize.x / 2 && Input.mousePosition.y > _screenSize.y / 2)
                _bullet.Rotate (Vector3.forward, 90, Space.Self);
        }
    }

    {

        if (Input.GetMouseButton(1)) {
            Debug.Log ("Pressed secondary button.");
            rightClicked = true;
        }
        if(rightClicked)
            _bullet.transform.position += (transform.right + _bullet.transform.up).normalized * speed * Time.deltaTime;

    }
    }
}

```

PS. I'm sorry if I shouldn't post here, but I'm in a little depression. I'm working on this code for a few days and I can't change anything.

PS 2. sorry for my English. Not English-speaking country.

# Answer
The code is a bit messy, but I think you'll want to set "mouseClicked" to false when you right-click. So in the Input.GetMouseButton(1) if statement:

```
if (Input.GetMouseButton(1)) {
    Debug.Log ("Pressed secondary button.");
    rightClicked = true;
    mouseClicked = false;
}

```

If you then want to fire the bullet again, you'll want to add the reverse in the left-click if statement. So you'll want to set "rightClicked" to false there.

At the moment it's continuously aiming because you're never telling it to stop doing so.

**Edit:**

As you said in your comment, you want to only be able to click the left mouse button once, then ignore it.

That can be achieved by adding a new boolean to check whether or not the left mouse button can be clicked. As displayed here:

```
private bool canClick = true;

if (canClick) {
        if (Input.GetMouseButtonDown (0)) {
            Debug.Log ("Left Mouse Button was pressed");
            moveSpeed = 0f;
            if (sr.sprite == sp1) { // if the spriteRenderer sprite = sprite1 then change to sprite2
                sr.sprite = sp2;
            }
            mouseClicked = true; //register that the mouse has been clicked and the sprite is changed to sprite2

            rightClicked = false;
            canClick = false;
        }
    }

```
> 0 votes

---
Tags: c#, 2d, movement, input, mouse
---


# Question
Title: MonoGame window is huge although it should be small
I'm using Monogame to create a simple game.

In my Game1 class initializer I set this:

```
Graphics.PreferredBackBufferWidth = 1280;
Graphics.PreferredBackBufferHeight = 1024;
Graphics.ApplyChanges();

```

My screen resolution is 2560x1600, so the window should be relatively small on startup. However, it's filling the entire screen and more. Why is that? I'm new to this so I have no idea what other information you might need to help me.

Thanks

EDIT: Okay, it had something to do with me messing with the Configuration Manager. There, I tried adding x64 support (no idea, if that's necessary). I'm not sure what I did there, though. I thought I deleted everything I added. However, after reverting the project to the last commit, the problem is gone. What happened there? Any ideas?

# Answer
**On MS Windows**

Are you on a high DPI setting and does your application manifest declare DPI-awareness?

Many parts of WinAPI use Device-Independent Pixels, and whether 1280 means pixels or DIPs (on a display with 2x DPI scaling, that's 2560 physical pixels) depends on how your application declares its DPI awareness.

I've encountered some interesting behavior in Monogame with regards to DPI handling, so for best results check both your dpiAware and dpiAwareness settings in the manifest.

---

**Non-Windows**

I don't have experience with Monogame on other platforms, so hopefully someone else can answer to that. I believe OSX native APIs also use DIPs, so should show the same effect.
> 0 votes

---
Tags: monogame
---


title: Serialize classes in unity c#

text:
# Question
Title: Serialize classes in unity c#
Is there some best practices to serialize objects to file on mobile devices in Unity using C#. I've tried to search it myself, but found only this link. However, it looks like here they are trying to cache `AssetBundles`. I'm new to `Unity`, but I have some experience in `iOS` (swift) development. Here we have opportunity to cache some objects(variables) in local storage, to avoid overusing network. So I wanted to create some static class (for example Storage), which caches variables to file permanently and return them by some key.

# Answer
> 1 votes
Unity provides a way to save primitive values(`float`, `int`, `string`) by keys using the PlayerPrefs class. https://docs.unity3d.com/ScriptReference/PlayerPrefs.html

For more in depth serialization, like complex objects into a file(byte\[\]) for reloading later, you can use the `[Serializable]` annotation to do so. Best practices found in the links below: https://blogs.unity3d.com/2014/06/24/serialization-in-unity/ https://docs.unity3d.com/Manual/script-Serialization.html

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


title: Off center forces on Chipmunk2D body

text:
# Question
Title: Off center forces on Chipmunk2D body
I am puzzled by the behaviour I am seeing in my game that uses Chipmunk2D for physics. I am not sure what I see is physically correct or not?

If I apply two forces as such, the tank turns, as expected.

The force at RHS of tank is much larger, causing the turn.

So far so good.

However, if the differential gets just a little smaller, as shown below, the tank goes **dead**-straight.

I emulate the friction by following the example for Chipmunk2D.

The forces are applied using the cpBodyApplyForceAtLocalPoint() function.

# Answer
Ok, I figured out what kept the tank from turning. The angular friction is stopping the turning. The delta in the force magnitudes is too small to overcome the angular friction.
> 0 votes

---
Tags: physics, chipmunk
---


# Question
Title: Problem connecting to Steamworks via Facepunch.Steamworks
I'm using Facepunch.Steamworks (https://github.com/Facepunch/Facepunch.Steamworks) to connect my Unity game to Steam. The login seems to work fine. The `board` object is an FP class, and `AddScore` is a call to the library to send the score to Steam.

I have the boards set up on Steam, and they come out with `IsValid == true`. Here are the output and the code. The boards currently have no data in them, so I don't think it's because the score isn't beating an existing one.

> ```
> xxxxxxxx
> Standard-Normal
> True
> Fail
>
> ```

```
public void SubmitScore(Globals.ApplicationMode mode, Globals.SkillLevels skillLevel, int score)
{
    int index = GetLeaderboardIndex(mode, skillLevel);
    if(index == -1 || !IsSteamPlatform())
    {
        return;
    }
    Leaderboard board = m_leaderboards[index];
    Debug.Log("xxxxxxxx");
    Debug.Log(board.Name);
    Debug.Log(board.IsValid);
    board.AddScore(true, score, null, AddScoreSuccessCallback, AddScoreFailureCallback);
}

private void AddScoreSuccessCallback(Leaderboard.AddScoreResult result)
{
    Debug.Log(result.Score);
}

private void AddScoreFailureCallback(Facepunch.Steamworks.Callbacks.Result result)
{
    Debug.Log(result.ToString());
}

```

Here's a shot of the leaderboards on the Steam control panel. They seem in order; their "Writes" attributes are false so that the client can submit to them directly.

# Answer
> 1 votes
Must fetch the scores before you can submit.

```
foreach(Leaderboard board in m_leaderboards)
{
    board.FetchScores(Leaderboard.RequestType.Global, 0, 10);
}

```

After executing the above code, submissions work fine.

---
Tags: unity, steam
---


# Question
Title: Detect minimum speed of a dynamic node in 3d space
I have a 3d dynamic node with speed & acceleration vectors. It has maximum speed (magnitude) and minimum speed such as if it exceeds maximum or goes below minimum, it stops accelerating and the speed is set to the respective maximum or minimum.

I have no problem detecting the maximum, I just have to check if the magnitude of speed vector is superior to the maximum.

But I am struggling for the minimum detection, magnitudes being in the positive field it seems to me more tricky. For example I want a minimum speed near 0, or 0, the object is decelerating, at one point it will pass through 0 and start accelerating following acceleration vector.

For example speed magnitude could be as such through frames: 5, 4, 2, 1, 3, 6 .. etc

There is no way to know if it did pass through zero, it could have well passed over zero between 2 and 1 and accelerate after, or between any other number.

Each frame I have these data: last speed vector, actual speed vector, acceleration vector.

How can I detect that next frame I'll cross my minimum value (zero in that example) ?

# Answer
Using tom10's idea, here is the solution I came up with for minimum detection when speed variation switches:

```
int speedCheck(bool variationSwitch, float& speed, float minThSpeed, float minSpeed, float maxSpeed) {
    // if change in speed variation ( decrease to minimum and increase again )
    if (variationSwitch) {
        // check if the theorical minimum speed that has been crossed is inferior to set up minimum speed
        if (minThSpeed <= minSpeed) {
            speed = minSpeed;
            return 3;
        }
    }
    else if (speed < minSpeed) {
        speed = minSpeed;
        return 2;
    }
    else if (speed > maxSpeed) {
        speed = maxSpeed;
        return 1;
    }

    return 0;
}

```

With `variationSwitch` calculated by checking the signs of dot products of speed & acceleration before and after applying acceleration:

```
lastParallelComponent = glm::dot(acceleration, lastSpeed);

speed += acceleration;

parallelComponent = glm::dot(acceleration, speed);

variationSwitch = lastParallelComponent * parallelComponent < 0.0f;

```

The theorical minimum speed, `minThSpeed` can be estimated with perpendicular component of speed over acceleration but I wasn't convinced about its accuracy so instead I calculated it using equations:

```
float get3DMinSpeed(Vector3f acceleration, Vector3f lastSpeed) {
    // t² * a + t*b + c = |v(t)|²

    float a = glm::dot(acceleration, acceleration);
    float b = 2 * glm::dot(acceleration, lastSpeed);
    float c = glm::dot(lastSpeed, lastSpeed);
    float t = -b / (2 * a);

    float min = (t*t)*a + t * b + c;
    float epsilon = 0.001f;

    if (min > 0.0f + epsilon)
        return sqrt(min);
    else
        return 0.0f;
}

```

So `minThSpeed`can be updated with that function each time a new acceleration is set up.
> 0 votes

# Answer
Check if the dot product of the acceleration is less, than 0, if it is, check if the acceleration's magnitude is larger, than the magnitude of the velocity. If both of these are true, then it will change direction the next frame.
> 0 votes

---
Tags: mathematics, algorithm
---


# Question
Title: OpenGL glVertexAttribFormat vs glVertexAttribPointer
I am attempting to change my code from using `glVertexAttribPointer` to `glVertexAttribFormat` as I have heard it;s more efficiend since it reduces binding calls overhead.

I have 2 versions of the code, one working one not.

The code looks like:

```
glGenBuffers(1, &tvbo1);
glBindBuffer(GL_ARRAY_BUFFER, tvbo1);
glObjectLabel(GL_BUFFER, tvbo1, 21, "\"Mesh Vertex Buffer\"");
glBufferData(GL_ARRAY_BUFFER, sizeof(vec3)*triangle.size(), triangle.data(), GL_STATIC_DRAW);

glGenBuffers(1, &tvbo2);
glBindBuffer(GL_ARRAY_BUFFER, tvbo2);
glObjectLabel(GL_BUFFER, tvbo2, 22, "\"Mesh Normals Buffer\"");
glBufferData(GL_ARRAY_BUFFER, sizeof(vec3)*ns.size(), ns.data(), GL_STATIC_DRAW);

glEnableVertexAttribArray(0);
//glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glVertexAttribFormat(0, 3, GL_FLOAT, GL_FALSE, 0); //comment
glVertexAttribBinding(0,0); //comment

glEnableVertexAttribArray(1);
//glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0);
glVertexAttribFormat(1, 3, GL_FLOAT, GL_FALSE, 0); //comment
glVertexAttribBinding(1,1); //comment

GLuint ptrs[] = {tvbo1, tvbo2};
GLintptr offsets[] = {0,0};
int strides[] = {0,0};
glBindVertexBuffers(0, 2, ptrs, offsets, strides); //comment

```

So whenever you see a //comment. That's to denote that in the other version that line is commented out.

The version that does work uses:

```
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

```

The version that does not work uses:

```
glVertexAttribFormat(0, 3, GL_FLOAT, GL_FALSE, 0); //comment
glVertexAttribBinding(0,0); //comment

glBindVertexBuffers(0, 2, ptrs, offsets, strides); //comment

```

The difference between working and not working is having a purple triangle vs having a black screen.

It seems that the error comes from the line

```
glBindVertexBuffers(0, 2, ptrs, offsets, strides); //comment

```

As having that line present results in a black screen regardless of the rest of the code.

# Answer
Strides cannot be zero.

Try:

```
int strides[] = { (int)sizeof(vec3), (int)sizeof(vec3)};
glBindVertexBuffers(0, 2, ptrs, offsets, strides); //comment

```

Otherwise, even if it was a valid OpenGL value, you'd be sending the same vector over and over.

This is the value to advance the feed pointer by when sending the next attribute to the vertex shader.

`glVertexAttribPointer` used to deduce automatically the stride when set to 0 for tightly packed values but neither `glBindVertexBuffers` nor `glBindVertexBuffer` have that feature. This was done to simplify driver code and reduce overhead.
> 2 votes

---
Tags: opengl, vertex-buffer, refactoring, vertex-attribute
---


# Question
Title: Is there a tool to automatically pack individual textures into one big png?
I~~'m currently~~ was working on a texture pack for minecraft (but this question is not restricted to that). All terrain textures are squared and stored in one big terrain.png. (FYI that's from Glimmar's Steampunk pack). I'd like to store each texture in an individual file and have same automated process pack them into the terrain.png later on (maybe leaving the not yet created ones their default). At the moment I do this manually by copy/pasting them with gimp (at least the raster helps a lot here) but I'd really like to do this automatically. Basically this seems to be what happens behind the scenes of the Painterly pack customizer already. So,

> Is there a tool that replaces some ~~squares~~polygons* in a png file with new ones (also png), the position of which might be configured in a separate file?

**edit** Some automated resizing for different resolution versions might be nice as well...

**edit2** Meanwhile I learned that "position \[...\] configured in a separate file" means atlas, and since the question originated from Minecraft texture packs (IIRC the format got changed meanwhile), the ideal tool would allow for using an existing atlas to replace some of the tiles

---

\*) might as well ask the general case

# Answer
> 4 votes
My favorite spritesheet packer is Texture Packer: http://www.texturepacker.com/

There's a free version that works pretty well, but the paid version adds features like resizing.

Another option is Zwoptex: http://zwoptexapp.com/

# Answer
> 1 votes
Try out Nick Gravelyn's Sprite Sheet Packer. I don't know if you can control scale with it, but you can easily automate that in script with ImageMagick

# Answer
> 1 votes
Another option is crunch which is a free open source cli tool originally designed for Celeste

---
Tags: textures, tools, texture-atlas
---


title: Build Unity from C# script

text:
# Question
Title: Build Unity from C# script
I'd like to build and package all the ports of my Unity game through a scripting system. Linux and Windows work fine through the Unity command line options, but there is none for WebGL.

For WebGL, the only existing solution seems to be its `BuildPipeline`. There is a gist with some sample code that has been referenced quit a few times. I changed its content to look like this:

```
BuildPipeline.BuildPlayer(scenes, "./WebGL-Test", BuildTarget.WebGL, BuildOptions.None);

```

and call it with `unity-editor-beta -executeMethod WebGLBuilder.build` (Btw, is there a way to call this method from within Unity? It doesn't help I have to restart Unity each time I want to test if the script works). It will fail with the following error:

```
Assets/Scripts/WebGLBuilder.cs(18,3): error CS0103: The name `BuildPipeline' does not exist in the current context
Error building Player because scripts had compiler errors

```

I also tried to use the `BuildPlayerOptions` class instead but no success. How do I get WebGL to build automatically?

# Answer
According to an answer on Unity Answers, you need to put the scripts used for building into a folder named `Editor` (specifically, `./Assets/Scripts/Editor`). Here's a full working build script:

```
using UnityEditor;
using UnityEngine;

class BuildSrcipt
{
    static string[] scenes = { "Assets/Scenes/MyScene.unity" };
    static string name = "MyGame";

    [MenuItem("Build/Build WebGL")]
    static void BuildWebGL()
    {
        BuildPipeline.BuildPlayer(scenes, "./" + name + "_Web/" + name, BuildTarget.WebGL, BuildOptions.None);
    }

    [MenuItem("Build/Build Windows")]
    static void BuildWindows()
    {
        BuildPipeline.BuildPlayer(scenes, "./" + name + "_Windows/" + name, BuildTarget.StandaloneWindows64, BuildOptions.None);
    }

    [MenuItem("Build/Build Linux")]
    static void BuildLinux()
    {
        BuildPipeline.BuildPlayer(scenes, "./" + name + "_Linux/" + name, BuildTarget.StandaloneLinux64, BuildOptions.None);
    }

    [MenuItem("Build/Build All")]
    static void BuildAll()
    {
        BuildLinux();
        BuildWindows();
        BuildWebGL();
    }
}

```
> 5 votes

---
Tags: unity, deployment, automation, unity-webgl
---


title: Interrupt on behaviour tree

text:
# Question
Title: Interrupt on behaviour tree
I'm using a custom Behaviour Tree library (not UDK or any other engine) so I'm wondering on the best way to cause an interrupt to a currently running node. I don't have decorators or parallel nodes in this library so looking for a different way to do it. I don't care about the specific reasons as to why the interrupt is needed. In general it just needs to tell the currently running node to stop running so the tree can be transversed again and that would find out the reason as the main "threats" would be checked.

I'm trying to think of a clean way to cause such interrupts in the tree. Generally the conditions that are already in the tree would be the reason for the interrupt (IsEnemyInRange, IsThirsty, IsHungry, etc) but if a node is running over multiple frames these don't get checked.

Any ideas given the above limitations I listed?

# Answer
If you are using C#, you can use interfaces. Implement an interface in the base method of all your nodes, then create a broadcaster class to invoke the method on the required node.

If you are not using C#, you can use inheritance instead.
> 1 votes

# Answer
A solution that stays 'within' the language of Behaviour Trees, so to speak, would be to introduce a `while` node in your BT. Find a design that works for you, but one solution could be a composite node that always has exactly 2 children.

It will run (and reset and rerun) the first, and, as long is it is not failing, it will also run the second.

This will give the effect of guarding the execution of a sub-tree by some condition (e.g. "there have been no interrupts") that is checked on every tick.

Another BT abstraction that can work is a `parallel` node, another composite node, that takes any number of children, and run them all, failing when *the first* child fails, or succeeding when the first child succeeds etc. depending on your concrete use case. In this way, you can race `LookForInterrupts` with `DoLongButInterruptibleAction`, and if `LookForInterrupts` succeed, the entire node is killed.
> 1 votes

---
Tags: ai, behavior-tree
---


# Question
Title: How to do an anti sway bar for a car in Unity 5?
I have researched some examples of anti roll bars for Unity but they are all for unity 4 and bellow so they do not work in unity 5. Can someone please assist me in making an anti roll bar script in C# for Unity 5?

Here is the best example I could find (I don't know how to convert it for unity 5):

```
using System.Collections;

public class AntiRollBar : MonoBehaviour {

  var WheelL : WheelCollider;
  var WheelR : WheelCollider;
  var AntiRoll = 5000.0;

  // Use this for initialization
  void Start () {

  }

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

    var hit : WheelHit;
    var travelL = 1.0;
    var travelR = 1.0;

    var groundedL = WheelL.GetGroundHit(hit);
    if (groundedL)
      travelL = (-WheelL.transform.InverseTransformPoint(hit.point).y - WheelL.radius) / WheelL.suspensionDistance;

    var groundedR = WheelR.GetGroundHit(hit);
    if (groundedR)
      travelR = (-WheelR.transform.InverseTransformPoint(hit.point).y - WheelR.radius) / WheelR.suspensionDistance;

    var antiRollForce = (travelL - travelR) * AntiRoll;

    if (groundedL)
      rigidbody.AddForceAtPosition(WheelL.transform.up * -antiRollForce,
                                   WheelL.transform.position);
    if (groundedR)
      rigidbody.AddForceAtPosition(WheelR.transform.up * antiRollForce,
                                   WheelR.transform.position);
  }
}

```

# Answer
You found your example here, I guess. I translated it in C# for Unity 5, and it works fine.

```
using UnityEngine;
using System.Collections;

public class AntiRollBar : MonoBehaviour
{
    public WheelCollider WheelL;
    public WheelCollider WheelR;
    private Rigidbody carRigidBody;

    public float AntiRoll = 5000.0f;

    void Start ()
    {
        carRigidBody = GetComponent <Rigidbody>();
    }

    void FixedUpdate ()
    {
        WheelHit hit = new WheelHit();
        float travelL = 1.0f;
        float travelR = 1.0f;

        bool groundedL = WheelL.GetGroundHit(out hit);

        if (groundedL)
        {
            travelL = (-WheelL.transform.InverseTransformPoint(hit.point).y
                    - WheelL.radius) / WheelL.suspensionDistance;
        }

        bool groundedR = WheelR.GetGroundHit(out hit);

        if (groundedR)
        {
            travelR = (-WheelR.transform.InverseTransformPoint(hit.point).y
                    - WheelR.radius) / WheelR.suspensionDistance;
        }

        var antiRollForce = (travelL - travelR) * AntiRoll;

        if (groundedL)
            carRigidBody.AddForceAtPosition(WheelL.transform.up * -antiRollForce,
                WheelL.transform.position);
        if (groundedR)
            carRigidBody.AddForceAtPosition(WheelR.transform.up * antiRollForce,
                WheelR.transform.position);
    }

}

```
> 6 votes

# Answer
```
using UnityEngine;
using System.Collections;

public class SwayBar : MonoBehaviour
{
public WheelCollider WheelL;
public WheelCollider WheelR;
public GameObject carRigidBody; //Car with rigidbody attached
private Rigidbody rb;

public float AntiRoll = 5000.0f;

void Start()
{
    rb = carRigidBody.GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    WheelHit hit = new WheelHit();
    float travelL = 1.0f;
    float travelR = 1.0f;

    bool groundedL = WheelL.GetGroundHit(out hit);

    if (groundedL)
    {
        travelL = (-WheelL.transform.InverseTransformPoint(hit.point).y
                - WheelL.radius) / WheelL.suspensionDistance;
    }

    bool groundedR = WheelR.GetGroundHit(out hit);

    if (groundedR)
    {
        travelR = (-WheelR.transform.InverseTransformPoint(hit.point).y
                - WheelR.radius) / WheelR.suspensionDistance;
    }

    var antiRollForce = (travelL - travelR) * AntiRoll;

    if (groundedL)
        rb.AddForceAtPosition(WheelL.transform.up * -antiRollForce,
            WheelL.transform.position);
    if (groundedR)
        rb.AddForceAtPosition(WheelR.transform.up * antiRollForce,
            WheelR.transform.position);
    }
}

```

I used mine on the on a empty gameobject of its own called swaybar attached inside the car so a few changes from the above one to suit. Add it twice and you can include rear right and left in one script and front right and left in the other.
> 0 votes

# Answer
I attempted to code my own script and it apears to make the car a little more physically stable

using UnityEngine; using System.Collections;

public class Anti\_Roll : MonoBehaviour {

```
public WheelCollider wheelL;
public WheelCollider wheelR;
public Rigidbody rb;
public float force;
public float position;

// Use this for initialization
void Start () {
    rb = GetComponent<Rigidbody>();

}

// Update is called once per frame
void Update () {
    RaycastHit hit;
    RaycastHit hit2;
    //Left wheel
    Ray cast = new Ray (wheelL.transform.position, -Vector3.up);
    Physics.Raycast (cast, out hit);
    float wheelL_force = hit.distance;
    //Right Wheel
    Ray cast2 = new Ray (wheelR.transform.position, -Vector3.up);
    Physics.Raycast (cast2, out hit2);
    float wheelR_force = hit2.distance;

    float applyL = wheelL_force - wheelR_force;
    float applyR = wheelR_force - wheelL_force;
    Debug.Log ("Difference:" + (wheelL_force - wheelR_force));
    rb.AddForceAtPosition (Vector3.down*applyL*force, (rb.position - wheelL.transform.position)*position);
    rb.AddForceAtPosition (Vector3.down*applyR*force, (rb.position - wheelR.transform.position)*position);

}

```

}
> -1 votes

---
Tags: unity, c#, physics, car
---


title: 2.5D game vector choice

text:
# Question
Title: 2.5D game vector choice
I'm developing 2.5D game (3D assets, 2D gameplay). Since gameplay takes place on horizontal plane, majority of game objects have y component equal to 0. Most of my algorithms work on `Vector2`s, since these calculations obviously make more sense (and are a little bit faster, I guess). This makes field for hard to catch bugs, since Unity allows transparent conversion from Vector3 to Vector2 via cutting off z component.

Since I'm still in a stage in which I can change calculations quite easily, my question is: which approach will cause me the least trouble?

* Current: Gameplay on XZ plane, custom conversion from Vector3.XZ to Vector2.XY
* Gameplay on XZ plane, calculations on Vector3.XZ (and making sure, that y is always 0 - otherwise some of calculations may be erroneous)
* Gameplay on XY plane (that may cause some problems in editor I guess) and automated conversion from Vector3.XZ to Vector3.XY
* Gameplay on XY plane, calculations on Vector3.XY (though I see no benefit over solution 2)

Or is there some other approach I may take?

# Answer
I'm working on a game that has 3D presentation, but has many aspects that are 2D in terms of game mechanics. Specifically, the game board locations have heights, but I don't allow units to stack, etc. For me, height only matters for displaying & sometimes line of sight calculations.

I choose to use X & Y to represent the plane parallel to flat ground. When height is involved, it uses the Z coord.

Most of my core data structures keep all 3 coords. My reasoning is as follows:

* memory is plentiful enough on my target platform(s)
* the memory footprint for a primitive is negligible when compared to other assets
* it hasn't negatively impacted performance
* it's easier to ignore information I don't need than vice versa
* the consistency gives me one less thing to worry about when making new something new

When I need to restrict things to 2D for processing, I just pass the coords needed.

In general, my guiding recommendations are:

* don't optimize prematurely
* try to keep things as simple & consistent as possible

Making a game is hard enough the way it is. Don't create additional barriers for yourself worrying about an extra primitive field. Save your worry for things like duping textures unnecessarily.
> 3 votes

---
Tags: unity, vector, 2.5d
---


# Question
Title: GameMaker Studio 2 - How to place object back beyond X coordinate for looping (warp)?
I'm making a side-scrolling shooter where I want an object to move from right to left (towards negative X), then, when it's passed out on the left side, jump back to beyond the window width (right side) at a randomly determined Y coordinate (using `irandom_range`) to loop back into view.

This object is not part of the background as it is meant to obstruct the player's movement (similar to Flappy Bird pipes).

I'm using the Drag'n'Drop interface in Game Maker Studio 2. Currently I have this setup, but the object remains at the right-side window edge, moving randomly up and down **each** step:

# Answer
> 0 votes
Your object is locked on the right side of the game window because the ***Jump To Point*** block is actually executed every step. If you notice, there's a red text saying *Empty* next to the ***If Variable*** block:

You didn't give any actions to perform when the condition is met, and the other block is always executed. That's the same as writing this GML code:

```
if (x <= 0);    // does nothing
x = room_width;
y = irandom_range(-416, -32));

```

To solve it, drag the ***Jump To Point*** block at the right of the ***If Variable*** block:

The green wire under the ***If Variable*** block means all the following instructions will be executed only when conditions are met. GML equivalent:

```
if (x <= 0)
{
    // condition applies here
    x = room_width;
    y = irandom_range(-416, -32));
}
// condition does not apply from here on

```

---
Tags: game-maker, gameobject, side-scroller
---