# Question
Title: Top down 2d orthogonal view with 3D elements (Unity)
I've decided to give Unity a go with my project. I want to create a 2d RPG perspective world, but with elements of 3D mixed in. So for instance, I think I might make trees and grass 3D, for this to work, the grass would have to realistically blend with the character (a 2d sprite) as they walk through it. To be clear, I'm thinking of grass like you would see in a fully 3D game (like this).

As I understand it, the sprite objects (characters and whatnot) would need to maintain their rotation values whatever the rotation of the camera is. I don't plan on rotating the camera, the game would appear like a 2d game (2.5d is perhaps a more appropriate term) but in order to achieve the effect I want they would not be allowed to rotate in the camera's view.

I'm very new to Unity so I'm not quite sure where to start. I should also note I don't plan on making everything 3d, just particular objects like the ones mentioned.

---

Edit 06.05.16:

I'm not sure why I can't find anybody else with this problem solving it the way I am. Here's a diagram of what I've implemented and it seems to work well:

The camera's Y axis is set to 45 degrees. I'm not sure why but the number 1.418 works as the scaleY value for the camera's projection matrix. for making both sides appear as equally proportioned squares.

I don't see any distortion of textures, shadowing looks ok, the whole distorited 2d rpg perspective feels just right.

I'm a bit confused as I've seen some overly complex suggestions and solutions to this problem on google, but this seems to me to be the simplest and most appropriate solution, and I've not found anyone suggest it. Everything appears in proportion. I assume I'm not aware of an important flaw in the solution because otherwise it would seem absurd other people wouldn't arrive at the same solution.

Regarding billboaridng - billboarding 3D movable sprites doesn't work well in 3d environments IMO, as they often will be tilted at a 45 degree angle and risk intersecting 3d objects:

http://answers.unity3d.com/questions/582680/billboard-issue-in-front-of-3d-object.html

Particularly tall sprites would be very problematic, unless the scenery was also tilted, like this screenshot from a Zelda game demonstrates:

# Answer
> 4 votes
When you have 2d sprites in a 3d environment, they work like two-dimensional planes. Think of them as cardboard-cutouts which are moving through the world.

When you want to rotate these cardboard cutouts to always face the camera, then the search term you are looking for is "Billboarding". It can be implemented by attaching this MonoBehaviour to it:

```
using UnityEngine;

public class Billboarding : MonoBehaviour
{
    void Update()
    {
        transform.LookAt(
            transform.position + Camera.main.transform.rotation * Vector3.forward,
            Camera.main.transform.rotation * Vector3.up
        );
    }
}

```

However, when you aren't going to rotate the camera anyway, then you won't need this script. The camera in a Unity game won't rotate or move unless you have a script which tells it to.

Just rotate your sprites into the direction of the camera in the editor and then keep them that way. Another option is to always keep the sprites perpendicular to the 2d ground-plane. This makes their sorting behavior more intuitive, but shortens them perspectively, so they will be vertically shortened and won't look exactly like they look in your image editor. But you can compensate for that by scaling them on the y-axis according to the camera angle.

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


title: Combe Rectangle and Vector movement

text:
# Question
Title: Combe Rectangle and Vector movement
I'm completely fresh to game development and came up to a problem which I'm not sure how to solve. I have textures which are quite too big for screen. So i used SpriteBatch.Method which uses rectangle as parameter which allows me to get custom size of texture. But I need as well Vector position for movement to specific direction. So I used method which uses Vector position and float scale to make it smaller. And now I can't check really if it Intersects with other objects or simple width, height properties. It seems that I cannot pass both vector position and rectangle as well. Isn't there a way to specify just a rectangle for texture's height/width to be rendered and vector for position?

# Answer
There are three overloads of the `SpriteBatch.Draw()` method available that will suit you:

```
SpriteBatch.Draw (Texture2D, Vector2, Nullable<Rectangle>, Color)
SpriteBatch.Draw (Texture2D, Vector2, Nullable<Rectangle>, Color, Single, Vector2, Single, SpriteEffects, Single)
SpriteBatch.Draw (Texture2D, Vector2, Nullable<Rectangle>, Color, Single, Vector2, Vector2, SpriteEffects, Single)

```

In each case, the second parameter is a `Vector2` representing the location on the screen where the texture should be drawn, and the third parameter is a (nullable) `Rectangle` that represents the portion of the texture to be drawn. You can read more about them at the MSDN page.
> 1 votes

# Answer
If the rectangle is where you want the picture to be drawn (destination rectangle), rather than the part of the texture you wish to draw (source rectangle), then a better answer would be to recreate the rectangle whenever the object moves using the vector2.

For example:

```
//movement code here
rectangle = new Rectangle((int)position.x, (int)position.y, width, height);

```

That will put the position vector2 in the top left hand corner. You can put it in the centre by:

```
rectangle = new Rectangle(
  (int)(position.x - (width/2)),
  (int)(position.y - (height/2)), width/2, height/2);

```
> 0 votes

---
Tags: monogame
---


title: Can't read input from keyboard

text:
# Question
Title: Can't read input from keyboard
I'm new to game dev,and I just trying to create my first game,a simple pong game.But i can't handle the keyboard input.

This is what i got :

```
const Uint8 * keystates = SDL_GetKeyboardState(NULL);
SDL_PumpEvents();

if (_keystates[SDLK_s])
    std::cout << "Down is pressed";

```

But if i run it and press 's',nothing ever happens.

```
if (_keystates[SDLK_RETURN])
    std::cout << "Return is pressed";

```

For this one is working just when i press 'j'... Yeah,right?

And more,if I add this line :

```
if (_keystates[SDLK_DOWN])
    std::cout << "Bla bla..";

```

My game crashes,what do you think is the problem?Thank you.

# Answer
As it says on the SDL documentation, `SDL_GetKeyboardState` returns an array of the keyboard state, with `SDL_SCANCODE` values as indices. You can't use the `SDLK_` values, they won't reference the right values. So change your code to use the `SDL_SCANCODE` values. There is a reference page here.

Your if-statement should then look like `if (_keystates[SDL_SCANCODE_RETURN]) {...}`.
> 2 votes

---
Tags: 2d, sdl, input
---


# Question
Title: The best way to store and protect game data
I'm writing a sandbox-type game and i'm looking for a good way to store game data. I tryed Lua and plain text files, but the have a big minus - player can edit them his self!

So how do I **protect** data from player? Thank you!

# Answer
> 0 votes
You can store the game data in a file, and obfuscate the data if you do not want the player to modify the stored values.

This would be done by encrypting your data, and then decrypting it when you load it up in your game. The encrypting / decrypting would be hard coded into your binary.

That being said, if someone wants to get at the game data, there will be attempts at cracking your encryption technique, and publish a hack. You can try to prevent the data from being hacked, but you cannot stop it entirely.

# Answer
> 0 votes
You can't.

If your game is a single player game or not connected to the internet, and you don't have them use any kind of DRM that big companies can have (Ubisoft, EA, Blizzard and the like), users will find a way to hack in your data and modify them.

There are ways to obfuscate it, and make their life harder, but ultimately, someone motivated enough will find a way to reverse engineer your data (savegame or assets), make an editor, and change the content of your game.

---
Tags: c++, data, configuration
---


# Question
Title: Global variables in a multiplayer environment
I would like to know what's the best approach to solve this problem. In a racing game, i need to create the final result chart. In a single environment i've tought something like:

```
private string [] arrivalOrder;

void playerArrived(string playerName) {
   arrivalOrder[arrivalOrder.getLength()+1] = playerName;
}

```

I would like to know how to do in a multiplayer environment.

How the client can communicate to server "my player finishes the racing"? Thanks

# Answer
In a multiplayer racing game, the client should be communicating position updates to the server. The server will then sanity check the message and update all the other clients. Never, ever trust the client to do these kinds of calculations for you.

If you have the server do all the calculations, then you don't need to worry about the client telling the server when they are "done" -- the server will know.
> 2 votes

---
Tags: unity, c#, architecture, multiplayer
---


# Question
Title: Rendering a distant star field in Unity using a separate camera for near stars
I'm currently working on a hobby project which is a universe simulator (exclusive to stars) built in unity3D. In order to deal with the raw scale of the universe I'm trying to implement two co-ordinate systems.

In my project I have two cameras; camera1 is the first co-ordinate system where all stars are loaded as high detail 3D objects. While camera2 is used for gathering a list of points within this "extended" frustum. I want to display these stars from camera2 on the farplane of camera1 in a lowdetail 2d manner.

I'm new to game development so this may be completely wrong; my plan was to generate a mesh from all the points in cameras2 frustum (this mesh now respresents my points in world space). I have a variable that represents the conversionFactor between the two co-ordinate systems. I will convert this mesh into projection view using the my conversionFactor in the translation component.

I will display this projection view on my camera1 farplane selling the illusion of far away stars? Please let me know the flaws in my deisgn! any help is much appreciated

# Answer
If you literally want to gather a list of points, it may make more sense to just use raycasts from Camera1's position to determine those points. To do this, you could instead have Camera2's frustrum be a collider, use Physics.RaycastAll from Camera1's position to each collision in the Camera2 collider, and the points you're looking for would be all the RaycastHits on the Camera2 collider.
> -2 votes

---
Tags: unity, 3d-meshes
---


# Question
Title: My displayed Tiled map is rendered with different tile indexes than in the editor in Slick2D. Why?
The first picture is what I have in the editor and the second one is what I got when I rendered my map.

```
@Override
public void init(GameContainer container) throws SlickException {
    this.container = container;
    this.map = new TiledMap("/src/main/resources/map/test2.tmx");
}

@Override
public void render(GameContainer container, Graphics g) throws SlickException {
    this.map.render(0, 0);
}

```

I would expect the two to be the same, but they're not. Why is that?

Edit : I solved the problem by removing the margin when I imported my tilset

# Answer
I'm not sure about in Slick2D, but in Unity this sort of problem can be caused by the engine not assigning indices to wholly transparent blocks. For example, if tiles 2-4 are totally transparent, Tiled would assign the fifth block as index 5 but Unity would assign the 5th block as index 2.

Work-arounds may include slicing a dummy image with a solid color and then overwriting it with your final image to keep the slicing information metadata, or just not having wholly transparent blocks in your tilesheet.
> 0 votes

---
Tags: rendering, maps, slick, tiled
---


# Question
Title: Get perpendicular vector from another vector
I should clarify that I understand there is an infinite amount of 'perpendicular' vectors in 3D space. I am creating an electricity effect, and to do this the ability to have any number of perpendicular vectors is a good thing. The hard part is how to select any random one of these vectors - how would I do that, given a base vector "direction" which has been normalised?

Keep in mind that I want the resultant vector to be random, not just always up and down on the y-axis or anything.

# Answer
Here's a Unity-specific option in the same vein as sam hocevar's answer:

