# Question
Title: Calling and functions/methods from different Classes in Unity
I am learning some of the basics with Unity and am running into calling/sending code to a different script.

For example, the code below is a basic menu of options. I have a different Scene set up in Unity for each one of the menu options. As you can see from the if/else if statements, depending on which option a user checks, will take them to a different portion of the program.

At this point it will obviously not compile because the 4 methods for each menu option are not referenced anywhere.

Lets say the user selects option 1 which is the StudyScreen() method. Now in the StudyScreen.cs script that I created, how do I link those so when option 1 is selected, it goes to the StudyScreen.cs and runs what I need it to run.

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

public class MainMenu : MonoBehaviour {

public Text menu;

// Use this for initialization
void Start () {
    menu.text = "Main Menu Options\r\n\r\n" +
                "1. Study\r\n" +
                "2. Quiz\r\n" +
                "3. Test\r\n" +
                "4. Exit\r\n";
}

// Update is called once per frame
void Update () {
    if      (Input.GetKeyDown(KeyCode.Alpha1))  {StudyScreen();}
    else if (Input.GetKeyDown(KeyCode.Alpha2))  {QuizScreen();}
    else if (Input.GetKeyDown(KeyCode.Alpha3))  {TestScreen();}
    else if (Input.GetKeyDown(KeyCode.Alpha4))  {ExitScreen();}

    }
}

```

I hope I was able to make it clear as to what I was trying to accomplish. Please let me know if anything is unclear.

Thanks in Advance. Curtis

# Answer
It depends on whether or not you have put your script on a game object. (Monobehavior is for that purpose.) If you have not, create an instance of it the normal way.

```
StudyScreen studyScreen = new StudyScreen();

```

then your update would be:

```
void Update ()
{
    if (Input.GetKeyDown(KeyCode.Alpha1))
    {
        studyScreen.StudyScreen();
    }
    else if (Input.GetKeyDown(KeyCode.Alpha2))
    {
        studyScreen.QuizScreen();
    }
    else if (Input.GetKeyDown(KeyCode.Alpha3))
    {
         studyScreen.TestScreen();
    }
    else if (Input.GetKeyDown(KeyCode.Alpha4))
    {
          studyScreen.ExitScreen();
    }
}

```

If you have, then you can simply find the instance of that script component by utilizing the GetComponent method and assign it to the variable. Your code would be:

```
StudyScreen studyScreen;

void Start()
{
   studyScreen = GetComponent<StudyScreen>();
}

```

The update method would be the same as above.

Now, that being said you should consider using their UI mechanics instead. You can add click events through the Unity UI instead of coding it up. Take a look at the tutorials that they've done:

If you do not yet have a grasp on how components in Unity work, I highly suggest you read on it. It is fundamental to creating games in Unity.
> 2 votes

# Answer
Basicaly, attach both scripts to the same gameobject (to make it simple) and in the MainMenu script just add the following variable

```
StudyScreen sc;

```

then in the `Start()` initialize it as follows

```
sc = GetComponent<StudyScreen>();

```

at this point anywhere in your script you can reference public stuff inside StudyScreen.cs by doing

```
sc.yourMethod();

```

or

```
sc.yourField;

```
> 1 votes

# Answer
Create a public variable and make it's type the name of the class you want to access so then just assign the script with the class to your variable in hierarchy and after that you can access the variables and functions in the class. Hope that helps.
> 0 votes

---
Tags: unity, c#, scripting, numerical-methods
---


# Question
Title: Unity 3D, Making contiguous looking worlds
Im currently involved in making a third person cooperative mobile game in Unity and in said game there will be an area for players to walk around in with various elevations and whatnot throughout the field. Its designed to be set up with 4 biomes in the area to go along with the games theme but I was wondering what would be the best way to mask the "boundaries" or "cut off points" in this area? From certain vantage points its pretty obvious that the terrain used to make the world simply stops and I was wondering if anyone knew any tips and insights on how to best mask these boundaries without too much "padding" in the game area in order to keep it relatively less taxing on a mobile device. Thank you in advance.

# Answer
You need to blend in natural looking borders. Different biomes need different types.

**Forest**

* Rock walls that are obviously to high to climb
* Cliffs you cannot possibly climb down. You could make the player fall and kill himself here.
* Rivers
* Fences for animals or private property

**Urban**

* buildings
* blocked roads (concrete blocks and those signs)
* fences or brick walls
* crashed vehicles

You need to model a bit beyond the border and perhaps block view above the camera height so you can have a skybox around your world that will be shown.

-edit-

Changing biomes is a whole different thing and very much depends on your needs. Minecraft for examle switches from biome to biome from one tile to the next. If you want a gradual switch in biomes you have to blend things along the border.

You need to create a mask along the border. I mask is a black/white image that can hold two textures. One is shown on pure black, the other on pure white. With grey levels you can mix the two textures. Obviously you should also blend in the objects like a view forest tree's expand outward to a savanna and you can spot some yellow grass in the front tree line. To get it perfectly has much more to do with design skill and observing the real world then making games.
> 1 votes

# Answer
There is two techniques for hiding the boundaries between disparate terrains.

1. Blend over some distance. This is usually the best looking but requires that you have tiles that can be blended. This works well for grass, dirt and water terrain textures, for examples.
2. A simpler approach is to use decorations/fringes to hide the seams at the boundaries. Similar to how the wood trim around your door hides the ugly gap between the door frame and the drywall. Example. at it's most basic, you might use randomly strewn rocks, bushes or trees to cover up the seams and break up any obvious straight lines.

You can also combine both of these approaches to make it even more natural looking.

For world boundaries, a simple solution is to use fog so the player simply can't see anything outside of the bounds.
> 0 votes

---
Tags: unity, world-design
---


title: Why does player still leave map?

text:
# Question
Title: Why does player still leave map?
I'm making a simple HTML5 RPG in pure JavaScript likened after Nox, Diablo or Titan Quest, with the character centered on the screen and the map moving around it.

**TL;DR:** My character, when colliding with the map edge, can still move outside the map in some cases. How do I quell this inconsistency?

**Explanation:** I have simple rectangles for the map, character, and one enemy, and I'm using bounding-box collision detection for them. When the character pushes against the map's edge, it stops moving, but the enemy box moves opposite of my character's trajectory of motion. When the enemy hits the wall, it stops, but the collision detection for my centered character fails and I'm flung into the void.

Here is a screenshot demonstrating this (map=white, character=blue, enemy=red):

Here are some bits of relevant code that might help:

Box object:

```
function Box() {
    this.x = 0;
    this.y = 0;
    this.width  = 50;
    this.height = 50;

    this.init = function(x, y, w, h, c) {
        ...
    };

    this.move = function(dir, amt, reverse) {
        ...
    };

    // stops 'obj' from leaving 'this'
    this.constrain = function(obj) {
        if(this.x > obj.x) {
            this.x = obj.x;}
        if(this.y > obj.y) {
            this.y = obj.y;}
        if(this.x + this.width  < obj.x + obj.width) {
            this.x = obj.x + obj.width  - this.width;}
        if(this.y + this.height < obj.y + obj.height) {
            this.y = obj.y + obj.height - this.height;}
    };
    this.draw = function() {...};
}

```

Main code:

```
var m = new Box();
var p = new Box();
var e = new Box();

function rand(a, b) {return ((Math.random()* (b - a)) + a);}

// monster moves away from player on player collision with map.
// player moves off map on monster collision with map.
function init() {
    p.init(cn.width/2 - p.width/2, cn.height/2 - p.height/2, 20, 20, "blue");
    m.init(p.x, p.y, 200, 200, "white");
    e.init(rand(m.x, m.x + m.width  - e.width), rand(m.y, m.y + m.height - e.height), 20, 20, "red");
}

function update() {
    if(key.left)  {
        m.move('left',  p.speed, true);
        e.move('left',  p.speed, true);
    }
    ...

    m.constrain(p);
    m.constrain(e);
}

function draw() {
    c.clearRect(0, 0, cn.width, cn.height);
    m.draw();
    p.draw();
    e.draw();
}

```

How would I make both the monster and the character consistently collide with the map?

I'm sorry in advance if the code/post is too long. I spent a good, long while shortening it up. I'll happily edit it, just ask. Thank you! :)

# Answer
Your constrain function seems to be flipped.

You call `m.constrain(p);` which is going to call:

```
// stops 'obj' from leaving 'this' (except that you shouldn't be setting variables of *this*)
this.constrain = function(obj) {
    if(this.x > obj.x) {
        this.x = obj.x;}
    if(this.y > obj.y) {
        this.y = obj.y;}
    if(this.x + this.width  < obj.x + obj.width) {
        this.x = obj.x + obj.width  - this.width;}
    if(this.y + this.height < obj.y + obj.height) {
        this.y = obj.y + obj.height - this.height;}
};

```

But it's not going to stop anything because your assignment operators are setting the map's coordinates instead of your passed object's coordinates

You want:

```
// stops 'obj' from leaving 'this'
this.constrain = function(obj) {
    if(obj.x < this.x) {
        obj.x = this.x;}
    if(obj.y < this.y) {
        obj.y = this.y;}
    if(obj.x + obj.width  > this.x + this.width) {
        obj.x = this.x + this.width  - obj.width;}
    if(obj.y + obj.height > this.y + this.height) {
        obj.y = this.y + this.height - obj.height;}
};

```

You have the right idea, but know that `=` does not set variables on both side
> 1 votes

# Answer
I finally found the solution!

*Draw the enemies with respect to the map's position!*

Just draw the map, and then the entities on top of it a certain distance away from the map's top-left corner. This way, no matter how the map's position changes, the entities will stay put because they're drawn based on where the map is. The player is drawn on top of everything else because the player isn't supposed to move at all.

Honeybunch's answer will not work. Reversing `this` and `obj` in `constrain()` moves the player around instead of stopping the map. The player's position never changes, as I said in my very first sentence in the post.

The problem is not with `constrain()`, but with motion in general. My player may have stopped at the map's edge, but I was still moving the monster around; it hasn't reached the edge yet, so why would it stop? Movement is relative to a point of reference, and this is easily forgotten.

My only point of confusion now is why my player was able to go outside the map at all, but that's inconsequential now.

Here's the code that works:

```
this.getOffsetsFrom = function(obj) {
    return [obj.x + this.x,  obj.y + this.y];
};

