# Question
Title: How am I supposed to timestep this gravitational simulator
The following code is what I use to simulate a particles movement in a gravitational scenario.

The problem is that this simulation needs to work well on devices with different aspect ratios, and different frame rates.

Basically offscreen particles spawn in corners are shot towards the corner of the opposite side. Meanwhile each touch on the screen is a gravitational force attracting the particles to it. The simulation works fine in 30fps, however at other fps' it begins to mess up.

```
func gravitationalMovement()
{
    var c = vv                                          //vv is simply holding the velocity I put it into c to make the code smaller, and debugging easier

    let pos = Point(x: particlePosX, y: particlePosY)   //In the real code this isn't that simple but for this questions sake it is

    var build = Point()
    let array = TB.allFingersDown                       //An array of finger structs for each one on screen

    for fing in array                                   //Go through every finger
    {
        let planet = fing.location
        let vector = Math.subtract(pos, planet)         //Vector between particle and finger
        let dist = Math.dist2Psq(vector)                //Distance squared
        let theta = Math.calculateAngle(vector)

        var force = 19920 / dist
        let cap = Storage.bounds.tb / 50                //Height / 50
        if (force > cap){force = cap}                   //Cap it off so things don't go bonkers

        build.x += force * cos(theta)                   //Add the resulting velocity to the one that will hold the additive velocity
        build.y += force * sin(theta)
    }

    c.x += build.x                                      //Add the resulting velocity from all of the fingers to the existing velocity
    c.y += build.y

    particlePosX += c.x                                 //Add velocity to position
    particlePosY += c.y

    let drag = pow(1.009, Storage.dtPercC)              //Drag the velocity
    c.x /= drag
    c.y /= drag

    if (isInBoundsPlus() != -1)                         //If out of bounds
    {
        //Respawn in one of the 4 corners, and get shot out to the opposite corner
        let corner = arc4random_uniform(4)              ///0-3
        var p2 = Point()
        if (corner == 0)
        {
            //Bottom left
            particlePosX = 0
            particlePosY = 0
            p2 = Point(x: Storage.bounds.rb, y: Storage.bounds.tb)
        }
        else if (corner == 1)
        {
            //bottom right
            particlePosX = Storage.bounds.rb
            particlePosY = 0
            p2 = Point(x: 0, y: Storage.bounds.tb)
        }
        else if (corner == 2)
        {
            //Top Left
            particlePosX = Storage.bounds.lb
            particlePosY = Storage.bounds.tb
            p2 = Point(x: Storage.bounds.rb, y: 0)

        }
        else if (corner == 3)
        {
            //Top Right
            particlePosX = Storage.bounds.rb
            particlePosY = Storage.bounds.tb
            p2 = Point(x: 0, y: 0)
        }
        let p1 = Point(x: particlePosX, y: particlePosY)

        let angle = Math.calculateAngle(p1, p2) + Math.rand2(-0.01, secondNum: 0.01) //Add some variance

        let ar = Storage.bounds.rb / Storage.bounds.tb                              //Multiplied by aspect ratio so that the particle has enough speed to get to other corner even if device is wide
        let diagonal = (Math.dist2P(p1, p2) / 60) * ar

        c.x = diagonal * cos(angle)                                                 //Set the velocity
        c.y = diagonal * sin(angle)
    }
    vv = c                                                                          //Save the velocity to the variable vv
}

```

I believe the solution is to better timestep this code. I have 2 variables that will help me with this.

1. dt: probably needs no explanation but this is the time between frames
2. Storage.dtPercC: This is the dt percent, which is basically `dt / (1 / 60.0)`. If the simulation runs at an ideal framerate this variable will be 1, however as the fps lowers that number will go up.

Yes I have checked and these number work and are accurate.

The movement is velocity based, each frame the velocity is added to position. The velocity is affected by two forces.

1. Drag
2. The additive force from the fingers
3. Bursting force when a particle spawns in a corner, it must be enough to get it to the other corner, but not too much where the particles skip around gravitation.

So far I have figured out how to make the drag force the same on all devices by doing `pow(1.006, Storage.dtPerc)` as a devisor to the velocity however I still have two issues.

1. The bursting time stepping, the lower the fps the less likely it is for particles to get to the other corner because of increased drag per frame
2. The velocity from the planets (fingers)

I have tried multiplying numbers by the dt percent, and pow'ing numbers to the dt percent.

My question is where in the simulation do I multiply, divide, or raise a value to the power of dt Percent? I can not figure out where and how this belongs.

# Answer
The solution is to abandon your concept of dtpercent. To make it framerate independent deltatime between frames is all you need.

Framerate 60 fps: dt will be 0.016 miliseconds with a framerate of 30 this value will be 0.032 miliseconds. Thus have everything based on the `dt` and scale your simulation units to 'x per second' and things will run framerate independant.

So if you want something to move *60 pixels per second*:

*at 60fps*: speed * dt = 60 * 0.016 =\> 1 pixel per frame.

*at 30fps*: speed * dt = 60 * 0.032 =\> 2 pixels per frame.

Looking at your code, swap out dtpercent for dt and it should work fine. You may need to adapt your base values (since those seem to be based on 30fps?)
> 2 votes

---
Tags: physics
---


# Question
Title: Can I use "Finding Dori" as my ios game title?
I am creating a fishing game for which I want to give name "Finding Dori". As the film is already released with title "Finding Dory", and they have game on App store named *Finding Dory: Just Keep Swimming*.

Is it okay if I use "Finding Dori" as my game name? Or any other possibilities to use such name? I have created Dori character in my style in different manners.

Thanks all for your quick responses and from your votes only I come to know how much people is loving copies :). Thus, I decided to use something unique. The app is under review for now.

Although the game will have updates sooner than later but I hope you will appreciate my work :).

# Answer
"Finding Dory" is a registered trademark by Disney Enterprises, Inc. You can look that up on the US Patent and Trademark Office.

A trademark is also violated when you use a name which is so similar that one might confuse it with the trademark. Most people looking for a game about the movie might not remember if the name is written with `y` or `i`, so the confusion potential seems quite high.

Note that Disney is a company which takes defending their intellectual property **very** seriously. So serious that they did in fact repeatedly lobbied politicians to change copyright laws so their most valuable IPs would not fall into the public domain. When you feel that there is *any* possibility your project might violate their trademarks, consult a lawyer.
> 10 votes

---
Tags: legal, trademark
---


title: Texture Editing with Multi-Threading