```
Vector3 GetRandomUnitPerpendicular(Vector3 v)
{
    float angle = Random.Range(0, Mathf.PI * 2f);

    // Generate a uniformly-distributed unit vector in the XY plane.
    Vector3 inPlane = new Vector3(Mathf.Cos(angle), Mathf.Sin(angle), 0f);

    // Rotate the vector into the plane perpendicular to v and return it.
    return Quaternion.LookRotation(v) * inPlane;
}

```

By construction, this returns a unit vector. Rotating by a `Quaternion.LookRotation` is a bit overkill here, but it lets us pass off the problem of picking a basis to existing code, rather than duplicating it, keeping the code concise.

Note that these methods based on a random angle will have better uniformity than those based on generating a random vector in a square or cube (which have a higher probability of giving vectors pointing toward the corners than toward the sides), and don't need special handling for cases when the pseudorandom input is all zeroes.
> 4 votes

# Answer
I would do the following:

* have your vector **u** (ensure it’s normalised)
* pick an orthogonal vector **v** using *any existing method* (ensure it’s normalised)
* pick a random angle α
* a good random unit vector is therefore: **v**·cos(α) + (**u** × **v**)·sin(α)

If you wish your vector to also have random length, you can then multiply it by a random number, or possibly by *the square root of a random number* depending on the kind of distribution you’re looking for.
> 1 votes

# Answer
We know that the cross product of two vectors in 3-dimensional space is another vector which is orthogonal to both original vectors.

Given a vector which starts at the origin, we can just pick any random vector which starts at the origin to do the cross-product against.

Since the cross-product produces a vector which is orthogonal to both, and we picked a random vector as the second input, we have a vector which is both in a random direction and orthogonal to the original input vector.

**NOTE:** As DMGregory points out in the comments, you can sometimes select a random vector that is parallel to the original one. For this case, check if the result of the cross-product is a zero vector. If it is, then picking a random offset from the input vector *should* suffice.

**Example** *(JavaScript and THREE.js). The red arrow is the original direction vector, the green arrow the random orthogonal one. The blue circle is the plane orthogonal to the red arrow*:

```
var con = document.getElementById('container');

var renderer, scene, camera;

renderer = new THREE.WebGLRenderer();
renderer.setSize(320, 240);
con.appendChild(renderer.domElement);

scene = new THREE.Scene();

camera = new THREE.PerspectiveCamera(45, 4 / 3, 0.1, 1000);
camera.position.set(2, 1, 10);
camera.lookAt(0, 0, 0);

function randPoint(){
  return Math.random() * 2 - 1;
}

// == Example ==
var vec1, vec2, vec3;

// Direction Vector
vec1 = new THREE.Vector3(2, 2, -2);
vec1.normalize();

// Random Vector
vec2 = new THREE.Vector3(randPoint(), randPoint(), randPoint());
vec2.normalize();

// Resultant Random Orthogonal Vector
// ===================================
vec3 = new THREE.Vector3();
vec3.crossVectors(vec1, vec2);

// Modify if needed. Offset vec1
// to ensure a vector which is not parallel.
if (vec3.x == 0 && vec3.y == 0 && vec3.z == 0){
  vec2 = new THREE.Vector3(
    vec1.x + Math.random() + 0.001,
    vec1.y + Math.random() + 1.001,
    vec1.z + Math.random() + 2.001
  );
  vec2.normalize();
  vec3.crossVectors(vec1, vec2);
}

vec3.normalize();
// ===================================

var origin = new THREE.Vector3(0, 0, 0);

var cGeo = new THREE.CircleGeometry(5, 32);
var cMesh = new THREE.Mesh(cGeo, new THREE.MeshBasicMaterial({color: 0x0000ff, wireframe: true}));
cMesh.position.set(0, 0, 0);
cMesh.lookAt(vec1);
scene.add(cMesh);

scene.add(new THREE.ArrowHelper(vec1, origin, 5, 0xff0000));
scene.add(new THREE.ArrowHelper(vec3, origin, 5, 0x00ff00));

renderer.render(scene, camera);
```

```
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r73/three.min.js"></script>
<div id='container'></div>
```
> 1 votes

# Answer
You are looking for any vector that is completely in the plane described by a normal vector. Let's call your normal vector `n`, and the result vector (what you want to calculate) `r`. You know something about the relationship between the two vectors, namely that their dot product must be 0. That's one equation, but you have 3 unknowns here (the `x`, `y`, and `z` components of `r`). It turns out that's as much as you can constrain this problem. You will need to randomly select two coordinates in `r` and then project the last coordinate into the plane by using the dot product. Here's a simple solution (in pseudo-ish code since I'm not overly familiar with Unity):

```
Vector3 GetOrthogonalVector(Vector3 n) {
    Vector3 r(Random.value, Random.value);
    r.z = -(r.x*n.x + r.y*n.y)/n.z;
    return r.normalized;
}

```

Of course, you need to be safe and make sure that the `z` component of `n` (`n.z`) is not zero and do something sensible there. Also, as pointed out in the comments, if `r.x = r.y = 0`, then you will get zero for `r.z`, so that should be handled as well.
> 0 votes

---
Tags: unity, vector
---


# Question
Title: 3D collision avoidance: finding the updated velocity vector (outside the "collision-velocities" cones)
I am trying to understand and implement the mechanism of a fully 3D collision avoidance (steering behavior) system for flight movement (six degrees of freedom), currently focusing on circumventing ***static obstacles*** (all with the shape of a sphere).

However, I don't quite get how to figure it out the new velocity vector of the moving agent. The figure below illustrates the scene. The moving agent (green) has to steer three static objects (blue). The red line represents the initial ahead velocity vector.

Notice that there are also three white/semi-transparent cones. These represent the "forbidden velocity vectors" regarding each obstacle. It means, the set of velocity vectors that, if used as the new ahead vectors of the agent, would make the agent collide with one or more of the obstacles (also note that the radius of each cone is equal the radius of the given obstacle plus the radius of agent, so to allow an offset for the player to maneuver around).

In order to find out the new ahead vector of the moving agent in such 3D environment, considering the three obstacles, a naïve approach would be to simply port to 3D the classic solution explained in this often cited article and exemplified by the following 2D image:

There, a new velocity (orange arrow) is simply calculated by normalizing the minimum distance (black arrow) between the original velocity and the center of the obstacle and then multiplying such normal by the sum between the radius of the obstacle and the radius of the moving agent. Then, an average of the new velocities calculated for each of the obstacles would give the total final velocity.

In many cases, that is sufficient. However, take a look at the cases below (exemplified in 2D to ease visualization):

In all of them, the naïve approach will result in a collision. In a and b, the final new velocity will coincide with the original velocity (red arrow) and the moving agent will move forward despite being partially or fully blocked. In c) and d), the new velocity (orange arrow) will still result in the same consequence.

So, my question is: what is the most computationally efficient way to find out the new ahead vector of the moving agent in such 3D environment, considering the three obstacles, in a way that avoids collision? Or, in other words, the new ahead vector that:

1) is not inside any of the cones;

2) is the closest possible to the original ahead vector (red line in the picture).

PS: Preferably, I am not looking for a library, I am looking to learn how to that.

# Answer
I don't think there's an efficient way of solving the problem exactly, but here's how I'd try to tackle it.

First, I'd use bounding volumes around each object, instead of the objects themselves. Each object can be approximated by the union of more than one bounding volume, though.

The simplest solution would be to compute a single bounding volume that contains all the objects that you need to avoid and compute the cone from that volume.

This might not be good enough if objects are not relatively close to each other. You might then want to do some clustering in a way that two objects belong to the same cluster if it's not possible, or at least not trivial to pass between them. Compute the cluster of objects considering their bounding volumes plus the size of the player's bounding volume plus some extra margin. You might use something like this:

http://lab.polygonal.de/?p=120

After you have the clusters, find the closest one and compute the cone to avoid colliding with it. Because of the way the clusters were created, if you steer just enough to avoid hitting one cluster, you won't hit another.

Furthermore, you can create a recursive structure when computing the clusters which will help you find the closest cluster .

There are a few things you can play with. For example, instead of picking the closest cluster, pick the two closest clusters and compute a single cone that avoids them both. Also, you could try other bounding volumes other than spheres.
> 1 votes

# Answer
There are two ways to address this question that I can see. First, if you simply want to find a way to steer, then you just need to implement pathfinding (I find this quite helpful). That would be the end of that (and is the correct practical answer to this question), but I think you are more curious about a mathematical solution to your problem.

To address that, let's look at an equivalent problem. Take a 2D slice of your scene "ahead" of your pilot of a plane that is normal to the original vector. What you will get is a point that represents your original vector and a series of ellipses that are the 2D projections of your occlusion cones. Now what you want to do is to find The closest point to your original point (let's call it `P`) that lies on the exterior of non-overlapping ellipses. It turns out that this is a pretty difficult problem to solve. There are 3 steps:

* Figure out the intersection points of all your ellipses
* Find any holes in the union of all your ellipses
* Figure out the closest point to `P` on all your ellipses outside the union (which can be inside a hole)

Okay, all of this requires Lagrange multipliers and angle checking and some other really complicated stuff to solve. Let's look at other options. If we transform our problem instead into angular space, we see that what we actually want to do is find the minumum distance between a point and multiple circles projected onto the surface of a sphere. In differential geometry, this is often called a 2-sphere and is useful here. So first, we need to find the distance between two points on the surface of the sphere, which we will use the 2-sphere metric to find. Luckily, it's pretty easy: `ds^2 = (R^2)*(dth^2) + (R^2)*(sin(th)^2)*(dph^2)`, where we hold `R` constant as the radius of our 2-sphere projected into 3-space. Coming from physics, I take `th` to be the angle from positive `z` and `ph` to be the angle from positive `x` with `s` being the distance.

What does doing this accomplish? It allows us to remove the use of Lagrange multipliers to minimize distance, and allows us to work in "native" coordinate (since we define our cones in terms of an angle of occlusion). So now we need to find the radius of our cone-projections. Let's take one cone for now, and call the angle that defines it `a`. The radius of the projection is then simply `R*a`. That was easy enough -- what other quantity do we need to know about the cones? We need to know the center of the projection, which is defined by the look vector from the actor. First we convert `x`, `y`, and `z` into spherical coordinates where we know we are at distance `R`, and solve for `th` and `ph`, which we can do by simply plugging into our conversion formulas: `th = acos(z/R)` and `ph = atan2(y/x)` (use `atan2` here to account for arctangent's quadrant ambigities). The process is the same to find the position of your original vector in spherical coordinates.

So the problem has been simplified. However, the problem is still quite difficult to solve, but now you only need to worry about circles and points instead of ellipses and points or angles and vectors. The rest of the process is rather procedural. You essentially need to find a bounding area formed by your circles, for which there are multiple solutions. I'll present one method which may not be the best, but will work.