this.draw = function(obj) {
    context.fillRect(
        this.getOffsetsFrom(obj)[0],
        this.getOffsetsFrom(obj)[1],
        this.width, this.height
    );
};

```
> 1 votes

---
Tags: collision-detection, javascript, game-mechanics, html5, rpg
---


# Question
Title: Problem disposing content from a screen's content manager
I have a problem with my game. I am using multiple classes for different screens, for exemple: Main Menu is one screen, When playing is another, and so on...

I decided to use multiple ContentManagers, different content for each screen, so the game won't consume very much RAM, and to load the screen's content when the user will navigate on that screen, and unload/dispose the content when user navigates away.

I have created different content managers for each screen that I had to, but for exemple if I navigate from main menu, to the playing screen, then back to the main menu (when the content from playing screen gets disposed), and then back to the playing screen, I get this error:

```
An exception of type 'System.ObjectDisposedException' occurred in MonoGame.Framework.DLL but was not handled in user code

Additional information: Cannot access a disposed object.

```

I googled this problem, and the only answer that I found was not to dispose the Content Manager, but each texture on that screen.

Is this the only way that I can handle this? To dispose each texture from the screen, when user navigates away?

Thanks.

# Answer
> 1 votes
Instead of disposing the contentmanager entirely; do `ContentManager.Unload()` This clears the contentmanager's content, freeing up resources and leaving it ready to load new content when it suits you.

See: https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.content.contentmanager.unload.aspx

I use this method myself in a game where the player can choose from a lot of different characters. The contentmanager loads the required spritesheets and sounds; the rest of the code always points to the same texture variable in the contentmanager. When the game is over, that contentmanager is unloaded, only to load a new set of content when a new gameround starts right after the character selection screen.

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


# Question
Title: glGenArrays - This functionality is not available
Whenever I call `glGenVertexArrays()`, I get the following exception:

> Exception in thread "main" java.lang.IllegalStateException: This functionality is not available. at org.lwjgl.system.Checks.checkFunctionality(Checks.java:36) at org.lwjgl.opengl.GL30.getInstance(GL30.java:651) at org.lwjgl.opengl.GL30.nglGenVertexArrays(GL30.java:3101) at org.lwjgl.opengl.GL30.glGenVertexArrays(GL30.java:3128) at me.package.name.ClassName.methodName(ClassName.java:ANY\_LINE\_NUMBER)

The operating system is OS X Yosemite 10.10.2, Java 7. I think that this problem is OS X specific.

Immediate mode drawing does work.

I am using LWJGL 3.

# Answer
The `glGenVertexArrays()` interface was added to OpenGL core contexts in version 3.0, the same version in which immediate mode rendering was removed from OpenGL (although it had long since been deprecated, 3.0 is where it finally absolutely went away)

So you are correct. If immediate mode drawing works, then you are using an OpenGL context old enough that `glGenVertexArrays()` hasn't yet been added to the standard, and may therefore be unavailable.

Some drivers may provide the old immediate-mode rendering interfaces in a 3.x context via a compatibility context, or may provide 3.0-style interfaces via EXT or ARB extensions on a 2.1 context, but neither of these are guaranteed to be available on any particular hardware/driver/OS. (OSX's OpenGL drivers in particular don't currently provide compatibility contexts or debug contexts. But the OpenGL spec doesn't mandate that anyone has to provide those, so you can't assume that anyone has them on any platform, not just OSX. You could quite possibly run into exactly the same problem on any computer in the world, if their video drivers simply didn't implement support for an OpenGL compatibility profile.)

Really, you want to pick whether you're going to use old-style OpenGL rendering or new-style OpenGL rendering, and stick with that choice for a whole program; not try to mix between immediate-mode fixed-function rendering and modern VBO-and-shader-based rendering.
> 1 votes

---
Tags: opengl, java, lwjgl, macos, exceptions
---


# Question
Title: Procedural generation of stars in the background with given random seed
I want to generate stars (actually a 2d vector) in the background. The player is moving left and right endlessly. When the player moves the stars, which aren't in sight anymore, should be deleted from the ArrayList to keep things small. But when the player turns back in the other direction again, the same star(coordinate) should be there again. But the random generator gets a different number, which is normal. How can I do something like lastInt() like I do with nextInt() ? Or what is the proper way to do something like this? Thank you very much.

# Answer
As Menno Gouw mentioned, you could use a noise function although you can actually use any PRNG. You will need to seed it every frame though, based off some predictable, relative value, such as the player position. If the player only moves horizontally, then this is simple. seed = player.x

I don't suggest a noise algorithm in this case, since the implementation is rudimentary and a noise function is relatively expensive for no real gain.

If the player moves in more than one direction then you will have to construct the seed value by combining the positions on each axis since most PRNG's only accept a single value for the seed. This is not very complicated either but I won't go into detail. If you need to generate a seed from a vector, then you may want to consider using a noise algorithm, though it is still overkill.
> 1 votes

# Answer
at the base of some perlin noise implememntatio there's a perturbation array

```
        private static int[] p = {151,160,137,91,90,15,
 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180};

```

and gradinet array

```
    float[] grad = new float[256];//used pseudo random generation form cooord (x) or (x,y) or (z,y,z) ...
//You must initialize it with float values in 0..1

```

given that we can generate a gradient for a point x,y:

```
  private float pseudoRandomFromPerm(int x, int y)
    {
        return grad[(x + p[y & 255]+Seed) % grad.GetLength(0)];
    }

```

after that perln noise does others (time consuming) thinks like interpolate a position fx , fy starting from x,y , and repeat the operation for a number n of octaves...

What I suggest is , instead of asking for a gradient for x,y ask for n (depending on star density) dx , dy (0..1 values) and set a star in x+dx\*(scale) , y+dy\*(scale)

you can ask , how can get n (0..1) values from X,Y? Add a costant value for each interrogation:

```
grad[(x + p[y & 255] + Seed  + 1) % grad.GetLength(0)]; //dx1
grad[(x + p[y & 255] + Seed  + 2) % grad.GetLength(0)]; //dy1
grad[(x + p[y & 255] + Seed  + 3) % grad.GetLength(0)]; //dx2
...n times

```
> 1 votes

# Answer
You need something like perlin or simplex noise. This will always generate the same noise based on position with a certain seed. Now you can add stars where the noise is a certain level.

Simplex and perlin noise always create the same noise based on location and seed. So if you would create a noise ranging from 0 to 255 you could generate a stars at a certain level of the noise. Both perlin and simplex is very versatile, there are some paremeters you can set and it generates values for you, you can use multiple noises on top of eachother. You will probably need to tweak these settings a lot to get the desired effect you want.

For example minecraft uses it for terrain height. You can use it for brighter and dimmer stars. If the noise of the first iteration is between 0-100 you check the noise of the 2nd iteration and where you get a specific value or two you generate a star. Then you run another noise to see if they are dim or bright.

Using this for each and every pixel of your screen might slow things down a bit but simplex and perlin are fairly fast duje to there simple nature. What you can do is setting up somekind of tile system for these stars, say a 10px by 10px tile system. Then run the noise on those tiles. and place your stars on those tiles. instead of having to check a 1920x1080 field (\>2.000.000 spots) you reduced it to 192x108 (a bit over 20.000).
> 0 votes

---
Tags: java, 2d, game-mechanics, procedural-generation
---


# Question
Title: How to create custom 3D "areas" at runtime
I've been puzzled for a few days trying to solve this problem, so far with no results.

On a map, currently a Terrain, I'd need to have some "areas" which can be controlled by a specific players. **The shape of those areas can arbitrarily change during the course of the game**, such as you add a marker in any point, and the area evolves (like a spline, say) to pass through that point too.

The problem isn't drawing the boundary itself, of course, but having the GameObjects detecting the area they are in.

Currently I have absolutely zero idea on how to make this **exactly**.

---

*I've thought about a nice approximation, which is splitting the terrain in fixed chunks, and having the player control them "chunk by chunk": every chunk can have its own collider, and that should be easy if not trivial. So the question is how to do it "properly", since I already have this workaround.*

# Answer
> 2 votes
I solved this problem using an hybrid approach, inspired by:

* my original workaround
* @`Felsir`'s post
* @`dnkdrone.vs.drones`'s post

# Solution

I have **Chunks**, which may have an owner or be **contested**.

* *Inside* a contested Chunk, different players have their areas of influence.
* Instead of using a definite polygon/line border, inside the Chunk itself every player may place **Flag**s.
* The Chunk itself is dividend into equally distanced **ChunkPoint**s.
* A ChunkPoint's owner is the nearest Flag's owner.
* Chunk's % ownership is how many ChunkPoints you own.

# Sources

Using a **polygon** approach turned out to be too complex because I had to detect the order of the points, and they could with time take very complex shapes, which wasn't obvious how to handle.

I considered using **voronoi**'s before realising that a ChunkPoint map was much easier and equally good for what I needed to do (but *trying* to use them was the source of inspiration that got me there).

In the **original workaround** idea, Chunks weren't "contested", they were just fully-owned by a single player, and that's why I didn't like them.

# Answer
> 6 votes
I suggest this approach.

Use voronoi 2d subdivision for your space (in the example the central points distr is (pseudo)random, but you can insert your logic)

Then asociate a value to each point that results (in the example image) in different color for each cell

You can play with the number of point and/or distribution to get more defined shapes. For the voronoi diagram property, when you click on the map , the origin point nearest to your click position identifies the voronoi cell you are in.

# Answer
> 4 votes
Create a polygon from the points, do a "is-point-in-polygon" check. So whenever the players add a point that would expand the "area" regenerate the polygon. On the update do a simple position check against that polygon to determine if an object or player is inside the area or not.

---
Tags: unity
---


title: AI for Minesweeper like game

text:
# Question
Title: AI for Minesweeper like game
I am currently developing a Puzzle/RPG game which works a little bit like Minesweeper.
You have a Field of Tiles and 2, 3 or 4 different colors from which you can choose. Now you have to uncover tiles in order to attack the enemy.
Therefore you need to choose the correct color for the tile you want to open. If you try the wrong color, the enemy may try. As long as you open tiles, the enemy may not try (same if it's the enemy's turn).

Now I wrote a really simple AI which works like this:
It iterates over the complete field and looks for all unopened tiles. For each of this unopened tiles, it calculates a score, depending on the tile's neighbours. So an unopened neighbour gives +0, an opened neighbour with a 0 gives +4, an opened neighbour with a 4 gives +4, with 3 gives +3 and so on.
At the end the score is weighted, depending on the fact how many different colours the neighbours have and how many beighbours it actually has (because tiles at the edge have less neighbours).

When it comes to choosing a tile, it works pretty well. Then for the chosen tile it tries every colour, starting with some colour of the neighbouring open tiles. But the ai has no understanding for what the neighbours can tell it. So there is no actual strategy except of: Look for a tile, try colours until it is opened.

I am really new in AI development and find it pretty hard to wrap my head around that topic. The only AI I wrote before was some simple chasing in 2D space shooter.

So my question is: How would a good AI in such a case look?
I thought it would be best to give the AI the same information as the player. So it only knows Tile count and which tiles are opened/closed and the colours of the opened and their neighbour counts. Is this correct or should the AI know everything?
Addtionally, the AI should be beatable.
Can you give me some hints on how this can be/should be/usually is done? Or is there some literature you can recommend for this topic?
(I already looked in an AI for games book I have here and thought I could use minimax but I could not find out how. Also I thought maybe seeing this problem as pathfinding problem would be a solution, but I am not quite sure.)

For better understanding, this is a game which works like what I am building, except this game has no AI and no rela enemy turns (The player just gets hit if he clicks a wrong tile): GameLink

# Answer
Two very general suggestions --

1. Often in board games a good human player runs through a list of rules or if-this-then-that *mentally*. If you can understand what a good human player in your game would do, then it's just a matter of translating that into code. This is generally referred to as "rules-based AI". If the game is strategically simple, then building these rules by hand is not difficult.
2. As for how to make an AI beatable, start with an implementation of the best possible AI. Once you have that, begin to insert "mistakes". Perhaps `x`% of the time, the best move to make is replaced with a randomly chosen non-best move, where `x` can vary according to "difficulty".
> 2 votes

---
Tags: java, ai, jmonkeyengine, puzzle, minesweeper
---


# Question
Title: libGDX sprite image not updating Event Handling InputHandler
I created a separate inputHandler class implementing InputProcessor. I'm using Event Handling (libgdx github page: https://github.com/libgdx/libgdx/wiki/Event-handling)

```
public class inputHandler implements InputProcessor {
    private cheetah cheetah;
    private gameWorld myWorld;
    private float cheetahX;