text:
# Question
Title: Texture Editing with Multi-Threading
So I have this giant Texture2D (4096 * 4096, don't ask why) and all its data stored in an array of Colors. When I hit left MouseButton I create a blue 64 by 64 square at the cursor's position using the following code.

```
        int dx = Mouse.GetState().X + (int)camera.Pos.X - graphics.PreferredBackBufferWidth / 2;
        int dy = Mouse.GetState().Y + (int)camera.Pos.Y - graphics.PreferredBackBufferHeight / 2;

        for (int x = dx; x < dx + 64; x++)
        {
            for (int y = dy; y < dy + 64; y++)
            {
                textureData[x + y * texture.Width] = Color.Blue;
            }
        }

        texture.SetData<Color>(lvlData);

```

Sadly this hangs the program for a split second. So I thought, maybe it's possible to run that piece of code in a different thread.

Is it possible to multi-thread that and if so, how would I go about doing that? Or is it another way to optimize this?

Thanks for any help!

# Answer
Setting data in the texture is an expensive operation at that resolution size. It should be avoided if you plan to do that every frame.

I don't know why you want to set the data in the source image like that, but for the texture there are a couple of options:

If you just want the blue square at the current mouse position:

1. Draw the texture to the screen and then draw a blue square where the mousecursor is.
2. Alternatively, create a `RenderTarget2D`; draw the texture and then draw the blue square to the rendertarget.

If you want to blue squares as if they were "painted" (thus not removed, which is what I gather from the code you posted):

3. Create a `RenderTarget2D` that isn't cleared between frames- that is use the `RenderTargetUsage.PreserveContents` flag when creating the rendertarget, draw the blue square to the rendertarget whenever the mousebutton is clicked.
4. Keep a list of mouseclicks and draw the blue squares in a spritebatch after you draw the texture to the screen.
> 2 votes

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


title: How to model vehicle driving physics?

text:
# Question
Title: How to model vehicle driving physics?
How to model the physics of a car in a racing game?

In real life, vehicle movement is inherited from the wheels. But after reading a few articles on the subject (a lot of which are 10 years old), I realize that the 'real world' physics is in fact often faked with various equations and constants.

I want to create custom driving model to learn about it mostly, but I don't want to start wrong so that's why I am here.

# Answer
Methods of creating vehicle physics changes dramatically from game to game. Often, as you have suggested, they focus on the body of the car and leaving the wheels as visual. The way I suggest going about this is using this system as a prototype, play around with what it can do and find the limitations, such as wheels clipping through uneven planes. This brings us to a second model, where wheels are the driving force. In this model you need to pay attention to a few factors:

\_Where wheels are attached to the car body (since the body will move and control the movement of the wheel) \_Traction between the wheel and surface \_and finally the suspension

These are all key factors in determining the movement of the body and the wheels as well as their positions relative to each other. Good luck with the project, a complex system such as a car, is often difficult to replicate on a computer with any degree of realism or accuracy. So definitely start with the first model, since it is much simpler and can highlight key problems you may run into later.
> 3 votes

# Answer
The way you'll do it really depends on the kind of game you want to make.

If you want to achieve a realistic behaviour, you'll have to start by modeling nearly the whole car, with a decent physics engine.

If you want to achieve a more casual feel (games like MarioKart), you'll have to simplify a lot of things.

In any case, you'll have to fake some things, because real-time real-life physics simulation for a car game is not needed. The game has to *feel* right, not *be* right. You'll have to fake things more in a casual game than in a realistic game.
> 0 votes

---
Tags: physics, car, vehicle
---


title: Real-time ray tracing: How is it done?

text:
# Question
Title: Real-time ray tracing: How is it done?
I wonder what technology applications like Xara3D use to be able to perform real-time ray tracing.

How is such good quality rendering done in real-time?

# Answer
> 6 votes
You can find the tutorial Jacco Bikker made here: http://www.flipcode.com/archives/Raytracing\_Topics\_Techniques-Part\_1\_Introduction.shtml

It's kinda advanced since it goes through almost all important topics about Ray-Tracing, including Reflections, Refractions, Soft Shadows etc.

# Answer
> 3 votes
This might interest you: http://made.nhtv.nl/~bikker/

This is Jacco Bikker's website, he's currently building a leading realtime raytracing and pathtracing engine called Brigade 2 ( 1 was non GPU, 2 is now utilizing the GPU ). You can find a lot of material on his website regarding realtime raytracing.

# Answer
> 0 votes
Here's another option - NVidia provide a free GPU accelerated raytracing engine, but it only works on their GPUs.

http://developer.nvidia.com/optix

# Answer
> 0 votes
Typically, its done via...

* GPGPU(General-purpose computing on graphics processing units) languages such as CUDA(An Nvidea specific api) or OpenCL(Platform independent).
* Doing the calculations in the fragment/pixel or compute shaders in raster graphics api's such as OpenGL or DirectX.

Or, if you really have to...

* Doing it cpu-side with **highly** optimized code.

Even doing it on the GPU isn't very fast. Which is why we typically employ octrees and various other methods of minimizing ray-primitive intersections.

And incase your up to some reading... https://graphics.stanford.edu/papers/rtongfx/rtongfx.pdf

---
Tags: raytracing
---


# Question
Title: How can I handle intellectual property violations in user-generated content?
I recently made a simulation game like Gamedev Tycoon where you are in charge of a game company and planning to release it on app stores soon.

I have few questions about trademark and copyright laws, as in game there are different companies (competitor) who release games, make sequels to previous games, release consoles etc. I know that under parody law I can change a company name from MICROSOFT to MICROCRAFT or MINORCRAFT etc. But what if I provide users an editor where they can change company names (if they want to) from MICROCRAFT to MICROSOFT?

Do changes made by players with my editor violate any copyright or trademark law? How can I handle that?

# Answer
> 5 votes
> But what if I provide users an editor where they can change company names (if they want to) from MICROCRAFT to MICROSOFT?

Generally, when you provide tools that allow your users to produce content for your game, you'll want to include in your game's license agreement terms that dictate how and what may be produced. The single- or multi-player nature of the game isn't really an issue, the issue is if the content can be reasonably expected to be distributed by users. It almost certainly always can.

For example, Skyrim is a single-player game that includes official modding tools in the form of its Creation Kit. The EULA for the Creation Kit requires that:

> You shall not create any New Materials that infringe upon the rights of others, or that are libelous, defamatory, harassing, or threatening, and You shall comply with all applicable laws in connection with the New Materials.

This kind of clause helps to indemnify you, the author of the software, against intellectual property violations perpetuated by (and appearing to be part of) your software.

Include such a clause in your EULA.

# Answer
> 4 votes
*I'm not a lawyer, this is not a legal advice site. Opinions, here, are just that: opinions. To have a definitive answer, you should consult a lawyer.*

> I know that under parody law \[...\]

I would suggest to be cautious about it. To use that it's easier if you have an history of goofing around with various subjects. *Microcraft* could very well be interpreted as defamatory by Microsoft. Since they have more money than you do, they'll be able to make their case clear to a judge more easily than you will.

> But what if I provide users an Editor where they can change company name \[...\]

It depends.

If your game is to be played in a single player fashion, and that this name will never be sent out in the public, nor shared, you won't have any issues.

However, if you're to publish content on the internet or to other users, this *could* become an issue. You will not have to enforce Copyright police until BigCompany thinks it's too much. You might want to consider putting a mechanism in your game to prevent the usage of certain names.

I'll say it again: **you should consult a lawyer, *before* you release your game**.

---
Tags: copyright, trademark
---


# Question
Title: What is the best way to handle the actual render loop?
I've been diving into OpenGL. So far, so good, with quite a few features implemented and objects look good. Now I want to move on to more complicated scene, with many objects.I just want to know how to properly handle rendering a large amount of different types of object.

---

Here is my code:

```
void RenderTests::renderModel2(MeshInfo& meshInfo, SArray<Point3>& positions,
    CameraView cameraView)
{
    bool status = SDLTools::initGL(3, 3);

    if(status = false)
    {
        dout+"OGL init failed!";
        dout++;
        return;
    }

    SArray<float>& verts = meshInfo.getVerts();

    DirectionalLight directionalLight;
    directionalLight.direction = Point3(-0.1f, 1.0f, 0.5f);
    directionalLight.ambient = Point3(0.3f, 0.3f, 0.3f);
    directionalLight.diffuse = Point3(0.2f, 0.2f, 0.2f);
    directionalLight.specular = Point3(0.2f, 0.2f, 0.22f);

    PointLight light;
    light.position = Point3(0.0f, 0.0f, 1.5f);
    light.ambient = Point3(0.2f, 0.2f, 0.2f);
    light.diffuse = Point3(0.8f, 0.8f, 0.8f);
    light.specular = Point3(0.8f, 0.8f, 0.85f);
    light.constant = 0.5f;
    light.linear = 0.09f;
    light.quadratic = 0.032f;

    Material& material = meshInfo.getMaterial();

    Point3 lightAdjustment(0.0f, 0.0f, 0.0f);

    SArray<glm::mat4> modelMatrices;
    modelMatrices.setSize(positions.length());

    for(long i=0; i<positions.length(); i++)
    {
        glm::mat4 model;
        SDLTools::transformModel(model, positions[i], Point3(1.0f, 0.3f, 0.5f),
            20.0f * (float)i, 1.0f);
        modelMatrices[i] = model;
    }

    Shader testShader("../../testShaders/renderObject17Vert.txt",
        "../../testShaders/renderObject17Frag.txt");

    //glEnable(GL_DEPTH_TEST);

    GLuint VBO, VAO, modelBuffer;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &modelBuffer);

    glBindVertexArray(VAO);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, verts.getContentsSize(), verts.getContents(),
        GL_STATIC_DRAW);

    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glEnableVertexAttribArray(2);
    glEnableVertexAttribArray(3);
    glEnableVertexAttribArray(4);
    glEnableVertexAttribArray(5);
    glEnableVertexAttribArray(6);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat),
        (GLvoid*)(3 * sizeof(GLfloat)));
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat),
        (GLvoid*)(6 * sizeof(GLfloat)));

    glBindBuffer(GL_ARRAY_BUFFER, modelBuffer);
    glBufferData(GL_ARRAY_BUFFER, modelMatrices.getContentsSize(),
        modelMatrices.getContents(), GL_STATIC_DRAW);

    glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 4*sizeof(glm::vec4), (GLvoid*)0);
    glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, 4*sizeof(glm::vec4),
        (GLvoid*)(sizeof(glm::vec4)));
    glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, 4*sizeof(glm::vec4),
        (GLvoid*)(2 * sizeof(glm::vec4)));
    glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, 4*sizeof(glm::vec4),
        (GLvoid*)(3 * sizeof(glm::vec4)));

    glVertexAttribDivisor(3, 1);
    glVertexAttribDivisor(4, 1);
    glVertexAttribDivisor(5, 1);
    glVertexAttribDivisor(6, 1);

    glBindVertexArray(0); // Unbind VAO

    glEnable(GL_DEPTH_TEST);

    bool quit = false;
    SDL_Event e;

    while(!quit)
    {
        while(SDL_PollEvent(&e)!=0)
        {
            if(e.type == SDL_QUIT)
            {
                quit = true;
            }
        }

    GLuint diffuseMap;
    GLuint specularMap;
    GLuint normalMap;

    SDLTools::loadAndGenerateTexture(diffuseMap, material.diffuseMap);
    SDLTools::loadAndGenerateTexture(specularMap, material.specularMap);
    SDLTools::loadAndGenerateTexture(normalMap, material.normalMap);

        GLfloat deltaTime = SDLTools::getFrameTime();

        lightAdjustment.x = -sin(deltaTime*0.0005f)*0.5f;
        lightAdjustment.y = sin(deltaTime*0.00025f)*1.0f;

        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, diffuseMap);
        glUniform1i(glGetUniformLocation(testShader.program, "material.diffuseMap"), 0);

        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, specularMap);
        glUniform1i(glGetUniformLocation(testShader.program, "material.specularMap"), 1);

        glActiveTexture(GL_TEXTURE2);
        glBindTexture(GL_TEXTURE_2D, normalMap);
        glUniform1i(glGetUniformLocation(testShader.program, "material.normalMap"), 2);

        testShader.use();

        glm::mat4 view = SDLTools::lookAt(cameraView);
        glm::mat4 projection = SDLTools::perspective(cameraView.fov, 0.1f, 100.0f);

        GLint modelLoc = glGetUniformLocation(testShader.program, "model");
        GLint viewLoc = glGetUniformLocation(testShader.program, "view");
        GLint projLoc = glGetUniformLocation(testShader.program, "projection");
        GLint lightPosLoc = glGetUniformLocation(testShader.program, "lightPos");
        GLint viewPosLoc = glGetUniformLocation(testShader.program, "ViewPos");

        GLint dlightPositionLoc = glGetUniformLocation(testShader.program,
            "directionalLight.direction");
        GLint dlightAmbientLoc = glGetUniformLocation(testShader.program,
            "directionalLight.ambient");
        GLint dlightDiffuseLoc = glGetUniformLocation(testShader.program,
            "directionalLight.diffuse");
        GLint dlightSpecularLoc = glGetUniformLocation(testShader.program,
            "directionalLight.specular");

        GLint lightPositionLoc = glGetUniformLocation(testShader.program,
            "light.position");
        GLint lightAmbientLoc = glGetUniformLocation(testShader.program,
            "light.ambient");
        GLint lightDiffuseLoc = glGetUniformLocation(testShader.program, "light.diffuse");
        GLint lightSpecularLoc = glGetUniformLocation(testShader.program,
            "light.specular");
        GLint lightConstantLoc = glGetUniformLocation(testShader.program,
            "light.constant");
        GLint lightLinearLoc = glGetUniformLocation(testShader.program, "light.linear");
        GLint lightQuadraticLoc = glGetUniformLocation(testShader.program,
            "light.quadratic");

        GLint materialShininessLoc
            = glGetUniformLocation(testShader.program, "material.shininess");

        // Pass the matrices to the shader
        glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
        glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));
        glUniform3f(viewPosLoc, cameraView.position.x,
            cameraView.position.y, cameraView.position.z);
        glUniform3f(lightPosLoc, light.position.x, light.position.y, light.position.z);

        glUniform3f(dlightPositionLoc, directionalLight.direction.x,
            directionalLight.direction.y, directionalLight.direction.z);
        glUniform3f(dlightAmbientLoc, directionalLight.ambient.x,
            directionalLight.ambient.y, directionalLight.ambient.z);
        glUniform3f(dlightDiffuseLoc, directionalLight.diffuse.x,
            directionalLight.diffuse.y, directionalLight.diffuse.z);
        glUniform3f(dlightSpecularLoc, directionalLight.specular.x,
            directionalLight.specular.y, directionalLight.specular.z);

        glUniform3f(lightPositionLoc, light.position.x+lightAdjustment.x,
            light.position.y+lightAdjustment.y, light.position.z);
        glUniform3f(lightAmbientLoc, light.ambient.x, light.ambient.y, light.ambient.z);
        glUniform3f(lightDiffuseLoc, light.diffuse.x, light.diffuse.y, light.diffuse.z);
        glUniform3f(lightSpecularLoc, light.specular.x, light.specular.y,
            light.specular.z);
        glUniform1f(lightConstantLoc, light.constant);
        glUniform1f(lightLinearLoc, light.linear);
        glUniform1f(lightQuadraticLoc, light.quadratic);

        glUniform1f(materialShininessLoc, material.shininess);

        glBindVertexArray(VAO);
        glDrawArraysInstanced(GL_TRIANGLES, 0, 36, modelMatrices.length());

        glBindVertexArray(0);

        // Swap the screen buffers
        SDLTools::swapBuffers();
    }

    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);
    glDeleteBuffers(1, &modelBuffer);

    SDLTools::cleanAll();
}

```

As you can see in `renderModel`, I just take a bunch of positions, some vertices and a material stored in the `meshInfo` object and use instancing. It seems to work well enough, at least, for a test. But what happens when I have dozens of objects? What I mean is, should I be rebuilding everything for each object every frame?

Obviously, I can't have the textures for say 50 objects just sitting on the graphics card, for example. What about at the bottom, where I delete all those buffers? Should that be happening every frame, assuming I have a "real" scene which is going to have lots of different geometries, and can't possibly fit? I have heard some about batching, but this would seem to work only with geometry that uses the same textures, while what I am talking about is distinct object types.

---

I moved the image loading stuff into the loop, and it slows it down, a lot. Should I be deleting these image buffers each frame, as well? The actual image data should be cached, it's not actually pulling it from the disk each frame. It's still quite slow, though.

Here is my code; I want to run through this whole process except, for N object types:

```
void SDLTools::loadAndGenerateTexture(GLuint& texture, SString fullPath)
{
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    int width, height;
    unsigned char* image = TextureUtil::loadImage(width, height, fullPath);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB,
        GL_UNSIGNED_BYTE, image);
    glGenerateMipmap(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, 0);
}

```

# Answer
> 3 votes
> I just want to know how to properly handle rendering a large amount of different TYPES of object.

Whatever you consider a "type of object," you can usually avoid actually having too many types of things that the renderer needs to know how to process and draw. Fundamentally, for every given draw call, the renderer needs to know:

* what geometry (vertex data) will I draw?
* what textures and shaders will I use?
* what transforms will I use?
* what other graphics state will I set (does this draw need blending, etc)?

You can generally abstract *all* of that into a single "render descriptor" type of object, at which point the various ways to fill out a render descriptor are how different "object types" control how they appear. It's quite easy to use such a type to draw animated 3D models as well as 2D geometry for UI or sprites, et cetera.

It's also fairly easy to then extend such a type with new fields and capabilities (maybe you add blending later, maybe you support post-processing later, et cetera) rather than create a whole new type of rendering description that duplicates a bunch of the boilerplate setup and buffer management code.

> But what happens when I have dozens of objects?

You do the same thing, but dozens of times. This is why wrapping up the process of describing a draw call into a class (for related state and functions) is useful. It makes it easier to do something more than once.

> What I mean is, should I be rebuilding everything for each object every frame?

Definitely not. That's *really* slow.

There are some things you would want to update dynamically. But for the vast majority of things you should load them once, at startup or similar. This includes loading textures from the disk, filling out buffers with static vertex data, and so on.

It is particularly useful to make your textures different objects than your render descriptor, for example. That way your descriptor can just have a *pointer or reference to* the textures it uses. Similarly with the geometry data. That means you don't duplicate complete sets of geometry and textures just to have another copy of an object.

(Instancing also helps here, but there are still cases where you'd want two different non-instanced sets of geometry to use some shared textures).

> Obviously, I can't have the textures for say 50 objects just sitting on the graphics card for example.

You probably could. GPUs have a ton of memory and if you're not going insane with your texture sizes they'll probably fit.

I wouldn't worry about this yet. At some point it will be a problem and you'll want to implement a streaming system that can let you discard textures you're not using and know when to reload them just before you need them again. But don't get bogged down in implementing that before you implement the rest of the basics, it won't be immediately necessary. It will be easier to add after the fact, especially if you do a good job building out your texture and render descriptor abstractions.

> What about at the bottom where I delete all those buffers? Should that be happening every frame

No. A good rule of thumb is "don't do it per frame." Anything you do per-frame becomes hot, and a potential bottleneck. Resource creation and destruction is usually expensive, and expensive things are not what you want to be doing in a hot inner loop.

> I have heard some about batching, but this would seem to work only with geometry that uses the same textures

Yes. Batching is generally about trying to group together objects with related state so you don't have to change states often while rendering, because state changes can be expensive. Consider this recent question about draw call performance. Batching is not something you need to worry about *immediately*. It will naturally be a lot easier if you only have type of thing (a render descriptor) to sort or group by.

> Also, I moved the image loading stuff into the loop and it slows it down a lot. Should I be deleting these image buffers each frame as well?

I'll leave that as an exercise for the reader ;) What do you think?

---
Tags: opengl
---


# Question
Title: How to bundle JRE with a game on Steam for Mac users?
Heyo!

I have looked for a step by step tutorial everywhere and haven't been able to find anything so please try to be helpful and fairly slow.

I am creating a game for Steam and I am using Java to write it. I chose Java as it can be run cross-platform and is the one in which I am the most familiar. On this recent question I asked I was told I could bundle the JRE I needed with the game using a program like Launch4J. But I can't find anything about converting the bundle into an executable that Mac users can run.

So my questions are thus:

1) Are there any step by step tutorials for bundling a completed Java program with the needed JRE into an executable for not only Windows but Mac users as well?

2) And if not, would someone be kind enough to create a quick step by step list of everything I need to do?

