# Question
Title: How to fix model matrices colliding in vertex shader?
I am new to OpenGL programming and I'm writing some basic code to display a few objects onto a screen.

I have a pyramid shape that I'm displaying, as well as a box shape that I am displaying. The pyramid shape is a class (C++), and each pyramid object creates it's own VBO (storing the points/colours). The same thing goes for the box.

The problem I'm having is that I have two shapes, and the shapes use the same vertex shader. Since I apply a model matrix for each object in the shader, the model matrix gets set for one object, but then when the other object goes to display itself it overwrites the model matrix for the previous object with it's own. So only one object has the correct model matrix after they are all done their display method.

I am also using hierarchical transformations to attach objects to each other. I have the root object storing the view/projection matrices, and the children of the hierarchy tree storing their individual model transformations. When a child wants to display itself, it walks up the tree to compute all the transformations it needs to do to itself. The problem also applies here, since the last child to be displayed will be the one whose model matrix is applied in the vertex shader.

I can't seem to figure out how to differentiate in the shader which MVP matrix to apply to which vertex. I think I'm missing something very basic here but I can't seem to figure it out... Any help would make my life a lot easier!

Edit: Is it possible that the shader is overwriting the MVP matrix in between glDrawArrays()/glDrawElements() calls?

# Answer
Typically, the MVP matrix (along with any other matrices you might be using) are specified using uniforms, for example:

```
#version 330
in vec3 iPosition;  // input from vertex attribute
out vec3 vPosition; // output to fragment shader
// other inputs/outputs for colors, texture coordinates, etc. as needed

uniform mat4 uMVP;

void main()
{
    vPosition = uMVP * iPosition;
    // ...
}

```

The term uniform stems from the fact that they cannot be changed while a `glDraw*` call is running; their value is uniform across all vertices being drawn. Therefore, each object that has a distinct transform needs to have it's own draw call, and you use the `glUniformMatrix` API to set the correct transform prior to each draw call. You'll also need to query the location of the uniform after compiling your shader program (using `glGetUniformLocation`).

```
GLint mvp_location;

void initShaderProgram()
{
    // Generate & Compile shaders, check for errors
    // ...

    GLuint program_id = glCreateProgram();
    // Link program, check for errors
    // ...

    mvp_location = glGetUniformLocation(program_id, "uMVP");
}

void drawObject(float* mvp /* ... */ )
{
    // Ensure correct program, VAO, etc are bound.
    // ...

    glUniformMatrix4fv(mvp_location, 1, false, mvp);
    glDrawElements( /* ... */ );
}

```

There are alternatives to this approach which allow greater performance by batching multiple objects into a single draw call (for example, by pre-computing the world-space coordinates of static meshes on the CPU so that the same view/projection matrix can be used for them all), but it sounds like you're not anywhere close to pushing the limits of your driver or GPU, so don't worry about that unless you have to.
> 1 votes

---
Tags: opengl, shaders, matrix, vertex-buffer
---


# Question
Title: Why are leaderboards often separated between platforms?
I noticed that many games (if not most or all) are employing different leaderboards for different platforms. For example, different leaderboard for iOS and Android. Different leaderboard for Xbox and PS.

I can't see the logic behind that. After all, let's say iPhone and Android are sending the data to a single service/system.

Is it a business decision?

# Answer
Different platforms may result in different scores even with the same skills. For example because you were forced to have less enemies on the Android game due to performance issues.

This (along with the control difference) is why console and PC games generally never play together (either multiplayer or through leaderboards).
> 29 votes

# Answer
It might be a business decision. It might be a convenience decision. It really depends; the only thing you can say for sure is that it's the decision of the people involved in making the game (developer, publisher, platform vendor, et cetera).

You're *assuming* that "iPhone and Android are sending the data to a single service," which isn't always the case. The iOS APIs for leaderboards (Game Center) send data to Apple. Google's Leadersboards service sends data to Google. A developer may choose to use the platform-provided leaderboard API for his or her game because it's easier or cheaper for them (despite the fact that they'll need to build an implementation against both APIs). They may also choose to do it because those APIs offer better device integration than 3rd party APIs might, and they feel this creates a better experience for the player.

There are various third-party leaderboard APIs a game might adopt. Some of these may have additional cost (either as retail products or in the form of requiring the developer to provide and pay for the hosting of the leaderboard databases). They may not look or feel as integrated with the device, either. Those potential disadvantages have to be weighed against the advantage of only having to write against the API once (in theory), reducing development time.

The particular balance of all those factors (and more) will all play into the decision of which particular method to use for leaderboards; it basically depends on the developer's needs and wants.
> 18 votes

# Answer
If you use GameCenter's built-in leaderboard functionality to avoid having to implement leaderboards yourself, then you end up with seperate leaderboards when you make your Android version.

For me, it's a decision that goes like this: "I don't want to reimplement a leaderboard server just so I can have cross-platform leaderboards."
> 3 votes

# Answer
Most of the answers here cover the reasons why.I would like to mention when it comes to iOS and Android development a new situation arises.

Apple favors games and apps that use native iOS features. You are more likely to be featured if you are using Game Center for leaderboards. They highly recommend it and may even contact you with offers to promote you on the front page if you switch to it.

Android is the same way with Google Play and Google+. So having two separate leader boards a GameCenter and GooglePlay/Google+ version is highly advantageous to get featured and promote your game.
> 1 votes

# Answer
New member, can't comment but I agree with these answers. As a gamer I would like to see my "global" rank on a game that is cross platform. However as a Software Developer I understand why they are separate.

The first thing that comes to mind is the fact that they are different companies (what @JoshPetrie mentioned). Microsoft has their own servers and databases while Sony has theirs. Since they are separate companies with separate data hubs, there will naturally be separate rankings. They would have to work together and share a system that houses both datasets. That doesn't seem likely because that would mean that Microsoft has access to Sony's data and vice versa. And nothing is more personal to a company than their data.

Let's assume however that this were true and there was a shared database where all the rankings are together. I bet the rankings wouldn't be as evenly distributed as one might think and it would be due to hardware differences which result in a big difference in the ability for a user to master the game. Each gaming console is a different environment, or medium, in which the user can play the game. Based on its design, the environment creates limitations on "how well" the user can play with respect to users on a different medium.

The biggest example I can think of (and was already mentioned in another answer) is the difference between Console and PC.

Let's use Team Fortress 2 as an example. The console version is played with a hand held controller. Usually the contoller is operated with both thumbs and index fingers (4 digits, at least how I play). The PC version uses the keyboard with W-A-S-D movement, other keys for functions, and the mouse (6 digits used at once, by my count).

Not only are the "controllers" different, but, like @ratchetfreak said, each system has its own degree of performance power. So the exact same game could be slow and laggy on Xbox, but very fluid on PS or PC.

Also PC's can be upgraded as opposed to console games which are static until the new version comes out. Which then the leaderboards would be different since a newer version of the game is required (which means a different server and database and blah blah...)

On top of these differences, you also have system settings like mouse speed which can be increased higher than joystick sensitivity (which, for me at least, makes up the biggest advantage of PC gaming).

Many other factors are involved I'm sure but these were the first things that came to mind when I saw this question. Sorry for being long winded, I got excited and blurbed it out as fast as I could.
> 0 votes

---
Tags: leaderboards
---


# Question
Title: Should actors in a game be responsible for drawing themselves?
I am very new to game development, but not to programming.

I am (again) playing around with a Pong type game using JavaScript's `canvas` element.

I have created a `Paddle` object which has the following properties...

* `width`
* `height`
* `x`
* `y`
* `colour`

I also have a `Pong` object which has properties such as...

* `width`
* `height`
* `backgroundColour`
* `draw()`.

The `draw()` method currently is resetting the `canvas` and that is where a question came up.

Should the `Paddle` object have a `draw()` method responsible for its drawing, or should the `draw()` of the `Pong` object be responsible for drawing its actors (I assume that is the correct term, please correct me if I'm incorrect).

I figured that it would be advantagous for the `Paddle` to draw itself, as I instantiate two objects, `Player` and `Enemy`. If it were not in the `Pong`'s `draw()`, I'd need to write similar code twice.

What is the best practice here?

Thanks.

# Answer
Having actors draw themselves is not a good design, for two main reasons:

1) it violates the single responsibility principle, as those actors presumably had another job to do before you shoved render code into them.

2) it makes extension difficult; if every actor type implements its own drawing, and you need to change the way you draw *in general*, you may have to modify a lot of code. Avoiding overuse of inheritance can alleviate this to some extent, but not completely.

It's better for your renderer to be handling the drawing. After all, that's what it means to be a renderer. The renderer's draw method should take a "render description" object, which contains everything you need to render a thing. References to (probably shared) geometry data, instance-specific transformations or material properties such as color, et cetera. It then draws that, and doesn't care what that render description is supposed to "be."

Your actors can then hold on to a render description they create themselves. Since actors are typically logic processing types, they can push state changes to the render description as needed -- for example, when an actor takes damage it could set the color of its render description to red to indicate this.

Then you can simply iterate every visible actor, enqeue their render descriptions into the renderer, and let it do its thing (basically; you could generalize this even further).
> 52 votes

# Answer
The Visitor Pattern can be useful here.

What you can do is have a Renderer interface that knows how to draw each object and a "draw yourself" method in each actor that determines which (specific) renderer method to call, e.g.

```
interface Renderer {
    void drawPaddle(Player owner, Rectangle position);
    // Note: the Renderer chooses the Color based on which player the paddle belongs to

    // Also drawBackground, drawBall etc.
}

interface Actor {
    void draw(Renderer renderer);
}

class Paddle implements Actor {
    void draw(Renderer renderer) {
        renderer.drawPaddle(this.owner, this.getBounds());
    }
}

```

This way it is still easy to port to another graphics library or framework (I once ported a game from Swing/Java2D to LWJGL and was very glad I had used this pattern instead of passing a `Graphics2D` around.)

There is another advantage: The renderer can be tested separately from any actor code
> 18 votes

# Answer
In your example you'd want to have the Pong objects implement draw() and render themselves.

Though you won't notice any significant gains in a project of this size, generally separating game logic and their visual representation (rendering) is a worthwhile activity.

By this I mean you'd have your game objects that can be update()'d but they have no idea of how they're rendered, they're concerned only with the simulation.

Then you'd have a PongRenderer() class that has a reference to a Pong object, and it then takes charge of rendering the Pong() class, this could involve rendering the Paddles, or having a PaddleRenderer class to take care of it.

The separation of concerns in this case is a fairly natural one meaning your classes can be less bloated, and it's easier to modify how things are rendered, it no longer has to follow the hierarchy that your simulation does.
> 2 votes

# Answer
If you were to do it in the `Pong`'s draw(), you wouldnt' need to duplicate the code -- simply call the `Paddle`'s draw() function for each of your paddles. So in your `Pong`'s draw() you'd have

```
humanPaddle.draw();
compPaddle.draw();

```
> -1 votes

# Answer
Every object should contain its own draw function which should be called by the game update code or draw code . Like