I would first compare the sum of the radii of all circle pairs and the distance between the centers, and then if they sum is larger than the center distance, set them equal and solve for `th` and `ph` to find the intersections. You know that each pair of intersections describes "forbidden angles" for the circle in question, which you would store as an array of intersection point angles (from the center of the circle) for each circle that intersects this one -- importantly you must "merge" any ranges that overlap as you add them to the array for the next part to work correctly. Then you find the closest point on the edge of the circle to the original point (which is as simple as drawing a line through the center point of the circle and the original point, then finding the location on the line at the radius of the circle away from the center). Then loop through your stored array and test if that angle is in the range of each forbidden angle. If so, then select the closest edge. That is the closest point to the outside described inside this circle. Repeat the process for all circles (some optimization can be done in the selection process -- you don't actually need to calculate this for every circle). Now compare all your shortest distances, find the smallest, and that is your answer, described in the angles `th` and `ph`. Remember that distance is described with the 2-sphere metric while performing this calculation. Since you don't care about the sphere that all of this is on, only the angles, you can set `R=1` and do these calculations on the unit sphere.

This is the simplest way I could think to do this. I'm not sure it's the absolute simplest way, but it would work pretty well. Practically for a game, however, you just want to implement pathfinding.
> 0 votes

---
Tags: collision-detection, 3d, steering-behaviors, collision-avoidance
---


# Question
Title: libgdx collision on moving Rectangle with other Rectangle
I'm making a soccer game where you touch the screen and the player shoot the ball to the touched position with the objective of scoring goals when it hits the goal. The player is just a Sprite and the Ball and the Goal are Rectangles. What I'm trying to do here is when the Ball collides with the Goal the player changes its position to a random one on the screen and the ball resets to the player position, although I'm not actually getting the collision between the Rectangles. Any help would be appreciated.

TLDR : make so that when the ball collides with the goal, the players position changes and the ball resets to the player position.

**Game class**

```
private SpriteBatch batch;
private OrthographicCamera cam;

private Texture player1;
private Sprite player;

private Sprite bg;
private Texture back;

private Texture ball1;
private Rectangle ball = new Rectangle();
private Sprite bs;

private Texture goal1;
private Rectangle goal = new Rectangle();

private Texture line;

Ball b = new Ball();

public void create () {

    cam = new OrthographicCamera();
    cam.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    batch = new SpriteBatch();
    batch.setProjectionMatrix(cam.combined);

    player = new Sprite(player1);
    player.setX(MathUtils.random(Gdx.graphics.getWidth()));
    player.setY(MathUtils.random(Gdx.graphics.getHeight() / 2));

    b.position.set(player.getX(), player.getY());

    goal.setWidth(420);
    goal.setHeight(130);
    goal.setX(Gdx.graphics.getWidth()/4-20);
    goal.setY(Gdx.graphics.getHeight() - 180);

    ball.setX(b.position.x);
    ball.setY(b.position.y);
    ball.setWidth(40);
    ball.setHeight(40);

}

public void render () {
    Gdx.gl.glClearColor(255, 255, 255, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    b.update(Gdx.graphics.getDeltaTime());

    batch.begin();
    batch.draw(bg, 0, 0);
    if (!Gdx.input.isTouched()) {
        batch.draw(bs, b.position.x, b.position.y);
    }else if (Gdx.input.isTouched()) b.shootToward(Gdx.input.getX(), Gdx.graphics.getHeight() - Gdx.input.getY());
    batch.draw(goal1, Gdx.graphics.getWidth()/4-20, Gdx.graphics.getHeight() - 180, 420, 130);
    player.draw(batch);

    if (goal.contains(ball)) {
        player.setX(MathUtils.random(Gdx.graphics.getWidth()));
        player.setY(MathUtils.random(Gdx.graphics.getHeight() / 2));
    }
    batch.end();
}

```

**Ball class**

```
public void shootToward(float targetX, float targetY) {

    velocity.set(targetX - position.x, targetY - position.y);
}

public void update(float deltaTime) {

    position.add(velocity.x * deltaTime, velocity.y * deltaTime);
    velocity.scl(1 - (.98f * deltaTime));
}

```

# Answer
It is because your "`Ball b`" and your ball's collider "`Rectangle ball`" know nothing about each other. When you update the ball's position with `b.update()` the rectangle `ball` stays put.

I would make the Rectangle be a member variable of the `Ball` class and update its position every time the ball's position updates.

i.e.

```
if(goal.contains(b.getCollider())

```
> 0 votes

---
Tags: android, collision-detection, libgdx
---


# Question
Title: How to get color or value from material with shader?
I have a sphere with a shader with colors for specific heights and I want to get the value at the cursor(height) or color of the point the cursor is on when clicked. Is there a good way to get this information or the whole texture and find the value that way?

What the object looks like and its inspector.

**Update:** I am using the below to try and capture the texture but it is just capturing black.

```
public class BakeMaterial : MonoBehaviour {
    public RenderTexture ResultTexture;
    public int Size = 2048;

    public Material ReplaceMaterial;
    public bool DoBake = false;
    void Update() {
        if(DoBake) {
            DoBake = false;
            Bake();
        }
    }

    // Use this for initialization
    public void Bake() {
        if(ResultTexture == null) {
            ResultTexture = new RenderTexture(Size, Size, 0);
            ResultTexture.name = "Baked Texture";
        }

        bakeTexture();

        if(ReplaceMaterial != null) {
            GetComponent<Renderer>().material = ReplaceMaterial;
            ReplaceMaterial.mainTexture = ResultTexture;
        }
    }

    void bakeTexture() {
        var renderer = GetComponent<Renderer>();
        var material = Instantiate(renderer.material);

        material.SetPass(0);

        Graphics.Blit(material.mainTexture, ResultTexture, material);

        Texture2D frame = new Texture2D(ResultTexture.width, ResultTexture.height);
        frame.ReadPixels(new Rect(0, 0, ResultTexture.width, ResultTexture.height), 0, 0, false);
        frame.Apply();
        byte[] bytes = frame.EncodeToPNG();
        FileStream file = File.Open(@"D:\Works.png", FileMode.Create);
        BinaryWriter binary = new BinaryWriter(file);
        binary.Write(bytes);
        file.Close();
    }
}

```

My Shader:

```
Shader "NanoRav/Planet-Lit" {
    Properties {

        _BumpMap("BumpMap", 2D) = "bump"{}
        _NormMap("NormMap", 2D) = "bump"{}

        _PeakColor("PeakColor", Color) = (0, 0, 0, 1)
        _Level3Color("Level3Color", Color) = (0, 0, 0, 1)
        _Level2Color("Level2Color", Color) = (0, 0, 0, 1)
        _Level1Color("Level1Color", Color) = (0, 0, 0, 1)
        _ShoreColor("ShoreColor", Color) = (0, 0, 0, 1)
        _WaterColor("WaterColor", Color) = (0, 0, 0, 1)

        _PeakLevel("PeakLevel", Float) = 0.5
        _Level3("Level3", Float) = 0.5
        _Level2("Level2", Float) = 0.5
        _Level1("Level1", Float) = 0.5
        _ShoreLevel("ShoreLevel", Float) = 0.5
        _WaterLevel("WaterLevel", Float) = 0.5

        _IceLevel("IceLevel",Float) = 0.4
        _IceStrength("IceStrength",Float) = 2.0
        _IceColor("IceColor", Color) = (0.95, 0.95, 0.95, 1)

        _Frequency("Frequency", Float) = 2.0
        _Lacunarity("Lacunarity", Float) = 3.0
        _Gain("Gain", Float) = 0.5

        _PlanetStretch("PlanetStretch",Float) = 0.4

        _AtmosNear("AtmosNear", Color) = (1,1,1,1)
        _AtmosFar("AtmosFar", Color) = (1,1,1,1)
        _AtmosFalloff("AtmosFalloff", Float) = 3

        [HideInInspector] _CityFrequency("CityFrequency", Float) = 250.0

        _CityColor("CityColor", Color) = (1.0, 1.0, 1.0, 1.0)
        [HideInInspector] _CityLevel("CityLevel",Float) = 0.7
        [HideInInspector] _isCities("isCities",Float) = 1.0

        _CloudFrequency("CloudFrequency", Float) = 2.0
        _CloudLacunarity("CloudLacunarity", Float) = 3.0
        _CloudGain("CloudGain", Float) = 0.5

        _CloudColor("CloudColor", Color) = (1.0, 1.0, 1.0, 1.0)
        _CloudLevel("CloudLevel",Float) = 0.05
        _CloudRotation("CloudRotation",Float) = 0.01
        [HideInInspector] _isClouds("isClouds",Float) = 1.0

        _CityTOP ("City Top",Float) = 0.8
        _CityBOT ("City Bot", Float) = 0.2
    }
    SubShader {

        Tags {
            "Queue"="Geometry"
            "RenderType"="Opaque"
        }

        Cull Back
        ZWrite On
        ZTest LEqual
        ColorMask RGBA
        Fog { Mode Off }

        CGPROGRAM
        #pragma surface surf BlinnPhongEditor vertex:vert
        #pragma target 3.0

        #include "UnityCG.cginc"

        uniform sampler2D _PermTable2D, _Gradient3D, _BumpMap, _NormMap;
        uniform float _PlanetStretch, _SpecPower, _PlanetType, _Frequency, _Lacunarity, _Gain, _IceStrength, _IceLevel, _Level3, _Level2, _Level1, _ShoreLevel, _WaterLevel, _PeakLevel;
        uniform float4 _ChosenColor, _IceColor, _PeakColor, _Level3Color, _Level2Color, _Level1Color, _ShoreColor, _WaterColor;

        float4 _AtmosNear;
        float4 _AtmosFar;
        float _AtmosFalloff;

        struct EditorSurfaceOutput {
            half3 Albedo;
            half3 Normal;
            half3 Emission;
            half3 Gloss;
            half Specular;
            half Alpha;
            half Custom;
          };

        inline half4 LightingBlinnPhongEditor_PrePass (EditorSurfaceOutput s, half4 light){
            half3 spec = light.a * s.Gloss;
            half4 c;
            c.rgb = (s.Albedo.rgb * light.rgb + light.rgb * spec);
            c.g -= .01 * s.Alpha;
            c.r -= .03 * s.Alpha;
            c.rg += min(s.Custom, s.Alpha);
            c.b += 5.75 * min(s.Custom, s.Alpha);
            c.b = saturate(c.b + s.Alpha * 0.02);
            c.a = 1.0;
            return c;
        }

        inline half4 LightingBlinnPhongEditor (EditorSurfaceOutput s, half3 lightDir, half3 viewDir, half atten){

            half3 h = normalize (lightDir + viewDir);
            half diff = max (0, dot ( lightDir, s.Normal ));

            float nh = max (0, dot (s.Normal, h));
            float spec = pow (nh, s.Specular*128.0);

            half4 res;
            res.rgb = _LightColor0.rgb * diff;
            res.w = spec * Luminance (_LightColor0.rgb);
            res *= atten * 1.0; //CHANGED TO 1.0 FOR 5.0

            return LightingBlinnPhongEditor_PrePass( s, res );
        }

        struct Input {
            float4 vertPos;
            float3 viewDir;
            float2 uv_BumpMap;
            float2 uv_NormMap;
        };

        float3 fade(float3 t){
            return t * t * t * (t * (t * 6 - 15) + 10);
        }

        float4 perm2d(float2 uv){
            return tex2D(_PermTable2D, uv);
        }

        float gradperm(float x, float3 p){
            float3 g = tex2D(_Gradient3D, float2(x, 0) ).rgb *2.0 - 1.0;
            return dot(g, p);
        }

        float inoise(float3 p){
            float3 P = fmod(floor(p), 256.0);   // FIND UNIT CUBE THAT CONTAINS POINT
            p -= floor(p);                      // FIND RELATIVE X,Y,Z OF POINT IN CUBE.
            float3 f = fade(p);                 // COMPUTE FADE CURVES FOR EACH OF X,Y,Z.

            P = P / 256.0;
            const float one = 1.0 / 256.0;

            // HASH COORDINATES OF THE 8 CUBE CORNERS
            float4 AA = perm2d(P.xy) + P.z;

            // AND ADD BLENDED RESULTS FROM 8 CORNERS OF CUBE
            return lerp( lerp( lerp( gradperm(AA.x, p ),
                                     gradperm(AA.z, p + float3(-1, 0, 0) ), f.x),
                               lerp( gradperm(AA.y, p + float3(0, -1, 0) ),
                                     gradperm(AA.w, p + float3(-1, -1, 0) ), f.x), f.y),

                         lerp( lerp( gradperm(AA.x+one, p + float3(0, 0, -1) ),
                                     gradperm(AA.z+one, p + float3(-1, 0, -1) ), f.x),
                               lerp( gradperm(AA.y+one, p + float3(0, -1, -1) ),
                                     gradperm(AA.w+one, p + float3(-1, -1, -1) ), f.x), f.y), f.z);
        }

        float fBm(float3 p, int octaves){
            float freq = _Frequency, amp = 0.5;
            float sum = 0;
            for(int i = 0; i < octaves; i++)
            {
                sum += inoise(p * freq) * amp;
                freq *= _Lacunarity;
                amp *= _Gain;
            }
            return sum;
        }

        void vert (inout appdata_full v, out Input o) {
            UNITY_INITIALIZE_OUTPUT(Input,o);
            o.vertPos = v.vertex;
        }

        void surf (Input IN, inout EditorSurfaceOutput  o) {

            if(_PlanetType == 6){
                IN.vertPos.xyz = IN.vertPos.xyz/float3(4,_PlanetStretch,1);
            }

            float n = fBm(IN.vertPos.xyz, 4);

                if(_Level1 < _ShoreLevel)
                    _Level1 = _ShoreLevel+0.02;

                if(_ShoreLevel < _WaterLevel)
                    _WaterLevel = _ShoreLevel-0.02;

                if(n >= _PeakLevel){
                    _ChosenColor = _PeakColor;
                }
                if(n <= _PeakLevel){
                    _ChosenColor = lerp(_Level3Color,_PeakColor, (n - _Level3)/(_PeakLevel - _Level3));
                }
                if(n <= _Level3){
                    _ChosenColor = lerp(_Level2Color,_Level3Color, (n - _Level2)/(_Level3 - _Level2));
                }
                if(n <= _Level2){
                    _ChosenColor = lerp(_Level1Color,_Level2Color, (n - _Level1)/(_Level2 - _Level1));
                }
                if(n <= _Level1){
                    _ChosenColor = lerp(_ShoreColor,_Level1Color, (n - _ShoreLevel)/(_Level1 - _ShoreLevel));
                }
                if(n <= _ShoreLevel){
                    _ChosenColor = lerp(_WaterColor,_ShoreColor, (n - _WaterLevel)/(_ShoreLevel - _WaterLevel));
                }
                if (n <= _WaterLevel){
                    _ChosenColor = _WaterColor;
                }

                if (_PlanetType == 0 && n >= _Level1 && IN.vertPos.y >= _IceLevel)
                    _ChosenColor = lerp(_ChosenColor,_ChosenColor*_IceStrength, (IN.vertPos.y - _IceLevel)/(_IceLevel));

                if (_PlanetType == 0 && n >= _Level1 && IN.vertPos.y <= -_IceLevel)
                    _ChosenColor = lerp(_ChosenColor,_ChosenColor*_IceStrength, (IN.vertPos.y + _IceLevel)/(-_IceLevel));

                if (_PlanetType == 2 && IN.vertPos.y >= _IceLevel)
                    _ChosenColor = lerp(_ChosenColor,_ChosenColor*_IceStrength, (IN.vertPos.y - _IceLevel)/(_IceLevel));

                if (_PlanetType == 2 && IN.vertPos.y <= -_IceLevel)
                    _ChosenColor = lerp(_ChosenColor,_ChosenColor*_IceStrength, (IN.vertPos.y + _IceLevel)/(-_IceLevel));

                if (_PlanetType == 3 && n >= _Level1 && IN.vertPos.y >= _IceLevel)
                    _ChosenColor = lerp(_ChosenColor,_IceColor, (IN.vertPos.y - _IceLevel)/(_IceLevel));

                if (_PlanetType == 3 && n >= _Level1 && IN.vertPos.y <= -_IceLevel)
                    _ChosenColor = lerp(_ChosenColor,_IceColor, (IN.vertPos.y + _IceLevel)/(-_IceLevel));

            o.Custom = 0.0;

            float4 Fresnel0_1_NoInput = float4(0,0,1,1);
            float4 Fresnel0=(1.0 - dot( normalize( float4( IN.viewDir.x, IN.viewDir.y,IN.viewDir.z,1.0 ).xyz), normalize( Fresnel0_1_NoInput.xyz ) )).xxxx;
            float4 Pow0=pow(Fresnel0,_AtmosFalloff.xxxx);
            float4 Saturate0=saturate(Pow0);
            float4 Lerp0=lerp(_AtmosNear,_AtmosFar,Saturate0);
            float4 Multiply1=Lerp0 * Saturate0;
            float4 Add0=Multiply1 + _ChosenColor;

            o.Albedo = Add0.xyz;
            o.Specular = 1.0;

            o.Gloss = 0.5;
            o.Normal = UnpackNormal(tex2D (_NormMap, IN.uv_NormMap));

            if(n > _ShoreLevel){
                o.Gloss = 0.1;
                o.Normal = UnpackNormal(tex2D (_BumpMap, IN.uv_BumpMap));
            }else if(_PlanetType == 2){
                o.Gloss = 0.1;
                o.Normal = UnpackNormal(tex2D (_BumpMap, IN.uv_BumpMap));
            }else if(_PlanetType == 5){
                o.Gloss = 0.1;
                o.Normal = UnpackNormal(tex2D (_BumpMap, IN.uv_BumpMap));
            }

            if(_PlanetType == 6){
                o.Gloss = 0.1;
                o.Normal = UnpackNormal(tex2D (_NormMap, IN.uv_NormMap));
            }

            if(_PlanetType == 0){
                if(n > _ShoreLevel){
                    o.Gloss = 0.01;
                }
                o.Gloss = 0.05;
            }

        }
        ENDCG

    }
}

```

# Answer
The cheapest (but not necessarily very flexible) solution would be to duplicate the shader code in your C# script.

When the player clicks, fire a ray through the mouse position. Capture the RaycastHit struct, and it will give you the world position and texture coordinates of the point directly under the mouse.

(If you've displaced your sphere out along the normals, mapping the raycast hit to the actual visibly struck position is non-trivial - fortunately it sounds like that doesn't apply in this case.)

Dump those parameters into your C# version of the shader code, and you can compute the colours identically to what's displayed on the model, without any expensive texture read-back.

The problem with this method is if you change your shader or its material paraeters, you need to remember to make a corresponding change to your C# script, or their results will diverge. This is rather brittle.

The bluntest way to do it would be to render either your full scene, or the mesh's surface, to a texture anytime it changes. Then you can use GetPixels to copy the contents of that texture so they're accessible to your C# script, and lookup the colour at the clicked point in the resulting colour buffer. This will be less code, and is flexible to shader changes, but it has a significant performance cost to consider.

It's past midnight here so I won't go into the full details just now. The key items you need to know are:

* Creating RenderTexture and setting it as the current target with `RenderTexture.active`
* Create a pass or version of your planet material where you replace the transformed vertex coordinates with`float4(i.uv * 2.0f - 1.0f, 0.0f, 1.0f);` so it outputs a texture map for the object instead of its 3D shape. You might need to flip the y direction and/or change the culling mode to make this work - I can never remember which way's right so I do these by trial and error. ;)
* `planetMaterial.SetPass(passID);` to bind a particular shader effect
* Graphics.DrawMeshNow to render into your RenderTexture
* Texture2D.ReadPixels to read the current RenderTarget into a `Texture2D` object you've created (this feels redundant, but it's the only way I know to do readback)
* Texture2D.GetPixel to look up a pixel colour in this texture, or GetPixels32 to copy the whole buffer into an array for bulk/repeated use.
> 2 votes