# Answer
> 1 votes
You might consider packr, one of the libgdx tools.

From the project's read.me description, it

> Packages your JAR, assets and a JVM for distribution on Windows, Linux and Mac OS X, adding a native executable file to make it appear like a native app. Packr is most suitable for GUI applications, such as games made with libGDX.

You can specify the JRE you wish to bundle. A good source of pre-built OpenJDK packages is Azul's Zulu OpenJDK distribution.

Another option might be to use Oracle's javapackager, which comes with the Oracle JDK. It's use is described in the Java deployment guide.

One advantage of packr over javapackager is that it supports minimization of the size that the JRE adds to your installation, mainly by removing unneeded classes from rt.jar.

---
Tags: java, macos, steam
---


# Question
Title: DrawString and Render graphics after custom time
I want to draw String after some second like "Boss is incoming",and after the string is disappeared i want to draw the Boss.I have the graphics and the string so my question is how to add timer for string and graphics?

# Answer
I'm assuming you have paintComponent() already set up. You just need to use java.util.Timer and java.util.TimerTask. Timer is a class that runs a method implemented in TimerTask after a delay. TimerTask is an abstract class that allows you to implement the method that Timer runs. The function that Timer runs is TimerTask's run().

In TimerTask's run(), you just need to add code that changes what repaint() draws.