```
class X
{
  public void Draw( )
  {
     // Do something
  }
}

class Y
{
  public void Draw( )
   { // Do Something
   }
}

class Game
{
  X objX;
  Y objY;

  @Override
  public void OnDraw( )
  {
      objX.Draw( );
      objY.Draw( );
  }
}

```

This is not a code but just for showing , how drawing objects should be done.
> -1 votes

---
Tags: rendering, game-loop, html-canvas
---


# Question
Title: Invalid coordinates returned by glutMouseFunc()
I am using GLUT's `glutMouseFunc()` function to retrieve the coordinates of mouse clicks. I want to move the object on that coordinate to another coordinate. But when I click on the object the coordinates returned by `glutMouseFunc()` are different than the original.

```
windowWidth=1250;
windowHeight=1000;

void onMouse(int button, int state, int x, int y);

int main(int argc, char** argv) {

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE);
    glutInitWindowSize(1250, 1000);
    glutCreateWindow("OpenGL - First window demo");
    // ...
    glutMouseFunc(onMouse);
    // ...
    glutMainLoop();
    return 0;
}

void onMouse(int button, int state, int x, int y) {
    flag++;
    if (state != GLUT_DOWN && button!=GLUT_LEFT_BUTTON)
        return;

    GLbyte color[4];
    GLfloat depth;
    GLuint index;

    glReadPixels(x, windowHeight + y - 1, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, color);
    glReadPixels(x, windowHeight + y - 1, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);
    glReadPixels(x, windowHeight + y - 1, 1, 1, GL_STENCIL_INDEX, GL_UNSIGNED_INT, &index);

    printf("Clicked on pixel %d, %d, color %02hhx%02hhx%02hhx%02hhx, depth %f, stencil index %u\n", x, y, color[0], color[1], color[2], color[3], depth, index);
    move();
}

```

Inside my render function i have set the window coordinates to 0,0 using glortho

```
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, windowWidth, windowHeight, 0, 0, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

```

If my object is at `(550, 900)`, `onMouse()` reports it as `(556, 650)` while if I click on an object which is at position `(375, 475)` the `onMouse()` returns `(376, 342)`.

Basically there is a huge difference between the value of y axis returned by the function.

How can i get the correct screen coordinates?

# Answer
> 1 votes
The documentation explicitly says that the sizes you provide to GLUT are hints to the windowing system. The actual size of the window has to be determined either via the reshape callback or by querying for the actual client area size, if available.

Your orthographic projection is thus probably not 1:1 mapping to pixels.

---
Tags: opengl, glut
---


title: Text width phaser.js

text:
# Question
Title: Text width phaser.js
Does phaser have any function that returns the width of the text or if not, how can I center text inside rectangle I've drawn?

Thanks!

# Answer
> 3 votes
It's just `Text.width`. Text objects have most the same properties as Sprites, so you can set their anchor, rotate them, etc.

---
Tags: javascript, phaser
---


title: Execute native ios code in unity

text:
# Question
Title: Execute native ios code in unity
I want to execute native iOS code in unity. For this I have added two files in /plugins/ios.

1. ViewController.h
2. ViewController.m

Code for each file represented as under.

**ViewController.h**

```
@interface ViewController

-(void)sampleMethod;
@end

```

**ViewController.m**

```
#import "ViewController.h"

@implementation ViewController

-(void)sampleMethod
{
     NSLog(@"Sample Method Execute");
}
@end

```

For C# file I have added following code

```
[DllImport("__Internal")]
private static extern void sampleMethod();

```

and call to above method

```
sampleMethod();

```

When I am export project for iOS, xCode give me following error that I can't able to understand.

I can't able to understand how to solve this problem? Please give some suggestion here.

**EDIT :**

I have added extern keyword in my .m file after reading some suggestion.

```
#import "ViewController.h"

@implementation ViewController

extern "C"
{
   -(void)sampleMethod
   {
        NSLog(@"Sample Method Execute");
   }
}
@end

```

But in xCode now I am getting **Expected Identifier or '('** at the line of extern keyword line. So what to do next?

# Answer
> 1 votes
Right now I'm not in a place to go over your code thoroughly, but at a glance I'm wondering if you need to declare your code with C linkage as explained here:

```
extern "C" {
  float FooPluginFunction();
}

```

# Answer
> 0 votes
I'm not sure if this answers your question but:

> iOS of course doesn't run Java since iOS requires all code to be compiled AOT to xcode / objective c. When you build an iOS project, Unity just creates an xcode project which then can be built using xcode. You are free to change the code that Unity has cross compiled, however you have to do this every time when you rebuild the xcode project from Unity.
>
> It's probably possible to compile a native library for iOS that you can add to the Unity project itself as "plugin". However i'm not familiar with iOS development.

http://answers.unity3d.com/questions/816358/executing-native-ios-code-in-unity.html

---
Tags: unity, ios, xcode, plugin
---


# Question
Title: How can you check your users' unlocked achievements (Google Play Game Services)?
Is it possible to see how many of your users have unlocked certain achievements on the Google Play Developer console? This information would be very useful. I guess that one could achieve this through integration with Google Analytics but I was wondering if there was a simpler way to get this data.

# Answer
The Google Play Games service actually provides an API for doing just that. I have provided an example for querying the state of all achievements in this answer on SO - but I will provide that information here as well.

The following method will retrieve and iterate **all** achievements, and should be run **asynchronously** (using `AsyncTask` or in a separate thread):

```
public void loadAchievements()  {
   GameHelper mHelper;        // GameHelper should be accessible for this to work

   boolean fullLoad = false;  // set to 'true' to reload all achievements (ignoring cache)
   float waitTime = 60.0f;    // seconds to wait for achievements to load before timing out

   // load achievements
   PendingResult p = Games.Achievements.load( mHelper.getApiClient(), fullLoad );
   Achievements.LoadAchievementsResult r = (Achievements.LoadAchievementsResult)p.await( waitTime, TimeUnit.SECONDS );
   int status = r.getStatus().getStatusCode();
   if ( status != GamesStatusCodes.STATUS_OK )  {
      r.release();
      return;           // Error Occurred
   }

   // process the loaded achievements
   AchievementBuffer buf = r.getAchievements();
   int bufSize = buf.getCount();
   for ( int i = 0; i < bufSize; i++ )  {
      Achievement ach = buf.get( i );

      // here you now have access to the achievement's data
      String id = ach.getAchievementId();  // the achievement ID string
      boolean unlocked = ach.getState == Achievement.STATE_UNLOCKED;  // is unlocked
      boolean incremental = ach.getType() == Achievement.TYPE_INCREMENTAL;  // is incremental
      if ( incremental )
         int steps = ach.getCurrentSteps();  // current incremental steps
   }
   buf.close();
   r.release();
}

```

This assumes you are using `BaseGameUtils` (and `mHelper` is already connected). The API documentation should provide any further information you need. You can also do this with callbacks if you don't want to manually run it asynchronously.

You should of course change the internals of the loop which are processing the results to do something more useful, since the example only illustrates how to access the information. For your question you may only need to check for unlocked achievements and count them.
> 2 votes

# Answer
# Callback approach

Apart from some small errors in the accepted answer I prefer the callback approach to get the results so we don't have to perform all of this in the background.

To simplify comparison I used the same `GameHelper`. This `GameHelper` object is a singleton containing a reference to the `GoogleApiClient` object.

Updated example code:

```
    GameHelper mHelper;        // GameHelper should be accessible for this to work
    boolean fullLoad = false;  // set to 'true' to reload all achievements (ignoring cache)

    // load achievements
    Games.Achievements.load( mHelper.getGoogleApiClient(), fullLoad ).setResultCallback(new ResultCallback<Achievements.LoadAchievementsResult>() {
        @Override
        public void onResult(Achievements.LoadAchievementsResult loadAchievementsResult) {
            for( Achievement achievement : loadAchievementsResult.getAchievements() ){

                // here you can work with the achievement objects
                // ...
                boolean unlocked = (achievement.getState() == Achievement.STATE_UNLOCKED);
            }
        }
    });

```
> 2 votes

---
Tags: android, google-play, google-play-services
---


title: Stock Game Ranking System

text:
# Question
Title: Stock Game Ranking System
I'm currently making a stock game where the user can buy fictional stocks. Upon registering the user will receive 1.000.000 DKK (danish krone) to spend on stocks.

I'm trying to create a ranking system, but I found this to be more difficult than I had imagined.

By giving the user 1.000.000 at the start of the game it's hard to evaluate how good a player is doing when compared to an inactive player.

Thing is, a player could sign up and receive the money and then do nothing else and (probably) do better than a lot of the people who get negative. In this way, inactive players are rewarded for doing nothing and will look better on the scoreboard.

Is there a good way to avoid this?

# Answer
> 1 votes
Rank players only by the amount that they receive after investing the money.

That way you rank they by their profit score.

# Answer
> 1 votes
I would rank people by their net worth, starting credits and all. If the value of the player's stocks have gone down, so be it. It's still useful to know if you're doing better than players that have just started.

---
Tags: ranking
---


# Question
Title: Pygame Surfaces: which (and when) do I need to .convert()?
I'm a bit puzzled about pygame's `Surface.convert()`:

It's common sense that I should convert a surface after loading an image to it (presumably a jpg/png/etc file), but what about surfaces that I only use pygame's "primitives" like `pygame.draw.circle()` or `Surface.fill()`?

Official documentation is very vague about it: it says *"fastest format for blitting. It is a good idea to convert all Surfaces before they are blitted many times"*.

Consider this simple ball-bouncing code:

```
import pygame

position = [100, 200]
velocity = [7, 17]
radius = 50

pygame.init()
clock = pygame.time.Clock()

screen = pygame.display.set_mode((800, 600))
background = pygame.Surface(screen.get_size())
screen.blit(background, (0,0))

ball = pygame.Surface(2*[radius*2])
pygame.draw.circle(ball, (0, 255, 0), 2*(radius,), radius)
bounds = (screen.get_size()[0] - 2 * radius,
          screen.get_size()[1] - 2 * radius)
rect = ball.get_rect()
rect.x = position[0]
rect.y = position[1]

done = False
while not done:
    for event in pygame.event.get():
        if event.type in [pygame.QUIT, pygame.KEYDOWN]:
            done = True

    for i in [0, 1]:
        position[i] += velocity[i]
        if position[i] < 0 or position[i] > bounds[i]:
            velocity[i] *= -1

    screen.blit(background, rect)
    rect.x = position[0]
    rect.y = position[1]
    screen.blit(ball, rect)
    pygame.display.update()
    clock.tick(60)

pygame.quit()

```

It has 3 surfaces: `screen`, `background` and `ball`. They are blitted a lot, as source or dest. Would any of these surfaces benefit from a `.convert()`?

If yes, then should I simply append a `.convert()` when creating *any* surface? Like

```
surface = pygame.Surface(...).convert()

```

A *lot* of pygame tutorials do that, even for a background that is just `.fill()`'ed. But this feels so... redundant. Why isn't the so called "fastest pixel format" the default when creating new surfaces?