---
Tags: unity, shaders, raycasting, materials
---


title: Having trouble with EOF in Xcode

text:
# Question
Title: Having trouble with EOF in Xcode
I'm getting an error that says "control may reach end of function" and I have gone through my code several times now and am not spotting the error. It may be something simple too.

```
// loop continually until the user gives a valid guess
FText GetValidGuess()
{
    EGuessStatus Status = EGuessStatus::Invalid_Status;
    do {
        // get a guess from the player
        int32 CurrentTry = BCGame.GetCurrentTry();
        std::cout << "Try " << CurrentTry << ". Enter your guess: ";
        FText Guess = "";
        std::getline(std::cin, Guess);

        // check status and give feedback
        Status = BCGame.CheckGuessValidity(Guess);
        switch (Status) {
            case EGuessStatus::Wrong_Length:
                std::cout << "Please enter a " << BCGame.GetHiddenWordLength() << " letter word.\n";
                break;
            case EGuessStatus::Not_an_isogram:
                std::cout << "Please enter a word witout repeating letters.\n";
                break;
            case EGuessStatus::Not_Lowercase:
                std::cout << "Please enter all lowercase letters.\n";
                break;
            default:
                return Guess;
        }
        std::cout << std::endl;
    } while (Status != EGuessStatus::OK); // keep looping until we get no error
}

```

# Answer
The compiler isn't smart enough to figure out that `Status != EGuessStatus::OK` is always true.

So it assumes that it might be true or false - and if it's false, then the computer would get to the end of the function without returning anything, which is what that warning is trying to tell you.

One solution would be to change the condition to `while(true)`.
> 1 votes

---
Tags: c++, xcode
---


# Question
Title: Is adding quaternions a useful operation?
I'm working with quaternions and 4x4/3x3 matrices and I have a doubt regarding the use of them.

I think that adding and multiplying quaternions is the same as converting the quaternion to a matrix, do the operation, and then convert back to quaternion.

**My question is:** In what situation could adding two quaternions be a thing? I mean, when you are working with matrices and you want to "add" two rotations, you have to multiply. Am I missing something?

# Answer
I can think of two reasons:

