title: Too many if statements cause lag?

text:
# Question
Title: Too many if statements cause lag?
I am trying to make a vertical scroller game with collision tiles on both sides. I'm using Libgdx and android studio.

The problem is that i have made every tile as an object with a rectangle for collision and there are 12 on each side that get checked every time the update method is called. I noticed the game hangs sometimes, can this this cause the lag?

My code for collision:

```
    public boolean collidesOuterCircle(Penguin penguin) {

    if(penguin.getX()>(136/2)){
        return (

            dirtRight1.collidesOuterCircle(penguin)|| dirtRight2.collidesOuterCircle(penguin)||dirtRight3.collidesOuterCircle(penguin)
                    ||dirtRight4.collidesOuterCircle(penguin)||
            dirtRight5.collidesOuterCircle(penguin)||dirtRight6.collidesOuterCircle(penguin)||dirtRight7.collidesOuterCircle(penguin)
                    ||dirtRight8.collidesOuterCircle(penguin)||dirtRight9.collidesOuterCircle(penguin)
            ||dirtRight10.collidesOuterCircle(penguin)||
            dirtRight11.collidesOuterCircle(penguin)||dirtRight12.collidesOuterCircle(penguin));

    }
    else {
        return( dirtLeft1.collidesOuterCircle(penguin)|| dirtLeft2.collidesOuterCircle(penguin)||dirtLeft3.collidesOuterCircle(penguin)||
                dirtLeft4.collidesOuterCircle(penguin)||
                dirtLeft5.collidesOuterCircle(penguin)||dirtLeft6.collidesOuterCircle(penguin)||
                dirtLeft7.collidesOuterCircle(penguin)||dirtLeft8.collidesOuterCircle(penguin)||
                dirtLeft9.collidesOuterCircle(penguin)||
                dirtLeft10.collidesOuterCircle(penguin)||dirtLeft11.collidesOuterCircle(penguin)||dirtLeft12.collidesOuterCircle(penguin));

    }

}

    public boolean collidesInnerCircle(Penguin penguin) {

    if(penguin.getX()>(136/2)){
        return(
        dirtRight1.collidesInnerCircle(penguin)|| dirtRight2.collidesInnerCircle(penguin)||dirtRight3.collidesInnerCircle(penguin)||dirtRight4.collidesInnerCircle(penguin)||
                dirtRight5.collidesInnerCircle(penguin)||dirtRight6.collidesInnerCircle(penguin)||dirtRight7.collidesInnerCircle(penguin)||dirtRight8.collidesInnerCircle(penguin)||dirtRight9.collidesInnerCircle(penguin)
                ||dirtRight10.collidesInnerCircle(penguin)||
                dirtRight11.collidesInnerCircle(penguin)||dirtRight12.collidesInnerCircle(penguin));
    }else{
    return (dirtLeft1.collidesInnerCircle(penguin)|| dirtLeft2.collidesInnerCircle(penguin)||dirtLeft3.collidesInnerCircle(penguin)||dirtLeft4.collidesInnerCircle(penguin)||
            dirtLeft5.collidesInnerCircle(penguin)||dirtLeft6.collidesInnerCircle(penguin)||dirtLeft7.collidesInnerCircle(penguin)||dirtLeft8.collidesInnerCircle(penguin)||dirtLeft9.collidesInnerCircle(penguin)||
            dirtLeft10.collidesInnerCircle(penguin)||dirtLeft11.collidesInnerCircle(penguin)||dirtLeft12.collidesInnerCircle(penguin));
    }

}

```

My code for reseting the tiles:

```
  if (dirtLeft1.isScrolledDown()) {
        dirtLeft1.reset(dirtLeft12.getTailY());
    } else if (dirtLeft2.isScrolledDown()) {
        dirtLeft2.reset(dirtLeft1.getTailY());
    } else if (dirtLeft3.isScrolledDown()) {
        dirtLeft3.reset(dirtLeft2.getTailY());
    }else if (dirtLeft4.isScrolledDown()) {
        dirtLeft4.reset(dirtLeft3.getTailY());
    }else if (dirtLeft5.isScrolledDown()) {
        dirtLeft5.reset(dirtLeft4.getTailY());
    }else if (dirtLeft6.isScrolledDown()) {
        dirtLeft6.reset(dirtLeft5.getTailY());
    }
      else if (dirtLeft7.isScrolledDown()) {
          dirtLeft7.reset(dirtLeft6.getTailY());
      }
      else if (dirtLeft8.isScrolledDown()) {
          dirtLeft8.reset(dirtLeft7.getTailY());
      }

      else if (dirtLeft9.isScrolledDown()) {
          dirtLeft9.reset(dirtLeft8.getTailY());
      }
      else if (dirtLeft10.isScrolledDown()) {
          dirtLeft10.reset(dirtLeft9.getTailY());
      }
      else if (dirtLeft11.isScrolledDown()) {
          dirtLeft11.reset(dirtLeft10.getTailY());
      }
      else if (dirtLeft12.isScrolledDown()) {
          dirtLeft12.reset(dirtLeft11.getTailY());
      }

    if (dirtRight1.isScrolledDown()) {
        dirtRight1.reset(dirtRight12.getTailY());
    } else if (dirtRight2.isScrolledDown()) {
        dirtRight2.reset(dirtRight1.getTailY());
    } else if (dirtRight3.isScrolledDown()) {
        dirtRight3.reset(dirtRight2.getTailY());
    }else if (dirtRight4.isScrolledDown()) {
        dirtRight4.reset(dirtRight3.getTailY());
    }else if (dirtRight5.isScrolledDown()) {
        dirtRight5.reset(dirtRight4.getTailY());
    }else if (dirtRight6.isScrolledDown()) {
        dirtRight6.reset(dirtRight5.getTailY());
    }
    else if (dirtRight7.isScrolledDown()) {
        dirtRight7.reset(dirtRight6.getTailY());
    }else if (dirtRight8.isScrolledDown()) {
        dirtRight8.reset(dirtRight7.getTailY());
    }else if (dirtRight9.isScrolledDown()) {
        dirtRight9.reset(dirtRight8.getTailY());
    }else if (dirtRight10.isScrolledDown()) {
        dirtRight10.reset(dirtRight9.getTailY());
    }else if (dirtRight11.isScrolledDown()) {
        dirtRight11.reset(dirtRight10.getTailY());
    }else if (dirtRight12.isScrolledDown()) {
        dirtRight12.reset(dirtRight11.getTailY());
    }

```

# Answer
> 2 votes
*Cursory answer*: "it might be". If you are doing "carpet testing" for collision detection, no offence, but you are doing it wrong (unless you have *very few* elements to test): pair checking of any kind is a O(n^2) operation, and will start to eat at your cpu time very fast as the number of objects you have in the game increases, so you *might* want to improve your algorithm (there are many). **However...**

...since the tiles don't collide with each othets, your tests are likely far less than most modern devices can handle (even low tier phones), so I wouldn't put my money on that :)

The point is, **why guess**? *The right thing to do* (instead of making people read tons of code ;-) ) is to pick the android "monitor", profile your game cycle and see where the bottleneck really is. See how much time your inner and outer collision detection functions are taking (exclusive time) and you'll have your answer, without margin of error.

Still, If I had to put my money somewhere, I would bet that the profiler will not point you to those two functions, as the culprits of your performance issue, as the symptoms you are describing (game that runs smoothly and then hangs for a while) look a textbook case of *memory allocation* problem.

I have not enough data, but might it be that you are creating objects in you tight loop? In that case, you might be allocating memory faster than the garbage collector is recycling it. This leads the Os to exhaust the memory for the process at set (**very periodic**, in fact) times, and hang the process while the garbage collector "catches up".

In conclusion: give a good look at the profiler (just to see that it exists, if you never used one already ;-) ), but then check the memory and CPU consumption graphs at the bottom of Android Studio (which are a very quick way to get pointed in the right direction with performance related problems): if the average CPU consumption is not high, but you see a sawtooth shape in the memory consumption, then you should definitely check your allocations (-\> profile them with the monitor ;-) ) and make sure not to do any in your tights loops.

Hope it helps (and break a leg for your game!)

---
Tags: android, libgdx, lag
---


title: Problem in Unity ad

text:
# Question
Title: Problem in Unity ad
I am trying to place ad in my game. i am using unity 5. trying to place admob in my game. in unity editor it displaying dummy message. tried to build the game in android phone after build completed game opened in the phone. in console it displays an error message..

i am new to this concept. anybody please help

1. Downloaded the plugin from admob website
2. In SDK manager google repository, Google Play Service and Google Play Billing Library was installed
3. AndroidMainfest.xml file is copied in the asset.

AndroidMainfest.xml

```
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.unity">
<!-- Google Mobile Ads Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Uncomment to add billing for in-app purchase ads -->
<uses-permission android:name="com.android.vending.BILLING" />
 <application
android:debuggable="false"
android:icon="@drawable/app_icon"
android:label="@string/app_name" >
   <activity android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen" android:label="@string/app_name" android:launchMode="singleTask" android:screenOrientation="fullSensor" android:name="com.unity3d.player.UnityPlayerNativeActivity">
   <intent-filter>
     <action android:name="android.intent.action.MAIN" />
     <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
   <meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="true" />
 </activity>
<!-- AdMob Plugin -->
    <activity android:name="com.google.ads.AdActivity"
              android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
              android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
</application>

</manifest>

```

In main Script i used

```
using GoogleMobileAds.Api;

public class GameScript : MonoBehaviour {
private BannerView bannerView;

Void Start(){
RequestBanner ();
}

private void RequestBanner()
{
    #if UNITY_ANDROID
    string adUnitId = "unity test id";
    #elif UNITY_IPHONE
    string adUnitId = "INSERT_IOS_BANNER_AD_UNIT_ID_HERE";
    #else
    string adUnitId = "unexpected_platform";
    #endif

    // Create a 320x50 banner at the top of the screen.
    bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.Top);
    // Create an empty ad request.
    AdRequest request = new AdRequest.Builder().Build();
    // Load the banner with the request.
    bannerView.LoadAd(request);
}

```

# Answer
I solved the problem. i removed all playstore plugin from my project, then i select Edit -\> Reimport all. then I import admob plugin. them in AndroidMainfest.xml i changed "android:value="true" to android:value="false" ".

```
<activity android:name="com.unity3d.player.UnityPlayerNativeActivity"
android:label="@string/app_name">
<intent-filter>
  <action android:name="android.intent.action.MAIN" />
  <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="unityplayer.UnityActivity" android:value="true" />
<meta-data android:name="unityplayer.ForwardNativeEventsToDalvik"
    android:value="false" />
</activity>

```
> 1 votes

---
Tags: unity, xml, google-play-services, advertisements
---


title: OpenGL Colour Issues

text:
# Question
Title: OpenGL Colour Issues
I am using a single VBO to store vertices in the follow format:

v1X, v1Y, v1Z, v1R, v1G, v1B, v2A, v2X, ...

Vertex positioning is fine, shapes show up where expected, however instead of using the colour provided, all shapes show up red.

The code given below simply draws two triangles to form one square ground shape.

Buffer data preparation method