```
//set up Timer so it runs after how many seconds you need the text to appear for.
//Then in your TimerTask implementation add code that removes the text and then renders your new image

@Override
public void run()
{
    //code that removes text
    //code that renders image
}

```

If you your paintComponent() draws based on an ArrayList of images, your run implementation could probably look like this:

```
@Override
public void run()
{
    imageList.remove(yourString);
    imageList.add(theBoss);
}

```
> 1 votes

---
Tags: java, graphics, timer, swing
---


# Question
Title: Which is the most efficient way to make the screen follow a sprite?
This is my first non-board game and I'm trying to learn a bit about 2D graphics in Java. But I don't know, how should I efficiently implement a *camera* to make the screen follow the main character. I have a position-fixed, unchanging terrain as *BufferedImage* on my map and other also mobile and animated entities, including the character itself. Right now I'm using some calculations(x of character - middle of screen) each time on *repaint()* to draw the level on the correct position from the (0,0) coordinates. But this method does a lot of calculation and drawing, even for the fixed map. Is there a better and more efficient way?

# Answer
**Everytime you move the sprite, move the camera too.**

This sounds like it's essentially what you're doing now. If you're encountering performance issues, then you should profile your code to determine where your slow code is. If you're not seeing performance issues, then you don't need to worry about performance issues. Doing a few calculations every frame to determine the camera position is miniscule in terms of processing power.
> 1 votes

---
Tags: java, sprites, camera
---


# Question
Title: How do you restrict sideway movement in 3D endless runner in Unity?
I have been making a endless runner 3d game and implemented 3 lane side way movement. It's working perfectly, although I want to restrict my movement for the 3 lanes only. If my character for example say on left lane, If I press left again it should not move to the side anymore since there's not lane beyond the left one. I did implemented a logic for this, though when I press either left or right in the borders of the lanes it freezes the side way movement. Any idea on how to stop this. This is my code.

PlayerMortor.cs

```
     private bool isChangingLane = false;
     private Vector3 locationAfterChanginLane = Vector3.zero;
     private Vector3 sideWayMovementDistance = Vector3.right * 2f;
     private float sideWaySpeed = 6f;

     void Update()
        {
            currentBaseState = anim.GetCurrentAnimatorStateInfo(0);

            if (controller.isGrounded)
            {
                verticalVelocity = -0.5f;
                if (currentBaseState.fullPathHash == locoState)
                {
                    if (Input.GetButtonDown("Jump"))
                    {
                        verticalVelocity = 18f;

                        anim.SetBool("Jump", true);
                    }
                }

                MoveLeftRight(); //Call sideway movement on update()

                if (isChangingLane)
                {
                    if (Math.Abs(transform.position.x - locationAfterChanginLane.x) < 0.1f)
                    {
                        isChangingLane = false;
                        moveVector.x = 0;
                    }
                }
            }
       }

    private void MoveLeftRight() //Sideway Movement function
    {
        if (controller.isGrounded && !isChangingLane)
        {
            isChangingLane = true;

            if (Input.GetKeyDown(KeyCode.A))
            {
                locationAfterChanginLane = transform.position - sideWayMovementDistance;
                moveVector.x = -sideWaySpeed;
            }
            else if (Input.GetKeyDown(KeyCode.D))
            {
                locationAfterChanginLane = transform.position + sideWayMovementDistance;
                moveVector.x = +sideWaySpeed;
            }
        }
    }

    private void OnControllerColliderHit(ControllerColliderHit hit) //Restriction when we move sideways beyond border
    {
        if (hit.collider.gameObject.tag == "Border")
        {
            Debug.Log("Border Hit");
            isChangingLane = false;
            moveVector.x = 0;
        }
    }

```

Any help would be appreciated. :)

# Answer
Imagine it as a simple state machine.

Keep track of your current state, and when you get an incoming state change request (the key presses), compare it to the current state to see what you should do.

```
//At the top of your script
public enum Lane {Left, Center, Right}
public enum MoveDirection {Left, Right, None}

Lane currentLane = Lane.Center;

//In the update method
MoveDirection requestedMoveDirection = MoveDirection.None;
if (Input.GetKeyDown(KeyCode.A)) {
    requestedMoveDirection = MoveDirection.Left;
} else if (Input.GetKeyDown(KeyCode.D)) {
    requestedMoveDirection = MoveDirection.Right;
}
switch(requestedMoveDirection) {
    case MoveDirection.Right:
        if(currentLane == Lane.Right) {
           break; //Do nothing when in right lane
        } else if(currentLane == Lane.Center) {
           MoveRight();
           currentLane = Lane.Right;
        } else if (currentLane == Lane.Left) {
           MoveRight();
           currentLane = Lane.Center;
        }
        break;
     case MoveDirection.Left:
        if(currentLane == Lane.Left) {
           break; //Do nothing when in left lane
        } else if(currentLane == Lane.Center) {
           MoveLeft();
           currentLane = Lane.Left;
        } else if (currentLane == Lane.Right) {
           MoveLeft();
           currentLane = Lane.Center;
        }
        break;
}

```
> 2 votes

# Answer
you can use Vector3.Lerp

Linearly interpolates between two vectors.

Interpolates between the vectors a and b by the interpolant t. The parameter t is clamped to the range \[0, 1\]. This is most commonly used to find a point some fraction of the way along a line between two endpoints (e.g. to move an object gradually between those points).

in below script Direction value is limied to the range \[-1, 1\].so I multiply this value to player's position.z

```
using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {
    public int Direction;

    void Update(){
        Analyze ();
        if (Input.GetKeyDown (KeyCode.A)) {
            print ("left");
            if (Direction == 0 || Direction == 1) {
                Direction--;
            }
        } else if (Input.GetKeyDown (KeyCode.D)) {
            print ("right");
            if (Direction == 0 || Direction == -1) {
                Direction++;
            }
        }
    }

    void Analyze(){
        transform.position = Vector3.Lerp (transform.position, new Vector3 (0, 0, 3 * Direction), 0.1f);
    }
}

```
> 1 votes

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


# Question
Title: Need simple 3D terrain render with big texture map
I have a 1000 x 700 height map

I have a 1000 x 700 texture map

I did something very similar about 8 years ago:

Using XNA. Unfortunately, when I bring up this old project and convert it to Visual Studio 2010 it will no longer compile and just throws tons of errors.

I'm looking for something very simple. Is there a 3D terrain single texture XNA example floating around out there that I can convert? I haven't touched XNA since about 2009 or 2010 and none of my old code will run anymore (I have no idea what's going on).

I need to do a 3D terrain proof of concept where the terrain texture is stretched over the height map. Nothing fancy. Maybe XNA.

Any ideas?

# Answer
> 14 votes
I have been able to do this using the 3d modeling software *Blender*. I used UV mapping to map the texture and the displacement modifier to apply the height map. If you need some form of XNA code for this, I cannot supply it. Here it is as a 3d terrain. Surprisingly, it worked best on a uniformly square mesh.

The steps required to create the terrain like i did in blender:

1. Download blender for your operating system from here.
2. Install and open blender.
3. Delete the default cube by right clicking on it and hitting `Del` then `Enter`.
4. Press `shift`-`a` and select Mesh-\>Plane from the dialogue box that pops up and press `Enter`.
5. Scale it up a bit by pressing `s` and dragging your mouse towards the corner of the screen. Then press `Enter`.
6. At the bottom of the window, towards the left, you will see a dialogue box that says Object Mode. Change that to Edit Mode.
7. Make sure the whole plane is selected. The edges, vertices and faces will be highlighted in orange if it is selected. If it is not, press `a` to select all of the mesh.
8. Press `w` and select Subdivide from the dialogue box that appears. Do this about 5 times.
9. On the far left towards the bottom of the screen, you will now see a new section appear with one field being called number of cuts. Change it from 1 to 8 or whatever resolution you want for your terrain.
10. Now with the whole plane selected, press `u` and select unwrap from the dialogue box. This will take more time if you did more subdivisions.
11. On the center top of your screen, select the dropdown menu that says Blender Render and change it to Cycles Render.
12. On the middle right hand side, you will see a window section with small buttons that look like a camera, a photo, some primitive shapes, a globe, etc. Click on the button that looks like a tiled sphere.
13. Click on the button that says New. You have now created a new material. To apply the image to your plane, on the section that says Surface, go to the field called Color and click on the small dotted box next to the color. From the popup box, under Texture select Image Texture.
14. Navigate to your image and select it.
15. Now, making sure you are in Edit Mode, select the whole plane and press `u` and select Unwrap from the dropdown menu. This may take your computer anywhere from 10 seconds to 2 minutes and the program may freeze depending on how many subdivisions you did.
16. Navigate back to the window with all the buttons and look at the top left of that window. You should see a symbol that looks like two pills with up and down arrows next to it. Select it and select UV/Image Editor from the dropdown menu.
17. At the bottom of the UV/Image Editor window, you should see a button that says Open. Select it and navigate to your texture again. That should do it for texturing.
18. If the orange rectangle (your mapped mesh) doesn't perfectly fit the rectangle of the texture, scale the rectangle in the UV/Image Editor window with `s`. Then press `x` for x axis scaling or `s` and then `y` for y axis scaling. And move it with `g` and `x` for x axis translation and `g` and `y` for y axis translation. Press `enter` each time you finish a transformation/scale. Try to fit the rectangle as well as you can to the image. Otherwise, just leave it as is.
19. Navigate back to the button you clicked at the top left of the window (it is now on the bottom left) where the pills were previously and now the UV/Image Editor icon (looks like a photo of a sunset) is and select Properties (the pill icon) from the dropdown menu.
20. Now from the buttons, select the one that looks like a wrench. Select the Add Modifier dropdown and select the Displace option from the dropdown menu.
21. Where you see the Texture section of the Displace modifier, click the New button.
22. Where the tiled sphere, primitive shape, wrench, etc are, select the one that looks like a tiled square.
23. From the dropdown box where it says Image Texture select Displace - Texture instead.
24. In the Image section, select Open and find your height map and select it.
25. Click on the Image Mapping section and select Clip.
26. Switch to Object Mode and see how the displacement map worked out. If there's a section that looks too straight on the edge either going straight up or dipping down, go back to edit mode, select your plane with a, and scale it up or down a tiny bit with `s`. Keep doing this until it's fixed.
27. Go back to the wrench and in the Displace modifier, change the strength to something like .2
28. Now to view the model textured, next to the Object Mode dropdown, there is a sphere dropdown. Select texture instead of solid.
29. As one final step, there is a window on the top left with a section called Shading. Click on smooth. And you should get something like the results below.

# Answer
> 4 votes
A basic height map can be produced as follows:

Generate a set of vertices that form a grid made of triangles in a regular pattern like

```
 A -- B -- C -- ...
 | \  |  / | \
 |  \ | /  |  \
 D -- E -- F -- ...
 |  / | \  |  /
 | /  |  \ | /
...  ...  ...

```

Each of `A`, `B`, `C`, et cetera represents a vertex in the grid. It also represents a point on the height; read the height value from the map at the appropriate point and use that times some scalar factor to set the Z coordinate of the vertex.

You can generate the UVs at each point by stepping by (1 / number of cells) in either dimesion; this will let you easily map your texture onto that geometry as well.

Then render the geometry with your color map.

---
Tags: xna, textures, heightmap
---


title: 2D moving sprites collision

text:
# Question
Title: 2D moving sprites collision
I'm trying to create a game where i have two abjects `A` and `B`

1 :I know the shape of the two objects(`Rectangles`) .

2 :The `speed` and `position` of each object.

And i'm trying to figure out if the two object **will eventually collide** .

I calcuted the point where the object's paths intersect using this formula

The same for y

But i still don't know if the two object will actually collide or will miss each other .

# Answer
> 2 votes
Check out this source. I wrote the code below based off of it to make it more friendly for a C# application. This works with convex polygons as well which might be a little overkill for you, considering you only need rectangles, but it works none the less.

I found more tutorials and explanations of why the separate axis theorem (which this uses) works, and so I think you'll appreciate this link. Also, this link might come in handy in the future too, if you're looking for specific points enclosed in polygons- :) .