* if your quats represent infinitesimal rotations, adding them together actually yields the composite rotation, provided the result is infinitesimal too (i.e. an element of that algebraic group). Quaternion addition, as opposed to multiplication, is **commutative** and, well, numerically **fast**. One situation where this might be "a thing" is if you work with high frequency gyroscopes where the rotation offsets actually amount to infinitesimal rotors.
* when you want to simply approximate an intermediate rotation via *normalized lerp* (short *NLERP*). This way, instead of slerping `q1` and `q2` with a factor `lambda` you compute the averaged sum `(1-lambda)*q1 + lambda*q2 -> q` and then reproject `q` onto the unit hypersphere by dividing it by `||q||`.

As a side note of "adding quaternions": quaternions are actually points on a 3-dimensional manifold (unit Hamiltonian hypersphere or whatever it is called). When points on a space that is not Euclidean (i.e. flat) are added, the result is no longer a point in the space of their origin.. unless the points are really close together and adding them approximately amounts to adding vectors in the tangent space of their vicinity. If you want a more detailed digression into the applications and implications of this observation, I refer you and any interested reader to this (more recent) paper on how to compute weighted averages on manifolds with the quaternion case thoroughly examined.
> 10 votes

---
Tags: 3d, quaternion
---


# Question
Title: Unity 5 - Mouse Disappears during runtime
My mouse cursor disappears during runtime. When I click esc, it appears and the moment I click on something, it disappears again. This is what I have done so far to fix this. I have added this to a script on an empty gameobject in my scene.

```
void Start()
{
    Cursor.visible = true;
}

```

The problem persists and so I added the code to the update function. Still the same. I do not understand what am I missing here. Why is the cursor disappearing the moment I click and why doesn't it appear automatically onStart during runtime? I have also tried to implement a custom cursor and the same problem again. I am using 5.3.2f. I hope someone can point me in the right direction. Cant find a solution in any forums.

# Answer
Okay so I have fixed this. Hopefully this answer will help someone else. Okay if you look at this script MouseLook.cs under StandardAssets/Characters/FirstPersonCharacters/Scripts/. Go to lines 83,88,89.

Make the following changes :

`m_cursorIsLocked = true;(line 83) change to 'false'`

```
 Cursor.lockState = CursorLockMode.Locked; (line 88) change to 'none'
 Cursor.visible = false; (line 89) change to 'true'

```

I think its pretty self explanatory what this does. Line 83 set m\_cursorIsLocked to true whenever I clicked my mouse. Line 88 used m\_cursorIsLocked as a condition to set my cursor lockmode to Locked and my cursor to invisible. Thast why even when I added Cursor.visible = true in my update function, it still did not work since MouseLook.cs was constantly turning my cursor to invisible. Anyways I cannot guarantee that these changes will not cause any other issues. This is because this script is being referred to by other scripts. But so far so good, everything works fine. Thanks.
> 1 votes

---
Tags: rendering, unity, mouse
---


# Question
Title: How to know when Android OpenGL Context has been preserved?
I am implementing a pause menu for my game in Android.

If the activity pauses and then resumes, it loses the OpenGL context. However, if you use `setPreserveEGLContextOnPause(true)` it **MAY** preserve the context if the device supports it.

How can I check if the context has been preserved or not?

# Answer
> 3 votes
If you require specific behavior, your best option is to use a plain SurfaceView rather than a GLSurfaceView.

GLSurfaceView is just a SurfaceView subclass that handles threading and EGL context management. You can find multiple examples of GLES use with plain SurfaceViews in Grafika, including some handy classes for working with EGL.

When OpenGL ES was first introduced into Android, the device could only have one EGL context at a time. Not one per *app*, one per *device*. This is why GLSurfaceView is so aggressive about releasing the context. It's still a good idea to release the context and any associated resources when an app is kicked into the background, since you don't know how long it will be there, and it's good practice to play nice with other apps.

In any event, you can tell if your context was preserved by trying to use something in it. If the attempt succeeds, you can assume you've still got the same context.

There's some notes for older versions of Android in this question, though some of the answers are a bit dodgy.

---
Tags: android, opengl-es2
---


# Question
Title: Workaround to losing the OpenGL context when Android pauses?
The Android documentation says:

> There are situations where the EGL rendering context will be lost. This typically happens when device wakes up after going to sleep. When the EGL context is lost, all OpenGL resources (such as textures) that are associated with that context will be automatically deleted. In order to keep rendering correctly, a renderer must recreate any lost resources that it still needs. The onSurfaceCreated(GL10, EGLConfig) method is a convenient place to do this.

But having to reload all the textures in the OpenGL context is both a pain and hurts the game experience for the user when reentering the app after a pause. I know that "Angry Birds" somehow avoids this, I'm looking for suggestions on how to accomplish the same?

I'm working with the Android NDK r5 (CrystaX version.) I did find this possible hack to the problem but I'm trying to avoid building an entire custom SDK version.

# Answer
Replica Island has a modified version of GLSurfaceView that deals with this issue (and works with earlier Android versions). According to Chris Pruett:

> Basically, I hacked up the original GLSurfaceView to solve a very specific problem: I wanted to go to different Activities within my app without throwing all of my OpenGL state away. The major change was to separate the EGLSurface from the EGLContext, and to throw the former away onPause(), but preserve the latter until the context is explicitly lost. The default implementation of GLSurfaceView (which I didn't write, by the way), throws all GL state away when the activity is paused, and calls onSurfaceCreated() when it is resumed. That meant that, when a dialog box popped up in my game, closing it incurred a delay because all the textures had to be reloaded.
>
> You should use the default GLSurfaceView. If you must have the same functionality that mine has, you can look at mine. But doing what I did exposed all sorts of awful driver bugs in some handsets (see the very long comments near the end of that file), and you can avoid all that mess by just using the default one.

Edit: I just realized you already posted the link to a similar hack. I don't think there is any built-in solution prior to honeycomb. Replica Island is a popular game working on many devices and you might find Chris's implementation and comments helpful.
> 22 votes

# Answer
I'd like to add another answer to this that was passed on to me a year or two back by Chris Pruett (Replica Island, Wind-Up Knight, etc). It's especially useful here in 2013 since setPreserveEglContextOnPause(true) doesn't seem to work on 4.3. (I could be wrong about that but that's how it looks to me right now as I update game code last touched in 2011).

Basically the trick is to detach your GLSurfaceView from the view hierarchy from your Activity's onPause(). Since it's not in the view hierarchy at the point onPause() runs, the context never gets destroyed.

So your Activity's onPause() should look like this:

```
@Override
public void onPause() {
    view.setVisibility(View.GONE);
    super.onPause();
    ...
}

```

And you restore your GLSurfaceView to the hierarchy *not* from onResume() but from onWindowFocusChanged() :

```
@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus && view.getVisibility() == View.GONE) {
         view.setVisibility(View.VISIBLE);
    }
    ...
}

```

Note that you never call the GLSurfaceView's onPause() and onResume() and that this is the official SDK GLSurfaceView, no hacked-up alternative version is required.
> 8 votes

# Answer
**\< rant \>** I spent a huge amount of time on this problem, I tried many different solutions and none worked until today, I think this is one of the most awful design decision I even seen, but coming from the Android team I'm not really surprised. **\< /rant \>**

So, the solution is to move the eglContext member upwards and make it static (global) so it won't be destroyed, then you simply have to check if it's null or not before creating it again.

So far this solution seems to works for us, and we don't care if it breaks on 2005 devices.
> 7 votes

# Answer
Use honeycomb API. There is an option do preserve your OGL context. Otherwise, you need to reload your context. It is not difficult nor painful.

You need to understand that there is a two cases (Android 2.1):

* Screen Pause: your application is always the front one =\> hack available
* Application Pause: there is another front application =\> No Solution

Note: old android gpus don't support multi context. So the opengl context is lost when you switch to another application =\> no solution available (You can hack to preserve your context on screen pause).

Note 2: HoneyComb function is setPreserveEGLContextOnPause
> 4 votes

# Answer
Some of the answers here are reasonable for early uses of OpenGL ES on Android. The first GLES devices only supported a single context, so GLSurfaceView was designed to aggressively discard state. Convincing GLSurfaceView to do otherwise isn't easy.

For more recent versions of Android (probably anything using GLES 2.x), the best answer is to use a plain SurfaceView and do your own EGL and thread management. You can find multiple examples of GLES used with a plain SurfaceView in Grafika, including a library of simple classes for creating and destroying EGL contexts.

It's still good practice to unload state when an app goes into the background, but for the example from Chris Pruett -- where the app was still in the foreground, but the Activity hosting the GLSurfaceView was switched away from -- there's no value in tearing down the context.
> 2 votes

---
Tags: android, opengl-es
---


# Question
Title: Unity3D: Making heavy calculation on separate thread
So, I've created a program with Kinect as its input. As you know, Kinect will send the data 30 frame per second.

I have a model that will mimic Kinect's input motion, so on Update() I read the motion from Kinect.

The problem is, on Update(), I've done a heavy computational algorithm. It makes the system lag and freezing. I've tried to do the calculation every 60 frames instead of each frame, but the system still got lag.

```
void Update(){
        ...
        //GET DATA FROM KINECT
        frame = new SkeletonRecorded();
        frame.root.rotation = skeletons[kinect2SensorID, playerID].root.rotation;
            ...
        frame.rightShoulder.position = skeletons[kinect2SensorID, playerID].rightShoulder.position;
        frames.Add(frame);
        if (frames.Count >= 60) {
            //CALLING THE CALCULATION METHOD (Here is the heavy part begin)
            comparatorClass.GetSkeletonData(frames);
            frames.Clear();
        }

}

```

The above code is just small parts of the Update() method (I cut it short for convenience). So, how should I call the GetSkeletonData() method without making the interface lag?

# Answer
Handle it on another thread.

http://www.dotnetperls.com/thread

Extremely simple example. Can also look into Async and BackgroundWorker. But this would be a way to start.

```
using System;
using System.Threading;

bool skeletalComputationDone = false;
Thread skeletalComputationThread;

// main game update loop
Update()
{
    // ... other game stuff ...

    // if computation done handle it then start again
    if(skeletalComputationDone)
    {
        // .. handle it ...
        skeletalComputationDone = false;
        skeletalComputationThread = new Thread(new ThreadStart(SkeletalComputationThread));
        skeletalComputationThread .Start();
    }

    // ... more game stuff ...
}

// thread where to do skeletal computation
void SkeletalComputationThread()
{
     // ... massive computation

     skeletalComputationDone = true;
}

```
> 2 votes

---
Tags: unity, multithreading, kinect
---


# Question
Title: Why do games have different ports for different maps?
A little old example for that would be Metin2, this is the only game I know which have that, but there may be more. In Metin2 there are maps which are accessable through other ports. I'm not a network specialist, but I think then it is needed to connect to an other port on an map change.

So would it not be possible todo all that on one port? Are there any benefits from that?

Could it be that there is a limit on port connections on a server, that this would be something for loadbalancing?