```
public void prepare(float[] data) {
    glBindBuffer(GL_ARRAY_BUFFER, vboID);
    FloatBuffer dataBuffer = RenderUtils.fArrayToBuffer(data);
    if(dataLength != data.length) {
        glBufferData(GL_ARRAY_BUFFER, dataBuffer, GL_STATIC_DRAW);
        dataLength = data.length;
    } else {
        glBufferSubData(GL_ARRAY_BUFFER, 0, dataBuffer);
    }
    glVertexAttribPointer(0, 3, GL_FLOAT, false, 7*4, 0);
    glVertexAttribPointer(3, 4, GL_FLOAT, false, 7*4, 3*4);
}

```

Render code

```
floorObj.prepare(new float[]{
    -5, 0, -5,   1, 0, 0, 1,
    5, 0, -5,   0, 1, 0, 1,
    -5, 0, 5,   0, 0, 1, 1,

    5, 0, -5,   1, 0, 0, 1,
    5, 0, 5,   0, 1, 0, 1,
    -5, 0, 5,   0, 0, 1, 1,
});
glDrawArrays(GL_TRIANGLES, 0, 6);

```

Vertex shader

```
#version 330 core

in vec3 position;
in vec4 i_color;
out vec4 color;

uniform mat4 transform;

void main(){
    gl_Position = transform * vec4(position, 1);
    color = i_color;
}

```

Fragment shader

```
#version 330 core

in vec4 color;
out vec4 f_color;

void main(){
    f_color = color;
}

```

As previously stated, vertex positions work fine, however colour does not. Just ask if any other code would be useful to determine the problem.

Thanks, - Jasper

# Answer
> 1 votes
There are a couple potential reasons why it doesn't work:

1. you have not enabled the Vertex Attrib 3: `glEnableVertexAttribArray(3)`.
2. you have not told GL where to find the color attribute: `glBindAttribLocation(..., 3, "i_color")` before linking. You should be doing the same thing for position, as Gabriel Roy mentioned, if you didn't yet.

# Answer
> 0 votes
Okay, I think your problem comes from the

```
glVertexAttribPointer(0, 3, GL_FLOAT, false, 7*4, 0);

```

Let me explain what this function does and what are its parameters :)

The first parameter (0) specify which vertex attribute we want to allocate. This determine which determine which VAO pointer will be linked to your array. Remember that OpenGL is a state machine and that the CURRENT binded buffer is linked with your vexter pointer. If you put 0 there, you must put 0 when u create your shader program and set the

```
glBindAttribLocation(m_Program_Cube, 0, "vertexPosition");

```

See the 0 (This is the index of the vertex pointer)

Next we have the size (This is either a 1,2,3 or 4) and determine which kind of vector is going to enter your vertex shader. Pretty simple.

Next is the type of variable which will enter the buffer ... Most of the time its GL\_FLOAT

Next is the normalization of the vertex, it's a pretty complicated thing and help with rotating when using geometry shader later one. Leave it at GL\_False

Next is the most important part, which is the STRIDE. The STRIDE helps determine the space in (GL\_Float) between each SETS of vertices. In your case you are using (7\*4) I personnaly don't know where u are getting that "4" at but put

```
7 * sizeof(GLfloat)

```

This will mean that between each set of Vertex Position (The first 3 vertices making the first vec3) there will be 7 other GL\_Float

Next and finally is the OFFSET which is pretty important when making a single VBO containing all the position, colors and maybe texturecoords

Another error you made there is using "3\*4". I still don't know where u are getting that "4" but its alright :) I'll correct it. The OFFSET is a value that is increase to the base starting position. For example your color vector3 start at the position 3 so it should be

```
(GLvoid*)(0* sizeof(GLfloat))

```

Don't worry about the GLvoid\* .. There is alot of things in OpenGL that you just simply cannot understand by yourself and you just need to accept them. This is one. Change the 0 for "3" which mean that your OFFSET will be set to 3.

Finally, you need to make sure that you are working in the same VAO. In your case you are using a single VBO (A big array) to contain every vertices for the position and colors. Later on you will learn to create multiple VBO to separate your arrays but right now keep it at one :)

But don't worry I'm sure you will learn just fine!!! :)

Ps: Don't forget to bind your attribute properly in your shader using the good location of the pointer.

This was my first time helping someone with OpenGl and I hope I did good :)

# Answer
> 0 votes
Turns out I was using the wrong attribute index (3 instead of 1).

In enabling attrib index 1 instead of 3, and changing my

`glVertexAttribPointer(3, 4, GL_FLOAT, false, 7*4, 3*4);`

to

`glVertexAttribPointer(1, 4, GL_FLOAT, false, 7*4, 3*4);`

I was able to solve the issue.

---
Tags: opengl, graphics, lwjgl
---


# Question
Title: How to make inputing large inputs more engaging
I asked this question on another exchange "Encrypted content in games" and it made me wonder about game design.

The basics of that question is that you are using user-input, either directly or indirectly through the current game state, to generate a decryption key which unlocks/decrypts some secret content. This input would be the solution to some puzzle or come from a series of clues.

The problem is that the input space has to have high entropy to prevent it from being brute-forced, even by a computer. Having a series of levers would mean you need to have 90-120 or so of them. If I want a shorter input like let's 7, then you need 7500 different symbols to match those 90 levers which is way to many for people to distinguish between.

**So I would like to hear ideas about how you could make an engaging/fun input method with high entropy.** Ideally one that's visible to the user, meaning that the user is aware of it and not happening in the background.

Here is one example I thought about:

Imagine a secret altar outside of any quest lines. In front of it are 10 slots. Any of the 500+ game objects can be placed in the slots. Based on the game objects used and their permutation, a unique decryption key is generated using the object's game-IDs. Then the clues to what objects to use and in what order could be cleverly hidden through the game or somewhere else.

It still suffers from users possible being unable to effectively distinguishing the 500 different objects in the game. Also if your game is small and doesn't have that many objects it doesn't work.

# Answer
Generally speaking, you don't.

What you're talking about is a general kind of puzzle that I would describe as a "combination lock". There's some interface for the user to enter a combination, but the number of entries is too vast to brute-force for the user. So instead, the user actually solves the clues needed to solve the puzzle.

Myst and its ilk thrive on such kinds of puzzles. The solution to the Mechanical Age in Myst I was a combination of 4 "digits", with each "digit" having between 8 and 10 different images. For a human, that's far too much to even consider brute-forcing.

Your problem is that you're not designing these puzzles for *humans*; you're designing them for machines. Your design goal is to make them unable to be brute-forced by a modern computer.

See, the Myst designers choose 4 digits rather than 5, 6, 20, etc, because 4 is a small number. It's small enough that you could quickly jot down the values you find on the age, then bring them to the place to enter it. The number of digits was choose for a similar reason. In total, you have a puzzle that has enough entropy to make brute force hard, but the scope is small enough to make remembering/copying the symbols easy.

If you are designing a puzzle that's hard for a *computer* to brute force, then you will have to create an interface that a human will find tedious to enter, even if they know the solution.

Take your idea. Boiled down, what you have is a 10-digit code, with 500 different possible values for each digit. Now maybe the user won't have collected all 500 before they know the solution. But they're still carrying around a satchel of 300-400 different things (which presumably have *no other in-game function*).

When they go through the various clues to figure out what the right ones are, they will have to sort through *hundreds* of choices. Even if you tell them outright which ones to use (the way Myst puzzles tend to do), they still have to search through their satchel to fish them out.

10 times.

That's not an interesting puzzle anymore. Or rather, whatever interest the puzzle may have generated is sabotaged by having to go through a great deal of tedium to tell the game the puzzle has been solved.

Remember: coming up with the solution to the puzzle is what people find interesting. Everything the user has to do *after* finding the solution is just dragging things out. If I spend 2 hours solving a puzzle, and then have to spend 15 minutes poking through a UI just to let the computer know I solved it, that's a problem.

Here's an example of a puzzle that had high entropy in Myst: the fireplace puzzle. You have to enter what is effectively a long binary number. It's a big pain to copy the pattern from the book, walk 5 feet, and then type it all in.

How much entropy does it provide? It's a binary matrix with 8 columns and 6 rows, which makes it 48-bits. The average *smartphone* can probably crack that. And remember: this is a puzzle that has reached the level of being tedious, since pretty much nobody likes it.

Admittedly, it's not actually a "puzzle"; at one point in the game, you're just told which pattern to enter.

But there is perhaps some chance for hope. Riven presents to you the Fire Marble puzzle. It's a 25x25 grid of locations. And you have to put 5 colored gems (from a set of 6; one of the tricks to the puzzle is knowing that 1 of them is superfluous) into 5 specific locations in the grid.

I'm no expert on determining the number of possible solutions for this scenario. However, when I computed 125 choose 5 to get an idea of what a similar reverse problem would be (choose 5 of 125 balls), an unordered choice represents an entropy only in the hundreds of millions. An ordered choice breaks a billion. But that's even less than the 48-bit encryption from before. It's nothing extraordinary.

I know those aren't the right calculations for the puzzle. But as order-of-magnitude estimates, even if you added a couple more zeros onto them, it seems clear that the entropy on this puzzle is probably not cryptographically secure.

And that's the *best* Myst ever got, entropy-wise. Not only that, Riven bent over *backwards* to justify having that many gird squares. Plus, they made it easy for you to jot down the solution. See, the grid is subdivided into 5x5 blocks of 5x5 locations (5 is an arc-number for Riven. It's literally written into the world). So you don't need to carry around a 25x25 grid; just 5 separate 5x5's with each one specifying which of the larger sectors it is.

So I don't believe that it's possible for you to come up with a puzzle that has cryptographically secure entropy, *without* being tedious to enter that solution or for the user to generate it to begin with. Or both.
> 1 votes

# Answer
I have found one system that could work well. I'd like to contribute some of it to Nicol Bolas which made me think of this while reading his answer.

The main difference here from what I've been thinking earlier is the realization that every input-slot doesn't need to be filled in. This "negative input space" as I like to call it adds to the number of combinations while not increasing the work necessary to input the key. So the input could have a high entropy while only requiring the user to input e.g. 7 out of 7 symbols. Having the input-slots arrange themselves in 2D also helps by shortening the distance to each one and making it easier to navigate while having many slots. 225 slots put end to end would not really be manageable.

Here is an example showing a 15x15 grid with 7 different colored marbles. A solution would consist of a certain number of colored marbles place correctly on the grid. This grid by itself with an unknown amount of marbles required have an entropy of 675 bits. This is way more than what's needed to keep someone out. However the point was to make the inputting process more engaging and less of a chore, so requiring the player to possibly fill all 225 squares it too much work. So the player might suspect this and assume you only need 4-12 marbles, but even then the entropy is still very high at about 98 bits. Even with a fully known input length of let's say 7 marbles the entropy is still a respectable 62 bits. This would make a computer doing one combination per nanosecond reach 1% of all combinations after about 1.5 years. Just increasing the number of marbles to 8 would mean it would have taken the computer 264.5 years instead to reach 1%.

Even though it's hard for both a human and a computer to randomly guess the input, it's still should be rather painless to actually input it if you know the solution. Both locating a square and identify a color should be easy for most players to do quickly. The grid should have a helper grid (here in dark blue) to allow the player to more quickly identify the square he/she needs.

One negativ factor with this system is that each input is independent and for each clue known the puzzle becomes easier. So with a known size of 7 marbles and 6 marbles known, the last should be within reach of even a human to figure out through brute force with only 1575 possibilities. Two ways of negating that is to not letting the size of the input be known and releasing clues in bunches where e.g. 3-4 marbles are revealed at once.