P.S. I wrote some additional comments in the code, please take your time to go over them.

```
public class MainForm {

    // Structure that stores the results of the PolygonCollision function
    public struct PolygonCollisionResult {
        public bool WillIntersect; // Are the polygons going to intersect forward in time?
        public bool Intersect; // Are the polygons currently intersecting
        public Vector MinimumTranslationVector; // The translation to apply to polygon A to push the polygons apart
    }

    // Check if polygon A is going to collide with polygon B for the given velocity
    public static PolygonCollisionResult PolygonCollision(Polygon polygonA, Polygon polygonB, Vector velocity) {
        var result = new PolygonCollisionResult
        {
            Intersect = true,
            WillIntersect = true
        };

        int edgeCountA = polygonA.Edges.Count;
        int edgeCountB = polygonB.Edges.Count;
        float minIntervalDistance = float.PositiveInfinity;
        Vector translationAxis = new Vector(); //default value
        Vector edge;

        // Loop through all the edges of both polygons
        for (int edgeIndex = 0; edgeIndex < edgeCountA + edgeCountB; edgeIndex++) {
            if (edgeIndex < edgeCountA) {
                edge = polygonA.Edges[edgeIndex];
            } else {
                edge = polygonB.Edges[edgeIndex - edgeCountA];
            }

            // ===== 1. Find if the polygons are currently intersecting =====

            // Find the axis perpendicular to the current edge
            Vector axis = new Vector(-edge.Y, edge.X);
            axis.Normalize();

            // Find the projection of the polygon on the current axis
            float minA = 0; float minB = 0; float maxA = 0; float maxB = 0;
            ProjectPolygon(axis, polygonA, ref minA, ref maxA);
            ProjectPolygon(axis, polygonB, ref minB, ref maxB);

            // Check if the polygon projections are currentlty intersecting
            if (IntervalDistance(minA, maxA, minB, maxB) > 0)
                result.Intersect = false;

            // ===== 2. Now find if the polygons *will* intersect =====

            // Project the velocity on the current axis
            float velocityProjection = axis.DotProduct(velocity);

            // Get the projection of polygon A during the movement
            if (velocityProjection < 0) {
                minA += velocityProjection;
            } else {
                maxA += velocityProjection;
            }

            // Do the same test as above for the new projection
            float intervalDistance = IntervalDistance(minA, maxA, minB, maxB);
            if (intervalDistance > 0)
                result.WillIntersect = false;

            // If the polygons are not intersecting and won't intersect, exit the loop
            if (!result.Intersect && !result.WillIntersect)
                break;

            // Check if the current interval distance is the minimum one. If so store
            // the interval distance and the current distance.
            // This will be used to calculate the minimum translation vector
            intervalDistance = Math.Abs(intervalDistance);
            if (intervalDistance < minIntervalDistance) {
                minIntervalDistance = intervalDistance;
                translationAxis = axis;

                Vector d = polygonA.Center - polygonB.Center;
                if (d.DotProduct(translationAxis) < 0)
                   translationAxis = -translationAxis;
            }
        }

        // The minimum translation vector can be used to push the polygons appart.
        // First moves the polygons by their velocity
        // then move polygonA by MinimumTranslationVector.
        if (result.WillIntersect)
            result.MinimumTranslationVector = translationAxis * minIntervalDistance;

        return result;
    }

    // Calculate the distance between [minA, maxA] and [minB, maxB]
    // The distance will be negative if the intervals overlap
    public static float IntervalDistance(float minA, float maxA, float minB, float maxB) {
        if (minA < minB) {
            return minB - maxA;
        } else {
            return minA - maxB;
        }
    }

    // Calculate the projection of a polygon on an axis and returns it as a [min, max] interval
    public static void ProjectPolygon(Vector axis, Polygon polygon, ref float min, ref float max) {
        // To project a point on an axis use the dot product
        float d = axis.DotProduct(polygon.Points[0]);
        min = d;
        max = d;
        for (int i = 0; i < polygon.Points.Count; i++) {
            d = polygon.Points[i].DotProduct(axis);
            if (d < min) {
                min = d;
            } else {
                if (d > max) {
                    max = d;
                }
            }
        }
    }
}

```

How to use: What you want to do is create a struct type PolygonCollisionResult. Call the PolygonCollision method with the required parameters and store the result in that struct.

The **concepts** in the code do not belong to me in any way, shape, or form.

Hope this helps, and good luck on your game!

# Answer
> 1 votes
You just need to compare sidelines. These are the algebraic representations of vertical or horizontal lines. Note, this will return only the current value, not what **will** be, but from here is only one step to do that.

Let's define a Rectangle with the following properties:

`Rectangle.x1`: rectangle's left side line (this is a vertical line)

`Rectangle.x2`: rectangle's right side line (same)

`Rectangle.y1`: rectangle's top side line (this is a horizontal line)

`Rectangle.y2`: rectangle's bottom side line (same)

These values are properties of your rectangle and they can be any type of numerical data (int, float,...). The algorithm will use two Rectangles, and compare their sides (in pseudocode):

```
Function rectCollision(rect1, rect2)
{
    if (rect1.x1 > rect2.x2) //the first rectangle is after the second rectangle, they are not colliding
      or (rect1.x2 < rect2.x1) //the first rectangle is before the second
      or (rect1.y1 > rect2.y2) //the first is under the second
      or (rect1.y2 < rect2.y1) //the first is above the second
    //then
    {
        return false
    }
    else
    {
        //there is explicitly no other way for collision
        return true
    }
}

```

How is this working? We are projecting the collision boxes on the x and y axis. They are not meeting, if they are not colliding on x **OR** on y axis. If they are colliding on x **and** y axis too, then bang, we got a collision.

You can find some images and additional code (in C++) about this on http://lazyfoo.net/tutorials/SDL/27\_collision\_detection/index.php.

Lasoloz

---
Tags: collision-detection, collision-prediction
---


# Question
Title: Can i put the main Love2D functions inside a table?
Instead of having a file with load, update,and draw can i say have a table called player, then put love.update and love.draw in that table to handle the drawing and updating of that particular player?

# Answer
> 0 votes
These functions are called by Love without knowing the rest of your program. It cannot know that they are inside a player table. As far as I know you cannot register other functions in their place, so you would need to call them from within the main update, draw etc. calls.

If you want to control the flow of your program, you can create some object with draw, update etc. functions that are the only things called in main functions. Once you got that, you can redirect them as you like for example to your player table. But ultimately you need to have to provide these functions so Love makes calls to your code.

---
Tags: game-design, lua, love2d
---


# Question
Title: C++ SDL OpenGL minimise / restore window issue
I'm partway through developing a 2D game in C++ using SDL and OpenGL; my IDE of choice is CodeBlocks. I've hit an issue that I can't seem to get around.

Basically, if I minimise and then restore the window that my game is in, the graphics more or less break. Initially I was presented with just a black screen, though with some trial and error of SDL and OpenGL initialising I've managed to get OpenGL primitives back. However textures are showing up as white boxes.