# Answer
> 3 votes
Massive multiplayer online games like Metin2 are often too large to be handled by just a single server. A common solution is to have multiple servers and have each server handle a different region of the game world. Usually every server needs their own IP address. But static IP addresses are not free. Every IP you need usually costs extra. A possible workaround is to assign one IP address to a router and have it route each port to a different server on the local area network behind it.

---
Tags: networking
---


title: design / data structures

text:
# Question
Title: design / data structures
I'm working on a game which I'm writing in Javascript and then porting to iOS/Android via phonegap/cordova.

For the most part, I understand how to code and how to get what I want to happen, BUT I have a major struggling point in using proper techniques and avoiding redundancy and over-complexity.

For example, one of my first forays into game dev, I had tried to answer a question on how to simplify a set of actions or functions that are related (you can check out my bad answer here How can I design lots of different attack types that can be combined? )

Now, I'm sort of at a similar pass at my game, I have different 'enemy types' that are supposed to trigger a different action when they touch the player. I have a if/else structure right now to change between these different circumstances.

Sean Middleditch did a good job of answering why 'data-driven' design works better than 'procedural' design, but for the life of me I can't figure out HOW to employ this. It seems to me that no matter how I want to structure my objects in my game, and which properties I give them, at some point I will need an if/else or switch statement, can anyone help me work past this?

```
if(enemyType == 'black'){  // enemyType is a color
            done(index);   // done is a function that removes the enemy after it touches the player
            updateScore(score); // black is score point so it updates score
}else if(enemyType == 'red'){  // red is a death so gameOver
    done(index);
    if(!gameVars.invincible && gameVars.lives == 1){ // but the player might be invincible or have extra lives
        gameOver();
    }else if (!gameVars.invincible){ // in that case we manage the lives or ignore the hit completely
        manageLives(-1);
    }
}else if(enemyType == 'blue'){ // the rest are power ups of types
    done(index);
    setInvincible();
}else if(enemyType == 'grey'){
    done(index);
    setSlowTime();
}else if (enemyType == 'green') {
    done(index);
    gameVars.teir_reducer += 2;
}else if (enemyType == 'yellow') {
    done(index);
    gameVars.speed_reducer += 10;
}else if (enemyType == 'orange') {
    done(index);
    updateScore(1000);
}else if (enemyType == 'purple') {
    done(index);
    manageLives(1);
}else if (enemyType == 'violet') {
    done(index);
    setMagenetic();
}else if (enemyType == 'gainsboro') {
    done(index);
    setWarp();
}

```

# Answer
In Javascript, a property can also be a function. Don't make enemyType a string. Make it an object which has multiple methods for different interactions.

```
violetThing = {
     name: "violet",
     sprite: "violetThing.png",
     onTouchFunction: setMagnetic,
     color: '#ffdd22'
}

yellowThing = {
     name: "yellow",
     sprite: "yellowThing.png",
     onTouchFunction: function() { gameVars.speed_reducer += 10; },
     color = '#00ddff'
}

//...

```

In the long function you posted above you would simply do:

```
done(index); // whatever that's supposed to do
enemyType.onTouchFunction();

```
> 1 votes

---
Tags: javascript, design-patterns, data-structure
---


# Question
Title: SDL2 SDL_PollEvent endless polling on key hold
What is wrong with SDL2 SDL\_PollEvent() function? When I press-and-hold a key it enters "while (SDL\_PollEvent())" block each frame. If in previous frame event queue was emptied and in new frame I press-and-hold button it should create one event - SDL\_KEYDOWN. Run this code. It has macro to compile for SDL2 and SDL1.2. SDL1.2 runs okay, polls keyhold and empies queue. SDL2 seems to pump it back each frame, so SDL\_PollEvents grabs the same even next frame.

```
#define USESDL2

#include <iostream> //cout
using namespace std;

#ifdef USESDL2
//link with -l SDL2
#include <SDL2/SDL.h>
#include <SDL2/SDL_events.h>

#else
//link with -l SDL
#include <SDL/SDL.h>
#include <SDL/SDL_events.h>

#endif // USESDL2

int main(int argc, char **argv)
{
    bool q = true;
    SDL_Event e;

    SDL_Init(SDL_INIT_VIDEO);
#ifdef USESDL2
    SDL_Window *win;
    win = SDL_CreateWindow("SDL2", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN);
#else
    SDL_Surface *buff;
    buff = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);
#endif
    while (q) {
        while (SDL_PollEvent(&e)) {
            cout << "Polling: ";
            switch (e.type) {
            case SDL_QUIT:
                q = false;
            break;
            case SDL_KEYDOWN:
                cout << "Key down: ";
                switch (e.key.keysym.sym) {
                case SDLK_q:
                    q = false;
                break;
                case SDLK_UP:
                    cout << "UP\n";
                break;
                case SDLK_r:
                    cout << "r\n";
                break;
                }
            break;
            }
        }
    }

#ifdef USESDL2
    SDL_DestroyWindow(win);
#endif
    SDL_Quit();
}

```

# Answer
> 4 votes
SDL2 actually generates key repeat events automatically. You need to manually filter repeated key events out by checking the `repeat` member of a `SDL_KeyboardEvent`. This is something that did not automatically happen in SDL1, so that's why the behaviour is different. See SDL\_KeyboardEvent for more info.

---
Tags: events, sdl2, keyboard, polling
---


# Question
Title: How to manage different speed of actions in RogueLike games?
How to manage different speed of actions in RogueLike games?

What I mean is that turn based games may have actors acting at different "speed", depending on the action and some other characteristics. The actors then effectively do more actions/turns than others if they have greater speed, or not.

How to determine when an actor should be able to act (turn scheduling?)?

It looks like there is different ways to do it? Can you explain some with algorithms?

# Answer
> 13 votes
In my roguelike game Tyrant I used a system of action points and speed ratings.

Basically:

* Most actions had a AP cost of 100
* Most creatures have a speed of 100

Then the game loop would go as follows.

* Hero takes an action.
* Elapsed time is calculated as `hero action AP cost * 100 / hero speed`
* All creatures get given APs equal to `creature speed * elapsed time / 100`
* Creatures take actions and have APs subtracted until their APs are \<= 0
* Repeat

This system worked very nicely overall, example nice features:

* If you have a very fast hero (perhaps due to a magic speed bonus), you can get several moves in before an individual creature can move (it's APs would be negative for a few turns because the elapsed time would be small)
* You can make some actions more or less expensive by varying the AP cost
* You can delay creatures by subtracting APs, or give them a sudden one-off boost by adding APs

# Answer
> 4 votes
Action points. Give each entity a "speed" so that faster actors get more points each turn. Make each action take a specific number of points to complete, and subtract that number from the player's points for that turn when he takes an action. If an action takes more points than the player has left, mark it as "partially completed", and let him finish it next turn.

# Answer
> 2 votes
Do you mean having actions take multiple turns (i.e., sleeping for 50 turns straight)?

What I would do is keep an object, player.currentAction. currentAction might contain how many turns the action would require, what the resolution of the action is, and a list of states that cancel the action (in danger, being attacked, too hot, etc). Each turn, before we checked for player input, we would check to see if the player was currently in the middle of an action, then do something like something like...

```
if(!player.currentAction.interrupted())
{
 if(player.currentAction.complete() == true)
   {
    player.currentAction.doAction(); //Some actions, like casting a spell, would have something happen here. Others, like sleeping, may or may not, depending on how you coded it.
    player.currentAction = null;
   }
else player.currentAction.decreaseTimer(); //Decrease our timer by one.
}
else
{
 player.currentAction.interrupt(); //Let the player know he's been interrupted. Bungle the spell, cancel sleep, etc.
 player.currentAction = null;
}

```

# Answer
> 2 votes
You can go with action points but no turns per se but ticks, which are much smaller. Suppose every actor has action point accumulation speed (e.g. 2 AP per tick). It starts an action worth, say, 10 AP. The game advances 5 ticks forward (because this is how much it takes for the actor to pay action's AP price).

When there are several actors. The game advances tick by tick until somebody has payed AP price at wich point this action is executed.

The approach is similar to @mikera's, only there are no negative APs.

# Answer
> -1 votes
**High Resolution Time**

If *punch* takes 400 turns, and *kick* takes 1000 turns, I can punch you at least twice before you kick me, and I can punch you 5 times by the time you kick me twice.

By making things take lots of turns, you have a lot of control over how long things take.

---
Tags: roguelikes
---


# Question
Title: Drawing visibility polygons in Unity (for vision cones with occlusion)
I'm currently trying to create an effect like the one displayed below in Unity:

However, it seems that I can't do this with any of Unity's built-in light objects, and I simply cannot find anything online that talks about this. Is there a way to achieve this in Unity? 2D or 3D solutions are fine, as I'm sure that they're both very similar to each other,

# Answer
You can use a dynamically generated mesh. The points for the mesh can be obtained using one of the techniques described in the links from the comments. Those steps are as follows:

1. Collect all the objects in your vision cone. This depends on what you're using for your vision cone and underlying data structure for keeping track of your objects. You could use a collider for your vision cone and maintain a list of objects using OnTriggerEnter and OnTriggerExit, or you could do a `Physics.SphereCastAll`.
2. For each object
    1. Get the points that define the object's collider, or otherwise find the edges of the collider.
    2. For each point
        * Cast a ray from your vision cone source through the point to the edge of your vision cone.
        * Wherever the ray hits, add that point to your mesh.
        * Cast two additional rays +- a small amount to either side of the point. Also add these hit points to your mesh.

The result ends up looking something like this:

Each line is a ray cast and each point is a place where ray cast hit. The points hitting along the center of geometry are rays that were meant for end points farther away, but hit something along the way.

Finally, complete the mesh, fanning out from the center point to each point around the vision cone.
> 3 votes

---
Tags: unity, visibility-determination
---


# Question
Title: Is it possible to use Java as a scripting language in unity?
I wonder if its possible to use Java as a scripting language in unity to create a basic 2d game?

# Answer
No. As far as i know, Unity is only made to use JavaScript and C#.
> 0 votes

# Answer
Unfortunately - No. Unity only supports: UnityScript (JavaScript for Unity) and C#. Boo support dropped in Unity 5.

But C# is very similar to Java, and I for myself started only with Java knowledge and it was no problem for me to learn C#.
> 0 votes

---
Tags: unity, java, 2d, scripting, unityscript
---


# Question
Title: How to sync new object (weapons/bullet) in a multiplayer photon game ?
I'm using Photon to develop a multiplayer game. I would like to know the best way to synchronize "weapons" bullets object between network players. Thanks

# Answer
> 1 votes
You don't need to continuosly sync the position of your bullets, you only need to know when and where a bullet was fired. This should be fine for most cases:

```
[PunRPC]
private void Fire(Vector3 pos, Vector3 dir)
{
    Instantiate(Resources.Load("Bullet"), pos, dir);

    if(this.photonView.isMine)
    {
        this.photonView.RPC("Fire", PhotonTargets.OthersBuffered, pos, dir);
    }
}

```

---
Tags: unity, multiplayer, photon
---


# Question
Title: A panel to change 3d object properties when right click on it (Unity)
I'm building a UI system to edit selected 3D objects. I have spheres on the screen and I want to be able to edit their proprieties (radius for example). In order to do that I want the user to be able to click on a sphere and then it show a panel next to the object. When the user changes slider value the radius of the sphere which as been clicked on change. Using the new unity event system, I think it's easy to achieve, but I'm a new to unity and even if I know the basic I don't know how to organize this properly.

At the end my goal would be to select multiple sphere, right click and edit the radius to all selected spheres. https://i.stack.imgur.com/DPPps.jpg Any tips on how to do that ? Sorry for my poor english. Thanks

# Answer
you should ray casts for selecting sphere game object, then use attached script to on value change in slider game object you can use this code

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

public class SelectSphere : MonoBehaviour {
public  GameObject selectedSphere;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if(Input.GetMouseButtonDown(0))
        {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, 100))
            selectedSphere=hit.collider.gameObject;
        }
    }
    public void ChangeRadiusOfSphere()
    {
        if(selectedSphere!=null)
        {
            float sildervalue=GameObject.Find("Slider").GetComponent<Slider>().value;
            if(sildervalue!=0)
                selectedSphere.transform.localScale=new Vector3 (sildervalue*2f,sildervalue*2f,sildervalue*2f);
        }
    }
}