    private float scaleFactorX;
    private float scaleFactorY;

    public inputHandler(gameWorld myWorld, float scaleFactorX,
            float scaleFactorY) {
        this.myWorld = myWorld;
        cheetah = myWorld.getCheetah();
        cheetahX = cheetah.getX();

        int midPointY = myWorld.getMidPointY();

        this.scaleFactorX = scaleFactorX;
        this.scaleFactorY = scaleFactorY;
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        System.out.println(cheetahX);
        cheetahX += 5;
        System.out.println(cheetahX);
        return true;
    }

```

cheetahX is updating in the console, but not on the screen. When I click on the DesktopLauncher window, the console prints cheetahX + 5 properly, but the image of the cheetah sprite remains still.

gameWorld class:

```
public gameWorld(int midPointY, int gameHeight) {
    currentState = GameState.MENU;
    this.midPointY = midPointY;
    cheetah = new cheetah(33, midPointY - 15, 10, 29);
}

public void update(float delta) {
    runTime += delta;
}

```

gameScreen class:

```
@Override
public void render(float delta) {
    // TODO Auto-generated method stub
    runTime += delta;
    world.update(delta);
    renderer.render(delta, runTime);
}

```

thanks in advance!

# Answer
Are you assigning `cheetahX` to something or drawing with it? You did not post your drawing method or where you use `cheetahX` further on in your code.

I predict that `Cheetah` holds your `InputHandler` then you need this:

```
public class inputHandler implements InputProcessor {
    private cheetah cheetah;
    private gameWorld myWorld;
    private float cheetahX;
    public float getCheetahX() { return cheetahX; } // This line

    private float scaleFactorX;
    private float scaleFactorY;

    public inputHandler(gameWorld myWorld, float scaleFactorX,
            float scaleFactorY) {
        this.myWorld = myWorld;
        cheetah = myWorld.getCheetah();
        cheetahX = cheetah.getX();

        int midPointY = myWorld.getMidPointY();

        this.scaleFactorX = scaleFactorX;
        this.scaleFactorY = scaleFactorY;
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        System.out.println(cheetahX);
        cheetahX += 5;
        System.out.println(cheetahX);
        return true;
    }

```

Now you can access it from cheetah. Somewhere in your update method you should grab it and assign the cheetah position with it.

```
public void update()
{
    position.x = inputHandler.getCheetahX();
    // Or
    batch.draw(cheetahTexture, inputHandler.getCheetahX(), position.y, ...);
}

```

I do not know how you draw or how you would like to use that variable so unless you supply all of your relevant code I cannot help you further.
> 1 votes

---
Tags: libgdx, sprites, input, eclipse
---


title: Creating chess like game AI

text:
# Question
Title: Creating chess like game AI
I want to create a AI for chess like game.

Could anyone point me to sources of information what should I know before implementing anything like that.

Some details about the game. There are 5 figures that can make moves and each of them can make a move based on cards that player own. After taking a move card is discarded and player must take another from the deck. Game is won after "king" is taken from the board or king's square is occupied by opposing king.

Any guidance is appreciated :)

# Answer
> 0 votes
**ORIGINAL ANSWER**

Here is the start of series of articles that explains making a chess game. It covers how to model the board in your code, and how to tell what the computer what moves moves are possible / viable. Its a bit older, and doesn't provide any code, but it will at least give you a strong start on making a CHESS-LIKE game.

This is an example of a simple chess game made in java for reference

**REVISED** What I think would be best would be to rework the chessmate project linked above. First remove the context of piece rank(take out pawns, queens, etc), and then then add them to individual pieces base on something like `Player.LastPlayedCard();`

---
Tags: ai, strategy, turn-based-strategy
---


title: Sprites not showing (C# - XNA 4.0)

text:
# Question
Title: Sprites not showing (C# - XNA 4.0)
I'm following a tutorial from XNA GPA, but in my project, none of the sprites are loading. I've followed all of the instructions exactly, and the code works as expected when I copy it from my project into the example project that he provides.

Here's my Game.cs

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Tutorial
{

    public class Game : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Paddle paddle;
        Rectangle screenRectangle;

        public Game()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            screenRectangle = new Rectangle(0, 0, graphics.PreferredBackBufferWidth,
                                            graphics.PreferredBackBufferHeight);
        }

        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            Texture2D tempTexture = Content.Load<Texture2D>("paddle");
            paddle = new Paddle(tempTexture, screenRectangle);
            // TODO: use this.Content to load your game content here
        }

        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here

            paddle.Update();

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here

            spriteBatch.Begin();
            paddle.Draw(spriteBatch);
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

```

Any help would be greatly appreciated, thank you.

# Answer
A possible problem is in your SetInStartPosition(). For setting the Y position it should be position.Y = screenBounds.**Height** \- texture.**Height**... not screenBounds.**Width** \- texture.**Width**...
> 2 votes

---
Tags: xna, c#, textures, sprites
---


# Question
Title: Libgdx inputlistener scrolled is not working
I am currently using libgdx. Below codes are added to a stage.

```
this.addListener(new InputListener() {
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("down");
            return true;
        }

        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("up");
        }
        public void touchDragged(InputEvent event, float x, float y , int pointer) {
            System.out.println("dragged");
            zoom(0.01f);
        }
        public boolean scrolled(InputEvent event,
                    float x,
                    float y,
                    int amount) {
            System.out.println("scrolled");
            zoom(0.01f);
            return true;
        }

```

everything is working just fine (touchUp touchDragged Touchdown) except scrolled. Can someone tell me what is the reason?

-edited for reply comment and answer- On screen class outside stage, I think I already added like screen.set input processor(stage). So touch dragged is working properly and print message 'dragged' and zoom is working. But when I scroll, message 'scrolled' is not printed and zoom function is not called I think. Thank you for comment and answer

# Answer
The reason why scrolled is not working is...

To activate scrolled in Scene2d, we need this one line

stage.setScrollfocus(actor);
> 2 votes

# Answer
You need to create an InputProcessor (or an InputMultiplexer) and register this with the LibGdx backend.

You then add your InputListener & Stage to this InputProcessor.

This is a typical use of the function:

```
Gdx.input.setInputProcessor(inputProcessor);

```

Read this page for more information https://github.com/libgdx/libgdx/wiki/Event-handling
> 0 votes

---
Tags: libgdx, scene2d
---


title: MMO - Boss Action Distribution

text:
# Question
Title: MMO - Boss Action Distribution
I was considering how MMO mechanics work and especially how NPC/mob decisions are calculated and distributed among players. Say for example that you have a team of 5 fighting a boss. The boss's actions/powers etc are hardcoded into the game code, but its decision making is based upon some probabilities, are those calculated server side and then distributed to all the players? For example, when it is going to use a specific "spell" or who it is even targeting.

1)If all these are calculated server side, is the boss considered as a single entity that acts based on input from other players or is it more event based?

If that is the case then how do people deal with latency? I mean the server has to emit the action of 5 characters to the other 4 + Boss and also then calculate what the boss is going to do?

2)Is one of the player's game engine "assigned" the control of the Boss's actions and when all the actions from the other players are broadcasted then the "choose" game engine calculates and distributes not only the players actions but also the boss's.

If that is the case then won't 1 player always be in favour due to latency being zero?

Thank you

# Answer
> Say for example that you have a team of 5 fighting a boss. The boss's actions/powers etc are hardcoded into the game code, but its decision making is based upon some probabilities, are those calculated server side and then distributed to all the players? For example, when it is going to use a specific "spell" or who it is even targeting.

Sure it is. The Server is the decision-maker, the client is the one to nicely "show" the decisions the server made by drawing graphics.

> 1)If all these are calculated server side, is the boss considered as a single entity that acts based on input from other players or is it more event based?

More or less. It does not *have to* act to input from players. Since it is a entity, things like *take damage* and so on are already working out of the box. It might do something special if someone casts *spell xyz* or it just has a set of possible actions and chooses one at random every once in a while. This depends on how you'd *like* the boss to act and react.

> If that is the case then how do people deal with latency? I mean the server has to emit the action of 5 characters to the other 4 + Boss and also then calculate what the boss is going to do?