This is a plot of entropy vs the number of missing marbles. This assumes that the number of marbles needed is known (8 here). As you can see the plot falls fast as marbles are revealed. Remember that entropy is log2 of number of combinations, so the y-axis is logarithmic. So a single bit lost of entropy means number of combinations cut in half. On average about 8.4 bits of entropy is lost each time a marble is revealed meaning that each time there are about 337 times fewer combination then before.

**Pros:**

* Can increase entropy easily without a lot of extra effort on the player.
* Can be done without a keyboard input, so still doable on consoles or in VR.
* The solution/clues can be compactly written, e.g. "RED-8-4".
* It's easy and direct to do with a known solution. Compare with asking to get a Rubik's Cube to a fixed configuration, not something everybody can do.

**Cons:**

* Entropy drops exponentially as clues become known. Hard to split up the solution.

Unfortunately I don't know if this drop of entropy problem can really be efficiently solved.
> 1 votes

# Answer
You're going in the wrong direction in my opinion. You want to have locks, wich can't be bruteforced. Making it like that makes the people angry and makes the feel of the game go away.

Ypu should make locks, wich no one wants to bruteforce.

If someone sees a lock with 7 levers, and 7 symbols in each of them, he either rage quits or checks the answer on the internet. You can't stop this.

And also, no matter what you do, entering the exct symbol in to 90 locks is tedious, frustrating and not very fun. Especially if someone f\**ks it up somewhere.
> 0 votes

---
Tags: game-design, input
---


# Question
Title: What's the best way to deal with platformer tile collisions?
I am starting with game development and creating a basic platformer game. I already have searched a lot and found some ways to implement the platformer aspect to the game, like apply a gravity, velocity and so on.

Everything is good, but always when I implement a way to deal with the collisions, a bug appears. If I fix it, it appears at other side, etc. The main problem is when the player intersects a tile and I need push him up back. The most simple way that I found is this:

```
player.Y = tile.Y - player.height;

```

The most problems comes when you also need verify the X axis, the player is pushed out from the tile, or it is thrown at other tile position, like this issue I had when trying to implement the XNA Platformer Example. Or even pass through the tiles if you are going too fast.

After some research I found a good way to avoid all this problems: instead of move the player to the next position and deal with the tiles to push him back, calculate a safe distance and move the player following this. The "safe distance" is for example, the `player.Y += player.Velocity.Y`, but if any tile is at the way, the safe distance is decreased to the player don't enter in the tile.

I read this excelent article and it's what is said about the algoritm:

> 5. The total movement of the player along that direction is then the minimum between the distance to closest obstacle, and the amount that you wanted to move in the first place.
> 6. Move player to the new position. With this new position, step the other coordinate, if still not done.

So, the best way is use the "safe distance" method?

# Answer
> 0 votes
Set their position to be almost perfect - account for floating point precision.

So if your player is 8 units tall, and your platform is at (5,6), and you land on the platform, then:

When you see an imminent collision, set the player's y position to 6+8+0.01

6 is the y position of the platform. 8 is the player size offset. 0.01 is the floating point precision correction.

This assume y grows upward, and the top left of the sprite is its location.

The correction for floating point precision is probably unnecessary, but depending on the implementation of your engine, it could be needed.

---
Tags: algorithm, platformer
---


# Question
Title: Should I add error handling to SDL_GL_SetAttribute?
As the title says, I wonder if I should handle errors for :

```
SDL_GL_SetAttribute

```

Can it actually fail to set?

And if it can, what could be a reason for it to fail?

# Answer
Probably.

As a general rule, if some function of some API is documented (explicitly or implicitly) as being capable of failure, you should account for that failure.

This means you check for the failure directly (checking the return value in the case of `SDL_GL_SetAttribute`) or you ensure earlier in your code that the conditions leading to failure cannot be true by the time you call the function. Even if you're doing the second option, it may be useful to check the return code directly in a way that's compiled out of release builds, for debugging or logging purposes.

The reason is because an API represents a contract between you and the implementer of that API, and part of that contract includes error checking. A well-written API should be easy to use correctly, and that means if errors are documented as possible, the author probably had a good reason to do so.

Of course, it is possible for APIs to be poorly written, and have documentation that they can fail that is incorrect; but it's also possible that they just can't fail *today* and might be updated to fail in the future and the author is being future-proof, so... it's a toss up. *Better for you to write your code defensively.*

---

Specifically in the case of `SDL_GL_SetAttribute`, you can see that it can fail in a variety of ways (as of the writing of this answer):

* It will fail if the video subsystem isn't initialized.
* It will fail if the value of the attribute parameter is invalid.
* It will fail if the value of the attribute parameter is `SDL_GL_CONTEXT_FLAGS` or `SDL_GL_CONTEXT_PROFILE_MASK` and the `value` parameter is not a legal value for that attribute.
> 1 votes

---
Tags: opengl, sdl2
---


# Question
Title: How to create a seemingly infinite text-based map in Python
I am looking to create a text-based map in which a player could (hypothetically) move through out infinitely. I was thinking I could do this through class objects defining towns / dungeons / etc. and placing them randomly through out the world. I was hoping this to be tile based, and for the tiles to have specific properties, i.e. water, dirt, grass, forest, town, dungeon, etc.

How could I go about doing this in Python 2.7?

# Answer
I agree with @abathur's comment, and a little more information would assist, but I've a few points that can provide a fair answer that you'll need to apply for yourself.

I've three sections: how you could think about the problem, some general implementation ideas and one area that should help refine the map to make it a bit more realistic seeming.

1. One way to consider the problem: It seems plausible to use a generative map approach with a pseudo random process to determine your map tiles' features and properties (possibly using a fixed seed, if you need the map to be consistent between games/players). Not sure if you're aware, but the game Elite in the 80s took this approach, sidestepping the need to store all their planet data. It's worth googling, but some details are here: http://wiki.alioth.net/index.php/Random\_number\_generator
2. Implementing: So ideally you'd need an idea of the tile features and properties you want. Write a handful of functions that take a number and turn that into a property from a cyclic group of options. The trick then is to turn any map coordinate into a number in a sequence as if it were on a chess board, eg row 2 column 3 might correspond to item 11. You plug that into a PRNG to get your random number out for that tile and then feed it into your feature functions and you've got a set of data for your map. The obvious limitation here as that the chess board (or bigger) still has a finite width. When the player reaches the edge you could then repeat the process but applying a multiple to the sequence number before it's feed in to obtain your random numbers. that multiple would correspond to that position in the bigger grid (of chess boards). I suspect there are other ways to come up with a sequence number that aren't bound by the board but I haven't any to hand.
3. Improvements: You can have a look at the map as you go, but it's likely that a truly random map will look a bit unrealistic. One area to investigate is Perlin Noise. It's used to provide noise that appears to be "natural". The Wikipedia page is a good start and there's an article here which gives some ideas. http://devmag.org.za/2009/04/25/perlin-noise/ The main difference is that you're not going to be directly drawing the noise but using it for your features.

I hope this at least gives you some areas to think about. I'd be interested to hear what you end up doing!
> 1 votes

---
Tags: python, rpg, text-based
---


# Question
Title: Implementing time step in main game loop
So ive read both http://gameprogrammingpatterns.com/game-loop.html and http://gafferongames.com/game-physics/fix-your-timestep/ and I kind of understand how I'm supposed to do it, but some parts are still blurry and I would like some guidance.

By the way, I have programmed my game from scratch and i do not want to change to some framework or anything that has an built in main loop, i want to do this by myself.

Anyway, this is what I have accomplished code-wise, I will re-produce my solution it in psudocode below.

```
func createPlayer()
{
oData = Empty Object()
oData.id
oData.name
oData.etc.....
Player = LoadSprite("filename", oData)
// Properties
Player.oSprite.x
Player.oSprite.y

Player.oSprite.scale
Player.oSprite.width
Player.oSprite.height
//Methods (Self-explanatory)
Player.oSprite.width()
Player.oSprite.height()
Player.oSprite.centerX()
Player.oSprite.centerY()

return Player
}

// Startup
oPlayer = createPlayer()
oWorld = 1D array of objects which has identical properties and methods from createPlayer()

// Main game loop
while(game){

 //User inputs
 _game_userInputs(byref oPlayer)

 // "Physics" jumps and world collission is done here.
 _game_Physics(byref oWorld, byref oPlayer)

 // rendering, draws the world frame with all inputs and physics done beforehand
 _game_render(byref boWorld,byref oPlayer)

}

```

This is how I "understand" what flow the loop should have

```
t = 0.0
dt = 0.0
currentTime = 0.0
accumulator = 0.0

while(game)
{

  newTime = _Timer_QueryPerformanceCounter() // Im feeling like this need something more than just the QueryPeformenceCounter?
  frameTime = newTime - currentTime

  if (frameTime > 0.25) {
        frameTime = 0.25
  }
  currentTime = newTime

game_input()

//This is causing my game to get stuck here, i belive it has something to do with my type of timer
 while accumulator > dt
 {
  game_physics(t, dt) //how is the deltatime helping me in my physics?
  t += dt
  accumulator -= dt
 }

 alpha = accumulator / dt
  game_render(alpha) // I dont know what im supopsed to do with this.
}

```

TLDR, what do i do with the t, dt in my physics? before i render?

# Answer
> 1 votes
Let's go through this:

```
t = 0.0
dt = 0.0
currentTime = 0.0
accumulator = 0.0

```

Okay, som basic initialization, this is good. However, as Boreal mentioned, dt of 0 will cause problems. And since you are intending to fix your timestep, you should perhaps make dt a const and just set the value to whatever you want up here. Also, your currentTime initialization should probably be a timestamp of now or you will run into problems at the beginning of your program.

```
while(game)
{

  newTime = _Timer_QueryPerformanceCounter() // Im feeling like this need something more than just the QueryPeformenceCounter?

```

I'm not familiar with QueryPerformanceCounter since I'm not a windows programmer, but from the MSDN docs, it's not a time but instead a number of counts, which means you'll need to do some calculations using frequency.

```
  frameTime = newTime - currentTime

```

This is where your initialization of currentTime could cause problems. You want this to be a relatively small number always, and in the first cycle, you will get something large. In the aforementioned link, you can see that you actually need to initialize currentTime like QueryPerformanceCounter(&currentTime), and then at this point in the code, you would do the subtraction, but then also divide by the result of QueryPerformanceFrequency() to get an actual elapsed time that is system agnostic. If you don't then your loop will time differently on different systems that have different clock speeds.

```
  if (frameTime > 0.25) {
        frameTime = 0.25
  }
  currentTime = newTime

  game_input()

```

I wouldn't cap the resulting time, because that would cause some funky results with anything that uses the elapsed time in a calculation. If you intend to run this loop every 0.25 seconds, then that's how you'd set dt.

```
//This is causing my game to get stuck here, i belive it has something to do with my type of timer
 while accumulator > dt

```

The reason this is getting stuck is because dt is 0, which (depending on the value of accumulator) can either completely skip this block or get trapped inside this block because you are never actually modifying t or accumulator. I'm assuming you are setting your accumulator value to frameTime somewhere, because it's supposed to be the amount of time elapsed since the last action.

```
 {
  game_physics(t, dt) //how is the deltatime helping me in my physics?
  t += dt
  accumulator -= dt
 }

```