I'm not sure where the issue is, though I think it has something to do with generating / binding OpenGL textures as the actual data of the textures seems to be present. Additionally, reloading all textures on window restore seems to solve this problem (though this feels like a very ugly hack).

I'd appreciate any help or guidance on this.

For context, here is the code I use to actually initialise OpenGL on program start:

```
bool init()
{
//Initialize SDL and all subsystems
if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
{
    return false;
}

Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096);

SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);

SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);

//Enable VSync
if( !SDL_SetHint( SDL_HINT_RENDER_VSYNC, "1" ) )
    printf( "WARNING: VSync failed" );

//Set texture filtering to linear
if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) )
    printf( "WARNING: Linear texture filtering failed" );

//Set up the primariy window
mainwindow = SDL_CreateWindow("...", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_OPENGL);// && SDL_WINDOW_FULLSCREEN);

//Tie mainwindow to main screen
screen = SDL_GetWindowSurface( mainwindow );

SCREEN_CENTRE_X = SCREEN_WIDTH / 2;
SCREEN_CENTRE_Y = SCREEN_HEIGHT / 2;

//Initialize SDL_ttf
if( TTF_Init() == -1 )
{
    return false;
}

//Initialization flag
bool success = true;

//Use OpenGL 3.1 core
//SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
//SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 );
//SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );

gContext = SDL_GL_CreateContext( mainwindow );

if( gContext == NULL )
{
    printf( "OpenGL context could not be created! SDL Error: %s\n", SDL_GetError() );
    success = false;
}
else
{
    //Initialize GLEW
    glewExperimental = GL_TRUE;
    GLenum glewError = glewInit();
    if( glewError != GLEW_OK )
    {
        printf( "Error initializing GLEW! %s\n", glewGetErrorString( glewError ) );
    }

    //Use Vsync
    if( SDL_GL_SetSwapInterval( 1 ) < 0 )
    {
        printf( "Warning: Unable to set VSync! SDL Error: %s\n", SDL_GetError() );
    }

    //Initialize OpenGL
    if( !initGL() )
    {
        printf( "Unable to initialize OpenGL!\n" );
        success = false;
    }
}

//If everything initialized fine
return true;
}

bool initGL()
{
//Success flag to return
bool success = true;

//Generate program and ID
gProgramID = glCreateProgram();

//Create vertex shader
GLuint vertexShader = glCreateShader( GL_VERTEX_SHADER );

char rvc;
std::string rvertshaderinput = "";
std::ifstream rvs("resources/shader_regularvert.glsl", std::fstream::in | std::fstream::app);

while(rvs.get(rvc))
{
    rvertshaderinput.push_back(rvc);
}

rvs.close();

const char *glrvertshaderinput = rvertshaderinput.c_str();

//Set fragment source
glShaderSource( vertexShader, 1, &glrvertshaderinput, NULL );

//Compile vertex source
glCompileShader( vertexShader );

//Attach vertex shader to program
glAttachShader( gProgramID, vertexShader );

//Create fragment shader
GLuint fragmentShader = glCreateShader( GL_FRAGMENT_SHADER );

char rfc;
std::string rfragshaderinput = "";
std::ifstream rfs("resources/shader_regularfrag.glsl", std::fstream::in | std::fstream::app);

while(rfs.get(rfc))
{
    rfragshaderinput.push_back(rfc);
}

rfs.close();

const char *glrfragshaderinput = rfragshaderinput.c_str();

//Set fragment source
glShaderSource( fragmentShader, 1, &glrfragshaderinput, NULL );

//Compile fragment source
glCompileShader( fragmentShader );

//Attach fragment shader to program
glAttachShader( gProgramID, fragmentShader );

//Link program
glLinkProgram( gProgramID );

//Initialize clear color
glClearColor( 0.f, 0.f, 0.f, 1.f );

//VBO data
GLfloat vertexData[] =
{
    -0.5f, -0.5f,
     0.5f, -0.5f,
     0.5f,  0.5f,
    -0.5f,  0.5f
};

//IBO data
GLuint indexData[] = { 0, 1, 2, 3 };

//Create VBO
glGenBuffers( 1, &gVBO );
glBindBuffer( GL_ARRAY_BUFFER, gVBO );
glBufferData( GL_ARRAY_BUFFER, 2 * 4 * sizeof(GLfloat), vertexData, GL_STATIC_DRAW );

//Create IBO
glGenBuffers( 1, &gIBO );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, gIBO );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, 4 * sizeof(GLuint), indexData, GL_STATIC_DRAW );

init_GL_blur_shaders();

//Set the viewport
glViewport( 0.f, 0.f, SCREEN_WIDTH, SCREEN_HEIGHT );

//Initialize Projection Matrix
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho( 0.0, SCREEN_WIDTH, SCREEN_HEIGHT, 0.0, 1.0, -1.0 );

//Initialize Modelview Matrix
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();

//Initialize clear color
glClearColor( 0.f, 0.f, 0.f, 1.f );

//Enable texturing
glEnable( GL_TEXTURE_2D );

glEnable(GL_DEBUG_OUTPUT);

glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

return success;
}

```

And here is the code I'm currently using to try and get the graphics back after window restore (which partially works but is very much a shotgun approach):

```
if(event.window.event == SDL_WINDOWEVENT_RESTORED)
            {
                printf("SDL window restored\n");
                //SDL_GL_DeleteContext(gContext);
                //gContext = SDL_GL_CreateContext( mainwindow );

                screen = SDL_GetWindowSurface( mainwindow );

                SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
                SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
                SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
                SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);

                SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
                SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

                SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
                SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);

                //Enable VSync
                if( !SDL_SetHint( SDL_HINT_RENDER_VSYNC, "1" ) )
                {
                    printf( "Warning: VSync not enabled!" );
                }

                //Set texture filtering to linear
                if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) )
                {
                    printf( "Warning: Linear texture filtering not enabled!" );
                }

                SDL_GL_DeleteContext(gContext);

                gContext = SDL_GL_CreateContext( mainwindow );

                if( gContext == NULL )
                {
                    printf( "OpenGL context could not be created! SDL Error: %s\n", SDL_GetError() );
                }
                else
                {
                    //Initialize GLEW
                    glewExperimental = GL_TRUE;
                    GLenum glewError = glewInit();
                    if( glewError != GLEW_OK )
                    {
                        printf( "Error initializing GLEW! %s\n", glewGetErrorString( glewError ) );
                    }

                    //Use Vsync
                    if( SDL_GL_SetSwapInterval( 1 ) < 0 )
                    {
                        printf( "Warning: Unable to set VSync! SDL Error: %s\n", SDL_GetError() );
                    }

                    glDeleteProgram(gProgramID);

                    gProgramID = glCreateProgram();

                    //Initialize OpenGL

                    if( !initGL() )
                    {
                        printf( "Unable to initialize OpenGL!\n" );
                    }

                }

            }

```

Simple prototype using the following code also falls prey to this issue:

```
void cgl_drawcirclefilled(float cx, float cy, float xr, float yr, SDL_Color color)
{
//Bind program
glUseProgram( gProgramID );

float vx = ((cx * 2) - (SCREEN_WIDTH)) / (float)SCREEN_WIDTH;
float vy = -((cy - SCREEN_HEIGHT) / SCREEN_CENTRE_Y + 1);

float vxr = xr / (float)SCREEN_WIDTH;
float vyr = yr / (float)SCREEN_HEIGHT;

fragmentcolourlocation = glGetUniformLocation( gProgramID, "fragcolour" );

glUniform4f(fragmentcolourlocation, (float)color.r/ 255.0f, (float)color.g/ 255.0f, (float)color.b/ 255.0f, (float)color.a/ 255.0f);

int num_segments = 100;

glEnable(GL_MULTISAMPLE);

glBegin(GL_TRIANGLE_FAN);
for (int ii = 0; ii < num_segments; ii++)
{
    float theta = 2.0f * 3.1415926f * float(ii) / float(num_segments);//get the current angle
    float x = vxr * cosf(theta);//calculate the x component
    float y = vyr * sinf(theta);//calculate the y component
    glVertex2f(x + vx, y + vy);//output vertex
}
glEnd();

glDisable(GL_MULTISAMPLE);

//Disable vertex position
glDisableVertexAttribArray( gVertexPos2DLocation );

//Unbind program
glUseProgram( NULL );
}

int main( int argc, char* args[] )
{
if( init() == false )
{
    return 2;
}

while(quit == false)
{
    while( SDL_PollEvent( &event ) )
    {
        //If the user has Xed out the window
        if( event.type == SDL_QUIT )
        {
            //Quit the program
            quit = true;
        }

        if( event.type == SDL_WINDOWEVENT)
        {

            if(event.window.event == SDL_WINDOWEVENT_RESTORED)
            {
                printf("SDL window restored\n");
            }
        }
    }

    cgl_drawcirclefilled(SCREEN_CENTRE_X, SCREEN_CENTRE_Y, 50, 50, colour_white);

    SDL_GL_SwapWindow( mainwindow );
}

return 0;
}

```

# Answer
OK so I have a partial answer (more of a kludge) that might eventually lead to the real, proper solution for this.

I've added some code to check for a SDL\_WINDOWEVENT\_RESTORED event; when this occurs, openGL is reinitialised, and all of the textures that were loaded on program start are cleared and re-loaded.

This feels very hacky, and carries about a 40MB memory leak for each time the window is minimised and re-opened, but it'll do for now. The memory leak is possibly the result of me not freeing all of the memory I should be freeing, but I'm unclear as to what parts of OpenGL initalisation actually takes up memory.