The server does not really *emit the action to the boss* the same way as it is emitting this event to the other players, since the boss itself is serverside, so no networking between server\<-\>boss involved. But yes, it works like this. But this *emitting the action* is not only done while boss-fighting, it is done *everytime* and *everywhere* when more than one player is in the same area, since all other players want to see what this one player does, everything. Walking, jumping, casting, .... And they want to see what other NPC-Characters do, so 4 players and one entity is really not much.

> 2)Is one of the player's game engine "assigned" the control of the Boss's actions and when all the actions from the other players are broadcasted then the "choose" game engine calculates and distributes not only the players actions but also the boss's.

No, control has the server. You could say, server itself plays the role of a client for its NPC's but the input doesn't come from a keyboard and a mouse, but from AI-Scripts, Waypoints, and so on. Your Client will **only** be controlling your own character, other clients control their characters and **everything** else is controlled by the server.

---

One more word about #1:

If you're concerned about latency, don't be. Really, 4 characters spamming spells plus one boss is really so little, thats not even worth thinking about. Lets say your packet `x casts y` is 20 bytes and your cast takes half a second, thats 2 casts per second, per player plus the boss, so 10 casts per second so 200 incoming bytes for the clients and 800 bytes outgoing for the server per second. And if your server somehow *batches* state-updates, you could get away with far far less.
> 1 votes

---
Tags: game-mechanics, mmo, client-server, distribution
---


# Question
Title: How can I avoid a delay with continues touch detection in swift?
I want control a character on my screen with a continuous swipe gesture. As soon as I do a swipe `+x` or `-x` my character moves left or right. And as long as I hold my finger it continuous to move to the direction in that I swiped. When I swipe into the opposite direction of my last swipe without leaving my finger from the touch ground, my character should move into this direction. When I release my finger from the touch screen, my character should stops instantly.

**My problem is that there is often a small delay within the change of direction. And this delay makes it less precise.**

```
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    /* Called when a touch begins */
    var player = self.childNodeWithName("man")

    for touch in (touches as! Set<UITouch>) {
        let location = touch.locationInNode(self)
        let touchedNode = self.nodeAtPoint(location)

        lastFingerPosition = location

    }
}

override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent){
    var player = self.childNodeWithName("man")

    for touch in (touches as! Set<UITouch>) {
        let location = touch.locationInNode(self)
        let touchedNode = self.nodeAtPoint(location)

        if(location.x > lastFingerPosition?.x && lastMoveDirection != "right"){
            movePlayer("right")
        } else if(location.x < lastFingerPosition?.x && lastMoveDirection != "left"){
            movePlayer("left")
        }
    }
}

//@Todo: Wenn man touchMoved und nicht über dem Button hoch geht, wird die Action nicht aufgehoben
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
    var player = self.childNodeWithName("man")

    for touch in (touches as! Set<UITouch>) {
        let location = touch.locationInNode(self)
        let touchedNode = self.nodeAtPoint(location)

        player?.removeAllActions()
        lastMoveDirection = ""
    }
}

func movePlayer(direction: String) {
    var player = self.childNodeWithName("man")

    if(lastMoveDirection != direction){
        player?.removeAllActions()
        lastMoveDirection = direction

        var duration:CGFloat? = 0
        var x = player?.position.x
        duration = x!

        if(direction == "left"){
            var xDestination:CGFloat = 10
            var run = SKAction.moveToX(10, duration: NSTimeInterval(Double(duration! / runSpeed)))
            player?.runAction(run, withKey: "moveLeft")
        } else if(direction == "right") {
            duration = self.frame.width - x!
            var xDestination = frame.size.width - 1
            var run = SKAction.moveToX(xDestination, duration: NSTimeInterval(Double(duration! / runSpeed)))
            player?.runAction(run, withKey: "moveRight")
        }
    }
}

```

# Answer
I think it is not a programmatic problem. It is more an issue of the control itself. Because a `swipe` with your finger into one direction and then, a swipe to the opposite direction results in a rotation of your thumb.

And while it's rotating a little bit, it is not moving and that causes the feeling of a delay.

I guess this control is useless, if you need really precise moves - just because of the anatomy of our thumbs.
> 1 votes

---
Tags: ios, touch, control, swift
---


# Question
Title: Nvidia Nsight 4.6 VS Edition. The Graphics debugger can't find glew32.dll
I'm trying to debug some textures and FBO's with Nvidia Nsight 4.6 VS Edition. But when I select either "Start CUDA debugging" or "Start graphics debugging" I get an error.

"The program can't start because glew32.dll is missing for your computer. Try reinstalling theprogram to fix this problem"

The application runs just fine when I'm not using Nsight. What might be my problem?

My system; Windows 7 x64 bit. Nsight 4.6 x64 bit. GTX 580 with lastest drivers. OpenGL version 3.3. Building a Win32 application. (Tried to change the build target to x64 but that just resulted in a bunch of linking errors for glfw and glew)

# Answer
> 1 votes
Okey I found the problem. I had placed my glew32.dll file in a separate folder and set the environmental path to that location. e.g: Properties \> Configuration Properties \> Debugging \> Environment = PATH=$(ProjectDir)..\dependencies\bin;%PATH%

Apparently Nsight didn't realize this and thus couldn't find the dll.

---
Tags: opengl, nvidia, cuda, glew
---


title: android canvas rope swing

text:
# Question
Title: android canvas rope swing
I'm creating the code, where a player swinging on a rope

for the moment I got this

```
double angle = Math.atan2(player_y - center_y, player_x - center_x) - Math.atan2(end_y - center_y, end_x - center_x);
if (direction == 'right') {
    player_x += 10;
    player_y += 10 * angle;
} else {
    player_x -= 10;
    player_y -= 10 * angle;
}

```

I know that I have to add gravity, speed, etc... but I'm not very good in physics. The question is How do I make rope swinging more realistic?

I don't use any engines or frameworks, only native canvas.

**EDIT**

Tried this code.

```
onStart...
angle0 = Math.atan2(player_y - center_y, player_x - center_x) - Math.atan2(end_y - center_y, end_x - center_x);
length = Math.hypot(center_x - player_x, center_y - player_y);
swing_start = System.currentTimeMillis();
T = 2 * Math.PI * Math.sqrt(length / 9.8f);

onDraw...
elapsed_time = (System.currentTimeMillis() - swing_start) / 1000;

#with this player makes a very slow circle with the wrong pivot point
player_x += Math.sin((2 * Math.PI / T) * elapsed_time);
player_y += Math.cos((2 * Math.PI / T) * elapsed_time);

#with this it makes backwards circle
double angle = angle0 * Math.cos((2 * Math.PI / T) * elapsed_time);
player_x += Math.sin(angle)
player_y += Math.cos(angle);

```

Where am I wrong?

onDraw called every 25ms

Log... start - 15:31:22.411

```
﹕ T: 39.83959786319781 angle: 1.1898202456306484
+15 the same
﹕ T: 39.83959786319781 angle: 1.175053634797472
+18
﹕ T: 39.83959786319781 angle: 1.13112033295045
+18
﹕ T: 39.83959786319781 angle: 1.059110834176187
+17
﹕ T: 39.83959786319781 angle: 0.9608125282061935
+17
﹕ T: 39.83959786319781 angle: 0.9608125282061935
+17
﹕ T: 39.83959786319781 angle: 0.6957011399544965
+17

```

end - 15:31:29.361

# Answer
You can use pendulum physic to approximate your rope swing.

Calculate the fluctuation period (this is true for small fluctuations)

```
T = 2*PI*SQRT(L/g)

```

where:

```
PI = 3.14

```

`g = 9.8` (if I remember) the earth gravity acceleration `L` : the rope length, or better the length from rotation fulcrum to the character hands.

Then you get the fluctuation angle as function of time t as :

```
angle(t) = angle0 * COS((2*PI/T)*t)

```

where `angle0` is the starting amptitude
> 2 votes

---
Tags: java, android, html-canvas
---


# Question
Title: Set the name of an animation in collada to be used by AssImp
I am using the collada file format to contain my model and animation but when I use AssImp to load the file the name will be empty for the animation. Where is the name for animation set on the collada file format? The documentation seems to have pointed me to library\_animations but I tried setting "name" and "id", but both did not end up setting the animation name.

To get the animation name I am simply doing

```
        aiAnimation* animation = mAIScene->mAnimations[i];
        auto test = animation->mName;

```

# Answer
> 1 votes
The problem is probably the exporter. According to official docs:

> **aiString aiAnimation::mName**
>
> The name of the animation.
>
> If the modeling package this data was exported from does support only a single animation channel, this name is usually empty (length is zero).

Try to find one which *does* support multiple animations channel.

---
Tags: c++, assets, assimp, collada
---


# Question
Title: How can I handle invulnerability in an entity system?
I currently have an entity component system with messaging. The messages are delivered to each subscriber, but each subscriber gets their own copy, basically meaning that altering a message doesn't affect any other subscriber. While this works fine for now, I was wondering how I would add an invulnerable state.

I have a combat system that solves combat. It takes a combat event (an intent to attack something) and emits a resolved combat event. This event contains information of who attacked whom and what kind of damage they took. It also has a bool which gives the status of whether or not the defending entity is alive after the attack. It also controls the the HP and deletes the entity if it was killed.

I do not have a problem breaking down this system. A system that calculates damage, a system that applies the damage, and a system that kills the entity. But where do I add my invulnerability? If I simply make it a component, then it has to be handled by the system that applies damage. What if I want to add something else later? I have to build up and up the damage system and it has to handle all the little edge cases and intricacies. What if I want to add an attack that goes through invulnerability?

Clearly this is an exponential nightmare, which is exactly what I hoped to avoid with an ECS. How should I handle invulnerability?

# Answer
ECS doesn't make miracles and not all the problems should be solved by it. In some point you will need especific code about the specific logic of your game.

You can put an "Invulnerable" flag inside your health component and a flag "PenetrateInvulnerability" inside the atack message and your system combat manage then.
> 1 votes

---
Tags: architecture, entity-system, component-based, design-patterns
---


# Question
Title: Curvilinear distortion for mapping texture on quad sphere
I'm using the formula I've found here to map procedural texture on to a quad sphere.

For example I'm working with a 3d panoramic cube map that I've generated with a simplex noise.

Each face of the cube will be seamless. That's not the point.