The value of `dt` is crucial to your physics, however, it should be a known constant value and shouldn't need to be passed around. This is what it means to have a fixed timestep. With that in mind, every calculation you do needs a timestep for things like acceleration updating velocity and velocity updating position, and any other timed physical effects counting down or up.

```
 alpha = accumulator / dt
  game_render(alpha) // I dont know what im supopsed to do with this.
}

```

`alpha` is the fraction of time you have left in a timestep and allows you to either interpolate results or simply save the accumulator for the next loop.

The effect of all of this is that you have fixed your timestep, but are allowing for the fact that your main loop won't run at exact multiples of your timestep. That's the point of the accumulator. It stores exactly how much time has passed since the last executed timestep, which is why you subtract a dt from it after every physics update; it is the mechanism by which you are *actually* fixing the timestep. There are also multiple ways in which to calculate current time, so I'll leave that up to you -- QueryPerformanceCounter does work (I'd think), but so would any number of other methods. The bottom line is that you want a fairly accurate timestamp or things can start to get jerky.

---
Tags: physics, mathematics, software-engineering
---


# Question
Title: How can I simulate the effects of network latency to test my lag compensation?
I am trying to observe the effects of lag compensation in my game by increasing my ping to 200+, adding loss, and by the limiting bandwidth to simulate wide area network delays using Network Emulator for Windows Toolkit.

It seems no matter the degree of latency that is applied I never see any visual changes to my character position on the server, as the lag compensation / interpolation method is always able to predict my exact position.

But in real-world situations, players connected from a far distance away do have poor synchronization. How can I produce the *same* poor synchronization that I witness in players connected from a far distance so that I can choose the ideal lag compensation technique for my game.

For reference, I'm making this game using Unity 3D and it's a fast-paced, twitch shooter game.

# Answer
> 2 votes
I actually wanted to add this as a comment, but since I need reputation to comment...

A long time ago, back in Unity 4, I tried using the Network Emulation and got this feeling that my prototype was handling lag and packet losses very nicely. Then I discovered that there are unclear circumstances in which the Network Emulation adds to nothing - in fact, even with emulation set, the game was behaving as if running with 100% near-instant delivery. I don't know if this problem persists in Unity 5 nor the reasons that made the emulation not kick in, but this might be exactly what's happening to you.