```
> 1 votes

---
Tags: unity, gui
---


title: Making Scene at editor mode

text:
# Question
Title: Making Scene at editor mode
On Button click at **editor mode** I am trying to make a scene of selected Hierarchy game-object but the problem is as i click the button new scene become upon and I lost the scene where i were selected the Game-object. My code given below:

```
 if (GUILayout.Button("Generate Scene"))
        {
            Scene newScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects);;
            SceneManager.MoveGameObjectToScene(Selection.activeGameObject, newScene);
            EditorApplication.SaveScene("Assets/RegionScene/" + gameObjectSelected[gameObjectSelected.Count - 1].name + ".unity"); //newScene

        }

```

# Answer
> 0 votes
Sounds like you want to use NewSceneMode.Additive to create the new scene without discarding the currently open scene(s).

Pass this as the second parameter of the NewScene() method.

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


title: Code for inventory function not working

text:
# Question
Title: Code for inventory function not working
I'm working on an inventory, and I've ran into some problems. Some code in my `CollisionDetection` class doesn't work properly.

My `CollisionDetection` class contains functions that involve mouse and item collision. You can pick up and place down items in your inventory, you can stack and split stackable items and you can replace items.

These is an example of the working function:

If you look closely you can see that the item that I'm holding with the mouse is drawn **above** the other item.

This is the example of the broken function:

I need to click twice before the item finally switches.

If you look closely you can see that the item that I'm holding with the mouse is drawn **below** the other item and the function doesn't work properly.

I think it has to do with the layer that the item is drawn on...

The stack/replace code (the whole function uses `i` which is the item. The function is started by a for loop that loops through the item and inventory tiles lists):

```
Item i2;
// Searches item 2
i2 = items.Find(x => x.itemBox.X == r.X + 9 && x.itemBox.Y == r.Y + 9 && !x.clicked && x != i);

// If the item intersects another item (item 2)
if (i.itemBox.Intersects(i2.itemBox))
{
  // If the item is stackable
  if (i.stackable && i2.stackable)
  {
    // Hiding one item visually
    if (!i.hide_Box_Def)
    {
      i2.quantity += i.quantity;
      i.hide_Box_Def = true;
      i.error = true;

      // Bool for changing the item state (picking up/ placing down)
      // But these 2 lines of code are not really used, I wrote these trying to fix this problem.
      i.m_Switch2 = true;
      i.watch.Start();
    }
  }
  // When the item is not stackable -> item needs to be replaced by another item
  else
  {
    // Item 1 (attached to the mouse)
    // clicked: a bool that attaches the item to the mouse
    i.clicked = false;

    // itembox: collisionbox for the item
    i.itemBox.X = i2.itemBox.X;
    i.itemBox.Y = i2.itemBox.Y;

    // Oldposition for the item
    i.oldPosition.X = i.itemBox.X;
    i.oldPosition.Y = i.itemBox.Y;

    // info bool: do/ do not show item info
    i.info = false;

    // Item 2 (in inventory)
    // mouse_Click_Left: bool that changes the item state (picking up/ placing down)
    i2.mouse_Click_Left = true;
    i2.info = true;
    i2.clicked = true;
    i2.itemBox.X = (int)coords.X - 15;
    i2.itemBox.Y = (int)coords.Y - 15;
  }

```

Summary:

The code works when the item that's attached to the mouse is **above** the other item.

The code doesn't work when the item that's attached to the mouse is **below** the other item.

**UPDATE**

I fixed the first problem, so I changed the question a bit.

# Answer
> 0 votes
I found the solution to my problems. I found out that some parts of my code were executed twice when an item was on a layer **below** the item in the inventory.

So I used some switches to prevent that the code was executed twice.

---
Tags: c#, monogame
---


# Question
Title: What is the term for collectibles which enhance storytelling (i.e. audio logs, bestiary entries, etc.)?
For example, Borderlands uses ECHO logs, there are audio entries in BioShock, RPGs often have "books" that you can collect pages to read a mini bonus story.

Is there a term more specific than "collectible" which conveys the element of storytelling?

# Answer
> 3 votes
In general, when these are not necessarily collectibles, they’re called the environmental storytelling.

Specifically for collectibles, I have seen “narrative collectibles” used here and there. Other options may include: narrative objects, collectible narrative objects, story collectibles.

# Answer
> 1 votes
If there isn't, I suggest we call them "narrative nuggets"

# Answer
> 0 votes
If you're looking for a more general term, Tynan Sylvester refers to details which provide flavor but don't directly impact the main gameplay as "Hair Complexity."

> Hair complexity is my term for pieces of the simulation that don’t affect anything outside themselves.
>
> I call it hair complexity because it sticks off the main ball of relationships without feeding back into it, like the hair on your head. Such hair complexity can be ignored by players who don’t wish to deal with it, while more interested or skilled players can pay attention and get its full flavor. It’s like the flavortext in a card game.

Source: The Simulation Dream

---
Tags: audio, terminology
---


# Question
Title: RAM usage unusually high, but CPU usage relatively low
I've created a relatively simple game using libgdx, but the RAM usage when I start up the game on my Android device is roughly 600-700 mb, but the CPU usage is only about ~0.05%. I've downloaded a game which seems to use similar components to mine, and its RAM usage is only ~100-200mb.

I use an AssetManager to load all of my assets, which are fair in size (the largest asset I have is probably my main game theme song which is ~3mb; all other graphic assets are ~1-2mb).

Are there any tips for how I can reduce the RAM usage of my game?

# Answer
The **Android** memory profilers that comes with the Android Developer Tools will allow you to figure out what is consuming your memory.

It comes in three parts;

* *Memory Monitor* (this is used to find performance problems, so we can ignore this one for this particular problem).
* *Tool Heap Viewer*
* *Allocation Tracker*

Using the *Heap Viewer* you can take snap-shots of the heap when your game is running and by comparing the graphs you can figure out what is consuming a lot of memory and how that changes over time.

When you've figured out what is consuming too much memory you can use the *Allocation Tracker* to figure out where in the code that memory is being allocated. The *Allocation Tracker* is more difficult to work with but there's good insight to be found using it if you manage to climb the steep learning curve.

The tools are available in IDE if you're using *Android Studio* or *Eclipse*.

More details on the tools can be found here.

If you find that all the memory allocated is correct in the sense that you don't allocate twice and forget to release then the next thing to look at would be when you actually need all the data. For example, is your game structured so that you can load a certain subset of the resources per level, and unload the unused ones from the previous level.
> 3 votes

---
Tags: java, libgdx, assets, memory
---


# Question
Title: Unity inspector script - making it save the global variables for what it's creating
I have a script which initialises a bunch of child `gameObject`(s). I wanted all of this to happen outside of the game, so I created an inspector script which has a button which triggers the method which does all the work. The problem is that when something is initialised it's global variables aren't saved for runtime this even goes so far that when I call a method outside of the one that the inspector script calls it forgets the parameters that were passed in (so they appear as null).

I've tried adding the `[Serializable]` attribute to the scripts but it doesn't change anything. What do I have to do?

# Answer
> 0 votes
So I solved the issue by making all the private global variables in the GameObjects `[Serializeable, HideInInspector]` This way when my editor script changes the thousands of game objects each save the state that they are given and when the scene in played those states are assigned to the GameObjects which work just like if I did all the calculations at the start of the scene.

As for the parameters being forgotten when a method was called from outside the main method the inspector was calling, I just made it a delegate inside the bigger method. The Method in question was only ever being called once from that method so removing it didn't make a difference.

# Answer
> 0 votes
Have a look at ScriptableObject . This'll allow you to persist this type of information over multiple sessions.

# Answer
> 0 votes
Maybe your problem is due to your are using a prefab to have all enclosed, so once you click on this prefab in your project folder the values will be reset to its default values. The solution is dont use a prefab, put your script in a empty game object.

Cheers!

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


# Question
Title: How do you create a funky moving background?
I'm trying to create something similar to what you would see if you loaded a song in Windows Media Player (the cool abstract background that moves and produces various colors). I have no idea how this can be accomplished in libgdx. I've seen other games, such as puzzle games, on the Android store that having moving backgrounds to add visual effect so that the background isn't so static/boring. How can I achieve a similar effect without consuming a ton of RAM or without high CPU usage?

# Answer
> 1 votes
I'm not going to go into details, but what you should be looking into is something like WinAMP's MilkDrop plugin presets and porting them to a shader.

A good selection of example shaders (and how to write them) can be found at https://www.shadertoy.com/. These examples run on WebGL and use the GLSL language to render procedural content that is usually fast enough to run in parallel with whatever you're rendering in addition.

Do beware that not all of them are freely reusable, so get the author's permission first if you want to reuse them.

---
Tags: java, libgdx
---


title: Reynold's Steering Behaviors

text:
# Question
Title: Reynold's Steering Behaviors
So I read Reynold's 1999 paper, \[Steering Behaviors For Autonomous Characters\]\[1\], and I presume something went over my head, because it doesn't seem to make any sense to me.

> ```
> steering_force = truncate (steering_direction, max_force)
> acceleration = steering_force / mass
> velocity = truncate (velocity + acceleration, max_speed)
> position = position + velocity
>
> ```

Not sure how this makes any sense. Unless there's a constant time step of 1s, this integration (a forward Euler, which is bad in it's own right), doesn't make much sense to me.

The behaviors themselves don't seem to make much sense either:

**Seek:**

> ```
> desired_velocity = normalize (position - target) * max_speed
> steering = desired_velocity - velocity
>
> ```

The `desired_velocity` is in the wrong direction? Should be `(target - position)`? It also doesn't return a force - it returns a difference of velocities. It doesn't scale at all with mass.

**Arrival**

> ```
> target_offset = target - position
> distance = length (target_offset)
> ramped_speed = max_speed * (distance / slowing_distance)
> clipped_speed = minimum (ramped_speed, max_speed)
> desired_velocity = (clipped_speed / distance) * target_offset
> steering = desired_velocity - velocity
>
> ```

This just doesn't make any sense to me. This will flat out not work. Sure, you'll eventually get a vector pointing away from the target, but depending on the vehicle's mass, may not be able to stop it in time. It's also dependent on an arbitrary slowing radius not tied to the objects max thrust, max speed, or mass. Like Seek, it also doesn't actually return a force.

I stopped reading after that. Clearly there is something I am missing here..

# Answer
> 1 votes
The paper is a simplified model that can be taken, modified and implemented into your specific situation. It's not intended to be an implementation you copy/paste into your game.

There are a few instances where the simplification is brought up, like when speaking about the simplified vehicle model:

> This vehicle model is based on a point mass approximation. On the one hand that allows a very simple and computationally cheap physically-based model (for example, a point mass has velocity (linear momentum) but no moment of inertia (rotational momentum)). On the other hand, it cannot be a very compelling physical model because point masses do not exist in the real world. Any physical object with mass must have a non-zero radius and hence a moment of inertia. **This use of an oversimplified non-physical vehicle model is merely for convenience and intended to be “without loss of generality”** — it should always be possible to substitute a more plausible, more realistic physically based vehicle model.

Emphasis mine. Basically, don't assume the algorithm presented will fit directly into your model. If you need a algorithm that's been adapted to fit something closer to the model your expecting, search for implementations of the steering algorithms in the engine of your choice.

---
Tags: ai
---


title: screen space or pixel space for a GUI?

text:
# Question
Title: screen space or pixel space for a GUI?
I want to design a very simple GUI for my game using OpenGL.

So far, every GUI implementation I have seen uses pixel space coordinates ( x range 0.0 to screen width and y 0.0 to screen height)

Why aren't they simply using screen space coordinates ? ( x and y range -1 to 1)

With screen space coordinates we would'nt have any issue with screen resizing, plus we won't have to transform coordinates for OpenGL since we use same space.

So why every GUI engine uses pixel space ?

# Answer
> 6 votes
> Why aren't they simply using screen space coordinates ? ( x and y range -1 to 1)

Because generally, it's easier for people to reason about (and make adjustments with) whole numbers. If you were to describe your entire UI in -1 to 1 or 0 to 1 ranges, you'd frequently be dealing with values like 0.4827 and 0.188881881. In addition to being more difficult to visualize, these values are potentially subject to all the representational issues floats have with respect to holding certain values or round-tripping through serialized formats precisely.

It's perfectly viable to choose to describe your UI in screen space coordinates, however...

> With screen space coordinates we would'nt have any issue with screen resizing,

...this is not true. You don't really solve anything by using screen space coordinates. The major issues you tend to run into have to do with *aspect ratio* and *scaling the art*. These remain problems even if you use a screen space representation.

> plus we won't have to transform coordinates for OpenGL since we use same space.

This isn't really true either; OpenGL is still going to do the transformations even if those transformations are effectively identity transforms. Even if they are skipped in some fashion, this is an extreme nano-optimization that's not likely to matter one bit in real-world applications.

---
Tags: gui
---


# Question
Title: SDL2 linux fullscreen issue at lower-than-desktop resolution
Having a problem trying to get proper fullscreen in linux.

I'm using *1440x900* on desktop. When i set SDL to use 1280x720 as fullscreen, it *does* change screen resolution. *But if i drag the mouse cursor to the bottom or right edge of the game screen, it "scrolls" the screen beyond the game surface and makes part of the desktop visible.*

Here's how I set the window/screen:

```
gameWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, screenWidth, screenHeight,
SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS ); }