I'm still pretty unsure what's actually causing this issue; I don't know if it's SDL or OpenGL, or just something simple I'm missing in initalisation that would otherwise prevent this.

Comments / insight welcome.

For posterity, I use the following code to free memory on window restore:

SDL\_GL\_DeleteContext glDeleteProgram glDeleteShader glDeleteBuffers glDeleteTextures
> 0 votes

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


# Question
Title: How to make a Infinite Verticle Scrolling Background in Pygame
Is there anyone who knows how to create an infinite verticle scrolling background in pygame?

Your help would be much appreciated, thanks in advance!

# Answer
> 2 votes
The idea behind infinitely scrolling backgrounds is pretty simple. You simply draw the background enough many times to fill the screen, and once a piece of the background moves off screen, you loop the rendering and start back from the beginning.

So, the basic functionality would go as follows: (pseudo code, should be easily adaptable to PyGame)

```
piece = yourBackgroundImage;
pieceHeight = piece.h;

scrollY = 0;

for (pieceY = (scrollY % pieceHeight) - pieceHeight; pieceY < screenHeight; pieceY += pieceHeight)
{
    render(piece, 0, pieceY);
}

```

First, you take your background image you want to loop. You need to know it's height, as that's what we used to calculate how often we need to render it. The `scrollY` variable in the code above is the value you would modify in your main loop to create the scrolling effect.

Now, the loop is slightly more complicated, but not much. We start by calculating how much vertical movement there is along a single piece (`scrollY % pieceHeight)`. We need to decrease that value by a single piece height, to make sure that the whole screen gets filled (you can try it without the decrement, and see that there will be a small piece of the background missing at the top of the screen). We will iterate as long as there is screen space to fill, and increment each step by the background image's height.

That should do it, and the algorithm is of course easily translatable to horizontal movement too.

---
Tags: python, pygame, parallax-scrolling, scrolling
---


# Question
Title: Frame rate slowing down after publishing XNA game in VB.NET
I will get to the main question later but I just want to give the backstory here first. I program a game in XNA using VB.NET. As I'm testing the game in debug it works at a certain speed (spritemovement, animations etc.). After I publish the game and install it on my other computer (which is newer), the game slows down considerably. To investigate that problem I used FPS code. It showed 75 on debug and 60 after installed. I have thus programmed the entire game for running at 75. To try to solve that problem I incorporated this:

```
TargetElapsedTime = TimeSpan.FromSeconds(1.0F / 75.0F)
IsFixedTimeStep = True

```

Now after trying to publish again the game actually ran smoothly at 75fps on the newer computer, but there was a catch: when I turn to fullscreen the game again slows down. However now without showing the lower fps. So the fps is still showing 75 but the game apparently runs at 60.

I've looked around for answers and find that I can possibly maximize the window (borderless) without making it fullscreen, and could perhaps solve the problem that way. However all the code suggested are in C# and I can't get it to work.

How can I either get a borderless maximized window to work with VB.NET, or in any other way solve my FPS issue?

Thank's for any help on this issue!

# Answer
If this is the code you wanted to use for a borderless window, here's the VB.NET version (it's untested as I don't have XNA on this machine)

```
Dim hWnd As IntPtr = Me.Window.Handle
Dim control = System.Windows.Forms.Control.FromHandle(hWnd)
Dim form = control.FindForm()
form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None

```

Is there a reason you want to increase the FPS to 75 and not the default of 60? This thread might be worth a read regarding that.
> 1 votes

---
Tags: xna, frame-rate, vb.net
---


# Question
Title: How to access a prefab's boolean property through collision (with the same Prefab but different Instance)?
I am a trying to recreate the first stage of Super Mario Brothers, but I am having a bit of trouble with the collision system between Koopa Shells. I have written two different scripts in hopes to achieve this:

This First script is to handle the Basic movement and start shell movement on Player Collision

It's Rather long so I took the liberty of including only parts that were in direct correlation/ causation of the problem

```
     public class KoopaShell : MonoBehaviour
     {
         //Makes this accessible to other Scripts
         public bool Moving;

         // Boolean Flags to be inherited
         bool shellLeft, shellRight, rightBlocked, leftBlocked;
         public float rayDis;
         public LayerMask enemyMask;
         public Transform rCast;

 [... Rest of the code..]
         void OnCollisionEnter2D(Collision2D coll)
         {
             if (leftBlocked || rightBlocked) // If the either side of the shell is hit
                 if (coll.gameObject.tag == "Player" && Moving == false) // If the player makes contact with a resting shell
                 {
                     MoveShell();
                 }
         }

         public IEnumerator MoveShell() //Courotine for 2D Collision
         {
                     //The Courotine will wait for the end of the frame
                     yield return new WaitForFixedUpdate();
                     //Then set moving to true
                     Moving = true;
         }
     }

```

The Second Script handles all other collision and inherits from the first in an attempt to simplify the calling from script to script.... Could also be the cause of my problem.

```
public class MovingShellScript : KoopaShell
{

//This is a continuation of the KoopaShell Script
//Dealing with 2D Collision

void OnCollisionEnter2D(Collision2D col)
{
   if (col.gameObject.tag == "Koopa Shell") //  if contact is made with another shell that is moving
     if(col.gameObject.Equals(Moving) == false) //if the shell is not moving
     {
      {
          Destroy(col.gameObject);  // Then the resting shell is destroyed
          Debug.Log("Looks like another shell is unemployed");
       }
     }

    if (col.gameObject.tag == "Enemy") // If a Enemy is hit by the Shell
       if (Moving == true) // and If the Shell is moving
       {
                     // The GameObject hit is Destroyed
                     Destroy(col.gameObject);
       }
     }
 }

```

Currently the script above does not destroy the various gameobjects under the Enemy and Player tag. Maybe this could be done implicitly with an associated script to the desired gameobject that correlates with the tag....

Also the script destroys both shells during a collision. I don't understand why my various boolean flags aren't creating the desired result(s)

* If both shells are moving then both shells are destroyed.
* If only one shell is moving then the resting shell is destroyed.

I am seeking to understand the error in my logic for this to work as desired.

Thank you for your time!

# Answer
> 0 votes
Firstly, my Moving Boolean was a static variable(this was changed before I asked this question). Secondly, I failed to reference the object I was colliding with thus building on my first logic error of the static Boolean - which made all instances share the same value. Lastly, after realizing the later of the two and the fact that my code was not properly allowing the entire engine to access the value of the Moving Boolean - which was kindly pointed out to me to check, it was then when I realized I was prematurely calling my coruotine without the use of StartCoruotine().

```
  IEnumerator MoveShell() //Courotine for 2D Collision
     {
                 //The Courotine will wait for the end of the frame
                 yield return new WaitForSeconds(0.001f);
                 //Then set moving to true
                 yield return Moving = true;
     }

     void OnCollisionEnter2D(Collision2D coll)
     {
         // Any collision that deals with the Player will be here
         if (leftBlocked || rightBlocked) // If the either side of the shell is hit
             if (coll.gameObject.tag == "Player" && this.Moving == false) // If the player makes contact with a resting shell
             {
                 StartCoroutine(MoveShell()); // Calls our Courotine
             }

         // Any collision that deals with other Koopa Shells will be here
         if (coll.gameObject.CompareTag("Koopa Shell")) //  if contact is made with another shell
         {
             // Get a reference to the other shell:
             KoopaShell otherShell = coll.gameObject.GetComponent<KoopaShell>();
             if (otherShell.Moving == false && this.Moving == true) //if one of the shells is at rest
             {
                 Destroy(coll.gameObject);  // Then the resting shell is destroyed
                 Debug.Log("The Shell at rest was destroyed");
             }
                 if(otherShell.Moving == true && this.Moving == true)// if both shells are not moving
                 {
                     Destroy(this.gameObject); //Destroy the moving shell that this script is attached to
                     Destroy(coll.gameObject); //Destroy the moving shell that is being collided with
                     Debug.Log("Both Shells involved were destroyed");
                 }
         }
     }

```

The Actually code is no where as near as this broken up. Please forgive the failed attempt of presentation.

Thank you again for all that followed or assisted me in any way! :)

# Answer
> 2 votes
I think you may be misunderstanding what the Equals() method does - it's checking whether the `GameObject` instance `col.gameObject` is equal to whatever you pass in as an argument. You're passing in a `Boolean` value, which is not a `GameObject`, so the result will **always** be false.

I think you mean to write something more like this:

```
void OnCollisionEnter2D(Collision2D col)
{
   if (col.gameObject.CompareTag("Koopa Shell")) //  if contact is made with another shell
   {
        // Get a reference to the other shell:
        KoopaShell otherShell = col.gameObject.GetComponent<KoopaShell>();

        if(otherShell.Moving == false) //if the other shell is not moving
        {
             Destroy(col.gameObject);  // Then the resting shell is destroyed
             Debug.Log("Looks like another shell is unemployed");
        }
    }

...

```

---
Tags: c#, 2d, collision-detection, unity
---


# Question
Title: Technique to find a mesh intersecting with a primitive solid without using colliders?
For what it's worth I'm using Unity3d, but I believe the problem is more general.

There are hundreds if not thousands of meshes with hundreds of vertices each. There is one sphere that can be intersecting any of those meshes and is constantly moving.

Are AABB colliders approximating the mesh's volume the best way to go about this? Or is there a more specific technique that can be used here?