My problem is that the corners of each face will have the typical distortion after mapping it onto the quad sphere.

Therefore I want to "manipulate" or prepare the texture ( in this case, the heightmap ) of each face individually with a curvilinear pincushion distortion.

1. Am I assuming right that the curvilinear pincushion distortion will compensate the distortion effect on the quad sphere ?
2. Can someone point me to a formula of the curvilinear distortion or the corresponding calculation of the formula I've linked ?

**A**: original texture. **B**: what my texture should look like after preparing.

*note that B is only a sketch !*

# Answer
> 2 votes
1. No, Pincushion distortion is not actually the inverse of Barrel distortion. (Proof below)
2. This paper seems to be shooting for exactly what you want: A Real-time FPGA Implementation of a Barrel Distortion Correction Algorithm with Bilinear Interpolation (by Gribbon, Johnston, & Bailey) (Formulas inside)

> **2 Algorithms**
>
> Barrel distortion occurs when the magnification of the lens decreases with axial distance causing each image point to move radially towards the centre of the image. This results in the characteristic “barrel” shape. The barrel distortion model \[2\] is:
>
> \\$r\_u=r\_d(1+kr^2\_d)\\$ (1)
>
> where \\$r\_u\\$ and \\$r\_d\\$ are the distance from the centre of distortion in the undistorted and distorted images respectively, as shown in Figure 1, and \\$k\\$ is the distortion parameter, which is specific to the lens.
>
> Figure 1: Illustration of barrel distortion model

Proof as promised: By contradiction for simplicity.

Extracting the relevant fact about Barrel (and/or Pincushion) distortion:

(2): \\$R\_{skew}=f\_k(R\_{flat})\\$

We construct an equation we can solve for our correction constant "j" in terms of the distortion constant "k":

(3): \\$R\_{flat} = f\_j(f\_k(R\_{flat}))\\$

(4): \\$R\_{{flat}}=R\_{{flat}}(R\_{{flat}}^2k+1) R\_{{flat}}^2j(R\_{{flat}}^2k+1)^2+1)\\$

Which we can then re-arrange to isolate "j":

(5): \\$j=\frac{-k}{R\_{{flat}}^6 k^3+3 R\_{{flat}}^4 k^2+3 R\_{{flat}}^2 k+1}\\$

Which depends on the independent variable, and thus is not a constant. Therefore a Pincushion or Barrel distortion does not compensate its complement distortion.

---
Tags: mathematics, textures, procedural-generation, uv-mapping
---


title: UDK - changing game type problem

text:
# Question
Title: UDK - changing game type problem
I have made a small game for testing purposes and a packaged the game, and ran my game but when I run it, it runs with the UTdeathmatch type game. and I made my `DefaultGame` to `DefaultGame=UDKBase.SimpleGame` but still I have a gun in my hand doesn't work How do i fix that?

# Answer
> 1 votes
Which map are you running? The map can also specify which game type to use on it. Look at View-\>WorldProperties-\>Default Game Type. I think there's also a game type for Play In Editor mode.

The game type can also be overridden via command-line ("?game=").

Finally, after the engine determines which GameInfo to load, it calls `SetGameType()` on that GameInfo. This gives you the option of overriding your own game type based on map name, command-line options, etc. (see `UTGame::SetGameType()`) The default functionality is for the GameInfo to just return its own class, so this feature is entirely optional.

---
Tags: udk
---


title: Scene2D: How to use Image.setDrawable()

text:
# Question
Title: Scene2D: How to use Image.setDrawable()
I'm trying to change the texture of an Image actor on my Scene2D stage, however I can't seem to get it working. It seems like setDrawable() doesn't really do anything.

For example, this will make the texture of the Image cookie.png:

```
Image itemImage = new Image(new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("cookie.png")))));
itemImage.setPosition(10, 10);
getStage().addActor(itemImage);

```

However, this will not:

```
Image itemImage = new Image();
itemImage.setPosition(10, 10);
itemImage.setDrawable(new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("cookie.png")))));
getStage().addActor(itemImage);

```

Am I missing something?

# Answer
> 6 votes
In the second case it is not drawing because the constructor with no arguments doesn't set a width and height for the image, however the constructor that takes the drawable obtains the values from it.

To fix in your case:

```
Texture texture = new Texture(Gdx.files.internal("cookie.png"));
Image itemImage = new Image();
itemImage.setPosition(10, 10);
itemImage.setDrawable(new TextureRegionDrawable(new TextureRegion(texture)));
itemImage.setSize(texture.getWidth(), texture.getHeight());
getStage().addActor(itemImage);

```

Also I'd save the textures as a field to later dispose of them (or you could obtain the drawable from the Image parse it to Texture and dispose it).

---
Tags: java, libgdx, scene2d
---


title: How do I store game data with cookies?

text:
# Question
Title: How do I store game data with cookies?
Im working on a game right now, but I was wondering how I would store the game data in cookies(in javascript) where you can load it up, and resume the last spot you were at. I was looking at some other websites like w3schools, but I didn't really understand it

# Answer
> 3 votes
You don't use cookies. Take a look at localstorage. It is intended for storing small bits if data, that is too big for a cookie. Here is more info: http://www.html5rocks.com/en/tutorials/offline/storage/

---
Tags: javascript, data, html
---


# Question
Title: How to handle (0,0) in 2D game quad tree?
I am not sure how to handle situation when out objects (player) is in center (0,0) point of game which is crossing of four quads. How to handle that case? This image shows problem:

Red rectangle is player BoundingBox, he is at center, he not fully contain in any quad but he partially belongs to four quads, so we should get content of those 4 green quads or whole pranet quad?

# Answer
> 2 votes
In this case you have to decide what to do. In most cases, this is done automatically for you because your sorting is based upon `<=`, `>=`, `<` or `>` where you definitely get an answer, either true or false, so it really depends which type of comparison you use.

For example

```
if(x < middle_of_this_quad)
    add_to_left_subtree
else
    add_to_right_subtree

```

This comparison already decided that everything smaller than `middle_of_this_quad`, 0 in this case, will go left and everything else, **including 0** will go right.

---

Apart from that, it is **highly** unlikely that you'll ever hit exactly 0.0 with floating-point arithmetic, unless you set it yourself, of course.

# Answer
> 0 votes
Not sure if this will help (I'm a very old hand at coding, but brand new at helping others with it \<.\<) but here goes.

I had a similar issue with inserting/retrieving 'uniquified' (?) mesh vertices in my engine, where the vertices must be capable of deforming slightly from their 'origin' yet still be considered to be 'owned' by a particular bounding box even if it deforms outside of it. In the simplest terms, I solved it by tracking the position in a multi-level cache; in your case, that may be as simple as flagging the entity as being in all boxes that bound it (the base children only, and/or all touching parent nodes), then flagging it again (or unflagging it as the case may be) when it has been retrieved from *any* of those boxes.

I'm happy to provide the (abridged) code from my engine showing how I did it if you need a more concrete example.

---
Tags: optimization, quadtree
---


# Question
Title: How to rotate a whole rectangle by an arbitrary angle around the origin using a transformation matrix?
Suppose, I have a rectangle ABCD. Where, A(0,0), B(7,0), C(7,5) and D(0,5).

I want to rotate the whole rectangle by theta = 50°.

I know that, a rotation transformation matrix can be used to do that.

So, I have done the following:

A' = `[0 0 1]` ; B' = `[7 0 1]` ;

C' = `[7 5 1]` ; D' = `[0 5 1]` ;

But the output has become skewed:

**What should be the correct calculation?**

# Answer
> 1 votes
I have solved the problem.

```
//Roation around the Origin
//Individual matrices

#include "graphics.h"
#include "Vector2d.h"
#include "Coordinates2d.h"
#include "Polygon2d.h"
#include <math.h>
#include <iostream>

#define PI 3.141
#define DEG 45.00f
#define RAD 6.283185308 / (360.0 / DEG)

int main()
{
    ////////////////////////////////////////
    Coordinates2d::ShowWindow("Roation around the origin(individual matrices)");
    ////////////////////////////////////////

    Matrix a(1,3);
    a.SetItem(0,0,0);   a.SetItem(0,1,0);   a.SetItem(0,2,0);
    a.Show();

    Matrix b(1,3);
    b.SetItem(0,0,140); b.SetItem(0,1,0);   b.SetItem(0,2,0);
    b.Show();

    Matrix c(1,3);
    c.SetItem(0,0,140); c.SetItem(0,1,100); c.SetItem(0,2,0);
    c.Show();

    Matrix d(1,3);
    d.SetItem(0,0,0);   d.SetItem(0,1,100); d.SetItem(0,2,0);
    d.Show();

    Matrix rot(3,3);
    rot.SetItem(0,0,cos(RAD));  rot.SetItem(0,1,sin(RAD));  rot.SetItem(0,2,0);
    rot.SetItem(1,0,-sin(RAD)); rot.SetItem(1,1,cos(RAD));  rot.SetItem(1,2,0);
    rot.SetItem(2,0,0);         rot.SetItem(2,1,0);         rot.SetItem(2,2,1);
    rot.Show();

    Matrix ma;
    ma = a.Multiply(rot);
    ma.Show();

    Matrix mb;
    mb = b.Multiply(rot);
    mb.Show();

    Matrix mc;
    mc = c.Multiply(rot);
    mc.Show();

    Matrix md;
    md = d.Multiply(rot);
    md.Show();

    Polygon2d poly;
    poly.Add(0, 0);
    poly.Add(140, 0);
    poly.Add(140, 100);
    poly.Add(0, 100);
    Coordinates2d::Draw(poly, Yellow);

    Polygon2d poly2;
    poly2.Add(ma.GetItem(0,0), ma.GetItem(0,1));
    poly2.Add(mb.GetItem(0,0), mb.GetItem(0,1));
    poly2.Add(mc.GetItem(0,0), mc.GetItem(0,1));
    poly2.Add(md.GetItem(0,0), md.GetItem(0,1));

    Coordinates2d::Draw(poly2, LightGreen);
    ////////////////////////////////////////
    Coordinates2d::Wait();
    ////////////////////////////////////////
}

```

# Answer
> 0 votes
Exerpt from the 3D CSG module I wrote for my engine. You should be able to derive from this easily enough.

```
SOLID_C *Rotate(const V3 &axis,const T angle)
{
    T a=radians(angle),c=cos(a),s=sin(a);
    V3 rt[3],m[3],mt[3],ax=((V3)axis).normalise(),t=ax*(1.-c);
    rt[0][0]=c+t[0]*ax[0]; rt[0][1]=0+t[0]*ax[1]+s*ax[2]; rt[0][2]=0+t[0]*ax[2]-s*ax[1];
    rt[1][0]=0+t[1]*ax[0]-s*ax[2]; rt[1][1]=c+t[1]*ax[1]; rt[1][2]=0+t[1]*ax[2]+s*ax[0];
    rt[2][0]=0+t[2]*ax[0]+s*ax[1]; rt[2][1]=0+t[2]*ax[1]-s*ax[0]; rt[2][2]=c+t[2]*ax[2];
    m[0].set(1,0,0); m[1].set(0,1,0); m[2].set(0,0,1);
    mt[0]=m[0]*rt[0][0]+m[1]*rt[0][1]+m[2]*rt[0][2]; mt[1]=m[0]*rt[1][0]+m[1]*rt[1][1]+m[2]*rt[1][2]; mt[2]=m[0]*rt[2][0]+m[1]*rt[2][1]+m[2]*rt[2][2];
    M3 mat(mt[0],mt[1],mt[2]);
    return Apply(mat);
}

SOLID_C *Apply(const M3 &mat)
{
    FACE *f; V3 t; UINT i=(UINT)vl.size(); while (i--) t=vl[i],vl[i]=mat*t;
    i=(UINT)fl.size(); while (i--) f=fl[i],t=f->nrm,f->nrm=mat*t,f->dist=f->nrm.dot(vl[f->vl[0]]);
    return this;
}

```

# Answer
> -2 votes
Most of trigonometric functions take radians as input, this may be your issue.

So your theta should be

```
float theta = angleInDegrees*PI/180

```

---
Tags: rotation
---


# Question
Title: 3D space indexing for nearest neighbor searching
I am developing a CAD-like application where the user can draw (digitize) new geometries (points, polylines & polygons). While digitizing, I want the user to be able to (optionally) snap the points of the new shape onto points or lines of existing geometries. I have already written the snapping algorithm that computes a ray from the mouse position and finds a line segment between the ray and the closest geometry (point or line segment). My scene is totally static but may contain too many shapes, which makes brute force searching inefficient.

What would be a good way to index the existing geometries so that I could quickly filter most of them out and consider a smaller set (the ones roughly within distance X) in my snapping algorithm?

I was thinking of doing something similar to what OpenGL (I am using DirectX 9 in my app) provides with the GL\_SELECT option, i.e. render my geometries on a bitmap, each one coded with a different color. However I am a bit worried since I will have to use a second device with a hidden window to achieve this.

Is there a 3D space partitioning data structure that I can use, which can efficiently compute the nearest neighbour to a ray?

# Answer
Try taking a look at KD trees; I use them in my engine for (amongst other things) preparing scenes for raytracing, and they are quite good at nearest neighbour searches for fairly large data sets (especially in conjunction with other structures like octrees if your dataset is massive). 'TinyRT' is a decent header libary which could get you started.
> 1 votes

---
Tags: directx9, space-partitioning
---


# Question
Title: How to detect a collision between a isosceles trapezoid and a circle
I figured one approach would be to divide the trapezoid in three parts, two triangles and a rectangle in the middle.

Then for the circle-rectangle case I would check collision like this:

```
function testCircleRectCollision(circle, rect) {
    closestX = clamp(circle.x, rect.left, rect.right)
    closestY = clamp(circle.y, rect.top, rect.bottom)

    distanceX = circle.x - closestX
    distanceY = circle.y - closestY

    return pow(distanceX, 2) + pow(distanceY, 2) < pow(circle.radius, 2)
}

```

For the circle-trangle case, I could only think of checking if the vertices of the triangle are inside the circle like this:

```
function vertexInCircle(circle, v) {
    return pow(v.x - circle.x, 2) + pow(v.y - circle.y, 2) < pow(circle.radius, 2)
}

```

But I still need to check two cases: 1) if the circle is completely inside the rectangle and 2) if the circle is intersecting with any of the triangle's edges. How can I do this?