And if such surfaces would benefit from a convert, *when* should I do so? After a `.fill()`, before, or it doesn't matter? Is once enough or should I "reconvert" after each draw? What if I load an image?

References and sources about proper `.convert()` usage are highly appreciated, thanks!

# Answer
> 7 votes
`convert()` is used to convert the `pygame.Surface` to the same pixel format as the one you use for final display, the same one created from `pygame.display.set_mode()`. If you don't call it, then every time you blit a surface to your display surface, a pixel conversion will be needed - this is a per pixel operation, very slow - instead of a series of memory copies. You may not feel the difference on your octa-core development PC, but when you're on constrained devices like handhelds (or just bring up your CPU counter), it makes a big difference. The recommendation is to do it as early as possible, preferably when you load or create your assets, or at least outside your game loop.

Why don't surfaces match the display by default? Good question, as it's an obvious newbie trap. I don't know the considerations that went into this design, but one issue is that you don't know until run time what your display pixel format will be. The user might specify 16-bit pixels and it might end up as some wacky format like BGR565. If you do some image processing at low bit depths, you might get results that you weren't expecting.

Another issue is that your display format most likely doesn't have alpha. If all surfaces matched the display format by default, then every time you try to blit semi-transparent surfaces, or ones loaded from PNGs or GIFs with transparent pixels, you end up with images over a black rectangle. If you need transparency, you can use `convert_alpha()`, which is marginally faster than unconverted but not nearly as fast as `convert()` \- alpha blending is expensive. Pygame can't tell whether you need alpha surfaces or not, so you need to specify yourself.

Of course all this may be moot because if you really cared about performance, you would use

* a faster language than Python
* a framework that was GPU accelerated (instead of pygame which is over SDL 1.X)

# Answer
> 1 votes
The official pygame docs say:

http://www.pygame.org/docs/ref/surface.html#pygame.Surface.convert

> It is a good idea to convert all Surfaces before they are blitted many times. The converted Surface will have no pixel alphas. They will be stripped if the original had them

So, as far as I can tell you should always .convert() them when you are going to blit them in the main loop, but it might cause some alpha problems (never happened to me).

If you try to draw many images on the screen at the same time you can see the performance difference by converting or not those.

Hope that helps.

---
Tags: python, pygame
---


# Question
Title: change the position of f3d objects randomly in action script
I have a f3d object and have different boxes to place the parts of the f3d objects.When i click on the button change the position of the boxes randomly. How it possible?This is the code for random array.

```
private function init(e:Event = null):void
    {
        removeEventListener(Event.ADDED_TO_STAGE, init);
        // entry point

        var startArray:Array = generateNumberArray(10);
        var randomArray:Array = randomArray(startArray);
        trace("startArray = " + startArray);
        trace("randomArray = " + randomArray);

    }
    /**
     * generate Array of numbers by length
     * @param   length
     * @return Array of numbers
     */
    public  function generateNumberArray(length:int):Array
    {
        var numberArray:Array = [];
        for (var i:int = 0; i < length; i++)
        {
            numberArray[i] = i+1;
            //trace("ersexrfegtdrgtdrygtfr"+numberArray[i]);
        }

        return numberArray;
    }

    /**
     * generate randomly mixed array by input array
     * @param   inputArray - simple not mixed array
     * @return Array - mixed array
     */
    public function randomArray(inputArray:Array):Array
    {
        var randomArray:Array = [];
        var tempArray:Array = [];
        for (var i:int = 0; i < inputArray.length; i++)
        {
            tempArray.push(inputArray[i]);
        }
        while (tempArray.length)
        {
            var randomNumber:int = Math.round(Math.random() * (tempArray.length - 1));// get random number of left array
            randomArray.push( tempArray[randomNumber] );
            tempArray.splice(randomNumber, 1);
            trace("randommmmmmmmmmmmmmmmmmmmmmmm"+randomArray);

                 // remove randomed element from temporary aarray
        }
        tempArray = null;
        delete [tempArray];
        return randomArray;

    }
    public function loadCompleteEvent(e:Event):void
    {
      if (stage) init();
        else
            addEventListener(Event.ADDED_TO_STAGE, init);

         // my boxes (want to change the position randomly of these boxes)
        Box2.setPosition(57.49752426147461, -2.987499237060547, 10);
        Box3.setPosition(57.49752426147461, -26.987499237060547, 10);
        Box4.setPosition(-48.50247573852539, -2.987499237060547, 10);

```

}

# Answer
> 1 votes
I'm not sure I understand the relevance of the random array function, but to set a random position for each box you could create a helper function which returns a random number between `min` and `max`:

```
private function randomNumber(min:Number, max:Number):Number {
    return Math.random() * (max - min) + min;
}

```

And then set the position of each box using:

```
box2.setPosition(randomNumber(0, 100), randomNumber(0, 100), 10);

```

Adjust the min and max values as you need.

---
Tags: actionscript-3, random
---


# Question
Title: Does Unity load the texture data of all the sprites in a sprite array property?
```
using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {

    public Sprite[] mySprites;

}

```

From the editor, you can put sprites in the array property.

I want to put several large sprites there, like, 20 huge ones. However, only one of the 20 will be used by a `SpriteRenderer` at any given moment (I just have them in an array so I can switch easily in the future).

My concern is performance: does having an array containing 20 "Sprite" references imply that Unity will ***load the texture data of all 20 sprites***? Or will Unity only load the data for the sprite that will be used by `SpriteRenderer` smartly?

# Answer
When you put anything in an array it's going to be in memory. So yes, it will load all 20 sprites.

However, the sprite renderer will only be rendering the sprite it has a target to, so you don't get any increased performance overhead CPU/GPU wise.

It does take more time to load 20 sprites compared to 1 sprite, but as long as this loading is done once and not multiple times in a short period, you shouldn't need to worry about performance issues. Also, twenty textures isn't a lot, unless they're super huge.
> 1 votes

# Answer
Sprite holds a reference to a texture. It is not a texture itself. Therefore, if you have 20 sprites using the same texture, it will only load the 1. Textures are resources, and should only be referenced, not copied.

http://docs.unity3d.com/ScriptReference/Sprite.html

Read about it here.
> 1 votes

---
Tags: unity
---


# Question
Title: Basic terrain shader without using external texture
I have this:

(Right now I have the height map in a x\*x size 2D array and a 1D vector too.)

What I am trying to achieve is something like this: Without using any textures, only plain colors. So basically smooth transitions and some shadow (using shaders). My vertex shader looks like this:

```
    #version 330
    layout (location = 0) in vec3 Position;
    layout (location = 1) in vec3 Normal;
    layout (location = 2) in vec3 Color;

    out vec3 fragmentNormal;
    out vec4 ex_color,pos;
    out vec3 N;
    out vec3 v;

    void main () {
    pos= vec4(Position,1);
    ex_color = vec4(Color,1);
    fragmentNormal = Normal;

    v = vec3(gl_ModelViewMatrix * pos);
    N = normalize(gl_NormalMatrix * Normal);

    gl_Position = gl_ModelViewProjectionMatrix * vec4(Position,1);

```

I have normals for all the vertices. Color is set simply in the c++ code based on height.

Here is the fragment shader

```
    in vec3 N;
    in vec3 v;
    in vec4 ex_color;
    void main(void)
    {
       vec3 L = normalize(gl_LightSource[0].position.xyz - v);
       vec4 Idiff = gl_FrontLightProduct[0].diffuse * max(dot(N,L), 0.0);
       Idiff = clamp(Idiff, 0.0, 1.0);
       gl_FragColor = Idiff*ex_color;
    }

```

So I guess my problem is what formula should I use to mix the colors. I think I don't need to set the colors in the c++ code but in the shaders.

**Update:** Here is the wireframe of the terrain.

**Update2:** Based on @Babis' answer the result is:

So the gradient is not "projected" onto the surface as I would like to do. What could cause this? Maybe my qustion wasn't clear.

# Answer
> 4 votes
It's a simple interpolation. Let's assume that your heights span -1 to 1, 0 is water surface and you have 3 colours: dark green, light green and white. A way to do what you want is to have the following color\_from\_height function in the pixel or fragment shader (depending on how efficient you want to be). In my shader below I visualize the gradient, but the function color\_from\_height should get the world space height.

```
// This is a shadertoy example (www.shadertoy.com) which will visualize the 4-colours palette

vec3 color_from_height( const float height )
{
    vec3 terrain_colours[4];
    terrain_colours[0] = vec3(0.0,0.0,0.6);
    terrain_colours[1] = vec3(0.1, 0.3, 0.1);
    terrain_colours[2] =  vec3(0.4, 0.8, 0.4);
    terrain_colours[3] = vec3(1.0,1.0,1.0);
    //vec3 terrain_colours[1] = vec3[1]{ vec3(0,0,0.6)};
    if(height < 0.0)
        return terrain_colours[0];
    else
    {
        float hscaled = height*2.0 - 1e-05; // hscaled should range in [0,2)
        int hi = int(hscaled); // hi should range in [0,1]
        float hfrac = hscaled-float(hi); // hfrac should range in [0,1]
        if( hi == 0)
            return mix( terrain_colours[1],terrain_colours[2],hfrac); // blends between the two colours
        else
            return mix( terrain_colours[2],terrain_colours[3],hfrac); // blends between the two colours
    }
    return vec3(0.0,0.0,0.0);
}

void main(void)
{
    vec2 uv = gl_FragCoord.xy / iResolution.xy;
    vec3 col = color_from_height(uv.y*2.0-1.0);
    gl_FragColor = vec4(col,1.0);
}

```

---
Tags: textures, shaders, glsl, terrain, blending
---


# Question
Title: Box2D Body creation causing performance issues
I have at max 10 dynamic bodies in my world at any time. they are created at random and fired up from below they screen. when a new body is being created, the fps falls from 59 - 61 to about 35- 40 and then jumps back up again straight away which obviously causes the other dynamic bodies that are moving about the screen to stick for a split second. i am creating the bodies like below...