The way was to simulate packet losses and latency by myself - the game was simple so I just added another component between the network and game components with the responsibility of "dropping" messages or "delaying" them. For your game that might be too much work to do, so you might want to dig around software like Clumsy (https://jagt.github.io/clumsy/) - I DIDNT TEST IT - and/or use virtual machines.

Side note, latency is bad, but your real enemy when using many compensation techniques will be the Jitter.

# Answer
> 0 votes
The Unity editor had built in network emulation which introduces latency and packet loss and slower download/upload speeds: http://docs.unity3d.com/Manual/NetworkEmulation.html

---
Tags: networking, interpolation, lag, latency
---


# Question
Title: How to create a camera that follows the player?
I have a javascript game where I use a tile grid somewhat like this:

```
var tiles = [
[0, 0, 0],
[0, 1, 0],
[0, 0, 1]
];

```

I want a camera to follow the player and when the player moves off the map, shift the camera over to new tiles. Even better just a map that follows the player.

# Answer
> 0 votes
In general, when you want to follow player, the way to do this is to update camera's position after every player position update:

```
for( var i = 0; i < DIMENSIONS; i++ ) {
    camera.position[i] = player.position[i] + camera.offset[i];
}

```

Offset should be set in your game editor or in game init, as the difference between player and camera initial positions ( which were set up in game editor ):

```
for( var i = 0; i < DIMENSIONS; i++ ) {
    camera.offset[i] = camera.position[i] - player.position[i];
}

```

# Answer
> 0 votes
Add map and objects to a container.

Example: container.x = -camera.x (illusion camera moved through world)

a = OBJECT location

b = TARGET location

t = decimal between 0 and 1

```
function lerp(a, b, t)
  return a + (b - a) * t
end

```

Return INTEGER to move from a to b. As a is closer to b, integer will become smaller (deceleration).

camera.x = 100

target.x = 200

spring = 0.6

```
integer = lerp(camera.x,target.x,spring)
camera.x += integer
container.x = -camera.x

```

---
Tags: camera
---


# Question
Title: Check collision with rectangle and pixels
I have done a function to check the pixels collision against two animated sprites, and now I need to check a "`Rectangle` x animated sprite" collision, but I have no idea how to do this. I tried to create a new `Texture2D` for the rectangle and fill it with some color, but it is expensive to do at every frame when I need check the collisions.

This is my function to check the pixel colisions of two animated sprites:

```
public static bool IntersectCharacterSpritePixels(CharacterSprite spriteA, CharacterSprite spriteB)
{
    if (!spriteA.BoundingBox.Intersects(spriteB.BoundingBox))
    {
        return false;
    }

    // Get the current frame for each sprite
    var rectangleA = spriteA.GetCurrentFrameRectangle();
    var rectangleB = spriteB.GetCurrentFrameRectangle();

    // Create the color data based on the current frame
    Color[] dataA = new Color[rectangleA.Width * rectangleA.Height];
    spriteA.TextureRegion.Texture.GetData(0, new Rectangle(rectangleA.X, rectangleA.Y, rectangleA.Width, rectangleA.Height), dataA, 0, dataA.Length);

    Color[] dataB = new Color[rectangleB.Width * rectangleB.Height];
    spriteB.TextureRegion.Texture.GetData(0, new Rectangle(rectangleB.X, rectangleB.Y, rectangleB.Width, rectangleB.Height), dataB, 0, dataB.Length);

    // Find the bounds of the rectangle intersection
    var boundingA = spriteA.BoundingBox;
    var boundingB = spriteB.BoundingBox;

    int top = Math.Max(boundingA.Y, boundingB.Y);
    int bottom = Math.Min(boundingA.Bottom, boundingB.Bottom);
    int left = Math.Max(boundingA.Left, boundingB.Left);
    int right = Math.Min(boundingA.Right, boundingB.Right);

    // Check every point within the intersectionbounds
    for (int y = top; y <bottom; y++)
    {
        for (int x = left; x < right; x++)
        {
            // Get the color of both pixels at this point
            Color colorA = dataA[(x - boundingA.X) + (y - boundingA.Y) * rectangleA.Width];
            Color colorB = dataB[(x - boundingB.X) + (y - boundingB.Y) * rectangleB.Width];

            // Ifboth pixels are not completely transparent,
            if (colorA.A != 0 && colorB.A != 0)
            {
                // then an intersection has been found
                return true;
            }
        }
    }

    // No intersection found
    return false;
}

```

# Answer
A couple of things:

You should avoid creating, and recreating the Color arrays. Find a way to create them once and avoid GC.

The textures are not generated by the GPU and won't force it to synchronize with the CPU, but you should avoid copying and/or sifting through it on the CPU if at all possible.

As a direct answer to your question, the Rectangle class, which you are already using, has an Intersects() methods. For rectangle vs. sprite, just loop through a sprite's color array like you are now and, if the color at X,Y is not fully transparent, check the rectangle for intersection with X,Y. If the result isn't Disjoint, they collided.

---

Instead, research using the OcclusionQuery class in conjunction with the stencil buffer. Doing so should allow you to check way more intersections, way faster, and can handle any intersection between anything renderable. The stencil buffer makes sure the GPU only processes the pixels within the intersection (far fewer than the combined CPU BoundingBox). It also processes each of those pixels at the same time in parallel ("instant").

**Edit:**
An OcclusionQuery design would go something like this:

1. Disable color writes
//No need to actually draw anything
2. Enable alpha testing
//Fully transparent pixels are omitted
3. Enable stencil buffer
4. Set stencil buffer to always pass, incrementing
//Write 1 to the stencil for every modified pixel
5. Render the first texture (or filled rectangle)
//Fill stencil
6. Set stencil buffer to pass when GREATER than 0
//Omit pixels where stencil=0
7. Begin query
//Start counting the number of colors "written"
8. Render the second texture
9. End query
//Stop counting
10. \[Do other stuff to give the GPU time to work\]
11. Read query result

The result contains the integer number of overlapping, non-transparent, pixels.
Any non-zero value is a collision.

Remember to re-enable color writes.
> 2 votes

---
Tags: xna, collision-detection, monogame
---


# Question
Title: How to detect a sign-out from Google Play achievements or leader-boards UI?
I am making an android game in Unity (C#), in which I've used the Google's official plugin for Google Play Services. My question is how to detect that a player has clicked on sign out button on Google's UI

# Answer
> 1 votes
Well, in Unity you can check GPGS and Game Center login status via `Social.localUser.authenticated`. This will return a `bool` value that indicates either the user is logged in or not. `true` for logged in and `false` for logged out.

```
void PrintUserStatus()
{
    if (Social.localUser.authenticated)
        print("Player is logged in");
    else
        print("Player is not logged in");
}

```

---
Tags: unity, google-play-services
---


# Question
Title: Libgdx Box2D random positions and intervals falling bodies
I need to make that objects fall from the top of the screen random intervals and positions. Here's my code where I create lot of objects and add them to ArrayList

```
private void createBalls() {
        BodyDef ballBodyDef = new BodyDef();
        ballBodyDef.type = BodyDef.BodyType.DynamicBody;

        CircleShape shape = new CircleShape();
        shape.setRadius(10/Constants.PPM);
        shape.setPosition(new Vector2(w/4/ Constants.PPM, 5));

        FixtureDef fd = new FixtureDef();
        fd.density = 1;
        fd.friction = 0.5f;
        fd.restitution = 0.5f;
        fd.shape = shape;

        do {
            float rand = MathUtils.random(-2.0f, 2f);
            shape.setPosition(new Vector2(w/4/ Constants.PPM + rand, 5));
            fd.shape = shape;

            bodyArrayList.add(world.createBody(ballBodyDef));
            bodyArrayList.get(bodyArrayList.size() - 1).createFixture(fd);
        } while (bodyArrayList.size() < 100);

        shape.dispose();
    }

```

this code works fine (except that all objects fall at single time). So is it possible to make that objects would fall at different time?

# Answer
You can call the `createBalls` at some interval from your game loop, and possibly pass in how many balls you want it to create.

For example; public class YourGame extends Game {

```
    private long lastTime;

    @Override
    public void create() {
    }

    @Override
        public void render() {
        if (TimeUtils.nanoTime() - lastTime; > 1000000000) createBalls(10);

        // Render the world
    }

    private void createBalls(int ballCount) {
        BodyDef ballBodyDef = new BodyDef();
        ballBodyDef.type = BodyDef.BodyType.DynamicBody;

        CircleShape shape = new CircleShape();
        shape.setRadius(10 / Constants.PPM);
        shape.setPosition(new Vector2(w / 4 / Constants.PPM, 5));

        FixtureDef fd = new FixtureDef();
        fd.density = 1;
        fd.friction = 0.5f;
        fd.restitution = 0.5f;
        fd.shape = shape;

        for (int i = 0; i < ballCount; ++i) {
            float rand = MathUtils.random(-2.0f, 2f);
            shape.setPosition(new Vector2(w / 4 / Constants.PPM + rand, 5));
            fd.shape = shape;

            Body body = world.createBody(ballBodyDef));
            body.createFixture(fd);
        }

        shape.dispose();
        lastDropTime = TimeUtils.nanoTime();
    }
}

```

Alternatively, if you just want 100 balls created once and then have them fall you could create them with a random `y` value in the position that extends beyond the screen. That would make the balls seem to fall at different times;

```
private void createBalls() {
    BodyDef ballBodyDef = new BodyDef();
    ballBodyDef.type = BodyDef.BodyType.DynamicBody;

    CircleShape shape = new CircleShape();
    shape.setRadius(10 / Constants.PPM);
    shape.setPosition(new Vector2(w / 4 / Constants.PPM, MathUtils.random(-100f, 5f));

    FixtureDef fd = new FixtureDef();
    fd.density = 1;
    fd.friction = 0.5f;
    fd.restitution = 0.5f;
    fd.shape = shape;

    do {
        float rand = MathUtils.random(-2.0f, 2f);
        shape.setPosition(new Vector2(w / 4 / Constants.PPM + rand, 5));
        fd.shape = shape;

        bodyArrayList.add(world.createBody(ballBodyDef));
        bodyArrayList.get(bodyArrayList.size() - 1).createFixture(fd);
    } while (bodyArrayList.size() < 100);

    shape.dispose();
}

```
> 1 votes

---
Tags: libgdx, box2d
---


title: Bullet only removing closest enemy

text:
# Question
Title: Bullet only removing closest enemy
I'm having an issue with my collision detection code. I'm making a top down shooter and when I shoot, the bullet will only destroy an enemy if it's the closest enemy. The bullet will go right through the 2nd closest enemy.

Here is my code:

```
// Iterate through bullets, if bullet ccollides with enemy, remove both
for (int i = 0; i < Bullet.Bullets.Count; i++)
{
    if (Collisions.IsColliding(
      (int)Bullet.Bullets[i].position.X, (int)Bullet.Bullets[i].position.Y,
      Bullet.sprite.Width, Bullet.sprite.Height,
      (int)Enemy.Enemies[i].position.X, (int)Enemy.Enemies[i].position.Y,
      Enemy.sprite.Width, Enemy.sprite.Height))
    {
        Enemy.Remove(Enemy.Enemies[i]);
        Bullet.Remove(i);
    }
}

```

And here is my is colliding method:

```
public static bool IsColliding(int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2)
{
    return x1 < x2 + w2 &&
           x2 < x1 + w1 &&
           y1 < y2 + h2 &&
           y2 < y1 + h1;
}

```

Can anyone please point me in the right direction? Thank you.

# Answer
You are only checking th i-th bullet with the enemy of the same index and not with every enemy there is.

You should do something like this

```
for (int i = 0; i < Bullet.Bullets.Count; i++)
{
    for (int j = 0; j < Enemy.Enemies.Count; j++)
    {
        if (Collisions.IsColliding(
          (int)Bullet.Bullets[i].position.X, (int)Bullet.Bullets[i].position.Y,
          Bullet.sprite.Width, Bullet.sprite.Height,
          (int)Enemy.Enemies[j].position.X, (int)Enemy.Enemies[j].position.Y,
          Enemy.sprite.Width, Enemy.sprite.Height))
        {
            Enemy.Remove(Enemy.Enemies[j]);
            Bullet.Remove(i);
        }
    }
}

```

This way you will check every bullet with every enemy, it's not the most efective way of doing it but it should work if you don't have tons of bullets and enemies at the same time.
> 2 votes

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


# Question
Title: Detecting Left and Right Mouse clicks on UI Text objects that are dynamically created
So, in my game I create a bunch of UI Text game objects dynamically (in the C# script), but I just can not find out how to properly detect Left and Right mouse clicks on these UI Text that were dynamically generated.

I have tried adding Colliders and Colliders2D to the UI Text game objects for raycasting, but with no luck. And differently from UI Button, it seems that Unity has left proper "on mouse click" functions out from UI Text

Can anyone help out on how to accomplish that?

PS: no, I can not use UI Buttons, it has to be Texts. And the UI Texts have to be generated on the fly, not in the editor

# Answer
> 1 votes
I suppose that when you create the UI Text objects, you are adding to them a RectTransform component, just like I answered you here: How to dynamically create an UI text Object in Unity 5?. Knowing that, one simple and very efficient solution for what you want is to detect if the desired mouse button was pressed AND if mouse cursor is over the RecTransform of the UI Text.

To do that last bit, you just get the 4 vertices of the UI Text's RectTransform at Screen Space and then run a plain and usual test of whether the mouse cursor position (which is given in Screen Space by default) is contained within the 2D rectangle formed by those 4 vertices.

Something like this:

```
//retrieves the position of the UI Text's RectTransform:
float rectX = yourUItextgo.GetComponent<RectTransform>().anchoredPosition.x;
float rectY = yourUItextgo.GetComponent<RectTransform>().anchoredPosition.y;

//retrieves half width and half height of the UI Text's RectTransform:
float rec_width = yourUItextgo.GetComponent<RectTransform>().sizeDelta.x*0.5f;
float rec_height = yourUItextgo.GetComponent<RectTransform>().sizeDelta.y*0.5f;

//calculates the 4 vertices of the UI Text's RectTransform:
Vector2 _X = new Vector2(rectX - rec_width, rectY - rec_height );
Vector2 _Y = new Vector2(rectX + rec_width, rectY - rec_height );
Vector2 _W = new Vector2(rectX - rec_width, rectY + rec_height );
Vector2 _Z = new Vector2(rectX + rec_width, rectY + rec_height );

//here you call any function that detects whether a 2D points is within a 2D rectangle:
bool wasoverUIText = YourPointInRectangleFunction(Input.mousePosition , _X, _Y, _W, _Z);

```

Then, it becomes easy to detect a left, right, middle or even double-clicks: you just have to put the usual `Input` inside an `if`condition, followed by `&& wasoverUIText)`.

For the right mouse button, for example, that would mean:

```
if(Input.GetMouseButtonDown(1) && wasoverUIText )
{
    //run whatever you intended to run when the UI Text is clicked
}

```

# Answer
> 0 votes
Attach this script to the "UI Text prefab" that you are creating Dynamically.

```
using UnityEngine;
using UnityEngine.EventSystems;

public class TextClick : MonoBehaviour,IPointerClickHandler
{
    #region IPointerClickHandler implementation
    public void OnPointerClick (PointerEventData eventData)
    {
    if (eventData.button == PointerEventData.InputButton.Left) // Checks if left mouse button is pressed
      {
        print ("left");
      }
    else if (eventData.button == PointerEventData.InputButton.Right) // checks if right mouse button is pressed
      {
        print ("Right");
      }

    }
    #endregion

}

```

---
Tags: unity, gui, mouse, text
---


# Question
Title: How to organize level blocks in an Infinite runner
I'm working on an Infinite Runner game. I have created many level blocks(sections) with different obstacles and pick-ups for the player. They are positioned and placed manually, in such a way, to give the player a challenge. I thought that making every block a prefab and placing every obstacle and coin as a child of that prefab is going to be easier for me..because the player is going to run and these block prefabs are going to be randomly spawned in front of him and then destroyed after the player gets past them. It worked well.

Then I wanted to make a change on my coins. So naturally I took the coin prefab, made the changes, and applied them hoping that the change is going to take effect on all my blocks... Well..it didn't. Then I found out that nested prefabs don't work in Unity, so now I have to reorganize everything again?

How do I create organized level blocks, and then make them randomly spawn in front of the player? Is there any other option besides prefabs? Don't tell me I have to use a script for every block?

Think about Banana Kong, Temple Run, Subway Surfers. The levels seem random, but it's an organized randomness with certain portions of the level repeating themselves. That's what I'm trying to do, and I don't know how to organize it...

# Answer
Please take a look at this; if I'm on the right track, I'll expand it and add narrative.

You'll draw a single terrain prefab over and over, having it morph based on the descriptions fed in via the per-instance buffer.

Example description elements:

```
Matrix worldMatrix;
UINT terrainTextureArrayIndex;

```

Pickups can be handled similiarly. Draw a single cube in many places with different appearance.

Example pickup description elements:

```
Matrix worldMatrix;
UINT pickupType = PICKUP_COIN; //Which texture(s)
UINT elapsedTime; //Used for animation

```
> 1 votes

# Answer
1. Design some level blocks with combination of obstacles coins etc. (Maintain a parent child relation).
2. Make a LevelGeneator script which will contain a Array of Transform or Gameobject.
3. Assign the level blocks to the Script object in inspector.
4. Randomly take a Transform and give it some force and make SetActive(true).

If its still not clear, let me know, I will provide the code
> 0 votes

---
Tags: unity, 2d, architecture, level-design
---


# Question
Title: Having trouble going from the menu I created w/ Android normally to my LibGDX game file
So I wanted to use Android Studio to create the menu for my game so I created a button with an onClick method that included the Intent i and startActivity(i) but when I clicked the button the app would just crash on me

# Answer
> -1 votes
LibGDX has an AndroidLauncher file that's located in the Android java folder that opens up the game file in the core folder but you have to add it to the android manifest for it to work

---
Tags: android, libgdx
---


# Question
Title: Swept AABB Collision and Response Problems
I am working on a simple 2D game, and I am having problems with collision detection and response. I am using code adapted from this article: http://www.gamedev.net/page/resources/\_/technical/game-programming/swept-aabb-collision-detection-and-response-r3084

I have tried many alterations to the code, but I cannot seem to get it to behave as expected. My algorithm attempts to detect collisions between a single moving entity and one or more static blocks. It uses the following logic:

> 1. Broad-phase collision detection:
>
> Create an AABB that encapsulates the movement of an entity, then detect overlaps with the AABBs of static blocks. Add those collision events to a list, and sort that list by time of impact.
>
> 2. Narrow-phase collision detection:
>
> Calculate the time of impact and collision normal for each collision event, and move the entity to the proper position outside of each static block. Use the collision normal to slide the entity to the proper position.

Here is the code I am using to calculate the time of impact for a collision event:

```
float Collision::collisionTime(QVector2D &normal)
{
    // _one is our moving entity, _two is a static block

    // Calculate the distance to entry and distance to exit
    QVector2D distToEntry, distToExit;
    QVector2D velocity = _one->velocity();

    if (velocity.x() > 0)
    {
        distToEntry.setX(_two->rect().left()  - _one->rect().right());
        distToExit.setX( _two->rect().right() - _one->rect().left());
    }
    else
    {
        distToEntry.setX(_two->rect().right() - _one->rect().left());
        distToExit.setX( _two->rect().left()  - _one->rect().right());
    }

    if (velocity.y() > 0)
    {
        distToEntry.setY(_two->rect().top()    - _one->rect().bottom());
        distToExit.setY( _two->rect().bottom() - _one->rect().top());
    }
    else
    {
        distToEntry.setY(_two->rect().bottom() - _one->rect().top());
        distToExit.setY( _two->rect().top()    - _one->rect().bottom());
    }

    // Calculate the entry and exit times.
    QVector2D entry, exit;
    if (velocity.x() == 0)
    {
        entry.setX(-std::numeric_limits<float>::infinity());
        exit.setX(std::numeric_limits<float>::infinity());
    }
    else
    {
        entry.setX(distToEntry.x() / velocity.x());
        exit.setX(distToExit.x() / velocity.x());
    }

    if (velocity.y() == 0)
    {
        entry.setY(-std::numeric_limits<float>::infinity());
        exit.setY(std::numeric_limits<float>::infinity());
    }
    else
    {
        entry.setY(distToEntry.y() / velocity.y());
        exit.setY(distToExit.y() / velocity.y());
    }

    if (entry.x() > 1.0)
    {
        entry.setX(-std::numeric_limits<float>::infinity());
    }
    if (entry.y() > 1.0)
    {
        entry.setY(-std::numeric_limits<float>::infinity());
    }

    // Find the earliest / latest times of collision.
    float entryTime = std::max(entry.x(), entry.y());
    float exitTime  = std::min(exit.x(),  exit.y());

    // If there was no collision...
    if ((entryTime > exitTime) ||
        (entry.x() < 0 && entry.y() < 0))
    {
        normal = QVector2D(0, 0);
        return 1.0;
    }

    // If there was a collision,
    // set the proper normal and return.
    if (entry.x() >= entry.y())
    {
        if (distToEntry.x() < 0)
        {
            normal = QVector2D(1.0, 0);
        }
        else
        {
            normal = QVector2D(-1.0, 0);
        }
    }
    else
    {
        if (distToEntry.y() < 0)
        {
            normal = QVector2D(0, 1.0);
        }
        else
        {
            normal = QVector2D(0, -1.0);
        }
    }
    return entryTime;
}

```

And here is the code that generates a collision response:

```
bool Collision::resolve()
{
    QVector2D collisionNormal;

    // Calculate the collision time and normal.
    float time = collisionTime(collisionNormal);

    // Move to the point of collision.
    _one->setPos(_one->pos().x() + _one->velocity().x() * time,
                 _one->pos().y() + _one->velocity().y() * time);

    float remainingTime = 1.0 - time;

    // If remainingTime > 0, there was a collision.
    // Apply a slide effect.
    if (remainingTime > 0)
    {
        float dotProduct = (_one->velocity().x() * collisionNormal.y() + _one->velocity().y() * collisionNormal.x()) * remainingTime;
        _one->setVelocity(QVector2D(dotProduct * collisionNormal.y(), dotProduct * collisionNormal.x()));
        return true;
    }
    return false;
}

```

Now, the problems--In the following situations, the moving entity stops completely. I had expected it to slide horizontally in both cases. I have been unable to determine if it is a problem with the collision detection code, or the collision response code:

```
1.
     |¯¯¯¯¯¯¯¯|
     | Entity |
     |        |
     |________|
|¯¯¯¯¯¯¯¯|     ⇲ velocity
| Block  |
|        |
|________|

2.
|¯¯¯¯¯¯¯¯|
| Entity |
|        | ⇲ velocity
|________|
|¯¯¯¯¯¯¯¯‖¯¯¯¯¯¯¯¯|
| Block  ‖ Block  |
|        ‖        |
|________‖________|

```

# Answer
> 1 votes
First, this line:

```
float dotProduct = (_one->velocity().x() * collisionNormal.y() + _one->velocity().y() * collisionNormal.x()) * remainingTime;

```

is calculating the wrong quantity (it should be x * x + y * y).

Second, if you want to slide, you simply need to set the component of the velocity parallel to the normal of the collision surface to 0, and retain the velocity orthogonal to that. Ie, you should be doing

```
// Apply a slide effect.
if (remainingTime > 0)
{
    // This should be a negative value since they are anti-parallel before collision
    // also notice the lack of time in this calculation, so the units of dotProduct will be velocity
    float dotProduct = (_one->velocity().x() * collisionNormal.x() + _one->velocity().y() * collisionNormal.y());

    // now we need to set the velocity in terms of the previous velocity
    // if you do the math, you'll find that v_perp (the sliding velocity) = v + (v.n)*collisionNormal
    // the + comes from the fact that collisionNormal is anti-parallel to the velocity component in the normal direction
    // if it's not then you don't have a collision
    _one->setVelocity(_one->velocity() + dotProduct * collisionNormal);
    return true;
}

```

---
Tags: c++, collision-detection, algorithm, aabb
---


title: Unity test/Play mode window problem

text:
# Question
Title: Unity test/Play mode window problem
I tried to find an answer to his problem but i wasn't successful. When i press play to test my game, instead of the play mode going to the Game tab and play the game there, with all the unity tabs and options still on the screen, it goes almost full screen, all of the unity window goes to the game mode and i can't see anything but the game, to see the scene, options, etc.. again i need to stop the play mode. For example, if i want to test triggers in play mode, i can't because all i see is the game window. How can i test the game just in the Game tab? Perhaps i changed some setting.

I'm not sure if im explaining my problem correctly.

Thank you

# Answer
It is the feature of unity. There is a small little surprising button does exist at the top of Game tab, called "Maximize on Play". You can disable this feature by pressing it again.
> 1 votes

---
Tags: unity
---


# Question
Title: HTML Canvas Makes Everything Bolder On Right Side
For some strange and sudden reason, my canvas seems to make lines thicker and darker on the right ~1/4-ish. I have tried multiple browsers and different computers and they all have the same rendering issue EXCEPT for Chrome for Android. Here is a screenshot of the test lines that I drew:

And here is the code in case anyone was wondering:

```
var canvas = document.getElementById("foreground");
var context = canvas.getContext("2d");
var height = 450;
var width = 600;

canvas.width = width;
canvas.height = height;

function draw() {
  context.clearRect(0, 0, canvas.height, canvas.width);

  for (var i = 1; i < (800 - (0 * 2)) / 35; i++) {
    context.beginPath();
    context.moveTo(200 + (i * 35) + 0 | 0, 50 + 0 | 0);
    context.lineWidth = 1;
    context.lineTo(200 + (i * 35) + 0 | 0, 50 + 800 - 0 | 0);
    context.strokeStyle = "black";
    context.stroke();
    context.closePath();
  }

  for (var i = 1; i < (800 - (0 * 2)) / 35; i++) {
    context.beginPath();
    context.moveTo(200 + 0 | 0, 50 + (i * 35) + 0 | 0);
    context.lineWidth = 0.5;
    context.lineTo(200 + 800 - 0 | 0, 50 + (i * 35) + 0 | 0);
    context.strokeStyle = "black";
    context.stroke();
    context.closePath();
  }

  requestAnimationFrame(draw);
}

draw();
```

```
<div id="container">
  <canvas id="foreground"></canvas>
</div>
```

# Answer
`context.clearRect()` has a method signature of:

```
context.clearRect(x, y, width, height)

```

In your code, however, you are passing the height and width in the incorrect positions. Changing your call to

```
context.clearRect(0, 0, canvas.width, canvas.height)

```

fixes the issue.

MDN clearRect() documentation.
> 3 votes

---
Tags: rendering, html5, html-canvas
---


# Question
Title: How do I detect image clicks in Dark GDK?
I am trying to determine if an image has been clicked, using the Dark GDK game engine. I've found no methods in the engine that do this.

I would rather not brute force this with a large nested if/else structure. I was thinking of setting up a container that takes an object which records the mouse position when clicked, as well as a bool value to determine if the image has already been clicked.

I apologize for not adding any example code here; I don't know how I would go about setting something like that up.

# Answer
The way I would do it is detect the `mousex` and `mousey` position when it is clicked and then use something like the following:

```
if (xmouse > something AND xmouse < something_else)
  AND (ymouse > whatever AND ymouse < whatever_else)
THEN
  pic_clicked = True

```

`something`, `something_else`, `whatever` and `whatever_else` would be the `x` and `y` `top`, `bottom`, `left` and `right` co-ordinates of the image.

This is just pseudo code and not GDK specific.
> 0 votes

---
Tags: c++, dark-gdk
---


title: Compute shader in directx 12?

text:
# Question
Title: Compute shader in directx 12?
I was just wondering since directx 12 is out does it have a compute shader like directx 11??? Ive tried searching and didn't find anything.

# Answer
> 1 votes
Yes it does and they work the same way as in DX11

---
Tags: directx
---


# Question
Title: How can i call a thing a lot of times (game: dodger)
Hey I am new to coding and i want to know how to get the same thing to hapen until i "say" stop.

The game is that you need to dodge stuff that is falling, i was thinking that i could use a while loop and Push the object in the list like the following:

```
Var i = 0;
Var theObjects = [ ];
While ( i < 100)
{
    theObjects.push();
    i ++;
}

```

But that would be 1. Spawn them at the same time and the it would be 2. This only works for x amount of time.

How can i make the object spawn til i say stop and spawn at difrent times

Sorry for my bad english.

# Answer
> How can i make the object spawn til i say stop and spawn at difrent times

You have two different questions there. One is how you can make the object spawn until you say it to stop. The other is how to spawn them at different times.

It is not very clear to me what you exactly mean regarding the first part. If you just wanna learn how to make a "while loop" that does run infinitely until you say it to stop, then this can be easily achieved with a minor change in your while loop code. For instance:

```
Var stopwhile = false;
Var theObjects = [ ];
While ( stopwhile == false)
{
    theObjects.push();

    //here you include your own code to test when stopwhile should be set to true, which will then make the while-loop stop
}

```

However, I have a suspicion that you might be making a confusion. If you are running your while-loop inside your general main game loop (the one that re-starts after each frame ends and is usually a function called "Update()" or "main()"), then there is your problem.

The main game loop (or the update() function) loops trough frames. It means, each game frame is an iteration of the loop. It means that if you put your while-loop inside the main loop, then each frame will only end after the whole while-loop runs. Consequently, every frame all spawning will happen in the same frame, giving the impression that they happened at the same time.

If that is the case, then you have to abandon the while-loop approach altogether. The simpler way to do it is to just create a function that does whatever you intend to, for example spawn balls and call it inside the main game loop after a given amount of time has passed:

```
var repeat_the_code = true;
var timecounter = 0;
var spawn_delay = 50; // or the value you prefer
var max_spawn_delay = 100; // or the value you prefer

function Spawn() {
    //here you put the code you want to repeat, like the `theObjects.push();` in your original example
    timecounter = 0; // you reset the counter every time a new spawn is generated
    spawn_delay = Math.random(max_spawn_delay); //when each spawn is finished, you randomly set how much delay you desire before the next spawn
}

Update(){  //or the name it may have in your engine, but basically it is the function that repeats throughout the game, with each game frame being its iterations

  if(repeat_the_code && timecounter == spawn_delay) { //if the timer has reached the desired delay value AND the trigger repeat_the_code is still set to 'true', then a new spawn occurs by calling the corespondent function:
          Spawn(); //this is how you call the spawn function that you defined before
  }
}

```

That way, you will both be able to stop spawning whenever you want (just create a condition that sets `repeat_the_code = false`) and also to spawn at randomly different amounts of time.

EDIT: as for a more concrete example, using your engine framework something like the following might work:

```
  var max_bollar = 10;
  var i = 0;
  var timecounter = 0;
  var bollarcounter = 0;
  var spawn_delay = 200;
  var min_spawn_delay = 25;
  var max_spawn_delay = 500;

  function spawn(i)
  {
  var boll = {x: random(totalWidth), y: random(totalHeight)}
  circle( boll.x, 10, 10, "blue");
  timecounter = 0;
  bollarcounter++;
  max_spawn_delay = ( random(max_spawn_delay - min_spawn_delay ) + min_spawn_delay );
  }

  function update()
  {
    timecounter += 1;
    if(timecounter == spawn_delay && bollarcounter < max_bollar) spawn(bollarcounter);
  }

```
> 0 votes

# Answer
This will execute the same function every 2 seconds change the delay to change how often the function is called and set carryOn to false to stop calling the function every "delay" number of milliseconds ...

```
var delay = 2000;
var maxDelay = 4000;
var carryOn = true;
setTimeout(stuffToDo, delay);

function stuffToDo() {
  //whatever code you want here
  DoPart1();
  DoPart2();

  if(carryOn) {
      delay = Math.round(Math.random() * maxDelay);
      setTimeout(stuffToDo, delay);
  }
}

function DoPart1() { ... }

function DoPart2() { ... }

```
> 0 votes

---
Tags: javascript, game-mechanics
---


# Question
Title: Sending high scores to a web server in an open source game
I've never dealt with sending/receiving data from web servers in my games, so I absolutely have no idea how to do this. I tried googling for a good solution but couldn't find anything satisfying.

I currently get data from my web server by doing a HTTP request that gets the contents of a JSON text file stored on the server, and parses them in-game.

I do not know how to "write" high scores to the server, and even worse I do not know how to avoid people sending what they want to the server since the game is open source.

How is this usually done?

# Answer
Here is several things you can do to validate score sent by player :

1. Before sending data to server, sign/encrypt it using a key (hidden in executable). Server will check if signature is valid.

Note : this can be easily defeated by reverse engineering the game, but it is a lot harder to break than when sending plain text information without any encryption.
2. Every time player make an action that affect score (shooting a target) or change game state in a significant way (lose a life) record it somewhere (with a timestamp). When sending score, also send these events. Server will process the events and check if sent score *appears* to be possible (eg: by summing individual scores).

Note : this can also be defeated because (after understanding how it works) user can create fake events.
3. Record *every* user input received by the game (mouse clicks + cursor position, keystrokes, ...). For each event, also record the frame number (aka `tick`) when event occured. Send all that information to server with score. Because sent information contain everything player have done and server have an exact copy of game, server will be able to replay the whole game from beginning to the end and then compare scores (score sent by player and simulated score).

Note : this require server and client to have *exactly* same version of game, and your game to be predictable (no matter the framerate, or if random elements are involved in gameplay, ...). See When should I use a fixed or variable time step? for more info. This technique make it hard to fake big scores because only way to create these events is actually to "play" the game. This is, anyway, ineffective against `bots`.

Solutions proposed in 2) and 3) can be combined with 1).
> 2 votes

# Answer
Just do it. You can make a PHP (or whatever) server which accepts high scores and adds them to a database (text file, sqlite? Whatever).

If someone wants to cheat, they will. As the game is client-side in Javascript, they could simply modify the game code so they get 1000000 points for killing the first badguy, or whatever.

In my experience, people aren't likely to waste their time reverse engineering your protocol and submitting bogus scores. If they do, you'll probably spot them, right?
> 0 votes

# Answer
The simplest approach would be to send an HTTP request with the high score and other relevant data in a query string in the URL. Then you can handle it on the server with a script to whatever data method you like.

Since the game is open source there is no real way to obfuscate the method for sending the scores. You could try to employ some way on the server but in my experience if someone wants to crack it. They will. Fiddler and the source code would make it an exercise in futility. Good luck
> 0 votes

# Answer
it sounds like you are using HTTP GET to post the scores you would use HTTP POST
> -2 votes

---
Tags: open-source, web, online, leaderboards, security
---


# Question
Title: Using Vertex Buffer Object in OpenGL, how do I fix the display driver being blocked when my window loses focus?
I'm creating a 3D display for a big object. I've managed to display it with OpenGL primitives, but it is very slow. I am using C#, powered by the TAO Framework.

I want to use the Vertex Buffer Object (VBO) optimization, but when I lose focus on the OpenGL window (even without hiding it), the display driver is blocked for some seconds; enough to shutdown my screens.

How do I fix this?

---

This is the code to load the object in to a VBO buffer:

```
void LoadVBO()
{
    Gl.glGenBuffersARB(1, out VBOObject.VBOid);
    Gl.glBindBufferARB(Gl.GL_ARRAY_BUFFER, VBOObject.count);

    Gl.glBufferDataARB(Gl.GL_ARRAY_BUFFER_ARB,
        (IntPtr)(VBOObject.count * 3 * sizeof(float)), VBOObject.xyz,
        Gl.GL_STATIC_DRAW_ARB);
}

```

The working code:

```
Gl.glEnableClientState(Gl.GL_VERTEX_ARRAY);
LoadVBO();

// Black Background
Gl.glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
// Depth Buffer Setup
Gl.glClearDepth(1.0f);
// The Type Of Depth Testing (Less Or Equal)
Gl.glDepthFunc(Gl.GL_LEQUAL);
// Enable Depth Testing
Gl.glEnable(Gl.GL_DEPTH_TEST);
// Select Smooth Shading
Gl.glShadeModel(Gl.GL_SMOOTH);
// Set Perspective Calculations To Most Accurate
Gl.glHint(Gl.GL_PERSPECTIVE_CORRECTION_HINT, Gl.GL_NICEST);
// Enable Textures
Gl.glEnable(Gl.GL_TEXTURE_2D);
// Set The Color To White
Gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

Gl.glBindBufferARB(Gl.GL_ARRAY_BUFFER_ARB, VBOObject.count);
Gl.glVertexPointer(3, Gl.GL_FLOAT, 0, null);

while (!toquit)
{
    // Loop That Runs While done = false
    DrawGLScene();
    // Process Events
    Application.DoEvents();
    bool res = Gdi.SwapBuffers(hDC);
}

Gl.glDisableClientState(Gl.GL_VERTEX_ARRAY);

```

The display method:

```
 private void DrawGLScene()
    {
        Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT);
        Gl.glLoadIdentity();

        Glu.gluLookAt(212, 60, 194, 186, 55, 171, 0, 1, 0);

        Gl.glRotatef(xv, 1f, 0f, 0f);
        Gl.glRotatef(yv, 0f, 1f, 0f);
        Gl.glRotatef(zv, 0f, 0f, 1f);

        Gl.glDrawArrays(Gl.GL_LINES, 0, VBOObject.count);
    }

```

# Answer
> 0 votes
yeah, thank you, But still the problem. ...

here, my code: https://drive.google.com/open?id=0B\_j9kxE7xxc2S0RaQkx1Ty1waVE

the "Tableau X.txt", "Tableau Y.txt" and "Tableau Z.txt" contains the x, y,z datas for each profiles.

# Answer
> 0 votes
So, I've done some code updates.

I've tested the TaoFrameWork test program for VBO (essai.cs). this one works.

next I wanted to adapt it to my case. But nothing is displayed (display.cs).

I've tried to center my object, to change the scale, but nothing.....

Here, the link to the source files.

http://www.developpez.net/forums/d1567177/applications/developpement-2d-3d-jeux/api-graphiques/opengl/csharp-taoframework-utilisation-vbo/

Thank you.

---
Tags: c#, opengl, vbo
---


# Question
Title: Mesh slicing/knifing with multiple planes
I have a ginormous mesh which I want to cut with multiple planes. For simplicity I want to know how to cut a mesh with single plane and repeat the logic.

Consider a `X-Y` plane of coords `(1,1,0,0) = (a,b,c,d)`, from the equation `ax+by+cz+d`, which is the equation of the plane.

How shall I use this information to cut a mesh? Any help will be invaluable.

# Answer
Find all triangles that intersect with the plane, split them into two polygons and triangulate the polygons.

If you want a cap, enumerate all vertices generated from the slice and create a cap to fill the possibly concave planar hole.

The devil is in the edge cases where you go exactly through vertices and edges, so make sure to robustly handle those.
> 2 votes

---
Tags: c++, mathematics, 3d-meshes, mesh
---


# Question
Title: C++ & OpenGL - Bad orthographic projection matrix?
So I'm trying to render 2D text in my Game Engine using programmable pipeline.

Normally I'm using perspective projection matrix but for UI elements I'm trying to create orthographic projection matrix with near plane -1 and far plane 1.

I was using deprecated solution before with `gluOrtho2D` and it was something like this:

```
        SDL_Color color = { (U8)textsToRender.at(i)->color->r, (U8)textsToRender.at(i)->color->g, (U8)textsToRender.at(i)->color->b };

        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        gluOrtho2D(0, Window::getWidth(), Window::getHeight(), 0);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();

        glDisable(GL_DEPTH_TEST);
        glEnable(GL_TEXTURE_2D);
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

        GLuint texture;
        glGenTextures(1, &texture);
        glBindTexture(GL_TEXTURE_2D, texture);

        TTF_Font *m_font = TTF_OpenFont(textsToRender.at(i)->file->getPath().c_str(), textsToRender.at(i)->size);

        if(!m_font && isGameRunning() == true) Error::throwError((char*) "Cannot load font file!");

            SDL_Surface *sFont = TTF_RenderText_Blended(m_font, textsToRender.at(i)->msg.c_str(), color);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, sFont->w, sFont->h, 0, GL_BGRA, GL_UNSIGNED_BYTE, sFont->pixels);

 glBegin(GL_QUADS);
                {
                    glTexCoord2f(0.0f, 0.0f); glVertex2f(textsToRender.at(i)->pos->x, textsToRender.at(i)->pos->y);
                    glTexCoord2f(1.0f, 0.0f); glVertex2f(textsToRender.at(i)->pos->x + sFont->w, textsToRender.at(i)->pos->y);
                    glTexCoord2f(1.0f, 1.0f); glVertex2f(textsToRender.at(i)->pos->x + sFont->w, textsToRender.at(i)->pos->y + sFont->h);
                    glTexCoord2f(0.0f, 1.0f); glVertex2f(textsToRender.at(i)->pos->x, textsToRender.at(i)->pos->y + sFont->h);
            }
            glEnd();

        glDisable(GL_BLEND);
        glDisable(GL_TEXTURE_2D);
        glEnable(GL_DEPTH_TEST);

        glMatrixMode(GL_PROJECTION);

        glDeleteTextures(1, &texture);
        TTF_CloseFont(m_font);
        SDL_FreeSurface(sFont);

```

And with this code everything is OK. I received really nice text, I could change size, even text color.

But because I'm creating my engine with programmable pipeline (GLSL shaders) solutions only I decided to create new shader program, 2 shader files and my own orthographic projection matrix "recipe".

Here is my code after changes:

```
        SDL_Color color = { (U8)textsToRender.at(i)->color->r, (U8)textsToRender.at(i)->color->g, (U8)textsToRender.at(i)->color->b };
        glDisable(GL_DEPTH_TEST);
        glEnable(GL_TEXTURE_2D);
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

        GLuint texture;
        glGenTextures(1, &texture);
        glBindTexture(GL_TEXTURE_2D, texture);

        TTF_Font *m_font = TTF_OpenFont(textsToRender.at(i)->file->getPath().c_str(), textsToRender.at(i)->size);

        if(!m_font && isGameRunning() == true) Error::throwError((char*) "Cannot load font file!");

        SDL_Surface *sFont = TTF_RenderText_Blended(m_font, textsToRender.at(i)->msg.c_str(), color);

        std::vector<F32> positions;

        positions.push_back(textsToRender.at(i)->pos->x);
        positions.push_back(textsToRender.at(i)->pos->y);
        positions.push_back(textsToRender.at(i)->pos->x + sFont->w);
        positions.push_back(textsToRender.at(i)->pos->y);
        positions.push_back(textsToRender.at(i)->pos->x + sFont->w);
        positions.push_back(textsToRender.at(i)->pos->y + sFont->h);
        positions.push_back(textsToRender.at(i)->pos->x);
        positions.push_back(textsToRender.at(i)->pos->y + sFont->h);

        std::vector<F32> textureVectors;

        textureVectors.push_back(0.0f);
        textureVectors.push_back(0.0f);
        textureVectors.push_back(1.0f);
        textureVectors.push_back(0.0f);
        textureVectors.push_back(1.0f);
        textureVectors.push_back(1.0f);
        textureVectors.push_back(0.0f);
        textureVectors.push_back(1.0f);

        U32 vaoID = VertexArrayObject::loadToVAO(positions, textureVectors);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, sFont->w, sFont->h, 0, GL_BGRA, GL_UNSIGNED_BYTE, sFont->pixels);

        uiShader->start(); //

        uiShader->loadProjectionMatrix(projectionMatrixOrtho); //LOADS projection matrix to my shader program

        glBindVertexArray(vaoID);
        glEnableVertexAttribArray(0);
        glEnableVertexAttribArray(1);

        glActiveTexture(GL_TEXTURE0);

        glDrawArrays(GL_TRIANGLES, 0, 4);

        glDisableVertexAttribArray(0);
        glDisableVertexAttribArray(1);
        glBindVertexArray(0);

        uiShader->stop();

        glDisable(GL_BLEND);
        glDisable(GL_TEXTURE_2D);
        glEnable(GL_DEPTH_TEST);

        glMatrixMode(GL_PROJECTION);

        glDeleteTextures(1, &texture);
        TTF_CloseFont(m_font);
        SDL_FreeSurface(sFont);

```

Recipe for my orthographic matrix:

> ```
> Matrix4 *projectionMatrix = new Matrix4();
>
> F32 left = 0.0f;
> F32 right = (F32) Window::getWidth();
> F32 bottom = (F32) Window::getHeight();
> F32 top = 0.0f;
> F32 near = -1.0f;
> F32 far = 1.0f;
>
> F32 xO = 2.0f / (right - left);
> F32 yO = 2.0f / (top - bottom);
> F32 zO = -2.0f / (far - near);
>
> F32 tx = -(right + left) / (right - left);
> F32 ty = -(top + bottom) / (top - bottom);
> F32 tz = -(far + near) / (far - near);
>
> projectionMatrix->m00 = xO;
> projectionMatrix->m10 = 0.0f;
> projectionMatrix->m20 = 0.0f;
> projectionMatrix->m30 = 0.0f;
> projectionMatrix->m01 = 0.0f;
> projectionMatrix->m11 = yO;
> projectionMatrix->m21 = 0.0f;
> projectionMatrix->m31 = 0.0f;
> projectionMatrix->m02 = 0.0f;
> projectionMatrix->m12 = 0.0f;
> projectionMatrix->m22 = zO;
> projectionMatrix->m32 = 0.0f;
> projectionMatrix->m03 = tx;
> projectionMatrix->m13 = ty;
> projectionMatrix->m23 = tz;
> projectionMatrix->m33 = 1.0f;
>
> ```

Vertex Shader:

> ```
> #version 400 core
>
> in vec2 position;
> in vec2 textureVector;
>
> out vec2 textureCoords;
>
> uniform mat4 projectionMatrix;
>
> void main(void)
> {
>   textureCoords = textureVector;
>   gl_Position = projectionMatrix * vec4(position, 0.0, 1.0);
> }
>
> ```

And Fragment Shader:

> ```
> #version 400 core
>
> in vec2 textureCoords;
>
> out vec4 out_Color;
>
> uniform sampler2D sampler;
>
> void main(void)
> {
>   out_Color = texture(sampler,textureCoords);
> }
>
> ```

And what I receive on my screen instead of nice font like before is something like this:

I'm using GLEW, SDL2 with SDL2\_image and SDL2\_ttf.

Everything is OK with my VAO, shader program. I guess here is something wrong with my orthographic projection matrix, I checked my code 100 times and didn't found any mistake. Maybe wrong recipe?

# Answer
Opengl has column major orderibg system, so when you put the tx to the m03 position, you put it in the first column's last row. Transpose it.
> 2 votes

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


title: Weird squares everywhere

text:
# Question
Title: Weird squares everywhere
So in unity I have some weird squares on surfaces of certain objects, which are buildings represented by planes:

I don't know what causes it, I tried changing some settings in lighting and material, but couldn't fix it. This only occurs with one object which is a few planes representing buildings temporarily. The lighting is baked (one directional light). Here's the screenshots of lighting and materials tab:

Does anyone know what could be the problem and how I can fix it? Ask for more information if needed. Thanks.

EDIT: The buildings were imported from blender.

# Answer
I solved the problem! It can easily be fixed by setting generate lightmap UV to true in the import settings of the model.
> 1 votes

---
Tags: unity, lighting, materials, lightmap
---


# Question
Title: How do I calculate a vertex's position on the CPU?
I'm creating light processor and I need light position and vertex position after translating, rotating and scaling (to calculate distance between them to check if light is affecting my vertex somehow).

But my question is how to properly multiply my position in Vector3 with transformation matrix to get real vertex position in the world?

To calculate it in GLSL I just simply use something like this:

```
vec4 vertexInWorldPosition = transformMatrix * vec4(vertexPosition,1.0);

```

But how properly do that with my vertex (Stored in Vector3) and Matrix4 in C++ code? Do I need to multiply each row or column by my original `vertexPosition` stored to Vector4? I have no idea what to do.

# Answer
> 2 votes
You do exactly the same thing. You have an initial (mode space) position as a 3-component vector, turn it into a 4-component vector by setting the 4th component to 1.0.

Then you have the model-to-world transformation matrix in a 4x4 matrix instance, so you can perform matrix multiplication of the 4x4 matrix with the 4x1 "matrix" that is the vector. Most math libraries that provide matrix and vector types also implement this multiplication operation for you, allowing you to write 'result = transformMatrix * initialVector' or similar.

If your math library does not you'll need to implement the operation yourself. The product of a matrix 'M' and a (column) vector v (on the right, as in your example) is equivalent to a series of dot products of the rows of M with v. The new x component is dot(row 0, v). The new y component is dot(row 1, v), and so on.

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


# Question
Title: Move a 2D point to a target (first accelerate towards the target, then decelerate)
I have a point entity that I would like to move to a target point (in 2D).

I think I would like it to accelerate away from its current position (the point could already have a velocity), to some maximum velocity, and decelerate as it approaches the target, eventually coming to a stop on the target.

I think both the acceleration and deceleration should have constant magnitudes, but given that the entity can have a velocity, which may not be in the same direction as the target, the direction of the acceleration/deceleration could be different every frame.

I am not coding in any particular language or framework yet, and just want to know if this is easy/possible. Am I describing something that is quite common (like a targeted missile that stops at the target/an AI controlled space ship in a game)? If it is hard, is there another way I can achieve the same kind of motion?

# Answer
> 7 votes
As zehelvion stated, you need to know when to begin slowing down. However, simply reaching the halfway point time-wise is not precise, especially if the acceleration is different from the deceleration. In fact working out the time just so we can calculate that is more tedious than using the distance.

The distance that you need to decelerate fully can be given by the following physics formula:

2ad = Vf^2 - Vi^2

a is the acceleration (or in this case, the deceleration or traction), d is the distance we need to work out, Vf is the final speed (in this case, it's 0), Vi is the speed before accelerating, in this case it's our normal velocity. After working out the formula (and considering that the deceleration is negative, but for the sake of simplicity, we will use a positive value in the code) gives us the following:

d = Vi^2 / 2a, which makes the code as following:

```
deaccDistance = velocity^2 / (2 * DECELERATION);

```

Lets define 'x', 'y' as the position of the chasing entity and 'targetX', 'targetY' as the position of the target. dt is the time that passed since the last frame. ACCELERATION, DECELERATION, TOPSPEED are constants

```
deltaX = targetX - x;
deltaY = targetY - y;
distance = Math.Sqrt(deltaX^2 + deltaY^2);
decelDistance = velocity ^ 2 / (2 * DECELERATION);

if (distance > decelDistance) //we are still far, continue accelerating (if possible)
{
    velocity = Math.Min(velocity + ACCELERATION * dt, TOPSPEED);
}
else    //we are about to reach the target, let's start decelerating.
{
    velocity = Math.Max(velocity - DECELERATION * dt, 0);
}

cx += velocity * cosangle * dt;
cy += velocity * sinangle * dt;

```

If the target is stationary, you can calculate the cosangle and sinangle beforehand, otherwise you will need to calculate them on every frame.. for reference:

```
angle = Math.Atan2(deltaY,deltaX);
cosangle = Math.Cos(angle);
sinangle = Math.Sin(angle);

```

This would work, if the dt is a constant, however it will vary from a frame to another, so we have to add a check before the code:

```
if distance < (velocity * dt) then      --we almost reached it, skip the rest
{
    x = targetX;
    y = targetY;
    velocity = 0;
    return
}

```

And that's pretty much it, you can add a variable named finished and call it as appropriate to be absolutely sure that it doesn't break, or make more checks to see if the lastdistance was bigger than the current distance and in that case you can snap the object to the target, but usually, this is not required.

# Answer
> 5 votes
You need to know when to begin slowing down.

To compute this, you need to know your current speed and the distance from the target.

Let `V` be your current speed and `d` be the current distance. We'll also need `a` which is your acceleration and deceleration rates and `t` which is the time it takes to stop at the current speed.

You'll begin slowing down when the following condition is met:

```
t = V / a;
if ( V * t / 2.0 >= d ) //begin to slow down

```

You can find more about deceleration here.

Otherwise you'll want to speed up towards the target. Lets define `cx`, `cy` as the position of the chasing entity and `tx`, `ty` as the position of the target. `dvx` and `dvy` will be the desired velocity for the one chasing and `vx`, `vy` will be the current velocity.

```
deltaX = tx - cx;
deltaY = ty - cy;
distance = sqrt(deltaX^2 + deltaY^2);
dvx = deltaX * maxSpeed / distance; //Normalizing and multiplying by max speed
dvy = deltaY * maxSpeed / distance;
deltaX = dvx - vx;
deltaY = dvy - vy;
diffSize = sqrt(deltaX^2 + deltaY^2);
ax = maxAcc * deltaX / diffSize;
ay = maxAcc * deltaY / diffSize;

vx += ax * dt // dt is the time that passed since the last frame
vy += ay * dt //

```

---
Tags: 2d, motion
---


# Question
Title: Can 2D Rigidbodies detect collisions with 3D Box colliders?
I would like to know if `Rigidbody2D`'s can detect collisions with 3D Box colliders and/or normal `rigidbodies`.

---

I seem to have a problem where my `2D Colliders` don't detect collision with my `3D Cubes`. :/

# Answer
No, the 2D and 3D physics worlds in Unity are treated completely separately, using different internal physics engines (2D is using Box2D, 3D uses a variant of PhysX)

If you need 3D physics, then the simplest way is to handle all of your physics objects as 3D, with appropriate constraints to keep the 2D objects from rotating out of their intended viewing plane.
> 3 votes

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