Or is there a better way to check for circle-trapezoid collision?

# Answer
> 2 votes
I'd go with splitting it into two triangles by connecting two opposite points and using two triangle-circle intersection tests.

Those tests needs to cover three cases:

1. A vertex of the triangle is inside the circle.
2. The circle is contained within the triangle.
3. An edge of the triangle intersects the circle.

The first part is easy - just calculate distances from the corners of the triangle to centre of the circle and compare to the radius.

For the second and third cases you need to test for intersections between the triangle edge lines and the circle, as well as working out which side of each line the circle is on.

The main advantage of testing on triangles is that you can reuse the code with any polygonal shape, although the triangulation itself can be complicated if it's not a convex polygon.

---
Tags: collision-detection
---


# Question
Title: Should input be per-frame or per-update?
I'm implementing a GUI system to look around a 2D tile-based world. At the moment, I'm updating it every time the mouse moves (which happens to be per frame, since that's when it polls for events). However, I'm wondering if implementing it per-update (by taking all input events, averaging them out, then deferring them for processing until the next update) would be better. I figure it would make the GUI feel more consistent but at the cost that it may not be as responsive (since I can't interpolate the movement without the controls feeling "sticky"). In terms of creative a better interface, which should I go with? What do games normally go with?

# Answer
What's the context?

For UI, it's very sensible to poll per-frame, especially for cases where the UI and the game simulation have no good reason to be tied together, e.g. highlights when you mouse over a selectable object.

For control of a character or the like inside the game simulation, this advice can be flipped. Consider batching up all inputs for character control and then applying them during the next simulation update. This will be implicit in any physics-driven game, of course, since even if you set an input force at each frame, it won't actually have any effect on the simulation until the physics updates next.

Yet other inputs are "continuous" and don't really fall into the above states. Consider a joystick. You probably don't care at all about the events in yrou game and instead would just care about sampling the direction and magnitude of the stick's offset whenever it's time to try to apply input to the target object.

And then there's even the option of putting input polling and your main loop on separate threads so that you can sample input far more frequently, which can essentially nullify the entire question. This is common for more twitchy games that need to absolutely minimize all input lag.
> 1 votes

# Answer
It depends on what you want to do, whether it's GUI-like or game-like.

Most game situations only care about **where the mouse is right now**, so you go through all the mouse move events and simply act on the last one. This would be **per-frame**. One example is using the mouse to look.

However, there are some GUI-like situations where the **intermediate mouse positions are all important**. Consider drawing freehand curves using the mouse - your player could have fast hands and a high-frequency mouse, compared to your slow frame rate. If you only used the per-frame mouse positions, the output would be very jagged. This would be **per-event** (or what you call "per-update"). It's rare in games, but those using mouse gestures might be a good example.

So unless you have a GUI-like situation where freehand curves are drawn, stick with per-frame, except for press/release events, where:

* you should use the location of the press/release event, instead of the last mouse event, since they can be different
* if you're counting your own presses/releases, count every mouse down / mouse up event, since there could be multiple per frame
> 0 votes

---
Tags: game-design, game-loop, gui, interface
---


title: 2D multiple circle collision response

text:
# Question
Title: 2D multiple circle collision response
I'm trying to implement simple 2D circle collision system. There are circles with different radiuses and velocities (the larger the circle the slower it is). Contrary to all the questions on the Stack, the circles do not bounce at all.

There is no problem with collision response for two circles that overlap. There are two approaches that I thought of:

1. Pushing the circles apart with displacements dependent on the ratio of circles' radiuses.
2. Pushing the smaller circle away so it doesn't collide with the bigger circle anymore.

However, neither of these approaches works for multiple circle collisions. Let's consider an easy example:

Three circles are moving towards the same point but with different velocities:

In the next frame they overlap like this:

Then with either of the two approaches the smallest circle gets pushed away from the biggest one:

And then the right-most circle would push the smallest circle to the right making an infinite collision loop.

Of course, the more circles, the more complicated the collision resolving would be. Additionally, I'm going to add static walls thus making collision system even more complex.

What algorithm can I use to make multiple collisions work? I guess that the desired effect would look like this:

# Answer
> 3 votes
The way that common physics engines work is that they deal with collision responses for each pair of colliding objects independently.

In your case that means when the three circles are overlapping it would try to do something like push the circles apart in each colliding pair by just a little bit.

Since dealing with pairs at a time isn't going to give a global solution in one pass (a resolution to one overlap may make another overlap worse), multiple iterations are done until either there are no overlaps, or the maximum number of iterations has been reached.

For best quality results you move the objects only a very small amount each time, but have a high number of max iterations. For fastest results however, you move the objects more and have a lower number of max iterations.

In your specific case, the objects have penetrated too deeply for a standard collision response "push objects apart" algorithm to give very good quality.

If you can prevent the objects from penetrating each other so deeply, you'll have better results.

One way to do this would be to not let your objects move so quickly.

Another way to do this would be to do multiple smaller movement steps and collision responses per game loop instead of moving the full amount in one go.

A third way could be to do swept shape collision detection to find where exactly an object collides with other objects while moving along its path. In this scenario if implemented as described, you move each object one at a time and check for collision times and make it move only as far as it can and then stop. This ought to work decently in practice but you might see some strange interactions when many objects move relatively long distances each frame.

Basically, objects that move too far in a frame are a source of problems in many types of physics algorithms, including yours, causing the problems you are trying to overcome (:

# Answer
> 0 votes
I agree with mostly everything Alan Wolfe said except the following :

> Since dealing with pairs at a time isn't going to give a global solution in one pass (a resolution to one overlap may make another overlap worse), multiple iterations are done until either there are no overlaps, or the maximum number of iterations has been reached.

The system I implement only needs to make ~2 iterations through the collision resolver to converge onto a valid solution. There are **two** **significant** **details** which I've picked up on.
The first is to split up your x-direction and y-direction collisions.
The second is to move every object at the same time before resolving the pair-wise collisions.

So here's the flow of my implementation:

1. Collect each objects 'wanted' movement (either through AI or user input)
2. For each object, apply its x-direction movement
3. For each pairwise collision, append the reaction to the two object's lists of 'pushes' (which could be in x & y direction)
4. For each object, sum up its reaction list and apply that movement to its position
5. Repeat steps 2-4 but for the y-direction

You should also put in checks or flags for each object so that you don't recalculate collisions
This process will converge quicker and is more deterministic since it waits until all collisions have been resolved before applying changes

---
Tags: 2d, collision-resolution
---


title: Non linear scaling to show a sol system

text:
# Question
Title: Non linear scaling to show a sol system
In a sol system 2d simulation I have some problems in showing the entire system (ie: eaven planets far away than saturn ) letting distinguibles the nearest planet orbits.

Actualy a use a simple scaling logic like this

```
    double _x = W / 2.0 + ((x ) / maxW) * W;
    double _y = H / 2.0 + ((y ) / maxH) * H;

```

where `x` is real planet x position (assuming sun at origin (0,0)) `y` is real planet y position `W` is canvas width (i.e 512) `H` is canvas height (i.e 512)

`maxW` and `maxH` are the system real border (or the portion I decide to simulate) : in the example I put `maxW = maxH = 20.0 * 149597870700.0;` (20 times the sun earth distance)

What I ask : there's a methot to calculate a (non linear) scaling that let show a bigger portion of the system but keeping some distance between objects near the center ?

EDIT: Here what I get if I enlarge the system borders: `maxW = maxH = 60.0 * 149597870700.0;` (60 times the sun earth distance(UA) )

# Answer
Use a logarithmic scale where `drawnRadius = log(actualRadius)`.

You then end up with a spacing like this which shows all the planets quite neatly separated:

(this representation appears to be using logarithm to base 4)

When you want to apply this to your planetary simulation, you first need to convert the carthesian coordinates (x, y) of each planet to polar coordinates (angle, distance) relative to the center, calculate the logarithm of the distance, convert back to carthesian and draw it.
> 7 votes

---
Tags: c#, simulations, scale, orbit
---


title: OpenGL ES God Ray Precision error

text:
# Question
Title: OpenGL ES God Ray Precision error
I have encountered the following (i think) precision error.

(missing link need 10 rep)

My source of inspiration was:

(missing link need 10 rep)

On the PC everything works fine, but on android it shows those weird squares.

I had the same problem with a procedurally masked sprite. When the radius of the circle was getting too big i had the same error so i changed the mask from a shader radius uniform to a texture mask uniform, so i guess there is a precision problem.

This guy here had the same problem but unfortunately i can't see the answer.

(missing link need 10 rep please someone upvote me.)

The code adapted to OpenGL ES is the following:

```
#version 100

precision mediump float;

uniform sampler2D tex_diff;
uniform vec2 light_on_screen;

varying vec2 texture_coord;

const int NUM_SAMPLES = 128;

void main()
{
    const float exposure = 0.0225;
    const float decay = 0.95;
    const float density = 0.95;
    const float weight = 3.75;

    // Inner used valuesa
    vec2 deltaTextCoord = vec2(texture_coord.st - light_on_screen.xy);
    vec2 textCoo = texture_coord.st;
    deltaTextCoord *= 1.0 / float(NUM_SAMPLES) * density;
    float illuminationDecay = 1.0;

    vec4 c = vec4(0, 0, 0, 0);

    for(int i=0; i < NUM_SAMPLES ; i++)
    {
        textCoo -= deltaTextCoord;

        textCoo.s = clamp(textCoo.s, 0.0, 1.0);
        textCoo.t = clamp(textCoo.t, 0.0, 1.0);

        vec4 sample = texture2D(tex_diff, textCoo);

        sample *= illuminationDecay * weight;

        c += sample;

        illuminationDecay *= decay;
    }

    c *= exposure;

    c.r = clamp(c.r, 0.0, 1.0);
    c.g = clamp(c.g, 0.0, 1.0);
    c.b = clamp(c.b, 0.0, 1.0);
    c.a = clamp(c.a, 0.0, 1.0);

    gl_FragColor = c;
}

```

Showing the whole engine is useless since it's huge. All the shader input is correct, the coordinates are correct, the only problem is the inner shader computation.

Anybody encountered this or has any ideas for any workarounds?

Scanned the whole net for a solution for this, and i couldn't seem to find one. Any can point me in the right direction? Or maybe someone encountered this type of error in a different context or in a different shader? Maybe i can apply the same workaround here too.

# Answer
> 0 votes
Updated with a minor fix:

Yes, the problem was:

```
textCoo -= deltaTextCoord;

```

Due to the fp precision the error accumulated grows to something like 2.7%. Calculating it each loop instead of subtracting a delta fixes a big part of the problem.

As for optimization, I am using some techniques, got a reasonable 40fps.

See this post, I asked the same question here.

For optimizations used see this post about god ray precision error.

---
Tags: opengl, android, glsl, opengl-es, opengl-es2
---


# Question
Title: Tone mapping and eye adaptation - pale colors and darker image
I'm trying to implement tone mapping along with eye adaptation and HDR. Actually I implemented this already but I'm not satisfied with result and I think that I made something wrong.

My final image (before postprocessing) I store in half float texture. I have also 2 helper textures. The first one stores log luminance and avg, min and max color of it in last mip-map. The second one stores adapt value which is computed as:

```
prevLum + (avgLum - prevLum) * (1.0 - exp2(-adaptionRate))

```

where prevLum is previous adapt value (size of this texture is 1x1). Log luminance texture is R8B8G8 format and the second one is R8. In tutorials I saw that half float textures are used but in my case I've got too bright images (almost white).

In the final postprocess shader I'm using all of there values to obtain eye adaptation and tone mapping using this code:

```
float autokey(in float lum) {
    return 1.03 - 2.0 / (2.0 + log10(lum + 1.0));
}

float hejl(in float color) {
    float x = max(0.0, color - 0.004);
    return (x * (A * x + B)) / (x * (A * x + C) + D);
}

float adaptedLum = texture(adaptedLuminance, vec2(0.5)).r;
float exp = exposure * autokey(adaptedLum) / adaptedLum;
result *= exp;

result.xyz=RGB2xyY(result.xyz); // conversion to CIE xyY

result.z = hejl(result.z);

result.xyz=xyY2RGB(result.xyz);

```

And here is my results:

* eye adaptation and tone mapping turned on
* eye adaptation only
* tone mapping only
* everything off

As you can see when tone mapping is turned on bunny color is paler. And when eye adaptation is turned on final image is much darker. Could someone explain me what could cause that, because I think that something here is wrong. Maybe it's something with color spaces which I don't understand well? Or with bloom which is applied before tone mapping and eye adaptation?

I have also another strange behaviour with eye adaptation. When I'm looking on dark areas, background (sky) get brighter. It's ok but it happens always when the center of camera is on black area (no matter how far camera is from this area).

I basen on implementation included in projects on this pages: John Chapman, Nutty Software

# Answer
You just don't tonemap bloom, or blur, or depth of field.

Those effects come on top of all other. Try to experiment with the values also.
> 1 votes

---
Tags: opengl, post-processing, hdr
---


title: Unpacking UE4 .pak's?

text:
# Question
Title: Unpacking UE4 .pak's?
Is there any way to properly unpack/repack resources of UDK-based games *(.pak files)*? . From what I've tried already, gildor.org's viewer seems to skip/ignore these .pak's (also, UDK, which is UE3 though, wont read renamed .pak-\>.uassets).

# Answer
> 4 votes
You can just use UnrealPak.

```
    Engine\Binaries\Win64\UnrealPak.exe somepak.pak -extract X:\extract\here

```

---
Tags: modding, unreal, assets
---


title: Waitforseconds is skipping over

text:
# Question
Title: Waitforseconds is skipping over
I have a function for a timer using waitforseconds but instead of waiting for how long I want to, it just skips it.

A ui text should become "foo" then 5 seconds later become "bar" but it turns to bar as soon as it starts.

Code:

```
void Update () {
     text1.text = "foo";
     wait (5);
     text1.text = "bar";
 }

 IEnumerator wait(int time)
 {
     yield return new WaitForSeconds(time);
 }

```

# Answer
You have to use StartCoroutine (probably not in the Update) in order to start its execution. Otherwise it's only a method call:

```
void Start()
{
    StartCoroutine(wait(5));
}

```
> 2 votes

# Answer
You have to call you coroutine by writing "StartCoroutine( wait )". You should put something before and after the yield command or else it is skipped. Try creating a boolean and disabling or enabling it before and after the yield, then you could adjust your code to check for that boolean and then run.
> 0 votes

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


# Question
Title: OpenGL Core profile - Array of arrays in glBufferData for VBOs
I want to send each face as VBO, and I structured the data as this

```
facevbo[0] =  x x x x x x   //x,y,z,r,g,b,s,t
facevbo[1] =  x x x x x
facevbo[2] =  x x x x x x x
facevbo[3] =  x x x x
.
.
.
facevbo[numfaces] = x x x x

```

Basicly I have dynamic 2d array with different column size:

```
GLfloat** faceVBO = new GLfloat*[m_numOfFaces];
faceVBO[dfaceIndex] = new GLfloat[pFace->numOfVerts*8];

```

When I print all the faces, everything is fine, but when im trying to put them to use, i have problem at this line: (ideally I would iterate trough all the faces to bind each face, but lets take the first column)

```
glBufferData(GL_ARRAY_BUFFER, 4*oindices, faceVBO[0], GL_STATIC_DRAW);

```

the third parameter (faceVBO\[0\]) "argument of type GLfloat is incompatible with param. of type const void\*"

but if i tead from array, like

```
GLfloat facevbo[] = {x,x,x,x...}

```

and

```
 glBufferData(GL_ARRAY_BUFFER, 4*oindices, faceVBO, GL_STATIC_DRAW);

```

it works OK. How should i send the data in this case?

Thanks

# Answer
The problem is you are passing an address value to data rather than the data itself. A naive solution is to change:

`glBufferData(GL_ARRAY_BUFFER, 4*oindices, faceVBO[0], GL_STATIC_DRAW);`

to:

`glBufferData(GL_ARRAY_BUFFER, 4*oindices, *faceVBO[0], GL_STATIC_DRAW);`

To clarify: in your implementation, 'faceVBO' is a pointer to a set of pointers, and glBufferData() requires a pointer to the data, so sending it 'faceVBO\[0\]' directly is an attempt to send the pointer to the data as the data itself, which is incorrect.
> 1 votes

---
Tags: opengl, vbo
---


# Question
Title: My bullet changes the velocity depending on where I click
I want to build a little 2D-Sidescrolling shooter and I'm now at the shooting script.

I already figured out how to shoot a bullet towards my mouse pointer. I got something like this :

```
Vector3 shootDirection;
        shootDirection = Input.mousePosition;
        shootDirection.z = 0.0f;
        shootDirection = Camera.main.ScreenToWorldPoint (shootDirection);
        shootDirection = shootDirection - transform.position;

        shootDirection.Normalize ();

        Rigidbody2D bulletInstance = Instantiate (rocket, transform.position, Quaternion.identity) as Rigidbody2D;
        bulletInstance.velocity = new Vector2 (shootDirection.x * speed, shootDirection.y * speed);

```

Now obviously the bullet goes faster if my Direction coordinates are big and slower if they are smaller. Have you some better code for me or how can I fix that issue?

I added now some loop like this, which brings a horrible performance, but kinda works out for the problem, but I'm still looking for a better solution.

```
while (((shootDirection.x * speed) + (shootDirection.y * speed)) < 20) {
            speed += 0.1f;
        }

```

So the loop makes sure that the overall speed is always almost the same, but this solution ends in an infinity loop if the values get too small.

# Answer
> 1 votes
Actually the 2D-Vector solved the problem, I don't know why, because I think it should do the same but this is my code now and it's working

```
        Vector2 target = Camera.main.ScreenToWorldPoint (new Vector2 (Input.mousePosition.x, Input.mousePosition.y));
        Vector2 myPos = new Vector2 (transform.position.x, transform.position.y);
        Vector2 direction = target - myPos;
        direction.Normalize ();
        Rigidbody2D projectile = Instantiate (rocket, myPos, Quaternion.identity) as Rigidbody2D;
        projectile.velocity = direction * speed;

```

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


# Question
Title: Unity - Check if object is facing Vector3 coordinates
I am having a hard time figuring this out, I want to have objects that move around randomly, and when they get new coordinates to move towards, face them, and then move.

Here's explained:

1. Target moves towards point A.
2. Target reaches point A.
3. Get new coordinates.
4. Rotate towards the new coordinates WITHOUT moving
5. When facing the new target coordinates, start moving

I am trying it with Raycast, but it doesnt work, it tells me it always looks at them...

```
if (Physics.Raycast(transform.forward, randomTargetCoords, out hit)) {
    Debug.Log("spotted");
}

```

I want to project the ray from the front of the object to the target coordinates (Vector3), and if true, do any code inside the if method.

How can I do it?

EDIT: Here is the code for moving and rotating the object

```
transform.position = Vector3.MoveTowards(transform.position, targetCoords, moveSpeed * Time.deltaTime);
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);

```

# Answer
> 5 votes
Calculate the dot product to determine how close two vectors are. The dot product is 1 when they are exactly the same, -1 when they are exactly opposite, 0 when they are perpendicular, and decimal values when partway.

So take the current direction, the target direction, then Vector3.Dot() and check if greater than .9 (or whatever threshold you decide looks good).

# Answer
> 2 votes
jhocking's answer about dot product is the right answer to the question, but if you are rotating your object over time to face the right direction, inside that function you must be calculating how much you have left to rotate so that you know what direction to rotate and so that you don't rotate too far and overshoot.

That means that inside that function, you already ought to have knowledge of when the object is done rotating and is in fact facing the right direction - even in the case that it started out facing the right direction and had to do no rotation at all.

Whatever work you are doing in there could be used for this, without having to do extra calculations. Maybe that function returns true if it had any rotations to do that frame, so that you can watch for it to return false, to know when it's time to start moving.

# Answer
> 0 votes
You can use Quaternion.LookAt() always and then just move your object forward whenever you want.

---
Tags: unity, 3d, rotation, vector, raycasting
---


# Question
Title: Render specific part of a texture in OpenGL (2D Sprite Sheet)
I've looked at this answer to find out how to render just a part of a texture: C++ Opengl render part of an image

I tried that, but the problem is, this is how I render my texture:

```
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex2f(x, y);
glTexCoord2f(1, 0); glVertex2f(x + w, y);
glTexCoord2f(1, 1); glVertex2f(x + w, y + h);
glTexCoord2f(0, 1); glVertex2f(x, y + h);
glEnd();

```

I tried doing this to render the top left quarter:

```
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex2f(x, y);
glTexCoord2f(0.5, 0); glVertex2f(x + w, y);
glTexCoord2f(0.5, 0.5); glVertex2f(x + w, y + h);
glTexCoord2f(0, 0.5); glVertex2f(x, y + h);
glEnd();

```

But it just totally messes up and makes my texture bigger and cut off. What I want is to just draw a part, like you would on a sprite sheet. I've been messing around with those lines for awhile and I just can't seem to find out how to do what I want.

I've been messing around with this:

```
// yeah i know this math is crappy and weird but im trying EVERYTHING at this point,
// it draws until the dcw (width) just fine but i cant seem to integrate cx/cy...

double dcw = double(cw) / double(w);
double dch = double(ch) / double(h);

double dcx = double(cx) / double(dcw);
double dcy = double(cy) / double(dch);

std::cout << "dcw:" << dcx << "\n" << "dch:" << dcy << "\n";

glBegin(GL_QUADS);

//bottom right
glTexCoord2f(0, 0); glVertex2f(cx, cy);
//top right
glTexCoord2f(dcw, 0); glVertex2f(cx + cw, cy);
//top left
glTexCoord2f(dcw, dch); glVertex2f(cx + cw, cy + ch);
//bottom left
glTexCoord2f(0, dch); glVertex2f(cx, cy + ch);

```

# Answer
> 0 votes
Well, I finally got it after messing around with the math for awhile I kinda understand it. If anyone wants the code here it is.

```
double dcx = double(cx) / double(w);
double dcy = double(cy) / double(h);

double dcw = (double(cx)+double(cw)) / double(w);
double dch = (double(cy)+double(ch)) / double(h);

glBegin(GL_QUADS);

glTexCoord2f(dcx, dcy); glVertex2f((cx)+x, (cy)+y);
glTexCoord2f(dcw, dcy); glVertex2f((cx + cw)+x, (cy)+y);
glTexCoord2f(dcw, dch); glVertex2f((cx + cw)+x, (cy + ch)+y);
glTexCoord2f(dcx, dch); glVertex2f((cx)+x, (cy + ch)+y);

glEnd();

```

# Answer
> 2 votes
I don't quite understand what your problem is, since you're not being very specific. But I'll try.

Your code seems fine to me.
glVertex2f() controls **where** you want to render your quad to the screen. glTexCoord2f() controls **what part** of the texture you want to apply to the quad.
So obviously if you increase the size of your quad but don't increase the part of the texture you apply to it, it will become stretched.

---
Tags: opengl, c++, textures, texture-atlas
---


# Question
Title: Should I use textures not sized to a power of 2?
In the early days of OpenGL and DirectX, texture sizes were required to be powers of two. This meant interpolation of float values could be done very quickly, using shifting and such.

Since OpenGL 2.0 (and preceding that, via an extension) non-power-of-two texture dimensions have been supported.

Do power-of-two textures have performance advantages on modern integrated and discrete GPUs? What advantages do non-power-of-two textures have?

Does a significant desktop population have cards supporting non-power-of-two textures?

# Answer
**Are there performance advantages to sticking to power-of-two textures on modern integrated and discrete GPUs?**

Most of modern GPUs support non-power of two (NPOT) textures and handle them well. Performance drop is quite little. But there are few problems to consider:

* When using NPOT texture it takes more space in RAM, just like next-sized POT texture. Technically you just waste the space that could be used to put something in there;
* NPOT textures may be handled noticeably slower (in OpenGL 2.1 I had up to 30% performance drop) compared to POT of next size;
* Older GPUs and on-board/on-chip GPUs are not so advanced, they often support NPOT textures, but support is quite slow and clumsy;
* Even older GPUs may refuse to accept/display NPOT textures at all;
* There could be edging artifacts caused by mip-map interpolation, your 25x25 texture might have a black fringe where pixels were added to stuff it to 32x32 size.

P.S. I don't know for sure about mobile devices, there might be even more restrictions regarding POT textures.

**What advantages do non-power-of-two textures have, if any?**

As far as I know there are only 2 advantages:

* They take less space on HDD if they are not packed (when packed empty areas give very little add)
* You can save time on writing NPOT -\> POT converter. You will need one for release version, but using NPOT textures for designing and prototyping interface / models is just fine

**Are there large populations of desktop users who don't have cards that support non-power-of-two textures?**

As far as I know and tested on PC - Yes. That includes major percentage of speed-drop / minor bugs GPUs and minor percentage of cards that won't handle NPOT at all.
> 22 votes

# Answer
One common use of non-power-of-two textures is for 'screen-sized' or 'half-screen-sized' (and so on) render target textures used for postprocessing effects.

In these cases, mipmaps aren't needed, the buffer is always uncompressed, so odd texture sizes cause less problems here
> 6 votes

# Answer
There were limitations for NPOT textures on older hardware. As mentioned on this OpenGL wiki, some older hardware requires NPOTs not to have mipmaps, compressed textures require alignment of 4x4 pixels, but new hardware should handle it perfectly.

In my experience, some even relatively new hardware experiences major performance hit if you use NPOT textures instead of POTs. I don't know what the issue is; it's possible that in some combination of render states, the rendering is actually done in software. So, unless you have good reasons, I'd recommend still trying to use POTs as much as possible.

As to why use NPOTs instead of POTs - if you have images that are of NPOT dimensions, say for example 1600x1200, using 2048x2048 pixel surface will waste a lot of video memory.
> 4 votes

# Answer
power of 2 textures increase performance about 30% for any type of GPU not only old GPUs (30% faster is the difference between a high end GPU and an average one) they take 30% more ram but less vram is needed they increase quality by providing proper texture size for specific distance it works like anti-aliasing for textures dark line artifact should be handled by game engines and aaa engines handle them fine
> -1 votes

# Answer
My programmer art is only of the correct size.

It certainly simplifies my display logic to know that if I want to set a texture to the top left of the screen that I can just set 0,0 as the top left of the texture and see *all* the texture there in the correct location, whereas if I had to add 0alpha padding, positioning the texture against the edge of the screen would be more complex. Plus, of course, that 0alpha still has to be alpha blended, and if I'm looking at opaque textures, I may prefer not to have an alpha channel.
> -3 votes

---
Tags: opengl, textures, performance
---