```
private void addBadger(){
    badgerCount++;
    //dimensions
        //pix
            float badgerWidthPix = RandomNum.randFloat(screenWidth/16f, screenWidth/16f);
            float badgerHeightPix = badgerWidthPix;
        //meters
            float badgerWidthMet = badgerWidthPix*pix2met;
            float badgerHeightMet = badgerHeightPix*pix2met;
    //position
        //pix
            float badgerXPosPix = RandomNum.randFloat(0, screenWidth-badgerWidthPix);
            float badgerYPosPix = -badgerHeightPix;
        //met
            float badgerXPosMet = badgerXPosPix*pix2met;
            float badgerYPosMet = badgerYPosPix*pix2met;
    //Image
        Badger badger = new Badger(badgerAliveTexture, badgerShotTexture, badgerXPosPix, badgerYPosPix, badgerWidthPix, badgerHeightPix, String.valueOf(badgerCount), manager, tweenManager, this, screenWidth, screenHeight);
        badgerArray.add(badger);
        badgerGroup.addActor(badger);
    //body
        //get object from json
            jsonBodyLoader = new BodyEditorLoader(Gdx.files.internal("json_objects/badger.json"));
        //define body
            bodyDef = null;
            bodyDef = new BodyDef();
            bodyDef.position.set(badgerXPosMet, badgerYPosMet);
            bodyDef.gravityScale = 1;
            bodyDef.fixedRotation = false;
            bodyDef.type = BodyType.DynamicBody;
        //set velocities
            float xVel = RandomNum.randFloatPossNeg(0.25f, 1f);
            float yVel = RandomNum.randFloat(11.5f, 14f);
            float rotation = RandomNum.randFloat(1, 5);
            if(xVel < 0){ rotation = -rotation; }
            bodyDef.linearVelocity.x = xVel;
            bodyDef.linearVelocity.y = yVel;
            bodyDef.angularVelocity = rotation;
        //define fixture
            fixtureDef = null;
            fixtureDef = new FixtureDef();
            fixtureDef.density = 2;
            fixtureDef.friction = 0.5f;
            fixtureDef.restitution = 0.25f;
            fixtureDef.filter.categoryBits = CollisionCategories.BADGER;
            fixtureDef.filter.maskBits = CollisionCategories.BADGER;
        //create body
            Body badgerBody = world.createBody(bodyDef);
            badgerBody.setUserData(badger);
        //attach fixture
            jsonBodyLoader.attachFixture(badgerBody, "Badger", fixtureDef, badgerWidthMet, 1, 1);
        //set body to image
            badger.body = badgerBody;

//call new badger
    //get interval
        badgerCreationInterval = (RandomNum.randFloat(minAddBadgerDelay, maxAddBadgerDelay));

```

the filtering I am using on the Images is mipmap.LinearNearest, Nearest

# Answer
You are loading textures and models from files on disk, that's your problem. File I/O is very expensive and should be avoided as much as possible. Preload your model and whenever you need to add a badger, clone one from the preloaded and just alter the properties that you need to.
> 1 votes

---
Tags: java, libgdx, box2d
---


# Question
Title: 2D sprite 360 degrees rotation according to the mouse
I am trying to make my top down character rotate according to degrees between its position and the mouse. I'm using this code:

```
float xDiff = mouseState.X - (graphics.PreferredBackBufferWidth / 2);
            float yDiff = mouseState.Y - (graphics.PreferredBackBufferHeight / 2);

float angle = (float)(Math.Atan2(yDiff, xDiff)) * 180 / Math.PI);

```

But it's not working. At the place where I should get somewhere about 0 degrees - I get about -75.

# Answer
If you look at a circle with the angles marked you will see that `270 degrees` corresponds with `(0,-1)` i.e. straight down.

By convention degrees are marked as acceding in a counter-clockwise direction. They do however form a loop and as such `270 degrees` (purple arrow) can also be expressed as `-90 degrees` (orange arrow) i.e. a quarter turn in the opposite direction.

The coordinates that you provided `(-2, -145)` correspond with both `269.21` and `-90.79 degrees` depending on how you choose to express this angle..

The documentation for `Atan2()` for .Net 4.5 states that it will return value is the range `-π <= θ <= π`, after converting to degrees this is `-180 <= θ <= 180`.

To further explain the expected results here is a table with the results of the following formula with the corresponding values of `x` and `y`.

```
angle = Math.Atan2(y, x) * 180 / Math.PI;

         x    -1       0       1
   y   +------------------------
   1   |     135      90      45
   0   |     180       0       0
  -1   |    -135     -90     -45

```

If you prefer to have your angles expressed in the range `0 <= θ <= 360` they are easy to convert:

```
while (angle > 360) {
    angle -= 360;
}
while (angle < 0) {
    angle += 360;
}

```
> 1 votes

---
Tags: c#, 2d, rotation, mouse
---


# Question
Title: Surface creation algorithm using points cloud
I am looking for a **realtime** algorithm to create a **2D mesh** using **points**. But I am quite confused. It seems that **Delaunay triangulation** can help me create mesh using point clouds, but **Meta-balls** seems also useful for isolated points for example. And what about concave shapes ?

I am looking for interesting **links**, **white-papers**, **code sample**, etc...

Here is an example of what I am trying to achieve. As you can see the aim is to create a **2D fluid surface**.

In **red** should be the generated mesh, I tried to reproduce the special condition that could happen like **concave shape**, **isolated points**, etc. In **black** you can see the points used to create the shape.

Thank you.

# Answer
You may do what you need in 2 step:

1. **Clustering**: First you can cluster your point. There are many clustering algorithms which will put your points into multiple close-distance group. K-means is one of your options.
2. **Convex Hull**: Then you can create Convex Hull for each cluster. such as: Gift wrapping algorithm, Quick Hull, Bridge, ...

There is a trade-off between simplicity and performance issue for named algorithms.

As you run these algorithms in real-time, your case go to performance-intensive category which need some research in order to find best algorithms for your game.
> 3 votes

# Answer
Metaballs is a good way to think about solving this problem. It's usually the way that people develop implicit surfaces using particle-based fluid simulation like Smoothed Particle Hydrodynamics. There have already been a few questions asked about how to render metaballs:

How to render metaballs?

2D metaball liquid effect - how to feed output of one rendering pass as input to another shader

2d metaballs with shader to give blobs of water effect?

In order to actually generate the implicit surface of the water, there is a very good GPU Gems 3 chapter on the subject:

Point-Based Visualization of Metaballs on a GPU
> 0 votes

---
Tags: c++, 2d, unity, 3d, algorithm
---


title: Consume input events in Unity 4.6

text:
# Question
Title: Consume input events in Unity 4.6
How do I consume the input events in the new 4.6 unity gui system? If I click on a button for instance I don't want anything else non GUI related that might be listening for mouse input to react to the event.

# Answer
> 4 votes
Here's a solution from the Frequently Asked UI Questions thread on Unity Forums:

> **How do I stop clicks/touches on the UI from 'going through it' and being clicks in my game world?**
>
> Use EventSystem.current.IsPointerOverGameObject() to check whether the mouse is over a GUI element before you process your game world clicks. See this post for an example. Also, on mobile, you may need to specify which finger you're asking about - see this thread for details.