(A limitation I have is that my colliders need to be rotated, so they're each stored in a game object, so the number of game objects becomes absurdly large for my meshes(tens of thousands) which is slowing down my game.)

I have a couple of properties unique to my situation I believe might allow me to ditch colliders:

* I don't care about the meshes colliding with each other. Just the one sphere.
* I only need to know that the intersection exists, I don't care about the point of the intersection or any other metadata. Just a boolean of the intersection occuring and what mesh it happened with.
* I don't need to know the exact moment/frame when the intersection occurs. If I can find out an intersection occurred within 100-200ms/20-30 frames of it happening it'll be fine.

# Answer
> 1 votes
As a general solution, a sphere collider can be imitated with this a simple 3D distance formula equation: `Distance = sqrt((x_2 - x_1)**2 + (y_2 - y_1)**2 + (z_2 - z_1)**2)` where x\_1, y\_1, and z\_1 are the x, y, and z coordinates of center of the sphere and x\_2, y\_2, and z\_2 are the x, y, and z coordinates of a given vertex.

Using this idea, you could simply write something like (and this is pseudocode):

```
for(each Mesh)
{
    for(each Vertex in Mesh)
    {
        Distance = sqrt((Sphere.x - Vertex.x)**2 +
                        (Sphere.y - Vertex.y)**2 + (Sphere.z - Vertex.z)**2);
        if(Distance < Sphere.radius)
        {
            Mesh.isColliding = True;
        }

    }
}

```

---
Tags: unity, collision-detection, mesh, aabb
---


title: Pygame: Collision detection

text:
# Question
Title: Pygame: Collision detection
I've been adding some extra stuff like Gravity and a table to a simple pong game made with Pygame and Python, the problem is that I don't know how to add collision detection, so when the ball hits the table it changes its direction like when the ball hits the paddle (right now my table is just moving upward and downward).

This is the code:

```
import pygame
from pygame.locals import *
from sys import exit
import random
import time

pygame.init()

screen=pygame.display.set_mode((640,480),0,32)
pygame.display.set_caption("Pong Pong!")

#Creating 2 bars, a ball and background.
back = pygame.Surface((640,480))
background = back.convert()
background.fill((0,0,0))
bar = pygame.Surface((10,50))
bar1 = bar.convert()
bar1.fill((0,0,255))
bar2 = bar.convert()
bar2.fill((255,0,0))
table = pygame.Surface((10,144))
table1 = table.convert()
table1.fill((255,255,255))
circ_sur = pygame.Surface((15,15))
circ = pygame.draw.circle(circ_sur,(0,255,0),(15//2,15//2),15//2)
circle = circ_sur.convert()
circle.set_colorkey((0,0,0))

# some definitions
bar1_x, bar2_x = 10. , 620.
bar1_y, bar2_y = 215. , 215.
table1_x = 325.
table1_y = 205.
circle_x, circle_y = 307.5, 232.5
bar1_move, bar2_move = 0. , 0.
speed_x, speed_y, speed_circ = 250., 250., 250.
bar1_score, bar2_score = 0,0
gm = 3 #Table Movement
g = 7.5 #Gravity
isDown = True #Table Flag

#clock and font objects
clock = pygame.time.Clock()
font = pygame.font.SysFont("calibri",40)

while True:

    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
        if event.type == KEYDOWN:
            if event.key == K_UP:
                bar1_move = -ai_speed
            elif event.key == K_DOWN:
                bar1_move = ai_speed
        elif event.type == KEYUP:
            if event.key == K_UP:
                bar1_move = 0.
            elif event.key == K_DOWN:
                bar1_move = 0.

    score1 = font.render(str(bar1_score), True,(255,255,255))
    score2 = font.render(str(bar2_score), True,(255,255,255))

    screen.blit(background,(0,0))
    frame = pygame.draw.rect(screen,(255,255,255),Rect((5,5),(630,470)),2)
    middle_line = pygame.draw.aaline(screen,(255,255,255),(330,5),(330,475))
    screen.blit(bar1,(bar1_x,bar1_y))
    screen.blit(bar2,(bar2_x,bar2_y))
    screen.blit(table1,(table1_x, table1_y))
    screen.blit(circle,(circle_x,circle_y))
    screen.blit(score1,(250.,210.))
    screen.blit(score2,(380.,210.))

    bar1_y += bar1_move

# movement of circle
    time_passed = clock.tick(30)
    time_sec = time_passed / 1000.0

    speed_y += g
    circle_x += speed_x * time_sec
    circle_y += speed_y * time_sec
    ai_speed = speed_circ * time_sec +5
#AI of table.
    if isDown:
        table1_y += gm
        if table1_y >= 331:
            isDown = False
    else:
        table1_y += -gm
        if table1_y <= 10:
            isDown = True
#AI of computer.
    if circle_x >= 305.:
        if not bar2_y == circle_y + 7.5:
            if bar2_y < circle_y + 7.5:
                bar2_y += ai_speed
            if  bar2_y > circle_y - 42.5:
                bar2_y -= ai_speed
        else:
            bar2_y == circle_y + 7.5

    if bar1_y >= 420.: bar1_y = 420.
    elif bar1_y <= 10. : bar1_y = 10.
    if bar2_y >= 420.: bar2_y = 420.
    elif bar2_y <= 10.: bar2_y = 10.

#since I don't know anything about collision, ball hitting bars goes like    this.
    if circle_x <= bar1_x + 10.:
        circle_y += 5
        if circle_y >= bar1_y - 7.5 and circle_y <= bar1_y + 42.5:
            circle_x = 20.
            speed_x = -speed_x
    if circle_x >= bar2_x - 15.:
        if circle_y >= bar2_y - 7.5 and circle_y <= bar2_y + 62.5:
            circle_x = 605.
            speed_x = -speed_x
            #
            #
    if circle_x < 5.:
        bar2_score += 1
        g = -g
        circle_x, circle_y = 320., 462.5
        bar1_y,bar_2_y = 215., 215.
    elif circle_x > 620.:
        bar1_score += 1
        g = -g
        circle_x, circle_y = 307.5, 462.5
        bar1_y, bar2_y = 215., 215.
    if circle_y <= 10.:
        speed_y = -speed_y
        circle_y = 10.
    elif circle_y >= 457.5:
        speed_y = -speed_y
        circle_y = 457.5

    pygame.display.update()

```

Suggestions?

# Answer
> 1 votes
I would try making sprites, but if you're new to pygame and python that can be a complicated idea. What I would do then, is draw a rect around your paddles that have the same position as your paddles so the rects will follow the paddle. Afterwards, I'd put a rect around the ball. Then make a collision detection that says:

```
if ball_rect.collidepoint(x,y):
    change ball position incrementally.

```

`x,y` would be the paddle positions. And if the ball hits the paddle positions you can change the balls position incrementally.

# Answer
> 1 votes
I wrote this in C#, but It has the same idea, and can be taken as pseudo code.

Because in pong you're only dealing with rectangles and not polygons, it makes collision detection and response fairly easy. In C#, the .NET 4.5 framework already has a method at allows you to check if a rectangle is intersecting (touching) another rectangle. (Keep in mind that your ball doesn't have to be a circle, only the sprite does). Check this source out for information on how to detect collision, it's actually really simple to do.

This probably isn't the most efficient method, but it works fast and is easy to understand. Here's how it works:

Counters are made for all sides when trying to know what side of the rectangle (paddle, in your case), hit. Through a series of if statements, the velocity of the ball is analyzed, and gives a point to whichever the possible sides hit are.

For example, left say I have a ball moving to the right, and is about to hit the paddle. We can be sure that the ball can only hit the top, bottom, or left side of the paddle. The ball could never hit the right side of the paddle, because it never travels to the left in a decreasing X velocity. Here's a graphic I made that might be a little more clear:

The red sides indicate all the possible sides that ball is able to hit when the X velocity is increasing (going to the right). After testing the X and Y velocity, we now test the position of the ball relative to the paddle. Using the same format, if the ball is to the left of the paddle, it is most likely to hit the left, top and bottom sides. We then add points appropriately. Through a series of these tests, if we test both the X and Y velocity and position, we get results that might look like:

top: 3

bottom: 3

left: 4

right: 2

Because "left" has the highest number, it means that it contains the highest number of possibilities that the ball is able to hit. Therefore, this is the side that the ball hit.

```
        //counters for the sides
        byte top = 0;
        byte left = 0;
        byte right = 0;
        byte bottom = 0;

        //testing for X velocity
        if (_velocity.X > 0)
        {
            top++;
            bottom++;
            left++;

        }
        else
        {
            top++;
            bottom++;
            right++;
        }

        //testing for Y velocity
        if (_velocity.Y > 0)
        {
            left++;
            right++;
            top++;

        }
        else
        {
            left++;
            right++;
            bottom++;
        }

        //testing for X position
        if (_position.X > rect.X)
        {
            top++;
            bottom++;
            right++;
        }
        else
        {
            top++;
            bottom++;
            left++;
        }

        //testing for Y position
        if (_position.Y > rect.Y)
        {
            left++;
            right++;
            bottom++;
        }
        else
        {
            left++;
            right++;
            top++;
        }

        //using results
        byte[] sides = { top, left, right, bottom };

        //sides.Max() just means that of all the results in the array, the
        //it returns the side that had the highest (max) number.
        if (sides.Max() == top)
        {
            _velocity.Y = ball.velocity.Y * -1;
        }
        else if (sides.Max() == bottom)
        {
            _velocity.Y = ball.velocity.Y * -1;
        }
        else if (sides.Max() == left)
        {
            _velocity.X = ball.velocity.X * -1;
        }
        else if (sides.Max() == right)
        {
            _velocity.X = ball.velocity.X * -1;
        }

```

I hope this helps, and good luck on your coding!

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