```
* Am i missing some flag(s) perhaps?
* Is this a common problem? I'm on Linux Mint **MATE** (Rosa).
* This problem also occurs when trying to run the same build in an *Openbox* session.
* Using nVidia drivers (x64, v340.96) from nvidia.com, on 9600 GT card(s). No twin/dual screen or second Workspaces.

Any good tips on how to avoid or workaround this issue?

# Answer
> 1 votes
The flag called SDL\_WINDOW\_INPUT\_GRABBED **seems** to prevent the problem from happening. But still not sure if that is the, or a, correct solution.

```
SDL_CreateWindow( "SDL Tutorial",SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, screenWidth, screenHeight,
SDL_WINDOW_FULLSCREEN | SDL_WINDOW_SHOWN | SDL_WINDOW_BORDERLESS | SDL_WINDOW_INPUT_GRABBED );

```

---
Tags: graphics, sdl2, linux, fullscreen
---


# Question
Title: Is Update(GameTime) called before it's finished?
Code at the beginning of `Update(GameTime)` is being called over and over again, and code at the end of `Update(GameTime)` is only being called after a delay. Is `Update(GameTime)` called again before it's finished?

Relevant code:

```
    public override void Update(GameTime gameTime)
    {
        Console.WriteLine($"Current Position (Outer): {Texture.Position.Y}");
        if (Keyboard.IsKeyDown(Keys.Space))
        {
            Jump(gameTime);
        }

        UpdateGravity(gameTime);

        if (Keyboard.IsKeyDown(Keys.A))
        {
            velocity.X = -HorizontalMoveSpeed*(float) gameTime.ElapsedGameTime.TotalMilliseconds;
        }
        else if (Keyboard.IsKeyDown(Keys.D))
        {
            velocity.X = HorizontalMoveSpeed*(float) gameTime.ElapsedGameTime.TotalMilliseconds;
        }
        else
        {
            velocity.X = 0f;
        }

        Texture.Position += velocity;

        CheckCollisions();

        base.Update(gameTime);
    }

    private void UpdateGravity(GameTime gameTime)
    {
        velocity.Y += Gravity * (float) gameTime.ElapsedGameTime.TotalMilliseconds;
    }

    private void Jump(GameTime gameTime)
    {
        if (jumping) return;
        jumping = true;
        velocity.Y -= JumpSpeed * (float) gameTime.ElapsedGameTime.TotalMilliseconds;
    }

    private void CheckCollisions()
    {
        foreach (var platform in CryoGame.Platforms.Where(CollidesWith))
        {
            Console.WriteLine($"Current Position (Inner): {Texture.Position.Y}");
            var collision = false;

            var topInsideOther = Texture.Top <= platform.Texture.Bottom;
            var bottomOutsideOther = Texture.Bottom >= platform.Texture.Bottom;
            if (topInsideOther && bottomOutsideOther)
            {
                Texture.Top = platform.Texture.Bottom;
                collision = true;
            }

            var topOutsideOther = Texture.Top <= platform.Texture.Top;
            var bottomInsideOther = Texture.Bottom >= platform.Texture.Top;
            if (topOutsideOther && bottomInsideOther)
            {
                Texture.Bottom = platform.Texture.Top;
                collision = true;
            }

            if (collision)
            {
                velocity.Y = 0f;
            }
        }
    }

```

Example output:

```
Current Position (Outer): ...
Current Position (Outer): ...
Current Position (Outer): ...
Current Position (Outer): ...
Current Position (Outer): ...
Current Position (Outer): ...
Current Position (Outer): ...
Current Position (Outer): ...
Current Position (Outer): ...
Current Position (Outer): ...
Current Position (Outer): ...
Current Position (Inner): ...

```

\`\`\`

# Answer
> 1 votes
No. You have a condition in `CheckCollision()` that only prints 'Inner' if the condition is true (the condition is that there has to be at least one `Platform` that is in the proper state to apply the code block to. So for several Update calls, the code flow went to `CheckCollision()` but there were no `Platform`s colliding (probably) so there was zero items to run the code in the `foreach` block so the block was skipped before running the print "Inner" line. At some point, something triggered a `CollidesWith` and the `foreach` had something to do so its code ran and "inner" was printed to the output console.

---
Tags: c#, xna, game-loop, latency
---


# Question
Title: How can I shoot when I touch the Box Collider
I want to change the Computer Input to Mobile Touch Input, if I press Space Button it shoots but how do I change this \[Code\] to Touch Input ?

I want it to have it into void OnTouchDown() but what do I have to put into the if(...) in the ShootingScript if I want to have it for Mobile to work ?

Here is my Shooting Script and my Player Controller Script

ShootingScript:

```
public GameObject shootingBullets;

// Update is called once per frame
void Update ()
{
    if (Input.GetKeyDown (KeyCode.Space))
    {
        Instantiate(shootingBullets, transform.position, Quaternion.identity);
    }
}

```

---

PlayerControllerScript:

```
public float jumpHeight;

void OnTouchDown()
{
    if (GameObject.FindGameObjectWithTag("Player").GetComponent<Rigidbody2D>().velocity.y < 0.001f && GameObject.FindGameObjectWithTag("Player").GetComponent<Rigidbody2D>().velocity.y > -0.001f)
    {
        GameObject.FindGameObjectWithTag("Player").GetComponent<Rigidbody2D>().AddForce(Vector2.up * jumpHeight);
    }

}

// Update is called once per frame
void Update ()
{
    if (Input.GetKeyDown (KeyCode.UpArrow) && GetComponent<Rigidbody2D>().velocity.y < 0.001f && GetComponent<Rigidbody2D>().velocity.y > -0.001f)
    {
        GetComponent<Rigidbody2D>().AddForce(Vector2.up * jumpHeight);
    }

    if (Input.GetKeyDown (KeyCode.DownArrow))
    {
        GetComponent<Rigidbody2D>().AddForce(-Vector2.up * jumpHeight);
    }

}

```

# Answer
> 1 votes
So from what I understand you want to shoot using `OnTouchDown()`, well if thats what you want to do then you simply repeat what you did in the playerController class.

ShootingScript:

```
public GameObject shootingBullets;

// Update is called once per frame
void Update ()
{
    if (Input.GetKeyDown (KeyCode.Space))
    {
        Instantiate(shootingBullets, transform.position, Quaternion.identity);
    }
}

void OnTouchDown()
{
    //no if needed as it is only called when touch input is down
    Instantiate(shootingBullets, transform.position, Quaternion.identity);
}

```

alternatively you could put it into the update function using the input class:

```
void Update ()
{
    if (Input.GetKeyDown (KeyCode.Space))
    {
        Instantiate(shootingBullets, transform.position, Quaternion.identity);
    }
    else if(Input.touches[0].deltaPosition.y < 0.01f){
        //if the first touch on the screen is moving down start shooting
        Instantiate(shootingBullets, transform.position, Quaternion.identity);
    }
}

```

With the that last bit of code I'm assuming that the `OnTouchDown()` is literally when the player is moving there finger down the screen. If it was just touching the screen replace that with:

```
else if(Input.touchCount > 0)
    //if the first touch on the screen is moving down start shooting
    Instantiate(shootingBullets, transform.position, Quaternion.identity);
}

```

I think that solves your problem unless I've misunderstood your question :)

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