I should warn though that while this method seems working (I'm using it myself), it is still not documented at the moment, and there is no guarantee it won't be changed in future when Unity 4.6 is officially released.

---
Tags: unity, gui
---


# Question
Title: How do I make a scrolling map within an HTML5 canvas?
My project is a 2D tactics game with a square grid. It's all HTML5/Javascript/JQuery.

I have been able to draw out the grid and have a system where I can load different maps with tiles where units can and cannot move. Now I would like to make it so only a portion of the map is displayed in the canvas and the player can scroll around to different characters and stuff (like in normal tactical games).

However I have no idea even where to get started doing this with an HTML5 canvas. I did something similar in Unity but the level of abstraction with the cameras basically did it for me.

# Answer
You can accomplish this with `CanvasRenderingContext2D`'s methods `setTransform`, `save`, and `restore`. Together they allow you to create a draw transform stack, which permits you to draw all your tiles at their (unchanging) world position, but have them move around on screen.

If you have a position of the left-top world-position of your viewport, you can create a simple camera object:

```
var camera = {x: xPosition, y: yPosition};

```

Then you can update only that value and use it to offset your view by setting an initial base-transform. (Pay attention to argument order, as they comprise a 2x2 matrix followed by a 2d translation vector):

```
context.setTransform(
  1, 0,
  0, 1,
  -1 * camera.x,
  -1 * camera.y);

```

Then when you draw individual objects, you can add another transform, draw the image, and then pop that transform back off the stack:

```
var tile = {pos: {x: xPosition, y:yPosition}, img: tileImage };
context.save();
context.translate(tile.pos.x, tile.pos.y);
context.drawImage(tile.img, 0, 0);
context.restore();

```

Adding zoom and rotation can be accomplished with the same technique, but they require more terms in the transform. Clamping the motion of the camera, as well as picking items in screenspace, are more complicated. But those would all be separate topics.
> 3 votes

# Answer
If I understand the question correctly, you want a camera that you can move, which is not a standard with vanilla canvas. To emulate this, you should create two variables for the x and y position of the camera. You can then manipulate these values for instance if you want the camera to move when the player moves. To make all your scenes objects act properly with the camera, you should offset all of your draw calls with the x and y of the camera, simply by subtracting the cameras position with the objects position. This can turn messy having to put the offset on everything you draw, so you might want to write some code that you can call to offset all the values automatically.
> 0 votes

---
Tags: html5, maps, scrolling
---


# Question
Title: Randomize and display sprites in a 4x6 grid - Cocos2d-x
I am creating a card matching game. I have a vector that stores 16 unique cards. I am trying to randomize the order and select only the first 12 cards, then setup in a 4x6 grid for a total of 24 matching pairs. I'm having trouble randomizing it and displaying it in the grid. Also, I am using Cocos2d-x 3.2. Thanks for any advice.

```
std::vector<Sprite*> cards;
std::vector<std::string> cardNames = { "0.png", "1.png", "2.png", "3.png", "4.png", "5.png", "6.png", "7.png", "8.png", "9.png", "10.png", "11.png", "12.png", "13.png", "14.png", "15.png" };

for (int n = 0; n < cardNames.size(); n++)
{
    auto sprite = Sprite::create(cardNames.at(n));

    sprite->setPosition(cocos2d::Point((50 * (n + 1)), 20));
    sprite->setTag(n);

    cards.push_back(sprite);

    addChild(sprite);
}

std::random_shuffle(cards.begin(), cards.end());

for (int n = 0; n <= 11; n++) // select forst 12 cards to display in the grid
{
    // logic to create grid
    // set position of each card

    addChild(cards); // error here
}

```

# Answer
> 1 votes
To do random numbers in C++ you need to `#include <random>` and `#include<time.h>` then create a seed using:

```
srand(time(NULL))

```

Then you must create a random number like so.

```
int randNum = rand() % 10 + 1;

```

This will create a random number in the range of 0-9 but then we add 1 and it will be somewhere between 1-10.

Keep in mind it's not the only way to generate a random number.

As for your program just assign all the the cards a number, then create another array of random numbers, and those will be your random positions in the vector. (Don't forget to prevent repeats.)

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


# Question
Title: How do I make a sprite collide with walls in pygame?
I've been trying to create a collision detection between the player (Blue), and the walls (Green), but the player can just move through the walls. I made it so that every collision is printed in the console, just to see if the code was even detecting collisions. When I ran this version of the program, it was constantly printing "collide," indicating that there was always a collision detected, but even so, none of my code for when a collision was detected ran. Here is my code:

```
import pygame, random, sys
from pygame.locals import *

# Set FPS
FPS = 30

# Window Dimensions
WINDOWWIDTH = 640
WINDOWHEIGHT = 480

# Colors
BLUE = (0, 0, 255)
BLACK = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)

# Key Constants
UP = 'up'
DOWN = 'down'
RIGHT = 'right'
LEFT = 'left'

class Player(pygame.sprite.Sprite):

    def __init__(self, x, y):
        # Call the parent's constructor
        pygame.sprite.Sprite.__init__(self)

        # Set Properties
        self.image = pygame.Surface((30, 30))
        self.image.fill(BLUE)
        self.rect = self.image.get_rect()
        self.width = self.image.get_width()
        self.height = self.image.get_height()
        self.x = x
        self.y = y
        self.vx = 0
        self.vy = 0
        self.vel = 5

    def onKeyDown(self, event): # Move 3 pixels when a directional key is pressed
        if event.key == K_LEFT:
            self.vx = -self.vel
        if event.key == K_RIGHT:
            self.vx = self.vel
        if event.key == K_UP:
            self.vy = -self.vel
        if event.key == K_DOWN:
            self.vy = self.vel

    def onKeyUp(self, event): # Stop moving when key is released
        if event.key == K_LEFT or event.key == K_RIGHT:
            self.vx = 0
        if event.key == K_UP or event.key == K_DOWN:
            self.vy = 0

    def update(self):
        # Move Player
        self.x += self.vx
        self.y += self.vy

        # Check for Collisions
        for wall in wallList:
            if pygame.sprite.collide_rect(self, wall):
                print("collide")
                if self.vx > 0:
                    self.rect.right = wall.rect.left
                if self.vx < 0:
                    self.rect.left = wall.rect.right
                if self.vy > 0:
                    self.rect.bottom = wall.rect.top
                if self.vy < 0:
                    self.rect.top = wall.rect.bottom

class Enemy(pygame.sprite.Sprite):

    def __init__(self, x, y):
        # Call the parent's constructor
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.Surface((30, 30))
        self.image.fill(RED)
        self.rect = self.image.get_rect()
        self.width = self.image.get_width()
        self.height = self.image.get_height()
        self.x = x
        self.y = y
        self.vel = 2

    def move(self):
        self.y += self.vel

class Wall(pygame.sprite.Sprite):

    def __init__(self, x, y):
        # Call the parent's constructor
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.Surface((30, 30))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.width = self.image.get_width()
        self.height = self.image.get_height()
        self.x = x
        self.y = y

def main():
    global FPSCLOCK, DISPLAYSURF, wallList, enemyList, walls
    pygame.init()
    random.seed()

    FPSCLOCK = pygame.time.Clock()
    DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
    pygame.display.set_caption('Lembalo')
    player = Player(WINDOWWIDTH / 2, WINDOWHEIGHT - 100)

    enemyList = [
        Enemy(random.randint(0, WINDOWWIDTH - 30), random.randint(0, WINDOWHEIGHT - 430)),
        Enemy(random.randint(0, WINDOWWIDTH - 30), random.randint(0, WINDOWHEIGHT - 430)),
        Enemy(random.randint(0, WINDOWWIDTH - 30), random.randint(0, WINDOWHEIGHT - 430)),
        Enemy(random.randint(0, WINDOWWIDTH - 30), random.randint(0, WINDOWHEIGHT - 430)),
        Enemy(random.randint(0, WINDOWWIDTH - 30), random.randint(0, WINDOWHEIGHT - 430))
        ]

    wallList = [
        Wall(70, 100),
        Wall(100, 100),
        Wall(130, 100),
        Wall(160, 100),
        Wall(190, 100),
        Wall(220, 100)
        ]

    allsprites = pygame.sprite.Group()

    allsprites.add(player)
    allsprites.add(enemyList)
    allsprites.add(wallList)

    while True:

        DISPLAYSURF.fill(BLACK) # Drawing the window

        for event in pygame.event.get(): # Event handling
            if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
                pygame.quit()
                sys.exit()
            if event.type == KEYDOWN:
                player.onKeyDown(event)
            if event.type == KEYUP:
                player.onKeyUp(event)

        # Update player position
        player.update()

        # Render enemies and update position
        for enemy in enemyList:
##            enemy.move()
            DISPLAYSURF.blit(enemy.image, (enemy.x, enemy.y))

        # Render walls
        for wall in wallList:
            DISPLAYSURF.blit(wall.image, (wall.x, wall.y))

        # Render player
        DISPLAYSURF.blit(player.image, (player.x, player.y))
        allsprites.update()
        pygame.display.update()
        FPSCLOCK.tick(FPS)

if __name__ == '__main__':
    main()

```

# Answer
> 1 votes
You updated velocity and then checked for collision. I see how you clipped the character to whichever wall he was at afterwards with the series of conditional statements. But this isn't how collision is typically done and could spell problems later.

You should think about changing the velocity due to the collision rather than seeing there is a collision and then just positioning your character at that wall.

Make another rectangle (We will call it the speculative rectangle) with the addition of vx and vy as if you were updating the characters position. (But don't actually update the characters position just yet.) Then check for collision between this speculative rectangle and the walls. If there is a collision you change your velocities to the distance between the characters actual rectangle (not the speculative) and the wall. Then, during the next go around, if you're still trying to walk into the wall the distance between the character and the wall would be 0 so the velocity would be 0. Making your character unmoving.

This is called speculative collision. Here are some more articles on it.

http://www.wildbunny.co.uk/blog/2011/03/25/speculative-contacts-an-continuous-collision-engine-approach-part-1/

http://jitter-physics.com/wordpress/?tag=speculative-contacts

---
Tags: collision-detection, python, pygame
---


# Question
Title: How to bundle a HTML5 JavaScript game as native Windows application?
As the web browsers evolve, HTML5 game development with JavaScript, Canvas, webgl is increasingly becoming popular. The advantage of web-based games compared to native apps is that they run on multiple platforms, and you don't have to fiddle with OS-specific libraries or programming environments.

You can already sell your web games via the chrome web store, but I think it's too unpopular yet for being profitable for indie game developers.

I think you may reach a larger crowd by selling your games at the Mac App Store or Steam, but therefore you have to bundle it as standalone application.

For mac, you can easily bundle your HTML5 games as native app by using the Apple's WebView component. Here is an example on how to do that.

Now I wonder: is there an equivalent way for Windows platform?

# Answer
I've been targeting node-webkit for my html5/js game. Most of my code runs browser-side, so the node.js aspects are mostly because its simple enough to have it run a small server and send down the html/js code to the embedded browser.

A good demo of a fast-paced game is, "A Wizard's Lizard". They talk about their success on reddit, and they apparently use node-webkit.

The people behind "Gamedev Tycoon" released their steamworks integration api as open source. It lets you interact with steam's innards from node-webkit.

A popular (read: newbie friendly) game development platform "Construct 2" lets you create simplistic games using html5/canvas behind the scenes. They also use node-webkit to package up the game as an executable. My non-programmer friend with an digital-media background picked it up fairly quickly. I hosted a small demo of his first test game as an example.

Another option, if you don't want to go with html/javascript (but still want a browser based game) is to use either the Unity framework or the Unreal Engine. The Unreal Engine may not have full support currently, but according to their roadmap it is becoming a first class feature. It was fairly easy to integrate serverside stuff with them and the engines both have great integration with popular services and can be made to interact with server-side elements quite easily. You can read more about how they are integrating with the web on mozilla's new blog post on the subject.

All of these work well with itch.io \- which is where I'm hoping to publish.
> 7 votes

# Answer
If I'm not mistaken, the Winforms API in the .NET Framework has a web browser component that you can add to an application, to display HTML content, and modify via a simple interface. It relies on an already installed web browser (usually IE), so you'd have to verify that the user has everything necessary to view your game, but other than that, I don't see why it wouldn't work.

This looks promising. Hope I helped :)
> 3 votes

# Answer
You can use Qt with the QtWebkit widget, which will work on all major platforms.
> 1 votes

# Answer
Titanium Desktop offers a HTML5 CSS3 Javascript plataform for making native apps for Windows, the only disadvantage is that the source code of the app stays totally open for anyone to edit or see.
> 1 votes

---
Tags: html5
---


title: Should I check SDL_Event for NULL?

text:
# Question
Title: Should I check SDL_Event for NULL?
I have taken as a practice (as many others, I think) to always do this when working with pointers:

```
void I_take_pointer(some_type* arg1)
{
    if(arg1)
    {
        //safely do stuff with pointer
    }
    //optionally an else statement
}

```

...in almost all functions, except those where I can be sure arg1 will never be null.

Is it good practice/should I perform this check on the `SDL_Event*` I get on input when working with SDL2?

# Answer
> 2 votes
You do not need to test for nullness in this case.

The reason is that the ultimate source of the object is your code.

```
SDL_Event e;
SDL_PollEvent(&e);

```

Both ways of getting events from SDL demand that you pass in the event object to be filled, so it can thus not be NULL unless you fail to allocate one beforehand.

---
Tags: c++, sdl2
---


title: Problem with uniforms in OpenGL

text:
# Question
Title: Problem with uniforms in OpenGL
I have a strange problem I can't figure out. On the CPU I have class that handles the material properties for a model.

```
material = new Material();
material->Emissive = vec3(0.1, 0.0, 0.0);
material->Ambient = vec3(0.1, 0.0, 0.0);
material->Diffuse = vec3(1.0, 0.0, 0.0);
material->Specular = vec3(1.0, 1.0, 1.0);
material->Shininess = 10.0f;
material->Alpha = 1.0f;

```

To send them to the GPU, I have some methods in my Program class (a class for adding shaders, vertex attributes, uniforms etc):

```
program->Uniform3fv("uniEmissive", material->Emissive);
program->Uniform3fv("uniAmbient", material->Ambient);
program->Uniform3fv("uniDiffuse", material->Diffuse);
program->Uniform3fv("uniSpecular", material->Specular);
program->Uniform1f("uniShininess", material->Shininess);
program->Uniform1f("uniAlpha", material->Alpha);

```

Which internally looks like this

```
// This map stores names and indexes for a uniform
map<GLchar*, GLint> uniformList;

void Program::Uniform3fv(GLchar *name, glm::vec3 value)
{
    if (!UniformListContains(name))
    {
        AddUniformLocation(name);
    }

    if (UniformListContains(name))
    {
        glUniform3fv(uniformList[name], 1, glm::value_ptr(value));
    }
}

```

The "uniformList" is a map with name of the uniform in the shader and the index of the uniform. So first in this function it looks if it is in the list, if not it adds it. Then it uploads the value to the GPU, by looking in the "uniformList" for this name, and if found it retuns the index for the uniform. This is how the "uniformList" looks when everything for this program has been uploaded. Which seems correct to me, because none of the indices are -1.

So, now to the problem. In my fragment shader I have this code

```
vec3 N = normalize(normal);
vec3 L = normalize(lightDir);
vec3 R = reflect(-L, N);
vec3 V = normalize(-position);

vec3 emissive = uniEmissive;
vec3 ambient = uniAmbient;
vec3 diffuse = uniDiffuse * max(dot(N, L), 0.0);
vec3 specular = uniSpecular * pow(max(dot(R, V), 0.0), uniShininess);

fragColor = vec4(emissive + ambient + diffuse + specular, uniAlpha);

```

This, doesn't work! But if I remove "emissive" it renders the model properly. Also, if I just use "vec4(emissive, uniAlpha)" it also renders the model, and with a very dark red color, which is correct.

Another way it is working is by "hard coding" the material properties in the shader, note: emissive is used here also.

```
vec3 Emissive = vec3(0.1, 0.0, 0.0);
vec3 Ambient = vec3(0.1, 0.0, 0.0);
vec3 Diffuse = vec3(1.0, 0.0, 0.0);
vec3 Specular = vec3(1.0, 1.0, 1.0);
float Shininess = 10.0;
float Alpha = 1.0;

vec3 emissive = Emissive;
vec3 ambient = Ambient;
vec3 diffuse = Diffuse * max(dot(N, L), 0.0);
vec3 specular = Specular * pow(max(dot(R, V), 0.0), Shininess);

fragColor = vec4(emissive + ambient + diffuse + specular, Alpha);

```

Regarding this I don't believe the problem is in the fragment shader itself, but probably something with the upload of the uniforms. I hope someone has time to look through this, thanks in advance! :)

UPDATE #1: showing below how I retrieve the uniform location:

```
void Program::AddUniformLocation(GLchar *name)
{
    GLint location = glGetUniformLocation(program, name);

    if (location != -1)
    {
        uniformList.insert(pair<GLchar*, GLint>(name, location));
    }
    else
    {
        printf("Error: the uniform \"%s\" doesn't exist, or isn't used, in program\n", name);
    }
}

```

UPDATE #2: I'm writing some scenarios here, some works, some doesn't (by working I mean the model is rendered). I'm getting insane, I really hope it isn't something very silly that is wrong. :)

```
vec3 diffuse = uniDiffuse * max(dot(N, L), 0.0);
vec3 specular = uniSpecular * pow(max(dot(R, V), 0.0), uniShininess);

// This works, 1.0 instead of uniAlpha.
fragColor = vec4(uniEmissive + uniAmbient + diffuse + specular, 1.0);

// Doesn't work, added uniAlpha
fragColor = vec4(uniEmissive + uniAmbient + diffuse + specular, uniAlpha);

// These are working
fragColor = vec4(uniEmissive, uniAlpha);
fragColor = vec4(uniEmissive + uniAmbient, uniAlpha);
// Adding diffuse doesn't work.
fragColor = vec4(uniEmissive + uniAmbient + diffuse, uniAlpha);
// Just diffuse, works!
fragColor = vec4(diffuse, uniAlpha);

```

UPDATE #3:

```
bool Program::ShaderInfoLog(GLuint shader, GLenum shaderType)
{
    GLint compiled;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);

    if (!compiled)
    {
        GLsizei length;
        glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length);

        GLchar* log = new GLchar[length+1];

        glGetShaderInfoLog(shader, length, &length, log);

        cerr << GetShaderType(shaderType) << ": " << endl << log << endl;

        delete[] log;

        return false;
    }

    return true;
}

```

# Answer
glUniform\*() only affects the currently bound program. Therefore one must call glUseProgram() before making any calls to glUniform\*().
> 2 votes

---
Tags: opengl, glsl
---


title: How to find the entity I'm looking at?

text:
# Question
Title: How to find the entity I'm looking at?
I am currently making a mod for Minecraft but I have come to a stop because I am lacking in some knowledge. I need to get data for the entity I am looking at, which I believe requires the use vectors, something I don't really know how to use.

How would I achieve this? Some stuff that I think could help are `mc.thePlayer.getLookVector()` which returns the normalized vector of the user and `mc.theWorld.loadedEntityList`, which is a List with all the loaded currently loaded entities.

# Answer
**Using Existing Methods/Variables**

Since you are making a mod for Minecraft, and judging by the naming scheme of the methods you mentioned, I would suggest looking into the methods `EntityRenderer.getMouseOver()` and `EntityLivingBase.rayTrace() (getMouseOver() uses it, and you can access the method by using mc.renderViewEntity.rayTrace())`.

Also `mc.objectMouseOver` (an instance of MovingObjectPosition) may interest you. It is the variable set by using `EntityRenderer.getMouseOver()`. The `MovingObjectPosition` class has a field of type `EnumMovingObjectType` and also a field of type `Entity`. The former may be able to help you, but I'm pretty sure the latter is the field that you would be more interested in, seeing as if you are pointing at an entity, that would be the entity within range.

**Re-implementing or modifying the methods**

Aside from that, you could re-implement/modify the ray tracing clip that the game already uses to find whatever object you are pointing at and make the range of the trace larger (currently looks to be the range in which you can touch/hit blocks) and also filter out all non-entities, however I do not know how much work this would require, and there are several layers of methods you may need to duplicate the effects of.
> 3 votes

# Answer
Here is how it's accomplished for the IngameInfo mod (my code): https://github.com/bspkrs/IngameInfo/blob/master/src/net/minecraft/src/mod\_IngameInfo.java#L968

```
MovingObjectPosition objectMouseOver = mc.objectMouseOver;
if (objectMouseOver != null)
{
    if (objectMouseOver.typeOfHit == EnumMovingObjectType.ENTITY)
    {
        return objectMouseOver.entityHit.getEntityName();
    }
    else if (objectMouseOver.typeOfHit == EnumMovingObjectType.TILE)
    {
        Block block = Block.blocksList[world.getBlockId(objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ)];
        if (block != null)
        {
            ItemStack pickBlock = block.getPickBlock(objectMouseOver, world, objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ);
            if (pickBlock != null)
            {
                return pickBlock.getDisplayName();
            }
            return block.getLocalizedName();
        }
    }
}

```

This example returns the name of the Entity or Block the player is currently looking at.
> 3 votes

# Answer
Here's a solution for 1.7.2. I also wanted to "recognise" an entity.

```
Minecraft mc = Minecraft.getMinecraft();
MovingObjectPosition objectMouseOver = mc.objectMouseOver;
// makes a variable for where you look
if(mc.objectMouseOver != null && mc.objectMouseOver.entityHit != null) {
    // checks if you hit an Entity
    Entity Target = objectMouseOver.entityHit;
    // make a variable: Target(just so I can use it easier) AND makes it "select the Entity"
    if(Target instanceof EntityLiving) /* or whatever you want recognised */ {
        // < Your operation >
    }
}

```

Just change `< Your operation >` appropriately.
> 0 votes

# Answer
Personally, I needed something with a little longer range than the default when I needed this. If that's the case for you too, I pretty much copied getMouseOver(), changing a few variables and names to get what I needed. Here's the original:

```
public void getMouseOver(float par1)
{
    if (this.mc.renderViewEntity != null)
    {
        if (this.mc.theWorld != null)
        {
            this.mc.pointedEntity = null;
            double d0 = (double)this.mc.playerController.getBlockReachDistance();
            this.mc.objectMouseOver = this.mc.renderViewEntity.rayTrace(d0, par1);
            double d1 = d0;
            Vec3 vec3 = this.mc.renderViewEntity.getPosition(par1);

            if (this.mc.playerController.extendedReach())
            {
                d0 = 6.0D;
                d1 = 6.0D;
            }
            else
            {
                if (d0 > 3.0D)
                {
                    d1 = 3.0D;
                }

                d0 = d1;
            }

            if (this.mc.objectMouseOver != null)
            {
                d1 = this.mc.objectMouseOver.hitVec.distanceTo(vec3);
            }

            Vec3 vec31 = this.mc.renderViewEntity.getLook(par1);
            Vec3 vec32 = vec3.addVector(vec31.xCoord * d0, vec31.yCoord * d0, vec31.zCoord * d0);
            this.pointedEntity = null;
            Vec3 vec33 = null;
            float f1 = 1.0F;
            List list = this.mc.theWorld.getEntitiesWithinAABBExcludingEntity(this.mc.renderViewEntity, this.mc.renderViewEntity.boundingBox.addCoord(vec31.xCoord * d0, vec31.yCoord * d0, vec31.zCoord * d0).expand((double)f1, (double)f1, (double)f1));
            double d2 = d1;

            for (int i = 0; i < list.size(); ++i)
            {
                Entity entity = (Entity)list.get(i);

                if (entity.canBeCollidedWith())
                {
                    float f2 = entity.getCollisionBorderSize();
                    AxisAlignedBB axisalignedbb = entity.boundingBox.expand((double)f2, (double)f2, (double)f2);
                    MovingObjectPosition movingobjectposition = axisalignedbb.calculateIntercept(vec3, vec32);

                    if (axisalignedbb.isVecInside(vec3))
                    {
                        if (0.0D < d2 || d2 == 0.0D)
                        {
                            this.pointedEntity = entity;
                            vec33 = movingobjectposition == null ? vec3 : movingobjectposition.hitVec;
                            d2 = 0.0D;
                        }
                    }
                    else if (movingobjectposition != null)
                    {
                        double d3 = vec3.distanceTo(movingobjectposition.hitVec);

                        if (d3 < d2 || d2 == 0.0D)
                        {
                            if (entity == this.mc.renderViewEntity.ridingEntity && !entity.canRiderInteract())
                            {
                                if (d2 == 0.0D)
                                {
                                    this.pointedEntity = entity;
                                    vec33 = movingobjectposition.hitVec;
                                }
                            }
                            else
                            {
                                this.pointedEntity = entity;
                                vec33 = movingobjectposition.hitVec;
                                d2 = d3;
                            }
                        }
                    }
                }
            }

            if (this.pointedEntity != null && (d2 < d1 || this.mc.objectMouseOver == null))
            {
                this.mc.objectMouseOver = new MovingObjectPosition(this.pointedEntity, vec33);

                if (this.pointedEntity instanceof EntityLivingBase || this.pointedEntity instanceof EntityItemFrame)
                {
                    this.mc.pointedEntity = this.pointedEntity;
                }
            }
        }

```

I put this all in it's own method, making float par1 an argument (which has something to do with ticks, put 1.0F) and how far away you want to look, which is double d0. I subtracted the if-else loop that changes d0 and d1 according to player reach (4.5 survival, 6.0 creative), and used the mc object in my class. Here's my modified version, which returns the EntityLivingBase that the cursor is on:

```
private EntityLivingBase getTarget(float par1, double distance)
{
    Minecraft mc = Minecraft.getMinecraft();

    Entity pointedEntity;
    double d0 = distance;
    MovingObjectPosition omo = mc.renderViewEntity.rayTrace(d0, par1);
    double d1 = d0;
    Vec3 vec3 = mc.renderViewEntity.getPosition(par1);
    Vec3 vec31 = mc.renderViewEntity.getLook(par1);
    Vec3 vec32 = vec3.addVector(vec31.xCoord * d0, vec31.yCoord * d0, vec31.zCoord * d0);
    pointedEntity = null;
    Vec3 vec33 = null;
    float f1 = 1.0F;
    List list = mc.theWorld.getEntitiesWithinAABBExcludingEntity(mc.renderViewEntity, mc.renderViewEntity.boundingBox.addCoord(vec31.xCoord * d0, vec31.yCoord * d0, vec31.zCoord * d0).expand((double)f1, (double)f1, (double)f1));
    double d2 = d1;

    for (int i = 0; i < list.size(); ++i)
    {
        Entity entity = (Entity)list.get(i);

        if (entity.canBeCollidedWith())
        {
            float f2 = entity.getCollisionBorderSize();
            AxisAlignedBB axisalignedbb = entity.boundingBox.expand((double)f2, (double)f2, (double)f2);
            MovingObjectPosition movingobjectposition = axisalignedbb.calculateIntercept(vec3, vec32);

            if (axisalignedbb.isVecInside(vec3))
            {
                if (0.0D < d2 || d2 == 0.0D)
                {
                    pointedEntity = entity;
                    vec33 = movingobjectposition == null ? vec3 : movingobjectposition.hitVec;
                    d2 = 0.0D;
                }
            }
            else if (movingobjectposition != null)
            {
                double d3 = vec3.distanceTo(movingobjectposition.hitVec);

                if (d3 < d2 || d2 == 0.0D)
                {
                    if (entity == mc.renderViewEntity.ridingEntity && !entity.canRiderInteract())
                    {
                        if (d2 == 0.0D)
                        {
                            pointedEntity = entity;
                            vec33 = movingobjectposition.hitVec;
                        }
                    }
                    else
                    {
                        pointedEntity = entity;
                        vec33 = movingobjectposition.hitVec;
                        d2 = d3;
                    }
                }
            }
        }
    }
    if (pointedEntity != null && (d2 < d1 || omo == null))
    {
        omo = new MovingObjectPosition(pointedEntity, vec33);

        if (pointedEntity instanceof EntityLivingBase || pointedEntity instanceof EntityItemFrame)
        {
            mc.pointedEntity = pointedEntity;
        }
    }
    if (omo != null)
    {
        if (omo.typeOfHit == MovingObjectType.ENTITY)
        {
            if(omo.entityHit instanceof EntityLivingBase)
            {
                return (EntityLivingBase)omo.entityHit;
            }
        }
    }
    return null;
}

```

Hope this helps, and good luck with your mod.
> 0 votes

---
Tags: java, 3d, vector, minecraft-modding
---


# Question
Title: How to use ROAM algorithm to adapt terrain's mesh?
I have a hard time understanding the idea behind ROAM algorithm

* ***"Real-time, continuous level of detail rendering of height fields"*** Peter Lindstrom, David Koller, William Ribarsky, Larry F. Hodges, Nick Faust, Gregory A. Turner SAIC http://dl.acm.org/citation.cfm?id=237217
* ***"ROAMing terrain: real-time optimally adapting meshes"*** Mark Duchaineau, Murray Wolinsky, David E. Sigeti, Mark C. Miller, Charles Aldrich, Mark B. Mineev-Weinstein http://dl.acm.org/citation.cfm?id=267028

The problem that I cannot grasp is that the whole idea behind the algorithm is that the terrain mesh is at all times divided to isosceles right angled triangles but when we arrange the terrain in a non flat mesh then the triangles that we divided the mesh into are supposed to be extended(?) to meet the height field requirements?

From what perspective is the terrain divided into those triangles and should they be isosceles right angled triangles generally or only when looked upon in up-down projection?

# Answer
It is easiest to consider only the height map case, at least initially. In this case, our terrain starts as a flat plane, which should be raised by the height values provided by the supplied height map.

When viewed from directly above, the ROAM mesh representing this terrain should appear as a nested tree of isosceles triangles. However, the y-coordinate of each triangle vertex should be set to the matching value from the height map, which, when viewed from the side, will result in the ROAM mesh loosely following the contours of the height map.

Subdivision in ROAM is generally performed by taking the 3 corners of a given triangle, and averaging them to obtain the height at the center of the triangle. You then compare this height to the value from the height map at the same location, and if the interpolated value is sufficiently different, subdivide this triangle (since the child triangles are smaller, and will more closely approximate the underlying height field).

---

I will note that ROAM methods for terrain rendering have largely fallen out of favour, due to the development of level-of-detail techniques which are both simpler to implement, and a better fit for modern rendering hardware, in particular CLOD (Chunked Level Of Detail) and Geo-mipmapping approaches.
> 1 votes

---
Tags: terrain, terrain-rendering, level-of-detail
---


title: OpenGL Texture Mapping distorts image

text:
# Question
Title: OpenGL Texture Mapping distorts image
So, I'm just trying to draw a texture to two triangles that are the same size as the viewport, but it breaks up the image and distorts it. I have tried resizing the image file and everything, but nothing seems to work. Below is the code that maps the texture and draws the triangles.

```
 public void Render()
    {
        Texture texture = _textureManager.Get("splash");
        Gl.glEnable(Gl.GL_TEXTURE_2D);
        Gl.glBindTexture(Gl.GL_TEXTURE_2D, texture.Id);

        double height = 720;
        double width = 1280;

        double x = 0;
        double y = 0;
        double z = 0;

        float topUV = 0;
        float bottomUV = 1;
        float leftUV = 0;
        float rightUV = 1;

        Gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        Gl.glClear(Gl.GL_COLOR_BUFFER_BIT);
        Gl.glBegin(Gl.GL_TRIANGLES);
        {
            Gl.glTexCoord2d(leftUV, topUV);
            Gl.glVertex3d(x - width, y + height, z);
            Gl.glTexCoord2d(rightUV, topUV);
            Gl.glVertex3d(x + width, y + height, z);
            Gl.glTexCoord2d(leftUV, bottomUV);
            Gl.glVertex3d(x - width, y - height, z);

            Gl.glTexCoord2d(rightUV, topUV);
            Gl.glVertex3d(x + width, y + height, z);
            Gl.glTexCoord2d(rightUV, bottomUV);
            Gl.glVertex3d(x + width, y - height, z);
            Gl.glTexCoord2d(leftUV, bottomUV);
            Gl.glVertex3d(x - width, y - height, z);
        }
        Gl.glEnd();

    }

```

Here is the original image:

And here's the result:

The image is 1920 x 1080, and the viewport is 1280 x 720, but I'm not too sure that matters because I have tried resizing the image and nothing seems to work.

edit: this is a cross-post from stack overflow (I asked it here as well because nobody seemed to have an answer): https://stackoverflow.com/questions/26723470/opengl-texture-mapping-distorts-image

# Answer
> 0 votes
Alright, so I ended up cutting the image in half down the center and just loading two images, and then I used four triangles. This may not be the most elegant solution, but it works just fine. I'm guessing it had to do with the dimensions of the image. (I also changed the parameters for the texture coordinates and all the vertices so that it is more straight forward in the context of Stack Overflow).

```
public void Render()
    {
        //Draw Left Half
        Texture texture = _textureManager.Get("splash1");
        Gl.glEnable(Gl.GL_TEXTURE_2D);
        Gl.glBindTexture(Gl.GL_TEXTURE_2D, texture.Id);

        Gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        Gl.glClear(Gl.GL_COLOR_BUFFER_BIT);
        Gl.glBegin(Gl.GL_TRIANGLES);
        {
            Gl.glTexCoord2d(0, 0);//top left
            Gl.glVertex2f(-1280 , 720);

            Gl.glTexCoord2d(1, 0);//middle top
            Gl.glVertex2f(0, 720);

            Gl.glTexCoord2d(0, 1);//bottom left
            Gl.glVertex2f(-1280, -720);

            Gl.glTexCoord2d(0, 1);//bottom left
            Gl.glVertex2f(-1280, -720);

            Gl.glTexCoord2d(1, 0);//middle right top
            Gl.glVertex2f(0, 720);

            Gl.glTexCoord2d(1, 1);//bottom middle
            Gl.glVertex2f(0, -720);
        }
        Gl.glEnd();

        //Draw Right Half
        texture = _textureManager.Get("splash2");
        Gl.glBindTexture(Gl.GL_TEXTURE_2D, texture.Id);

        Gl.glBegin(Gl.GL_TRIANGLES);
        {
            Gl.glTexCoord2d(0, 0);//middle top
            Gl.glVertex2f(0, 720);

            Gl.glTexCoord2d(1, 0);//top right
            Gl.glVertex2f(1280, 720);

            Gl.glTexCoord2d(0, 1);//bottom middle
            Gl.glVertex2f(0, -720);

            Gl.glTexCoord2d(1, 0);//top right
            Gl.glVertex2f(1280, 720);

            Gl.glTexCoord2d(0, 1);//bottom middle
            Gl.glVertex2f(0, -720);

            Gl.glTexCoord2d(1, 1);//bottom right
            Gl.glVertex2f(1280, -720);
        }
        Gl.glEnd();
    }

```

# Answer
> 0 votes
For starters, try replacing "x-width" with "x" and "y-height" with "y". Also, in order to debug it better, try and render only one triangle at a time.

# Answer
> 0 votes
I've found that you get better results if you use images where the height/width are powers of 2. ie. 16, 32, 1024 etc. Maybe take a look at the Texture class documentation and see if it specifies anything about that. It may be doing it's best to buffer the data but it gets garbled because of the dimensions. Also, somewhat less importantly, glBegin and glEnd are deprecated functions. If you are just getting started with textures I'd suggest getting familiar with using shaders / array buffers etc.

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


# Question
Title: How to Create a New Instance of a Game Object
Alright, please don't scald me here haha. I'm very new to XNA, C#, and game development as a whole. I have done web-design, but that is my main experience with programming. It is a Space Invaders type-ish game.

In the code below I have a Meteor class. In this class I want to create a meteor in a random location (on the X-axis) and then have it fall. I don't care much about it doing damage - yet.

I can always get one meteor created, and falling, yet when I press 'M' to create another instance of the class it isn't creating another meteor. I could very possibly be going about this entirely wrong...please forgive me if I am.

```
  class Meteor
   {

    private Random randomNumber = new Random();
    private Rectangle position;
    private int fallSpeed;
    private double damage;
    private int x, y = 0;
    private int WIDTH, HEIGHT;

    // List to hold meteors created (holds instance of Meteor class)
    List<Meteor> meteors = new List<Meteor>();

    // Texture for the meteor

    private Texture2D meteor;

    /// <summary>
    /// Create the meteor and each meteor's properties
    /// </summary>
    public Meteor()
    {
        HEIGHT = randomNumber.Next(0, 60);
        WIDTH = HEIGHT;
        fallSpeed = randomNumber.Next(0, 10);
        damage = fallSpeed * 2;
        x = randomNumber.Next(0, 600); // Randomly generates where meteor will spawn on X axis
    }

    public void createMeteor()
    {
        meteors.Add(new Meteor());
    }

    /// <summary>
    /// Load content (graphics) relating to the meteor
    /// </summary>
    public void LoadContent(ContentManager Content)
    {
        // Load meteor texture
        meteor = Content.Load<Texture2D>("Sprites/meteor");
    }

    /// <summary>
    /// Update the meteors position
    /// </summary>
    public void Update()
    {
        //Update position of metoer (falling)
        y++;

        // Testing purposes mostly...I want meteors to be created when I press 'M'
        if (Keyboard.GetState().IsKeyDown(Keys.M))
        {
            createMeteor();
        }
    }

    /// <summary>
    /// Draw the metoer (and it's new position).
    /// </summary>
    public void Draw(SpriteBatch spriteBatch)
    {
        position = new Rectangle(x, y, HEIGHT, WIDTH);
        spriteBatch.Draw(meteor, position, Color.White);

    }

    // So I can get the damage
    public double getDamage() { return damage; }
}
}

```

# Answer
You seem to be confused with some OO aspects here. When you have a class such as:

```
class Meteor
{
}

```

You are describing a template for every meteor you are going to create. This will describe what a SINGLE meteor should contain. So, following that, what attributes should EACH meteor have?

```
class Meteor
{
    Texture2D texture;
    Rectangle bounds;
    int       fallSpeed;
    double    damage;
    // x, y, WIDTH, HEIGHT are not needed here. That information can be obtained through the 'bounds' rectangle we have declared.
    // List of meteor is not needed. Why would each meteor contain a list of meteors?
}

```

So, that describes what each meteor would need. We need a reference to a texture2D in order to draw each, we need a bounds to describe the rectangle that the meteor lies within, for collision and position. We have a damage for each( bigger meteors might have bigger damage. ). That's it. x, y, width, and height would be a waste of memory here, because we know those things from the bounds rectangle.

So, what does each meteor *do*? It can be drawn, it can be updated, and it can be constructed:

```
class Meteor
{
    Texture2D texture;
    Rectangle bounds;
    int       fallSpeed;
    double    damage;

    public Meteor( Rectangle meteorBounds, int meteorFallSpeed, double meteorDamage,
                   Texture2D meteorTexture )
    {
        // We want to pass the bounds in as a parameter. This means, any one constructing
        // a meteor will be able to tell us how big they want it to be.
        bounds = meteorBounds;

        // Same again, we want different meteors to have different fall speeds, so let
        // that be descided by the owner of the object.
        fallSpeed = meteorFallSpeed;

        // Once again, decide the damage based on values that are passed in to us.
        damage = meteorDamage;

        // Pass in a reference. We do NOT want each meteor to allocate their own texture.
        // We would run out of vram pretty quickly. When the level is loaded, or the game
        // is started we load the texture. Then we pass it around to each meteor. This
        // way, each meteor knows where the texture is, it doesn't have it's own copy.
        texture = meteorTexture;
    }

    public void Update()
    {
        // Move the meteor down by the fall speed given to us in the constructor.
        bounds.y += ( int )fallSpeed;

        // No check for 'm' here. Why would a meteor create another meteor when 'm' is
        // pressed?
    }

    public void Draw( SpriteBatch spriteBatch )
    {
        // Just draw the texture we have at the rectangle x and y.
        spriteBatch.Draw( texture, new Vector2( bounds.x, bounds.y ), Color.White );
    }
}

```

There we go. Our meteor should be fully functional. It can be constructed( with any height, speed, damage, and texture ), it can be updated( moves downwards at it's falling speed ), and it can be drawn at it's current location.

So, how do we get a bunch of them on screen now? Well, let's go back to the Game1 class. Here we want to do a few things; load our meteor texture, make our random object, make a list of meteors, make it so we can add one when the 'm' key is pressed:

```
 public class Game1 : Microsoft.Xna.Framework.Game
 {
     GraphicsDeviceManager graphics;
     SpriteBatch spriteBatch;
     GraphicsDevice device;

     // Here we want our random class, so we can generate random positions for our meteors
     // just like the original code did.
     Random random = new Random();

     // Here we make the texture that will be loaded from a file somewhere. This will be
     // the only one that is loaded. All others will just be a reference to this one.
     Texture2D meteorTexture;

     // This is our list of meteors in our game.
     List<Meteor> meteors = new List<Meteor>();

     private void CreateMeteor()
     {
          int     size = random.Next( 0, 60 );
          int     fallSpeed = random.Next( 0, 10 );

          // We add a new meteor to the list. We give it a random size, randome fallSpeed,
          // and a damage based off the fall speed. The meteor texture we have already
          // loaded is passed in.
          meteors.Add( new Meteor( new Rectangle( Random.next( 0, 600 ), 0, size, size ),
                       fallSpeed, fallSpeed * 2, meteorTexture ) );
     }

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

     protected override void Initialize()
     {

         base.Initialize();
     }

     protected override void LoadContent()
     {
         spriteBatch = new SpriteBatch(GraphicsDevice);

         device = graphics.GraphicsDevice;

         // Load our meteor texture. This is the only place in the game this should be
         // done.
         meteorTexture = Content.Load<Texture2D>("Sprites/meteor");
     }

     protected override void UnloadContent()
     {
     }

     protected override void Update(GameTime gameTime)
     {
         if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
             this.Exit();

         if (Keyboard.GetState().IsKeyDown(Keys.M))
         {
             // If 'm' is down, we create a new meteor. Note that once this is working
             // this is going to make a lot of meteors. That's another issue, though.
             createMeteor();
         }

         // Here's something that was missing in the original code. It's not enough to
         // update one meteor, we must update each of them.
         foreach( Meteor meteor in meteors )
         {
              meteor.Update();
         }

         base.Update(gameTime);
     }

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

         // Only call begin and end once. You never want to call this for every object you
         // have.
         spriteBatch.Begin();
         // Once again we want to draw EACH meteor.
         foreach( Meteor meteor in meteors )
         {
              // Draw every single meteor, and pass in spriteBatch.
              meteor.Draw( spriteBatch );
         }
         spriteBatch.End();

         base.Draw(gameTime);
     }
 }

```

Here in our Game1 class, we maintain a list of meteors. Every frame we update them ALL by looping through them. We do the same with drawing. When we construct, we pass in information that should vary between meteors.
> 3 votes

# Answer
Welcome to the GameDev StackExchange.

For starters, as per the comments on your question, move the List of meteors out of the Meteor class, and into your base game class (by default Game1.cs) along with the createMeteor() function/

Then in Game1, modify the Update method to loop over the list of Meteors, and call update on them. Do the same for Game1.Draw

The next update is to move the meteor creation code from the Meteor's update into Game1's update method, either above or below the loop.

Next, shift the meteors LoadContent texture load call to Game1's LoadContent along with its corresponding variable. After that modify the Meteor's constructor to take a Texture2D object and store it, and use it in the draw.

In case you have having trouble following this description, I have provided a summary of the changes to help you see.

Game1.cs

```
List<Meteor> meteors = new List<Meteor>();

Texture2D meteorTexture;

...

public override void LoadContent()
{
    // Load meteor texture
    meteorTexture = Content.Load<Texture2D>("Sprites/meteor");

    ...
    // rest of LoadContent
}

public override void Update(GameTime gameTime)
{
    foreach (Meteor m in meteors)
        m.Update();

    // Testing purposes mostly...I want meteors to be created when I press 'M'
    if (Keyboard.GetState().IsKeyDown(Keys.M))
    {
        createMeteor(meteorTexture);
    }

    ...
    // rest of Update
}

public override void Draw(GameTime gameTime)
{
    foreach (Meteor m in meteors)
        m.Draw(spriteBatch);

    ...
    // rest of Draw
}

```

Meteor.cs

```
/// <summary>
/// Create the meteor and each meteor's properties
/// </summary>
public Meteor(Texture2D meteorTexture)
{
    // set texture here
    meteor = meteorTexture;

    ...
    // rest of constructor
}

/// createMeteors() and LoadContent() used to live here

```
> 0 votes

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


title: Bullet pointer becoming zero

text:
# Question
Title: Bullet pointer becoming zero
I am currently trying to implement the Bullet physics into my game project. However, when i add some rigid bodies to the scene, i occasionally get an error in *btDbvtBroadphase.cpp* at the line
*if(proxy-\>stage==STAGECOUNT)* (line 294).

If i then inspect the **proxy** pointer, it points to *0x0*. If I go back to the function *btCollisionWorld::updateSingleAabb(btCollisionObject * colObj)* on the call stack, and inspect the member **m\_broadphaseHandle**, it is non-zero, which is being passed as first parameter to *btDbvtBroadphase::setAabb(btBroadphaseProxy\* absproxy, const btVector3& aabbMin, const btVector3& aabbMax, btDispatcher\** \__ *formal)*.
In this method it is being cast into a *btDbvtProxy* pointer and stored in **proxy**. What I don't get here is, why **proxy** becomes *0x0*, even though a valid pointer is being passed to the function.

The call stack looks like this:

```
MyProject.exe!btDbvtBroadphase::setAabb(btBroadphaseProxy * absproxy, const btVector3 & aabbMin, const btVector3 & aabbMax, btDispatcher * __formal) Line 294   C++
MyProject.exe!btCollisionWorld::updateSingleAabb(btCollisionObject * colObj) Line 171   C++
MyProject.exe!btCollisionWorld::updateAabbs() Line 204  C++
MyProject.exe!btCollisionWorld::performDiscreteCollisionDetection() Line 220    C++
MyProject.exe!btDiscreteDynamicsWorld::internalSingleStepSimulation(float timeStep) Line 492    C++
MyProject.exe!btDiscreteDynamicsWorld::stepSimulation(float timeStep, int maxSubSteps, float fixedTimeStep) Line 452    C++

```

The initialization of bullet looks like this:

```
broadphase = new btDbvtBroadphase();
collisionConfiguration = new btDefaultCollisionConfiguration();
dispatcher = new btCollisionDispatcher(collisionConfiguration);
solver = new btSequentialImpulseConstraintSolver;

world = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
world->setGravity(btVector3(0.0f, -10.0f, 0.0f));

```

I create RigidBodies procedurally and this is, how I add them:

```
bp.mesh = new btTriangleMesh(true, false);

for (int i = 0; i < bp.numFaces; ++i)
{
    btVector3 a(vertices[indices[i * 3 + 0]].position.x, vertices[indices[i * 3 + 0]].position.y, vertices[indices[i * 3 + 0]].position.z);
    btVector3 b(vertices[indices[i * 3 + 1]].position.x, vertices[indices[i * 3 + 1]].position.y, vertices[indices[i * 3 + 1]].position.z);
    btVector3 c(vertices[indices[i * 3 + 2]].position.x, vertices[indices[i * 3 + 2]].position.y, vertices[indices[i * 3 + 2]].position.z);
    bp.mesh->addTriangle(a, b, c);
}

btMotionState* ms = new btDefaultMotionState;
btBvhTriangleMeshShape* shape = new btBvhTriangleMeshShape(bp.mesh, true);

sect->rigidBody = new btRigidBody(0.0f, ms, shape);

btWorld->addRigidBody(sect->rigidBody, 64, 128);

```

My question now is, why **proxy** occasionally points to *0x0*, even though it should be a valid pointer? I downloaded and successfully compiled bullet-2.82-r2704 with VS2012 and changed the project settings from /MT(d) to /MD(d), if this does matter.

---

Edit: I may also mention that the rigid bodies are added in a different thread, than the thread in which I initialize and simulate the bullet physics. Can this cause any problems?

# Answer
It seems that it was in fact, caused by adding rigid bodies from different threads. After I moved the call to *btDynamicsWorld::addRigidBody* into the main thread, I did not receive this error again.
> 0 votes

---
Tags: c++, bullet-physics, memory
---