# Question
Title: How is it possible to call abstract methods from another class?
Im creating a game using LWJGL and just as a bit of organising I made an Abstract class called Game so I could extend Game in my main class The game class is like so -

```
public abstract class Game {
    public abstract void init();
    public abstract void render();
}

```

Really simple stuff, and my plan was to call the render and init method in my DisplayManger class so every whenever I my display is created and updates it runs these methods so all games extending my game class with have their methods run. My approach was like this but as you probably have figured out you cannot a abstract method from another class nor from a static method from inside my abstract, it needs to be static to call from another class. Here was my approach -

```
public class DisplayManager {
    public DisplayManager(int width, int height) {
        try {
            Display.setDisplayMode(new DisplayMode(width,height));
            Display.create();
        } catch (LWJGLException e) {
            e.printStackTrace();
        }
        Game.init();
        while (!Display.isCloseRequested()) {
            Game.render();
            Display.update();
        }
        Display.destroy();
    }
}

```

Does anyone know how I can call these two methods from this Display class?

# Answer
> 2 votes
An abstract method is a method without a body. So you can't just call an abstract method of an abstract class (you cannot instantiate an abstract class directly). If you want to have your abstract game class with the abstract methods you need to have a class that extends this game class and specifically implements these methods without the abstract keyword.

Or you remove the abstract keyword from `init` and `render` and then the subclass of your `Game` class doesn't have to implement these methods but will take the one defined in your `Game` class.

Alternatively you can remove the abstract keyword from the methods in your game class but still @Override them in your subclass. That way you can define a default behavior for `init` and `render` and still change it in a subclass if needed.

```
public abstract class Game {

    public Game() {};

    public void init()
    {
        // do init stuff
    }

    public void render()
    {
        // do render stuff
    }
}

public class specificGame extends Game {

    public specificGame() {};

    // no need to implement init and render. But you can still override them

    @Override
    public void init()
    {
        // spefic init stuff
    }

    @Override
    public void render()
    {
        // specific render stuff
    }

}

```

More about abstract classes and methods https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html

Is this what you want?

This is the main file:

```
package devex;

import devex.SubClass;

public class MainClass
{

    public static void main(String[] args)
    {
        SubClass.init();
        AClass.init();
    }
}

```

The this is the abstract class defining a default init

```
package devex;

public abstract class AClass
{

    public static void init()
    {
        System.out.println("AClass init");
    }

}

```

This subclass extends AClass and overwrites init

```
package devex;

public class SubClass extends AClass
{

    public static void init()
    {
        System.out.println("Subclass init");
    }

}

```

# Answer
> 0 votes
The fact that your methods are abstract is secondary, here -- the main issue is that you're calling the methods as if they were declared `static`:

```
Game.init()
Game.render()

```

Instead, what you need in order to call these methods is an instance of the Game class and invoke those methods on that object:

```
Game game = new SubclassOfGame();
game.init()
game.render()

```

---
Tags: java, lwjgl3
---


# Question
Title: How do I know what to do with incoming network messages?
I am programming a 2D game in a server/client architecture with C# and lidgren. When a client sends a message to the server, how does the server know what to do with that message data?

The client could send different kinds of things, for example the coordinates of player 1 and 2 or the health. So how does the server know its the coordinates and stuff?

# Answer
In the data you send with the message, you include information about *what* the purpose of the message is. Not just the relevant data. For example, you'd create an enumerate of possible message types:

```
enum MessageType {
  MovePlayer,
  AttackPlayer,
  ChatToPlayer,
  Disconnect,
};

```

When you send some data related to moving a player, you don't just send the new position, you prefix the message with the message type `MovePlayer`. Likewise with sending a message about players attacking, or players disconnecting, or whatnot.

The message type tells the receiver (client *or* server) how to interpret the rest of the data in the message, which is why it's got to be one of the earliest pieces of data read from the message. Once you read the message type, you know if the subsequent data is a set of floats for position, an amount of health to deduct from a specific player, and so on.

Both the client and the server must (usually) have a mapping of message type to message format, and they must be agreement on this mapping. It's common, therefore, to put these messages and the definitions of the subsequent data into common code that can be shared between the client and the server.

(You can create message formats that are self-describing, so that the receiver of the message need not agree exactly with the sender on the format, however that's a whole different subject and often too verbose for most game networking protocols.)
> 0 votes

---
Tags: c#, networking, server, client
---


# Question
Title: Highlighing and hit detection on a geographic game
I'm developing a geographic game where you select a country and it highlights. At first I thought about using 196 images (1 for the world, 195 for each country highlight) with the same size, and the country images would only have the country drawn and the rest is transparent. That way they'd overlap perfectly.

This design doesn't feel quite right, and it would cause trouble doing hit detection on cases where a country is inside another one.

What's the best approach for this situation?

# Answer
You have multiple ways to solve this. And you are really trying to solve two separate issues here. One is the highlighting, the other one is figuring out which country has been clicked on.

Depending on your requirements for performance you can do multiple things.

If you don't care that much about performance, and it sounds like you don't have to, then you can use your proposed solution and solve the hit detection problem by simply picking the smallest country that has been clicked on.

Of course that solution is rather static and will make it difficult to change things later.

The other approach would be to create polygons for the world and each country. That approach would perform better and just generally allow you to do a lot of different things efficiently. In this case you could break each polygon down into triangles and just do triangle intersection tests to figure out what was clicked on.
> 0 votes

---
Tags: game-design
---


# Question
Title: How to "reload" a TTF Text during runtime?
As the title says I would like to know how to reload a TTF\_SDL Text during runtime in C++.

What I want to do is to update all the values of the text each frame so I can, to example change the font size and it will instantly change it in-game as well without needing to restart the entire game.

How would I do this?

---

**Note** : I'm using textures to render the text, using the `SDL_CreateTextureFromSurface()` function.

---

**This is the way I'm currently trying to update the TTF Text :**

```
void Text::Update(SDL_Renderer* renderer)
{
    SDL_FreeSurface(m_surface);
    SDL_DestroyTexture(m_texture);

    m_surface = new SDL_Surface();

    m_surface = TTF_RenderText_Solid(m_font, m_text.c_str(), m_color_fg);
    m_texture = SDL_CreateTextureFromSurface(renderer, m_surface);
}

```

And in the header file the two variables look like this :

```
SDL_Surface* m_surface = nullptr;
SDL_Texture* m_texture = nullptr;

```

---

And I currently get an error at `SDL_FreeSurface(m_surface);` which looks like this :

> Thread 1: EXC\_BAD\_ACCESS (code=EXC\_l386\_GPFLT)

However, the code can also be 1 with a address that seem to change every time I run my application

However I sometimes get another error on this line :

```
m_surface = TTF_RenderText_Solid(m_font, m_text.c_str(), m_color_fg);

```

Instead, which has the following error code :

> Thread 1: EXC\_BAD\_ACCESS (code=1, adress=0x11)

But the address on the error codes are not the same every time I run it.

(On both lines of code)

---

# \**Full sprite class code :\**

**Sprite.hpp :**

```
//
//  Text.hpp
//  SDL_Project
//
//  Created by Someone... on 2016-03-18.
//  Copyright © 2016 Someone... All rights reserved.
//

#ifndef Text_hpp
#define Text_hpp

#include <stdio.h>
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2_ttf/SDL_ttf.h>

class Text {

public:

    Text(std::string __m_text, int x, int y, SDL_Renderer* renderer);
    void Render(SDL_Renderer* renderer);
    void Update(SDL_Renderer* renderer);

    void SetText(std::string text, SDL_Renderer* renderer);

    void Destroy();

private:

    SDL_Rect* m_rect = nullptr;
    SDL_Surface* m_surface = nullptr;
    SDL_Texture* m_texture = nullptr;
    SDL_Color m_color_fg;
    TTF_Font* m_font;

    std::string m_text;

};

#endif /* Text_hpp */

```

**Sprite.cpp :**

```
//
//  Text.cpp
//  SDL_Project
//
//  Created by Still made by someone on 2016-03-18.
//  Copyright © 2016 :). All rights reserved.
//

#include "Text.hpp"

Text::Text(std::string __m_text, int x, int y, SDL_Renderer* renderer)
{
    m_text = __m_text;
    m_font = TTF_OpenFont("arial.ttf", 24);

    m_rect = new SDL_Rect();

    m_rect->x = x;
    m_rect->y = y;

    m_surface = TTF_RenderText_Solid(m_font, m_text.c_str(), m_color_fg);
    if (m_surface == nullptr)
    {
        std::cout << "Failed to create text surface : " << SDL_GetError() << std::endl;
    }

    m_texture = SDL_CreateTextureFromSurface(renderer, m_surface);
    if (m_texture == nullptr)
    {
        std::cout << "Failed to create text texture : " << SDL_GetError() << std::endl;
    }

    TTF_CloseFont(m_font);
    SDL_FreeSurface(m_surface);
}

void Text::Render(SDL_Renderer* renderer)
{
    SDL_RenderCopy(renderer, m_texture, NULL, m_rect);
}

void Text::Update(SDL_Renderer* renderer)
{
    // This part throws me a error and makes the game crash.

    std::cout << "1 : " << SDL_GetError() << std::endl;
    SDL_FreeSurface(m_surface);
    SDL_DestroyTexture(m_texture);

    std::cout << "2 : " << SDL_GetError() << std::endl;

    m_surface = TTF_RenderText_Solid(m_font, m_text.c_str(), m_color_fg);
    m_texture = SDL_CreateTextureFromSurface(renderer, m_surface);
}

void Text::SetText(std::string text, SDL_Renderer* renderer)
{
    m_text = text;
    Update(renderer);
}

void Text::Destroy()
{

}

```

# Answer
> 2 votes
You close your font with `TTF_CloseFont` at the end of your constructor. Remove that, and then the rendering should work. You want to move the closing code to the destructor.

Also, you release your `m_surface` first at the end of the `Text`-classes constructor, and then you do that again in the beginning of `Update`. You're essentially trying to delete already deleted memory, which obviously is something that might crash. You don't really even need the `m_surface`-member, it could just be replaced with a locally scoped `SDL_Surface*` variable.

# Answer
> 1 votes
For a relatively small number of fonts, just pre-compile and include them with your game. For sprite-based text rendering, each combination of \[Font\]\[Size\] is a different "font". You pass the font as a parameter to the text rendering methods so you can swap it easily.

Alternatively, you may be able to render each font using only the largest size (for highest resolution) and scale smaller fonts down during the render process (being mindful of aliasing).

As a side-note, be sure that you are legally allowed to redistribute the font. Some of the fonts included in your OS may not be public domain.

# Answer
> 1 votes
I have achieved this in my little testing and learning exercises. I have read that rendering text is a fairly expensive process, especially if using blended and wrapped mode. and so it should be avoided unless there is an actual change to the content.
My solution was to store the rendered texture inside whatever object has the text pinned to it and have a flag which is set if ether the text, font, textPosition or textColour are changed. This flag will trigger an updateText call on the next rendering loop which then recalculates the texts position to make sure it is still centered where it needs to be, and then regenerates the textTexture by first saving the surface locally then converting it to a texture.

forgive the missing stuff, lets assume this has an appropriate constructor and missing setters, getters and other button stuff is all there.

```
class MenuItem
{
public:
    void drawButton();

    void setFont(TTF_Font* newFont);
    //imagine several other setters and getters here...

private:
    bool _textUpdateNeeded;
    std::string text;
    SDL_Color textColour;
    SDL_Rect textPosition;
    TTF_Font* _font
    SDL_Renderer* _renderer;

    void updateTextTexture();
};

void MenuItem::setFont(TTF_Font* newFont)
{
    _font = newFont;
   //something has changed so we flag that the text needs updating on the next
   //render cycle
    _textUpdateNeeded = true;
}
//Assume the other setters are much the same

void MenuItem::updateTextTexture()
{
    TTF_SizeText(_font, _text.c_str(), &_textPosition.w, &_textPosition.h);
    //some stuff here to match the centers of the text and the object its
    //being rendered against which goes beyond the scope of this question.

    SDL_Surface* temp = TTF_RenderText_Solid(_font, _text.c_str(), _textColour);
    _textTexture = SDL_CreatetextureFromSurface(_renderer, temp);
    _textUpdateNeeded = false;
}

void MenuItem::drawButton()
{
    //Here we see if the text NEEDS to be updated first, If so then we will do
    //this now. If the text has not been changed we fall through this and just
    //keep rendering the old texture.
    if(_textUpdateNeeded) updateTextTexture();
    //imagine here we draw any bits that aren't the text first so the text
    //will appear on top of everything else.
    SDL_RenderCopy(_renderer, _textTexture, NULL, &_TextPosition);
}

```

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


# Question
Title: Camera.WorldToScreenPoint not working with perspective
```
transform.position = Camera.main.WorldToScreenPoint( new Vector3( origin.position.x, origin.position.y, origin.position.z ) );

```

I have this code on a Unity 4.6 UI object. The origin is some transform I want the UI element to stay above( like a floating health bar ).

The camera is top-down, but angled slightly on the x-axis. When the camera is moved, the UI element moves away from the origin slightly as if the camera was orthographic.

How would I go about compensating for the perspective? Is there another method I should be using to convert from world space to canvas space?

EDIT: Pictures added. Note that the transform is at the center of the model, not the base.

# Answer
> 1 votes
You want to move 2d UI (Label) with respect to your game object. **WorldToScreenPoint** transform the position from world space into screen space.

**Here you are on right track, what you are missing is that**

```
screenPosition = Camera.main.WorldToScreenPoint(transform.position);
screenPosition.y = Screen.height - screenPosition.y;

```

So, according to me your script like this:

```
var screenPosition :  Vector3;

function Update (){
    screenPosition = Camera.main.WorldToScreenPoint(transform.position);
    screenPosition.y = Screen.height - screenPosition.y;
}

function OnGUI (){
    GUI.Label(Rect(screenPosition.x, screenPosition.y, 50, 20),"Health...");

}

```

Or you can use this script: **Ready to use Script (Tested & works )**

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

public class SingleLbl : MonoBehaviour {

    private bool mShowGUIButton = false;
    public GameObject targetObject;
    public float btnWidth = 400f;
    public float btnHeight = 180f;

    void Start () {

    }

    void OnGUI ()
    {
        // Find the 2D position of the object using the main camera
        Vector3 boxPosition = Camera.main.WorldToScreenPoint(targetObject.transform.position);

        // "Flip" it into screen coordinates
        boxPosition.y = Screen.height - boxPosition.y;

        // Center the label over the coordinates
        //boxPosition.x -= boxW * 0.5f;
        //boxPosition.y -= boxH * 0.5f;

        GUI.Button(new Rect(boxPosition.x, boxPosition.y, btnWidth , btnHeight), targetObject.name);
        Debug.Log (boxPosition.z + "--x--" + boxPosition.x + "----y--" + boxPosition.y);

    }

}

```

# Answer
> 0 votes
would it be better for you to add a object you can reference as a child of the game object. It could be damage1 or something and then on a trigger you could

`Instantiate(damage1, transform.position, transform.rotation);`

you could then set that to a animation effect like moving up and fading out or whatever effect you like.

# Answer
> -1 votes
you can add this to the update function of your UI object:

```
transform.forward = -Camera.main.gameObject.transform.forward;

```

---
Tags: unity, camera, gui
---


# Question
Title: Getting the Right Vector from the Forward Vector
I'm currently working on a small Camera (ArcBall) and I finally am starting to understand how it will work.

I will first create a basic View Matrix using a LookAt function.

Then, I will send the Camera Position and the Camera Target to a function which will:

1: Calculate the Vector of (Camera Position - Camera Target)

2: Rotate this vector by X Pitch 3: Rotate the same vector by Y Yaw

This will determine the new Camera position. Now I need to find the Up Vector to be able to use LookAt() so I need to do the cross product of the forward and the right vector to find the Up Vector.

4: I will do (Camera Target - Camera Position) and normalize it so this will be my new Forward vector

5: ??? I need to find the right vector. How can I find the Right vector if I do not have the Up vector?

If you see flaws with my ArcBall camera, tell me, I am new to OpenGl and I'm trying to learn.

# Answer
> 1 votes
You can't get the "right" vector from just a "forward" vector. Any particular "forward" vector could have an infinite number of different legal "up" and "right" vectors.

For example, if I am looking forward along the z axis `forwardVector = vec3(0,0,1)`, then I could have up be along the y axis `upVector = vec3(0,1,0)` and right therefore be along the x axis `rightVector = vec3(1,0,0)`, or I could have up be along the -y axis `upVector = vec3(0,-1,0)` and therefore right would be along the -x axis `rightVector = vec3(-1,0,0)`. Or I could even have 'up' be along the x axis `upVector = vec3(1,0,0)`, which would mean that right is along the y axis `rightVector = vec3(0,1,0)`. And so forth. No one "up" or "right" vector can be considered "correct" if all you have is a forward vector, without imposing some extra constraints on the system.

One common constraint to add to this kind of system is that "up" should be pointing as close as possible to some objective "up" in the scene. Lots of 3D platform games do this, for example. In these, you can calculate your "right" vector by taking the cross product of the forward vector against vec3(0,1,0) (or whatever your world-space 'up' is), and then the cross product of the right vector against the forward vector. And that would work.

But it wouldn't be an arcball, since the camera would always be re-orienting itself so that its local 'up' pointed upward in the world, where arcballs are supposed to maintain their accumulated orientation as you rotate.

For a proper arcball, you need to not be storing the camera position at all; instead, you should just store the camera's orientation. Keep its forward, its up, and its right vectors, and rotate all of them based on the pitch and yaw, and then reconstruct a new camera position based upon the target position and the forward vector. And then you can LookAt using the up vector that you already have!

---
Tags: opengl, mathematics, camera, vector
---


title: How can I add holes to a sprite?

text:
# Question
Title: How can I add holes to a sprite?
I'd like to find a way to add holes caused by a 'bomb' to my floor sprite, a bit like what is in this game here.

Basically there is a sprite (the green floor) and another sprite (the bomb) that falls on top of the green floor and the bomb then explodes. Once exploded part of the green floor sprite is gone. The player (red ball) can then move the sprite inside the new cavity that was created in the green floor sprite.

# Answer
You can just draw holes over the floor object, here all the holes have their own class with separate properties from the floor class:
> 0 votes

# Answer
I'm not sure if this is the way that that game specifically did it but what you do is create a texture which is then subtracted from other textures. So in this can you create a shape which represents the whole in the ground, then you when the bullet explodes it subtracts the shape from the ground texture and leaves a whole in the ground texture.

When you move around you then check if your in one of these transparent textures so that you know that you can go into that area. If there aren't any special transparent textures more around normally.

Here is a similar question on the unity answers which goes into detail of how to implement this.

**Image taken from above unity link**

Keep in mind that is only one possible solution, for all we know they made a texture which they swap out when they need to remove a part of the screen which would have the same effect...

Hope this is what your looking for :)
> 0 votes

---
Tags: 2d, sprites
---


# Question
Title: A single libgdx gamescreen with pop-up menu, getting ready, hud and game over?
Is it possible and practical to have only one screen, like a GameScreen class, where the menu, getting ready (plus instructions), hud (only score) and game-over screens can pop-up when needed. Can I do this with the Table class from libGDX?

I'm asking this because I am working on a game where I would like to have the game-world in the background of the menu for game over etc. It's a 2D side-scrolling game, something like Flappy Bird or Swing Copters. I don't need the menu to be on a completely different screen! :D

# Answer
You should probably take a look at Scene2D's Window class. Think of it as a screen that just overlays other screens. It's also a `Table`, which means you can add buttons or any other `Actor` to it just like any other table. This also means you can directly add it to your `Stage`, if you wish.

A simple pause screen would be something like this:

```
Window pause = new Window("Paused", skin);
pause.setMoveable(false); //So the user can't move the window
pause.add(new TextButton("Unpause", skin)); //Add a new text button that unpauses the game.
pause.pack(); //Important! Correctly scales the window after adding new elements.
float newWidth = 400, newHeight = 200;
pause.setBounds((Gdx.graphics.getWidth() - newWidth ) / 2,
(Gdx.graphics.getHeight() - newHeight ) / 2, newWidth , newHeight ); //Center on screen.
stage.addActor(window);

```

and would turn out like this:
> 1 votes

# Answer
Yes. It is possible.

Any of the scene2dUI widgets, like `Table`, inherit from `Actor`. `Actor` has a `setVisible(boolean isVisible)` member that will hide it and all of its children and disable any touch events to it. You just have to make sure that your menu or game instructions are in front of your Game view by adding them to your `Stage` last.

You will also need to make sure that you pause any game logic that should not take place while the menu is visible. This can be done with just a `boolean isPaused` flag that your game engine checks before it does any position updating. If your game has animations that you still want to use while the menu is up, you will need to make sure that the `isPaused` flag doesn't prevent the animations from updating.
> 1 votes

---
Tags: 2d, libgdx, game-mechanics, side-scroller, menu
---


# Question
Title: Strategies for dealing with crowds at choke-points
I've recently switched my game engine over from steering behaviours to impulse based movement with proper time based collision resolution. This has solved so many problems (no more tunnelling, yay) and made the simulation a great deal more stable. However, with the stability has come a new problem.

The three balls started their journey near the bottom of the image, their target was where the pink ball has stopped. On the way the red and green balls have become stuck at the choke-point in the wall.

Before, I could rely on floating point errors and the general instability of steering behaviours to make the green and red balls jostle each other until they managed to get through the choke point. Now with proper collision resolution, the forces acting upon the balls cancel each other out which results in the balls remaining perfectly still.

What methods are commonly used to resolve such situations? Perhaps some sort of priority queueing system would work, though I can see it becoming complex once I need to decide priority between more than 2 objects.

# Answer
Assign each movable object a unique index & prohibit an object with a higher index from moving an agent with a lower index. This will allow 'older' objects to nudge 'newer' ones, but not vice versa & is less overhead than queuing. Essentially, the index acts as a movement priority.
> 3 votes

# Answer
add time to path finding

here is a paper that talks about that time cube: http://www0.cs.ucl.ac.uk/staff/D.Silver/web/Applications\_files/coop-path-AIWisdom.pdf

and here is an Objective-C implementation: http://allseeing-i.com/ASIPathFinder
> 2 votes

# Answer
Actually, i don't think you should fix it. If (i may guess) the arrows indicate force vectors applied to any sphere, at any position in the grid (probably interpolated "bi-linearly" or likewise, or somehow more "analog" than just being 0/1), well then the behaviour is physically correct and you should congratulate yourself for having a well behaving solution.

The 2 spheres are in a good balance, as they sit there and hate each other. Apparently, if they move a bit to right, the "force arrow" to right affects the right side sphere a bit more (and vice versa on the left side sphere; a bit less), and so they move back to balance. This is how it should be.

Imho, what *should* be fixed is the wall, or the sphere sizes, or something else among the buildstones themselves. You have created an impossibility and the correct behaviour in that situation is accordingly a deadlock (sorry for misabusing words, i hope you get them anyway :-)).

Perhaps instead disable the nearest left/right force arrows, or arrange them in some other way that **is not symmetrical and does not encourage to balance**?

I think it would be a bad fix to artificially fix it... would get hairy too early.
> 0 votes

---
Tags: collision-resolution
---


# Question
Title: How do I make my indices anti-clockwise, so I can cull triangles in OpenGL? (immediate mode)
At the moment, I'm attempting a *basic* game engine in OpenGL using immediate mode. I'm trying to render a cube. Cube is a class with the vertices, normals, and indices. Here is part of the Cube class:

```
// Note: I'm actually coding this in C# using a light OpenGL wrapper called OpenTK.
// But I'm giving my instructions in C++ for this post, for simplicity's sake:
// Please don't be confused if I switch between the two :-)

// C#:

Vertices = new Vector3[]
        {
            new Vector3(-1.0f, -1.0f,  1.0f),
            new Vector3( 1.0f, -1.0f,  1.0f),
            new Vector3( 1.0f,  1.0f,  1.0f),
            new Vector3(-1.0f,  1.0f,  1.0f),
            new Vector3(-1.0f, -1.0f, -1.0f),
            new Vector3( 1.0f, -1.0f, -1.0f),
            new Vector3( 1.0f,  1.0f, -1.0f),
            new Vector3(-1.0f,  1.0f, -1.0f)
        };

Indices = new int[]
        {
            // front face
            0, 1, 2, 2, 3, 0,
            // top face
            3, 2, 6, 6, 7, 3,
            // back face
            7, 6, 5, 5, 4, 7,
            // left face
            4, 0, 3, 3, 7, 4,
            // bottom face
            0, 1, 5, 5, 4, 0,
            // right face
            1, 5, 6, 6, 2, 1
        };

Normals = new Vector3[]
        {
            new Vector3(-1.0f, -1.0f,  1.0f),
            new Vector3( 1.0f, -1.0f,  1.0f),
            new Vector3( 1.0f,  1.0f,  1.0f),
            new Vector3(-1.0f,  1.0f,  1.0f),
            new Vector3(-1.0f, -1.0f, -1.0f),
            new Vector3( 1.0f, -1.0f, -1.0f),
            new Vector3( 1.0f,  1.0f, -1.0f),
            new Vector3(-1.0f,  1.0f, -1.0f),
        };

```

This all worked out fine. The sides of the cube are shadowed nicely, and all seems well. The inside looks like this (note, the lighting is actually coming from the top):

When I cull the 'non-visible' triangles with `glEnable(GL_CULL_FACE);` it looks okay normally, but the bottom looks like this:

And if you move the camera to the 'inside' of the cube, you can see the missing bottom face by looking down! This seems to me like I'm confusing OpenGL by declaring my vertices in the clockwise direction, instead of anticlockwise.

This seems to be causing two problems. Firstly, my culling is all messed up. Secondly, remember how the light is actually coming from the top of the cube? Well, from the inside of the cube, it looks like the light is coming from the bottom. Weird.

I'm rendering my cube by doing the following:

```
GL.Begin(PrimitiveType.Triangles); // Translation: glBegin
foreach (Shape shape in shapes) {
    foreach (int index in shape.Indices) {
        GL.Normal3(shape.Normals[index]); // Translation: glNormal3f
        GL.Vertex3(shape.Vertices[index]); // Translation: glVertex3f
    }
}
GL.End();

```

How do I fix this culling problem? Do I need to be worried that the lighting is messed up from the inside? I think I might just need to swap my indices around, but I don't know how I do this. The rendering works by passing the vertices in the array 0-7, in the order shown by the indices array. Hopefully, getting my indices in the right order will fix the issue.

If my logic upto here is correct, what are the correct (anti-clockwise) indices for my cube class? How did you work this out?

Thanks a lot for any help in advance. I sure appreciate it.

# Answer
Solved by reversing the indices for the problematic bottom face. Indices are now:

```
Indices = new int[]
    {
        // front face
        0, 1, 2, 2, 3, 0,
        // top face
        3, 2, 6, 6, 7, 3,
        // back face
        7, 6, 5, 5, 4, 7,
        // left face
        4, 0, 3, 3, 7, 4,
        // bottom face
        0, 4, 5, 5, 1, 0, // Back to front now.
        // right face
        1, 5, 6, 6, 2, 1
    };

```
> 2 votes

---
Tags: c#, opengl, vertex, normals
---


title: Perspective-Correct Texture Mapping

text:
# Question
Title: Perspective-Correct Texture Mapping
I am working on a small rendering engine for a personal project and I am having issues with the texture mapping part of it.

It seems to work for some cases, but not for others. For example, when one of the vertices is behind the camera, the texture is stretched.

*Seemingly* **Correct case**  **Incorrect case**

I am guessing that it has something to do with the texture mapping not being perspective-correct. I have tried various changes mainly involving the z-distance to the camera, but I could not find any quick fix to my code.

Here is my code for the perspective projection:

```
public double[] project(double x, double y, double z) {
    double tx = x - camera.x;
    double ty = z - camera.z;
    double tz = y - camera.y;

    double cx = Math.cos(camera.pitch);
    double cy = Math.cos(camera.yaw);
    double cz = Math.cos(camera.roll);

    double sx = Math.sin(camera.pitch);
    double sy = Math.sin(camera.yaw);
    double sz = Math.sin(camera.roll);

    double dx = cy * (sz * ty + cz * tx) - sy * tz;
    double dy = sx * (cy * tz + sy * (sz * ty + cz * tx)) + cx * (cz * ty - sz * tx);
    double dz = cx * (cy * tz + sy * (sz * ty + cz * tx)) - sx * (cz * ty - sz * tx);

    double ez = 1.0 / Math.tan(FOV / 2.0);

    double bx = ez / dz * dx;
    double by = ez / dz * dy;

    if (dz < 0.0) {
        bx = -bx;
        by = -by;
    }

    int px = (int) (width + bx * height) / 2;
    int py = (int) (height + by * height) / 2;

    return new double[] { px, py, dz };
}

```

and here my code for the texture mapping:

```
public double[] map(double x, double y, double x0, double y0, double x1, double y1, double x2, double y2, double x3, double y3) {
    double A = (x0 - x) * (y0 - y2) - (y0 - y) * (x0 - x2);
    double B = ((x0 - x) * (y1 - y3) - (y0 - y) * (x1 - x3) + (x1 - x) * (y0 - y2) - (y1 - y) * (x0 - x2)) / 2.0;
    double C = (x1 - x) * (y1 - y3) - (y1 - y) * (x1 - x3);

    double det = A - 2.0 * B + C;

    double u;
    if (det == 0.0) {
        u = A / (A - C);
        if (Double.isNaN(u) || u < 0.0 || u > 1.0)
            return null;
    } else {
        double u1 = ((A - B) + Math.sqrt(B * B - A * C)) / det;
        boolean u1valid = !Double.isNaN(u1) && u1 >= 0.0 && 1.0 >= u1;

        double u2 = ((A - B) - Math.sqrt(B * B - A * C)) / det;
        boolean u2valid = !Double.isNaN(u2) && u2 >= 0.0 && 1.0 >= u2;

        if (u1valid && u2valid)
            u = u1 < u2 ? u2 : u1;
        else if (u1valid)
            u = u1;
        else if (u2valid)
            u = u2;
        else
            return null;
    }

    double v1 = ((1.0 - u) * (x0 - x) + u * (x1 - x)) / ((1.0 - u) * (x0 - x2) + u * (x1 - x3));
    boolean v1valid = !Double.isNaN(v1) && v1 >= 0.0 && 1.0 >= v1;

    double v2 = ((1.0 - u) * (y0 - y) + u * (y1 - y)) / ((1.0 - u) * (y0 - y2) + u * (y1 - y3));
    boolean v2valid = !Double.isNaN(v2) && v2 >= 0.0 && 1.0 >= v2;

    double v;
    if (v1valid && v2valid)
        v = v1 < v2 ? v2 : v1;
    else if (v1valid)
        v = v1;
    else if (v2valid)
        v = v2;
    else
        return null;

    return new double[] { u, v };
}

```

and here is my quad drawing code:

```
public void renderFace(Screen screen, int x0, int y0, int z0, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) {
    boolean render = true;

    double[] p0 = screen.project(x0, y0, z0);
    int px0 = (int) p0[0], py0 = (int) p0[1];
    render |= p0[2] >= ZCLIP && px0 >= 0 && px0 < screen.width && py0 >= 0 && py0 < screen.height;

    double[] p1 = screen.project(x1, y1, z1);
    int px1 = (int) p1[0], py1 = (int) p1[1];
    render |= p1[2] >= ZCLIP && px1 >= 0 && px1 < screen.width && py1 >= 0 && py1 < screen.height;

    double[] p2 = screen.project(x2, y2, z2);
    int px2 = (int) p2[0], py2 = (int) p2[1];
    render |= p2[2] >= ZCLIP && px2 >= 0 && px2 < screen.width && py2 >= 0 && py2 < screen.height;

    double[] p3 = screen.project(x3, y3, z3);
    int px3 = (int) p3[0], py3 = (int) p3[1];
    render |= p3[2] >= ZCLIP && px3 >= 0 && px3 < screen.width && py3 >= 0 && py3 < screen.height;

    if (!render)
        return;

    int minX = Math.min(Math.min(px0, px1), Math.min(px2, px3));
    if (minX < 0)
        minX = 0;
    if (minX > screen.width)
        minX = screen.width;

    int minY = Math.min(Math.min(py0, py1), Math.min(py2, py3));
    if (minY < 0)
        minY = 0;
    if (minY > screen.height)
        minY = screen.height;

    int maxX = Math.max(Math.max(px0, px1), Math.max(px2, px3));
    if (maxX < 0)
        maxX = 0;
    if (maxX > screen.width)
        maxX = screen.width;

    int maxY = Math.max(Math.max(py0, py1), Math.max(py2, py3));
    if (maxY < 0)
        maxY = 0;
    if (maxY > screen.height)
        maxY = screen.height;

    if (minX == maxX || minY == maxY)
        return;

    for (int py = minY; py < maxY; ++py)
        for (int px = minX; px < maxX; ++px) {
            double[] uv = screen.map(px + 0.5, py + 0.5, px0, py0, px1, py1, px2, py2, px3, py3);
            if (uv == null)
                continue;
            double u = uv[0], v = uv[1];

            double pz = (1 - u) * ((1 - v) * p0[2] + v * p2[2]) + u * ((1 - v) * p1[2] + v * p3[2]);
            if (pz < ZCLIP)
                continue;

            int texX = 15 - Math.min(15, (int) (16 * u));
            int texY = 15 - Math.min(15, (int) (16 * v));
            screen.setPixel(px, py, pz, Art.WALLS.getPixel(texX, texY) * BRICKS);
        }
}

```

Can anyone point out what I am doing wrong? I am not very experienced as this is my first try at implementing a game engine.

Thank you for any insight.

# Answer
Your code isn't wrong at all. You are dealing with matrices and vertices the right way (your 3D simulation actually works), and even texture mapping is fine. Matter is, your texture mapping algorithm uses just a linear interpolation to map a point in the 3D space to a point in the 2D plan of a given texture.

**Texture mapping**
When mapping texture to mesh polygons, you usually consider a 3-ple in the tridimensional space (three 3D vertices), and associate it to another 3-ple in a 2D plan (three 2D vertices inside a texture). When drawing, the three 3D vertices are projected on the screen (*\[x,y,z\]* to *\[x',y'\]*); then the triangle considered on the texture (our three 2D vertices) is drawn on the screen, eventually transforming the 2D vertices to fit the previous projection. You know this because you actually did it.
*But*, the texture mapping algorithm you implemented is an *affine texture mapping*, meaning that the triangles are drawn using only plane affine transformations (thus, translation, rotation, scaling, flipping/mirroring), so when drawing you are considering the coordinates as they are, without information about their actual depth in their tridimensional counterparts. You are just drawing sprites.

**Perspective correction** To draw textures correctly in a 3D space projection, we need to consider the vertices along with some information about their depth in the space in relation to the 3D camera position. To accomplish perspective correction for textures, we consider the linear interpolation formula:

, where .

Affine texture mapping directly interpolates between two values, and *lerping* twice lets the engine to draw every texel needed. This is a fast calculation to perform, but the result is not that realistic.

By introducing information about depth, we are telling the engine that our triangle is not a flat shape on the screen, and this is achieved by editing the interpolation formula as follows:

where *zi* is the *depth* of vertex *i* in the interpolation. This way, when moving along the texture the computed texel will be in a different position compared to *lerp*, reflecting real perspective projection with much more fidelity. Usually this computation is harder to perform than *lerping*, and due to this complexity a dedicated GPU is preferable (and optimized) to calculate texture coordinates. Letting the CPU do all the work means forcing vertex processing, and is not good for your game performance.

Here's a comparison between the original texture (chessboard), its affine texture mapping, and perspective-correct texture mapping.

Drawing from texture to screen is achieved by screen sub division tecniques. These are methods to divide those area on the screen designated for drawing textures into pieces before performing texture drawing.
> 2 votes

---
Tags: java, textures, uv-mapping, perspective
---


title: Game puzzle pop in java

text:
# Question
Title: Game puzzle pop in java
I am making a game in Java based of those puzzle popping games. The objective is to select with the mouse and remove a tile. The game i want to build. I have a JPanel and on top, several Components, a board\[\]\[\], of type Tile. Tile has a BufferedImage and a Color as background. How to make a tile, which is a BufferedImage, change its state, for example, change color or remove it from a array\[\]\[\] using a mouse click. I have 4 classes,link to pastebin, didnt want to put 4 classes here Thanks in advance.

# Answer
I suppose the Tile class is the class of which all the "balls" are an object of? (i dont have much time to read the code).

If i understand correctly, what you are asking is how to change the balls color? if yes, i would suggest that when you want to change a balls color just get the tiles from your Tiles array and just:

```
board[x][y].background = //the new color;

```

EDIT:

Use (i write the code directly here so there may be some mistakes :/):

```
 public void mousePressed(MouseEvent e){
    int mx = e.getX();
    int my = e.getY();
    for(Tile[] balls : board[]){
      for(Tile ball : balls){
        if(mouseover(mx,my,ball)){
          //check if surrounding balls have the dame color, and if they do "break" them/change their color
        }
      }
    }
 }

```

and the mouseover() function would be something like :

```
 private boolean mouseOver(int mx, int my ,Tile ball){
     //width and height is the width/height off the balls
    if(mx <= ball.x + width && mx >= ball.x){
        if(my <= ball.y + height && my >= ball.y){
            return true;
        }else return false;
    }else return false;

}

```

I think this should work....or at least i hope so :D
> 1 votes

---
Tags: java, gui
---


# Question
Title: Game Maker: Studio - Make objects avoid other instances of same object with A* pathfinding
I have a game where there are multiple enemies who must chase a single player. I have pathfinding set up using the GML A\* pathfinding with mp\_grid and a path. However, these enemies can walk on top of each other when seeking the player. To fix this, I also told the path to ignore enemies as well with mp\_grid\_add\_instances, but then they stop moving altogether because they see themselves as obstacles, thus trapping themselves within a bounding box. Is there a way I can add "all other enemies BUT self" with mp\_grid\_add\_instances?

Here's my grid creation code (in a CONTROLS class for initializing variables):

```
global.zombie_ai_grid = mp_grid_create(0, 0, room_width / 50, (room_height - sp_dashboard.sprite_height) / 50, 50, 50);
mp_grid_add_instances(global.zombie_ai_grid, obj_obstacle, false);

```

This is my path initialization code (in Zombie class):

```
path = path_add();
alarm[0] = 5;

```

This is my path creation code in Alarm 0 (path updates every 2 seconds):

```
mp_grid_path(global.zombie_ai_grid, path, x, y, nearest.x, nearest.y, true);
path_set_kind(path, 1);
path_set_precision(path, 8);

path_end();
path_start(path, MAX_SPEED, 0, true);

alarm[0] = room_speed * 2;

```

# Answer
Probably the easiest way is to alter the A\* heuristic. Once a tile has been used in a path, increase the heuristic for this tile so that the next pathfinding call will try to avoid that tile. This will also make the zombies gather around the player.
> 1 votes

# Answer
Instead of using A-star from each zombie to the player, use a breadth-first (ie Dijstra's) out from the player, and as you encounter each zombie assign it the current best path. Have each zombie ignore other zombies for pathfinding but skip a step if the next node is occupied by a zombie.
> 0 votes

# Answer
Basically, you'll want the zombies to all be added to the grid EXCEPT the one who is currently pathfinding, correct? That way, it won't consider itself an obstacle and get stuck in place. Update the grid using "with" and doing an ID check. The downside is that we have to clear the grid all the time to constantly update enemy positions, but in my example each enemy had their own specific grid rather than a controller with a global variable grid. It looks like this:

```
// ---STEP EVENT---

mp_grid_clear_all(grid);
with enemy
{
    if (id != other.id) mp_grid_add_instances(other.grid, id, 0);
}

```

This code is run WITHIN the enemy itself. When it references "other", it's calling back to itself and checking its own ID. Real simple and it works flawlessly for having enemies avoid overlap and work their way around each other. In my case, I chose non-precise collisions because I didn't need to worry about that.
> 0 votes

---
Tags: ai, path-finding, game-maker
---


title: How to remove terrain in 3d?

text:
# Question
Title: How to remove terrain in 3d?
After the release of Minecraft I saw more and more rip offs of the game but some actually began to change it up a bit making the game have a organic look instead of the iconic blocky one that Minecraft does.
If you'd like to look at the game that i'm referring to you can do so here. If you skip to around 50 seconds on the first video the steam page offers you can see the mining part that i'm wondering about.
I was wondering how this affect is achieved where they are able to remove part of the 3D object on collison with the players pick. I have heard about constructive solid geometry before and figured that could have been used but i'm not so sure.

# Answer
It could be Constructive Solid Geometry indeed. But they said in the store page it is a voxel-based world (unless they lied of course). Which is basically pixels in 3D (or i could say cubes in the case of minecraft, and others).

In this case, it seems to me they smooth out those voxels to achieve that organic looks. Something like Castle Story which you can clearly see some are smoothen out, well not everything is like in Rising World, but you get my point.
> 0 votes

---
Tags: unity, c#, 3d, terrain
---


# Question
Title: How can I disallow the changing of a parent?
I want to disable transform.SetParent(Transform) for a particular GameObject.

I am not sure where to start, so it is really difficult to show what I have tried. Is this even possible?

# Answer
It isn't possible to prevent that, however you can get a call when the parent transform changes and set it back to the correct value.

```
Transform m_DesiredParent;
void Awake()
{
    m_DesiredParent = transform.parent;
}

void OnTransformParentChanged()
{
    if(transform.parent != m_DesiredParent)
    {
          transform.SetParent(m_DesiredParent);
          Debug.LogError("Cant change this parent, setting back to desired parent");
    }
}

```

Biggest downside is that you cant control if the position/rotation/scale will be set back to the same value since there is no way of knowing whether the call that changed it saved its local position/rotation/scale or its world/position/rotation/scale
> 2 votes

# Answer
It is very possible(with a quick refactoring), and you dont need to know the actual type, worry about deriving or need to instantiate every gameObejct manually in code. A simple trick with extension methods will do: just "add" a field and extension method to the `GameObject` class:

```
public static class GameObjectExtensions
{
    private static readonly ConditionalWeakTable<GameObject, bool> _canSet = new ConditionalWeakTable<GameObject, bool>();

    public static void ChangeCanSetParent(this GameObject go, bool value)
    {
         _canSet.Remove(go);
         _canSet.Add(go, value);
    }

    public static void TrySetParent (this GameObject go, Transform transform)
    {
         bool can;
         if(!_canSet.TryGetValue(go, out can) || can)
            go.SetParent(transform);
         else {
          //or just ignore it
          throw new ApplicationException("method SetParent() is disabled on this GameObject.");
         }
    }
}

```

Now just find/replace all(or simply just where it matters) occurrences of `SetParent` with your new custom `TrySetParent`, usage:

```
GameObject player; //can set safely from editor, it IS actually "normal" game object
//originally player.SetParent()
player.TrySetParent(transform); //will work
player.ChangeCanSetParent(false); //disable it
player.TrySetParent(transform); //will throw

```

while it does not technically disable original `SetParent`, it is clean solution with backwards compatibility and without worrying anything in "user" code, or unexpected behavior and errors caused by not testing for/casting to actual type.
> 3 votes

# Answer
No, not really, as the method is not virtual.

The closest reasonable approach is to derive from `GameObject` and implement a *new* `SetParent` method:

```
public new void SetParent (Transform transform) {
  throw new NotSupportedException("I'm afraid I can't do that.");
}

```

However, this will only fail at runtime and even then only if you call `SetParent` through an instance that is of the type of your subclass. That is, this code:

```
MyGameObject instance = new MyGameObject();
instance.SetParent(...);

```

will throw when `SetParent` is called. However this (likely very common) code:

```
GameObject instance = new MyGameObject();
instance.SetParent(...);

```

will not throw, because `SetParent` isn't virtual.

---

I suspect that whatever you're trying to accomplish by preventing `SetParent` from getting called, you're going to have to try doing so at a higher level, but without more information it's hard to suggest what you should try.
> 2 votes

---
Tags: unity
---


# Question
Title: Ability/Skill Data and Method Structure (C#, Unity3D)
So I've come to design my game which players will be having a unique set of skill or ability to come with. I can store skill name, mana cost, cooldown, etc in database which each skill have in common, but as we gamer know, a skill is unique not just by its attributes, like the sequence of movement, the object will be instantiate in the world, it's just that very unique.

So the question is, where do I put this "unique", the skill sequences? Do I make skill1.cs, skill2.sc for every single skill? xml for sequence then make script to read and define myXml?

For example, in a game, the effect of each card is very unique for example card1 allow player to deal damage and draw card, card2 just deal damage, card3 deal damage to enemy and then draw a card, and so-on, where and how they store this sequences or method of each card effect?

# Answer
Based on your description, I would make each card effect verb a class & then use composition to combine them into cards as needed. E.G. the *draw cards* action would be an effect class, its parameters might be # of cards, source drawn from & type of draw. *Damage player* might be another effect class & its parameters might be amount & target(s). By varying the parameters you could combine those two effect classes to make the following cards:

* draw 2 card from discard pile
* draw 1 card from another player
* deal 2 damage to another player
* take 3 and draw 1 random card from each player

Using this model, the card class is basically a collection of effects (plus anything else relevant to your game, such as art, flavor text, etc).
> 2 votes

---
Tags: unity, c#, architecture, data-structure, databases
---


# Question
Title: Do I need to delete a texture after calling SDL_DestroyTexture()?
Let's suppose I have this texture:

```
SDL_Texture* txt = IMG_LoadTexture(renderer, "path");
/* various code */
SDL_DestroyTexture(txt);
delete txt; // <- Is this part really necessary? Doesn't SDL_DestroyTexture() does it already?

```

Since there's not a lot of documentation about SDL, I haven't found an answer to my question on my own.

# Answer
> 2 votes
No.

SDL2 is a C library, and since C has no `delete` keyword, it wouldn't make sense here.

C allocates memory using `malloc` and friends, but usually C libraries take the approach of managing the memory for you, so if there are functions like `SDL_DestroyTexture`, you can assume that they also free the allocated memory.

# Answer
> 2 votes
```
SDL_DestroyTexture(txt);

```

should clean up and then free the memory used by the texture. However you will be left with a dangling pointer so be sure to deal with that.

```
txt = NULL //if using C
txt = nullptr //if using C++

```

*(Unless you're **really** sure the variable won't ever be used again before you leave the scope)*
Without doing this if the pointer variable is used again before being reassigned it will likely cause a crash or a bug.

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


# Question
Title: Error on MonoGame Content Pipeline: Texture Importer Error
I just encountered this kind of error when using the MonoGame Content Pipeline and it's my first time to use it to convert png to xnb files (I use a stand alone app for converting files to xnb in the past). I've done building spritefonts to xnb files and stuff like that in my previous MonoGame projects and I thought it would be similar but it turned out to be not the case.

So this is the error I have:

```
error: Importer 'TextureImporter' had unexpected failure!
System.NullReferenceException: Object reference not set to an instance of an object
  at Microsoft.Xna.Framework.Content.Pipeline.TextureImporter.Import (System.String filename, Microsoft.Xna.Framework.Content.Pipeline.ContentImporterContext context) [0x00000] in <filename unknown>:0
  at Microsoft.Xna.Framework.Content.Pipeline.ContentImporter`1[Microsoft.Xna.Framework.Content.Pipeline.Graphics.TextureContent].Microsoft.Xna.Framework.Content.Pipeline.IContentImporter.Import (System.String filename, Microsoft.Xna.Framework.Content.Pipeline.ContentImporterContext context) [0x00000] in <filename unknown>:0
  at MonoGame.Framework.Content.Pipeline.Builder.PipelineManager.ProcessContent (MonoGame.Framework.Content.Pipeline.Builder.PipelineBuildEvent pipelineEvent) [0x00000] in <filename unknown>:0

```

Is there a way to resolve this? Is there a tutorial of some kind I can follow to use the TextureImporter and the things I haven't yet understood on MonoGame's Content Pipeline with in-depth explanation about it?

# Answer
You need to download and install the Visual C++ Redistributable Packages for Visual Studio 2013.

---

These two posts on https://github.com/mono/MonoGame/issues/3556 worked for me:

**tomspilman**:

> Hum... the redist we need vcredist\_x64.exe is only 7MB. If you download and run it from the command line:
>
> vcredist\_x64.exe -?
>
> It tells you that it has /quiet and /norestart mode:
>
> We should be able to embed this into the Windows installer fairly easily if we want.
>
> Either that or we just add a note about it on the download site.

**gms9rc**:

> Problem solved. Despite the fact that I am using VS2012 I needed to install the 2013 redistributable. Right here for anyone who comes across this problem https://www.microsoft.com/en-us/download/details.aspx?id=40784
> 2 votes

---
Tags: xna, monogame, xna-content-pipeline, pipeline, png
---


# Question
Title: Simulating elastic ball collisions quickly escalates to disaster
I'm trying to learn HTML canvas and was working on a basic physical simulation, where a number of balls are drawn and set in motion, and the program simulates them colliding and bouncing off the walls and each other.

Here's the simulation.

Each ball is initially given a random position, direction, and a constant starting velocity. For simplicity, a ball's mass is simply equal to its radius. The velocity vectors are stored as (x,y) instead of polar coordinates to make the calculations simpler and the simulation faster, but this apparently has unintended consequences.

In the simulation linked above, I'm starting with ten balls, and each ball has an initial velocity magnitude of 3, so the total initial "speed" of the system should be 30 (= 10 * 3). On each frame, I calculate the total speed of all the balls and read it out in a form field, and with uniform balls of size 10, the total speed seems to stay a few units under 30. The same is true of the min and max radius are decreased so all the balls are size 5, or increased to 20: the total speed stays relatively uniform.

However, interesting things happen when the balls vary in size. If the minRadius is changed to 5 and maxRadius to 15, for example, you'll notice that the total speed of the system starts climbing over time. The bigger the difference, the faster the speed grows out of control.

SO my first guess is that I screwed up the physics, but I can't figure out how. My other guess is that this is caused by accumulating floating point error, but it's interesting that it only grows upwards, and never towards zero. Also, it does seem to have a limit; while it constantly fluctuates, it seems to be capped at some value related to the delta between the minimum and maximum ball size.

My question is really to understand why this is happening? Did I just screw up something simple, or is something more sinister going on?

# Answer
> 2 votes
First , your

```
polarToComponent(magnitude, angle) {
    return {
      x: magnitude * Math.cos(angle),
      y: magnitude * Math.sin(angle)
    };

```

Called for each ball at start time, introduce a numeric error. So you must calculate the total velocity before starting simulation and compare with that instead of 30.

Second your

```
function checkCollisions()

```

called each frame introduce some other numeric errors () for each collision, sum it all and you get the difference you see.

Assuming all masses are equal. Try to calculate the starting total velocity SV, then calculate the mean total velocity over N frames and compare that with SV.

Regarding

> However, interesting things happen when the balls vary in size. If the minRadius is changed to 5 and maxRadius to 15, for example, you'll notice that the total speed of the system starts climbing over time. The bigger the difference, the faster the speed grows out of control.

may be there's an error here:

```
    ballOne.velocity.x = ballOne.velocity.x + (scalarOne * direction.x);
    ballOne.velocity.y = ballOne.velocity.y + (scalarTwo * direction.y);
    ballTwo.velocity.x = ballTwo.velocity.x - (scalarOne * direction.x);
    ballTwo.velocity.y = ballTwo.velocity.y - (scalarTwo * direction.y);

```

should be : (forked here)

```
    ballOne.velocity.x = ballOne.velocity.x + (scalarOne * direction.x);
    ballOne.velocity.y = ballOne.velocity.y + (scalarOne * direction.y);
    ballTwo.velocity.x = ballTwo.velocity.x - (scalarTwo * direction.x);
    ballTwo.velocity.y = ballTwo.velocity.y - (scalarTwo * direction.y);

```

Finaly: with different ball masses comparing the total speed is inappropriate. You must compare the total momentum mass\*velocity

---
Tags: physics, javascript, vector, html-canvas, floating-point
---


# Question
Title: Java, spawn algorithm that gets harder each level
I am currently in the process of making my 3rd Java game (everything I have learned is from YouTube videos, so I may be doing some things wrong) named "Blocked". But I have run into a problem: how do I make an algorithm that gets progressively harder each "level". but first let me briefly explain the game, so you are a small human and blocks are falling from the sky, and you try to avoid them, there are 5 types of blocks: Basic, fast, shop, killer, safe. So I want my game to start with very few (basic only) tiles to fall, while the game is going (infinitely) I want it to get harder but not just unlocking new blocks, but also changing the frequency the more difficult blocks spawn (up to a certain threshold of course).

P.s. pseudo code is fine by me. P.s. (2) if you need any clarifications ask me!

# Answer
A first aproach could be giving a varying weight to each type of block, modifying such weight each level, decressing the probability of spawning an easy blocks and increasing the probability to spawn a harder ones.

I'm also going to suppose you have some kind of a parent Block class and different child classes for each type of block.

```
public Block createBlock(int level) {
    double wBasic = 1.0/(1*level);
    double wFast = 0.5*level;
    double wShop = 0.1*level;
    double wKiller = 0.05*level;
    double wSafe = 1.0/(2*level);

    double psum = wBasic + wFast + wShop + wKiller + wSafe;

    double wBasicNorm = wBasic / psum;
    double wFastNorm = wFast / psum;
    double wShopNorm = wShop / psum;
    double wKillerNorm = wKiller / psum;
    double wSafeNorm = wSafe / psum;

    double rangeBasic = wBasicNorm;
    double rangeFast = rangeBasic + wFastNorm;
    double rangeShop = rangeFast + wShopNorm;
    double rangeKiller = rangeShop + wKillerNorm;

    Random rgen = new Random();
    double r = rgen.nextDouble();

    if (r < rangeBasic) {
        return new BasicBlock();
    } else if (r < rangeFast ) {
        return new FastBlock();
    } else if (r < rangeShop) {
        return new ShopBlock();
    } else if (r < rangeKiller) {
        return new KillerBlock();
    } else {
        return new SafeBlock();
    }
}

```

With this we'll create a different probability for each block to spawn, and then normalize that probability giving it a value between 0 and 1 (wich is the range of the numbers returned by the random number generator).

Then we want to know the different "ranges" of probability of each block.The random number generated will fall in one of those ranges, and this is what will set the type of block created. This can be seen as placing the probabilities of each block in a line like this:

```
     basic    fast        shop         killer       safe
0.0|-------|---------|------------|--------------|--------|1.0
                ^
                |
           random numer

```

PS: This is my first answer ever, hope it helps.
> 2 votes

# Answer
Let's assume you have `float gameTime;`

Let's also assume you spawn in the blocks completley randomly.

And finally let's assume you have some kind of update method which gets called every frame.

With the above assumptions you could probably write something like this

```
float gameTime = 0; //The total game time, in seconds.
float spawnTime = 0; //A counter to keep track of the next spawn

public void update(){
    gameTime += Time.deltaTime; //increment the gameTime by the game delta
    spawnTime += Time.deltaTime;

    //The game difficulty must have some kind of limit or it will no longer be fun
    //after you go over a certain time. With this example the spawn time will vary from
    //once per 1.6 seconds down to once every .16 seconds. You can obviously change the values
    //to make the game harder or easier
    float difficulty = 60f; // Higher is harder
    float minDifficulty = 10; //Low means the game can get harder
    float maxDifficulty = 100; //Higher means the game starts off easier
    float spawnLimit = clamp(maxDifficulty-gameTime, minDifficulty, maxDifficulty) / difficulty;

    if(spawnTime > spawnLimit){
        spawnBlock();
        spawnTime = 0;
    }

}

public void spawnBlock(){
   //...code for spawning certain blocks based on how much time has passed ...//
}

```
> 0 votes

---
Tags: java, algorithm
---


# Question
Title: LibGDX game crash without errors (maybe AssetManager)
i have a problem with my game. It's a endless run shooter/platform made with LibGDX (Scene2d and box2D).

I do tests with LG G2, LG G3, Galaxy s4, desktop and android emulator and i have no one problem, but when i try to start my game on Galaxy s3 i have a very strange problem. The game crashes with no error in android and no error in android studio, simply crashes... i think its very strange because i'm developing it since a year and i always got wich error makes it crashes.

I think it's AssetManager fault because crashes often happens during loading or just finished loading (sometimes after 20-30 seconds of playing), so i tried to load less stuff and its work. I added one piece per time and at a certain point i always got a crash. In total my assets are 11mb... not so much i think. The biggest asset is the background, 2 pieces 1920\*1080, near 2\*70kb (yes, 70kb)...

i have in Android Studio monitor, cpu use 10~20% kernel and 10~20%user and 10~12mb memory

Here it is where the crash happens, i hope to solve soon... Thanks guys!

```
   public class ScreenSwitcher extends Game {
   private static ScreenSwitcher instance = null;

   public static AssetManager manager  = new AssetManager();

   private ScreenSwitcher(){
   }

@Override
   public void create () {
        loadTitle();
   }

   public static ScreenSwitcher getInstance(){
      if(istanza==null)
         istanza = new ScreenSwitcher();

      return istanza;
   }

   public void loadTitle(){
      manager.load("atlas/splash.png", Texture.class);
      manager.load("atlas/mainTitle.atlas", TextureAtlas.class);
      manager.load("atlas/shop.atlas", TextureAtlas.class);
      manager.load("atlas/loading.atlas", TextureAtlas.class);
      manager.load("atlas/duro.atlas", TextureAtlas.class);
      manager.load("atlas/sfondo.atlas", TextureAtlas.class);
      manager.load("atlas/nuovoRoy.atlas", TextureAtlas.class);
      manager.load("atlas/altro.atlas", TextureAtlas.class);
      manager.load("atlas/shipFlag.atlas", TextureAtlas.class);
      manager.load("atlas/collezionabili.atlas", TextureAtlas.class);
      manager.load("atlas/lucertole.atlas", TextureAtlas.class);
      manager.load("atlas/lumaca.atlas", TextureAtlas.class);
      manager.load("atlas/terreni.atlas", TextureAtlas.class);
      manager.load("atlas/decorazione.atlas", TextureAtlas.class);
      manager.load("atlas/piatte.atlas", TextureAtlas.class);
      manager.load("atlas/nuvolette.atlas", TextureAtlas.class);
      manager.load("atlas/pezzi.atlas", TextureAtlas.class);
      manager.load("atlas/pulsanti.atlas", TextureAtlas.class);
      manager.load("atlas/ragnetto.atlas", TextureAtlas.class);
      manager.load("atlas/scatole.atlas", TextureAtlas.class);
      manager.load("atlas/volante.atlas", TextureAtlas.class);
      manager.load("atlas/volanteBonus.atlas", TextureAtlas.class);
      manager.load("atlas/volantePorta.atlas", TextureAtlas.class);
      manager.load("atlas/trappole.atlas", TextureAtlas.class);
      manager.load("atlas/esplosione.atlas", TextureAtlas.class);
      manager.load("atlas/jumpfall.atlas", TextureAtlas.class);
      manager.finishLoading();

      setScreen(new GameScreen());
   }

```

# Answer
When you use the **Assetmanager** , you should dispose the loaded **textures** after the use. This can be done by implementing the **Disposable** and **AssetErrorListener** interfaces .This way you get the method called `dispose()` to dispose the **Assetmanager**. Here is a quick example:

```
 public class gh implements Disposable,AssetErrorListener {

@Override
public void error(AssetDescriptor asset, Throwable throwable) {
    // TODO Auto-generated method stub

}

@Override
public void dispose() {

  //so you can release the AssetManager
    AssetManager.dispose;
    // TODO Auto-generated method stub

}

   }

```
> 1 votes

# Answer
In my experience, Box2D is a little fussy about dealing with things such as line lengths that are shorter than a hard-coded lower limit. I don't recall the lower limits, but you can find the checks in the Box2D source. Box2D will throw an exception which is unable to cross the JNI boundary and brings the whole process down with no explanation. Maybe add some of your own checks at points where you make calls to Box2D to make sure data is within the limits it will accept?
> 0 votes

---
Tags: libgdx, box2d, scene2d
---


# Question
Title: Make object follow mouse cursor in unity
I was watching a tutorial on how to move objects on mouse movement. https://youtu.be/7OJQ6MbHuvQ

this is the link to that tutorial and below is the error I got while scripting. Please watch the whole tutorial to understand.

# Answer
This is the signature of the function you're trying to use

```
Vector3.Project(Vector3 vector, Vector3 onNormal)

```

you're passing it only 1 parameter. And this is the first problem. The latter is that a `Vector3` does not contain a `Camera` property.
> 2 votes

---
Tags: unity, movement, mouse
---


# Question
Title: How do I reference one game object in a script attached to another?
This is all in Unity, with C#.

I have attached a script to my player that should destroy a `TreeGroup` (as in a forest) whenever I press 'Q' and instantiate one when I press 'E'.

Here is the code:

```
using UnityEngine;
using System.Collections;

public class DisableTrees : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

        if (Input.GetKeyDown (KeyCode.A)) {
            //Disable Trees on A Keypress

            Debug.Log("Trees Disabled!");
        }

        if (Input.GetKeyDown (KeyCode.E)) {
            //Enable Trees on E Keypress

            Debug.Log("Trees Enabled!");
        }

    }
}

```

How do I access and find my 'TreeGroup' object group while script not being attached to 'TreeGroup' but my character instead and then Destroy on Q Keypress? And how do I Instantiate it?

# Answer
> 2 votes
You have several options:

* Create a variable `public GameObject TreeGroup` in your DisableTrees behavior. The variable will now appear as a field in the inspector of DisableTrees. You can then drag the TreeGroup game object to it.
* Use `GameObject.Find` to find the tree group by its name. But keep in mind that this method is very slow on larger scene graphs.
* Add an unique tag to the tree group and use `GameObject.FindWithTag`
* When the TreeGroup is a child or parent of the GameObject from where you need it and the TreeGroup has some unique component, you can use `GetComponentInParent` / `GetComponentInChildren` and use the returned component to navigate to its GameObject.

# Answer
> 0 votes
You can tag the tree in your group and then use FindGameObjectWithTag to get a list of all them. Next iterate over the list and destroy the game objects.

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


# Question
Title: In Unity, Meta Files are Tracked but Behaviours Fall Off
My team is working on a Unity game, and we are using a mercurial repository on BitBucket. Whenever we update, all of the behaviours 'fall off' of state machines, behaviours, etc. When searching for a solution, I discovered that this information was stored in the meta files. I had previously ignored the meta files, but the are now being tracked. However, the files still 'fall off'. I cannot find any other reason this would be happening.

Any assistance you can give me would be appriciated. Let me know if you need any additional details.

# Answer
In Unity editor navigate to Edit -\> Project Settings -\> Editor, and:

1. Set Version Control to "Show meta files"
2. Set Assert Serialization to "Force Text"

Also update the .gitIngore File to something like this:

```
Library
Temp
*.sln
*.csproj
*.pidb
*.userprefs
*.unityproj
# Xcode
.DS_Store
*/build/*
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
profile
*.moved-aside
DerivedData
.idea/
*.hmap
*.xcscheme
xcuserdata/*

# eclipse specific git ignore
*.pydevproject
.project
.metadata
bin/**
tmp/**
tmp/**/*
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/
.loadpath

```
> 2 votes

# Answer
Maybe I know whats is happening :), as you can read in the unity documentation:

http://docs.unity3d.com/Manual/ExternalVersionControlSystemSupport.html

When you use version control Unity has problems to manage the Library folder and you have to delete it manually. So the process is the following

1. Close Unity
2. Make a pull of the repository
3. Go to the folder where you have the unity project and delete the Library folder, that has to be in the same place that assets (this has to be done outside the engine obviously).
4. Open unity and develop your pretty game.

This procedure should fix you problem.

Cheers!
> 0 votes

---
Tags: unity, version-control
---


# Question
Title: How to create a color aura around actors in libGDX?
Is there an easy mechanism to create a color aura around an actor in libGDX?

Thanks for all tips!

# Answer
There may be a better/more efficient way to do it, but an easy way would be to draw a tinted, mostly transparent circle on top of an actor. (Or beneath the actor if you don't want the actor itself tinted.)

If you have a white circle texture and want a red aura, then the draw code would look like this

```
Color oldColor = batch.getColor();
batch.setColor(1,0,0,.2f);
batch.draw(circleTexture,x,y,width,height);
batch.setColor(oldColor);

```
> 0 votes

---
Tags: libgdx
---


# Question
Title: Just how expensive is it to bind textures in OpenGL? (LibGDX)
I'm using LibGDX on top of OpenGL and currently my game engine does something along the lines of the following per frame

1. Bind a terrain texture sprite atlas and a set of transparency masks in another texture atlas
2. Render terrain tiles using the 2 bound textures to a FBO
3. Bind a character and item texture sprite atlas
4. Render characters over the terrain to the same FBO
5. Bind the same transparency mask atlas and a normal map texture for the terrain
6. Draw the same terrain tiles' normal map version to a different FBO
7. Bind the character and item normal map texture atlas
8. Render character normal maps over the terrain normal map FBO
9. Bind this normal map FBO as a texture
10. Render lighting information to a different FBO using the normal map texture information
11. Bind the diffuse and lighting FBOs as textures
12. Use these to render the combined final image to the main display

So in summary, each frame I'm binding a total of 9 different textures, one or two at a time.

Should I look into changing my code so all 9 textures are always bound, and the correct one is referenced at the right time? Or is this a reasonable amount of texture binds per frame that isn't going to impact overall performance to a noticable effect? Assume I'm aiming for 60fps and there's a fair amount of other calculations going on per frame.

# Answer
From my experience, it's not expensive to bind textures. I have a program that binds about 30 textures per frame and it runs pretty smooth. Since you're using only 9 textures and VBOs on top of that, I imagine your game actually runs very well.
> 1 votes

---
Tags: opengl, java, libgdx
---


title: Making an object hang

text:
# Question
Title: Making an object hang
This image is pretty self explanatory I hope:

How can I achieve this effect without animating it? I want to avoid animations as there are many objects hanging and I dont want them to move the exact same way.

# Answer
> 2 votes
What you are looking for is a `HingeJoint`.

Note that when you want it to start swinging, you need to give it a little push in form of a small impulse (like with AddForce on Start, for example).

# Answer
> 0 votes
I don't know if this idea will work for you, but could you use a single animation and randomly offset starting point of it for each handle? They won't sync up because they are all randomly offset. Of course, if you want them to swing to the train movement, this may not look so good.

---
Tags: unity
---


# Question
Title: Rendering issues in Monogame when using shaders
I am currently fiddling with Monogame, trying to work with Shaders and I have encountered a really weird issue. If the first ever draw in the application's lifetime is with a custom shader all further draws without a custom shader get this red tint (as if blue and green channels were set to 0):

(A is the correct one, the sprite is white and black)

The following code produced these:

```
spriteBatch.Begin(); // Use this for A
//spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, Gfx.MyShader); // Use this for B
spriteBatch.Draw(Gfx.PlayerStand2, new Vector2(10, 10));
spriteBatch.End();
spriteBatch.Begin();
spriteBatch.Draw(Gfx.PlayerStand2, new Vector2(50, 50));
spriteBatch.End();
spriteBatch.Begin();
spriteBatch.Draw(Gfx.PlayerStand2, new Vector2(80, 80));
spriteBatch.End();

```

And this is the shader:

```
sampler TextureSampler : register(s0);

float4 PixelShaderFunction(float2 texCoord : TEXCOORD0) : COLOR0
{
    return tex2D(TextureSampler, texCoord);
}

technique Shader1
{
    pass Pass1
    {
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```

---

It all depends on the first draw - if I replace the first two lines with this:

```
counter++; // Starts at 0
if (counter == 1){ // Run only on the first draw
    spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, Gfx.GaussianBlur);
} else {
    spriteBatch.Begin();
}

```

They all become red. If I replace `==` with `!=` they all display correctly.

I am using OpenGL for rendering. I am aware I could circumvent this problem by always using a custom shader but I fear that this is but a symptom of a greater issue that will come later to bite my bottom. Or hopefully something completely trivial that I missed.

**Update:** I tried to reproduce it in DirectX version and in this case the batch with the shader does not render, but the other sprites are not red. I also tried to compile the files via Monogame Pipeline with the same effect.

# Answer
I accidentally stumbled upon a template for the shaders in Monogame installation directory and replaced the shader with this one:

```
#define SV_POSITION POSITION
#define VS_SHADERMODEL vs_3_0
#define PS_SHADERMODEL ps_4_0_level_9_1

Texture2D SpriteTexture;

sampler2D SpriteTextureSampler = sampler_state
{
    Texture = <SpriteTexture>;
};

struct VertexShaderOutput
{
    float4 Position : SV_POSITION;
    float4 Color : COLOR0;
    float2 TextureCoordinates : TEXCOORD0;
};

float4 MainPS(VertexShaderOutput input) : COLOR
{
    return tex2D(SpriteTextureSampler,input.TextureCoordinates) * input.Color;
}

technique SpriteDrawing
{
    pass P0
    {
        PixelShader = compile PS_SHADERMODEL MainPS();
    }
};

```

And it solved the issue! It works fine both in OpenGL and in DirectX. My best bet is that the shader was invalid which is why it did not work at all in DirectX and partially in OpenGL - it might've done some kind of memory corruption which affected the default shader used by Monogame (did I accidentally do a buffer overflow attack on my GPU?).

I haven't bothered to inspect exactly how much I'd need to change the working shader to reproduce the issue so I don't know where specifically the problem was.
> 1 votes

---
Tags: opengl, shaders, monogame
---


# Question
Title: Screen tearing in fragment shader on R9 380 GPUs
two players are encountering an issue with my game where the screen is tearing when it uses a fragment shader but it only seems to be doing this for players with a R9 380 GPU. Here is what it looks like in game:

After working with one of the players I narrowed it down to using the shader but it could be something not being done properly in the calling code. Here is what the shader looks like (note I'm still learning GLSL).

```
uniform sampler2D lightTexture;
uniform sampler2D targetTexture;
uniform sampler2D backgroundTexture;
uniform vec2 tileSize;

vec3 SaturationBrightness(vec3 color, float brt, float sat)
{
    // Increase or decrease theese values to adjust r, g and b color channels seperately
    const float AvgLumR = 0.5;
    const float AvgLumG = 0.5;
    const float AvgLumB = 0.5;

    const vec3 LumCoeff = vec3(0.2125, 0.7154, 0.0721);

    vec3 AvgLumin = vec3(AvgLumR, AvgLumG, AvgLumB);
    vec3 brtColor = color * brt;
    vec3 intensity = vec3(dot(brtColor, LumCoeff));
    vec3 satColor = mix(intensity, brtColor, sat);
    return satColor;
}

void main(void)
{
    vec2 position;
    position.s = gl_TexCoord[0].s;
    position.t = gl_TexCoord[0].t;
    vec4 lightColor = texture2D(lightTexture, position);

    //Return the lighting if the light is pure dark since the tile behind it was not rendered
    if (lightColor.r == 0.0 && lightColor.g == 0.0 && lightColor.b == 0.0) {
        gl_FragColor = lightColor;
        return;
    }

    //Get the average of the the nearby light
    position.t -= tileSize.t;
    vec4 lightColorUp = texture2D(lightTexture, position);
    position.t += tileSize.t*2.0;
    vec4 lightColorDown = texture2D(lightTexture, position);
    position -= tileSize;
    vec4 lightColorLeft = texture2D(lightTexture, position);
    position.s += tileSize.s*2.0;
    vec4 lightColorRight = texture2D(lightTexture, position);
    position.s += tileSize.s;
    vec4 lightColorFarRight = texture2D(lightTexture, position);
    position.s -= tileSize.s*4.0;
    vec4 lightColorFarLeft = texture2D(lightTexture, position);
    position.s += tileSize.s*2.0;
    position.t -= tileSize.t*2.0;
    vec4 lightColorFarUp = texture2D(lightTexture, position);
    position.t += tileSize.t*4.0;
    vec4 lightColorFarDown = texture2D(lightTexture, position);
    lightColor = lightColorRight + lightColorUp + lightColorDown + lightColorLeft + lightColorFarRight + lightColorFarUp + lightColorFarDown + lightColorFarLeft;
    lightColor.r /= 8.0;
    lightColor.g /= 8.0;
    lightColor.b /= 8.0;
    lightColor.a /= 8.0;

    //Get the target (foreground) that we apply the light to
    vec4 targetColor = texture2D(targetTexture, gl_TexCoord[0].st);
    if (targetColor.a == 0.0) {
        //Foreground is transparent meaning that we never rendered to it so instead render the background without light
        gl_FragColor = texture2D(backgroundTexture, gl_TexCoord[0].st);
    } else {
        //Apply averaged light to target
        gl_FragColor = vec4(SaturationBrightness(lightColor.rgb, 1.15, 1.1), lightColor.a) * targetColor;
    }
}

```

Here is the backend code (c++) using SFML.

```
SpecialRenderTexturePtr targetTexture = boost::static_pointer_cast<SpecialRenderTexture>(target);
targetTexture->display();

m_texture->setView(m_view);
m_texture->clear(Color(0, 0, 0, 255));
m_texture->draw(m_vertices);
m_texture->display();

m_shader.setParameter("lightTexture", m_texture->getTexture());
m_shader.setParameter("targetTexture", targetTexture->getTexture());
m_shader.setParameter("backgroundTexture", m_render->getBackgroundTexture()->getTexture());
Vector tileSize(Sizes::SUBTILE / 2.0 / m_texture->getSize().x, Sizes::SUBTILE / 2.0 / m_texture->getSize().y);
m_shader.setParameter("tileSize", tileSize.toSfml());
sf::Sprite lightSprite(m_texture->getTexture());
Vector viewPosition = m_view.getCenter();
const Vector& viewSize = m_view.getSize();
viewPosition.x = ceil(viewPosition.x - (viewSize.x / 2.0f));
viewPosition.y = ceil(viewPosition.y - (viewSize.y / 2.0f));
lightSprite.setPosition(viewPosition.toSfml());

target->draw(lightSprite, &m_shader);

```

Is there anything obvious here that I'm missing that I shouldn't be doing. Anyone know of any issues with R9 380 drivers? Looking at the tearing from what I'd guess is that we're sampling from the target texture incorrectly but I don't see how or why.

# Answer
> 7 votes
I came back to this today and after some more investigation and trial and error I discovered that the culprit was targetTexture. With some more investigation I learned that reading and writing to the same texture in a shader is bad practice (not surprisingly) and will cause undefined behavior on GPUs.

The solution was to copy the target texture to a new texture and then read from the copy while still writing to the original target texture.

---
Tags: c++, 2d, glsl, sfml
---


# Question
Title: Scaling a single scalar using OrthographicCamera
I'm trying to convert a length (well, a radius) from world coordinates to screen coordinates using an OrthographicCamera. However, the only method I've figured out so far is to do a projection, with some basic vector math before/after, but this seems...expensive.

Here's what I have so far (apologies, written in Kotlin):

```
val cam: OrthographicCamera = ...
val behavior: SteeringBehavior<Vector2> = ...

// calculating the center of the circle
val coords = Vector3()
val wander = behavior as Wander<Vector2> // defined elsewhere above
coords.set(wander.wanderCenter, 0F)
cam.project(coords) // coords now has wanderCenter in screen coordinates

// now, the part I'm interested in, calculating the radius
val radiusCoords = Vector3(wander.wanderCenter, 0F).add(wander.wanderRadius, 0F, 0F)
cam.project(radiusCoords)
radiusCoords.sub(coords)
val radius = radiusCoords.x // this is the value I want

```

The first half of the code snippet is fine, and provided for context. But the second half...I'm basically taking a scalar and plugging it through a Vector3 and a series of Complicated Matrix Math to convert it to another larger scalar. Is there an easier way to do what I'm doing? I've looked around a bit -- like at OrthographicCamera's `combined.getScaleX()` field, but it doesn't seem to have the value I need.

# Answer
> 0 votes
Turns out this was pretty easy. You know the width of the screen, you know the width (and zoom) of the camera's viewport...just math it up:

```
fun Float.metersToPixels(cam: OrthographicCamera): Float {
    return this * cam.scale
}
fun Float.pixelsToMeters(cam: OrthographicCamera): Float {
    return this / cam.scale
}
val OrthographicCamera.scale: Float
    get() = Gdx.graphics.width / viewportWidth / zoom

```

---
Tags: libgdx
---


# Question
Title: In Unity, How to format Old RPCs into new "PunRPCs"
In older unity versions you could simply used RPC. With newer verisons of Unity my code now doesn't work and it says that it needs to be transformed into "PunRPC" , Pun being "Photon Unity Networking." I am not sure how to reformat it to work with current unity versions. Can anyone shed light on this?

My Code

FXManager.cs

```
1 using UnityEngine;
2 using System.Collections;
3
4 public class FXManager : MonoBehaviour {
5
6   [RPC]
7   void SniperBulletFX( Vector3 startPos, Vector3 endPos ) {
8       Debug.Log ("SniperBulletFX");
9
10  }
11}

```

PlayerShooting.cs

```
1 using UnityEngine;
2    using System.Collections;
3
4    public class PlayerShooting : MonoBehaviour {
5
6   public float fireRate = 0.5f;
7   float cooldown = 0;
8   public float damage = 25f;
9   FXManager fxManager;
10
11  void Start() {
12      fxManager = GameObject.FindObjectOfType<FXManager>();
13
14      if(fxManager == null) {
15          Debug.LogError("Couldn't find a FXManger.");
16      }
17  }
18
19
20  // Update is called once per frame
21  void Update () {
22      cooldown -= Time.deltaTime;
23
24      if (Input.GetButton ("Fire1")) {
25          //Player wants to shoot...so. Shoot.
26          Fire ();
27      }
28  }
29
30  void Fire() {
31
32      if (cooldown > 0) {
33          return;
34      }
35
36      Debug.Log ("Firing our gun");
37
38      Ray ray = new Ray (Camera.main.transform.position, Camera.main.transform.forward);
39      Transform hitTransform;
40      Vector3 hitPoint;
41
42      hitTransform = FindClosestHitObject (ray, out hitPoint);
43
44      if (hitTransform != null) {
45          Debug.Log ("We hit:" + hitTransform.name);
46
47          // We could do a special effect at the hit location
48          // DoRicochetEffectAt (hitPoint);
49
50          Health h = hitTransform.GetComponent<Health> ();
51
52          while (h == null && hitTransform.parent) {
53              hitTransform = hitTransform.parent;
54              h = hitTransform.GetComponent<Health> ();
55          }
56
57          // Once we reach here, hitTransform may not be the hitTransform we started with!
58
59          if (h != null) {
60              // This next line is the equivalent of calling;
61              //                  h.takeDamage( damage);
62              //Except more "networky"
63              PhotonView pv = h.GetComponent<PhotonView> ();
64              if (pv == null) {
65                  Debug.LogError ("Freak out!");
66              } else {
67                  h.GetComponent<PhotonView> ().RPC ("TakeDamage", PhotonTargets.AllBuffered, damage);
68              }
69          }
70
71          if (fxManager != null) {
72              fxManager.GetComponent<PhotonView>().RPC ("SniperBulletFx", PhotonTargets.All, Camera.main.transform.position, hitPoint);
73          }
74      }
75      else {
76          // We didn't hit anything (except empty space), but let's do a visual FX anyway
77          if (fxManager != null) {
78              hitPoint = Camera.main.transform.position + (Camera.main.transform.forward*100f);
79              fxManager.GetComponent<PhotonView>().RPC ("SniperBulletFx", PhotonTargets.All, Camera.main.transform.position, hitPoint);
80          }
81      }
82
83      cooldown = fireRate;
84  }

```

If anymore information is needed, please let me know, I would love to figure out how the new "PunRPC(Photon Unity Neworking)" works so I can use it in future projects.

Edit: This is the error I get "PhotonView with ID 2 has no method "SniperBulletFx" marked with the PunRPC or @PunRPC(JS) property! Args: Vector3, Vector3 UnityEngine.Debug:LogError(Object)"

# Answer
> -2 votes
You just change `[PUN]` to `[PunRPC]`.

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


title: Filling in 3d Shapes

text:
# Question
Title: Filling in 3d Shapes
For a college project I need to draw an empty cube and then show the cube being filled.

So far I have heard that JME and voxels is the way to go but I have no idea where to start. Can anyone point me towards a tutorial or any reading?

My project is in Java but any pseudo-code is welcome.

# Answer
> 1 votes
There was a Wolfire Games Blog entry about voxelization of one of their complex rabbit meshes, you can findt it here.

I think it'll give you some insights on how can be the voxelization process performed.

# Answer
> 0 votes
From what I've read so far, I think these jMonkeyEngine would be a great candidate for this. If you want to jump right into it, LWJGL is also an excellent choice.

But for the idea itself, you will most likely have to use specific coordinates that will be looped through to be filled with the smaller cubes.

---
Tags: java
---


# Question
Title: Java multiple player objects/enemy objects?
NOTE: I'm a beginner and learning :D

Alright, so in my game I have a class for the player (with the parameters of x, y, color, width, height, and health, same parameters with the enemy). But I have a problem. So, in my player class, I have a draw method which sets the color and fills a rectangle with the variables specified in the parameters. In my main class, I create an instance of that player, and call the draw method from there, too. However, when I try to create more than 1 player object, it just renders the second one, rather than both, even if the x, y, color, and pretty much everything is different.

Basically, I can't draw more than 1 player to my screen. Same thing with the enemy.

# Answer
> 1 votes
This is most likely because to make more than one instance of this you will need an array of these objects. Usually there would only be one player and multiple enemies so the player would be a single object and the enemies an array. Here's do simple code to explain this:

```
Enemy[] enemies = new Enemies[10];
for (int i = 0; i < enemies.length; i++)
{
    enemies.render();
}
Player player = ...
player.render();

```

Or if you want multiple players the players variable would be an array as well.

---
Tags: java
---


# Question
Title: How do I change a value gradually over time?
I'm using Unity3D 5-point-something, and I'm planning on making a game where the player travels through a hot, dry desert, and so the heat causes the player's energy to deplete. The object of the game is to reach a certain point before the player's stamina runs out.

What I was planning on doing is having different landmarks in the game world that the player can visit, and these will help replenish their Health or Stamina.

# Answer
> 7 votes
Having a value deplete over time can be done a few different ways. The simplest is likely using the update method to deplete at a constant rate.

```
public float myValue = 10; // the total
public float subractPerSecond = 1; // remove this every second

public void Update() {
    //subtract at a constant rate
    myValue -= subtractPerSecond * Time.deltaTime;
}

```

But we can make it a bit more robust than that, to allow for change in either direction and to keep the value within specified bounds:

```
public float maxMyValue = 10;
public float minMyValue = 0;
public float myValue = 10; // the total
public float changePerSecond = -1; // modify the total, every second

public void Update()
{
    //modify at a constant rate, keep within bounds
    myValue = Mathf.Clamp(myValue + changePerSecond * Time.deltaTime, minMyValue, maxMyValue);
}

```

We can also calculate the rate automatically by telling the system how long you want it to last total.

```
public float maxMyValue = 10;
public float minMyValue = 0;
public float myValue = 10; // the total
float changePerSecond; // modify the total, every second
public float timeToChange = 15; // the total time myValue will take to go from max to min

public void Start()
{
    changePerSecond = (minMyValue - maxMyValue) / timeToChange;
}

public void Update()
{
    // modify at a constant rate, keep within bounds
    myValue = Mathf.Clamp(myValue + changePerSecond * Time.deltaTime, minMyValue, maxMyValue);
}

```

For your use case, you might also want to subtract based on movement.

```
public float maxMyValue = 10;
public float minMyValue = 0;
public float myValue = 10;
public float decreasePerUnit; //subtract this from the total, every unit moved
float lastXPosition; //keep the last X position to know how far we travel per frame

public void Start()
{
    lastXPosition = this.transform.position.x;
}

public void Update()
{
    //first find the distance we traveled on the X axis
    float thisXPosition = this.transform.position.x;
    float distanceTraveled = Mathf.Abs(thisXPosition - lastXPosition);
    lastXPosition = thisXPosition;

    //subtract distance traveled times the decrease per unit and keep the value >= 0
    myValue = Mathf.Clamp(myValue - (distanceTraveled * decreasePerUnit), minMyValue, maxMyValue);
}

```

When you get to the point where you want to refill, I'd just turn the above value to a positive value and slowly fill up. Or you can simply add a specific amount to the value.

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


title: SFML Increasing random falling meteors

text:
# Question
Title: SFML Increasing random falling meteors
Im working on a small project where i have to creat a 2d game using C++ and SFML (it wasn't my choice to use them) i did every thing like creating the ship ,shooting ,score counter ..etc i managed to make like 5 meteors falling in random direction and entering the screen again whenever they leave the window the only thing that confuses me is making the number of meteors increase during the gameplay ,any tip to help?

# Answer
> 1 votes
Instead of a static size `std::array`, which size can't be changed during the execution, you could use a `std::list`, this will allow you to change the amount of meteor arbitrarily.

And for the increased amount, you don't supply much information about how your code currently works, but...

If you use a fixed time step, you need to have a frame counter at some point where you decide to add a new meteor to the list.

```
// pseudo-code
int mMeteorAddIntervalFrame = 300; // frame
int mMeteorAddAccumulatorFrame = 0; // frame
std::list<sf::sprite> mMetorSprites;

void update():
  ++mMeteorAddAccumulatorFrame
  if mMeteorAddAccumulatorFrame >= mMeteorAddIntervalFrame:
    mMetorSprites.push_back(new sf::sprite) // and initialize the sprite
    mMeteorAddAccumulatorFrame = 0

```

If you use a variable time step, instead of a frame counter, you need a delta-time accumulator: if the time passed is above your desired threshold, add a new meteor to the list, and decrease the accumulator by the time desired:

```
// pseudo-code
double mMeteorAddIntervalMs = 3000; // ms
double mMeteorAddAccumulatorMs = 0; // ms
std::list<sf::sprite> mMetorSprites;

void update(double aDeltaTimeMs):
  mMeteorAddAccumulatorMs += aDeltaTimeMs
  if mMeteorAddAccumulatorMs >= mMeteorAddIntervalMs:
    mMetorSprites.push_back(new sf::sprite) // and initialize the sprite
    mMeteorAddAccumulatorMs -= mMeteorAddIntervalMs // this ensures that it's always
                                                    // approximately at the desired interval,
                                                    // without losing miliseconds here and
                                                    // there

```

# Answer
> 0 votes
You could create an empty array of circleshapes which is larger than 10 (size = max number of meteors on the screen, for example 25) and just fill its first 10 indexes, and then, as time passes, add more circleshapes to the array until the maximum size is reached.

You may want to keep a variable holding the actual size of the meteors array, but remember to increase it as you add more meteors.

---
Tags: sfml, random
---


# Question
Title: why isn't onTrigger invoking on collision with a trigger or a rigidbody?
```
void onTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("Pick Up"))
    {
        other.gameObject.SetActive(false);
        count = count + 1;
        setCountText ();
    }
}

```

This is the methodI want to invoke, on collision of a sphere with another cube. The cube is set as a trigger, and a rigidbody component is attached to both of the objects. Still, on collision, the method is not invoked. Is there anything else that may be done, for this method to execute?

# Answer
> 1 votes
`onTriggerEnter` has a typo, and it *should* be `OnTriggerEnter`.

`OnTriggerEnter` is invoked whenever there is a collision between a trigger and a rigid body. Thus, the `Collider` object will be referenced by the trigger, and hence, the defined action would be performed as of the function definition by the original question.

---
Tags: unity
---


# Question
Title: Move collider along with model with Mecanim jump animation
I've been creating an infinite runner game in Unity3D for a while and I got stuck in this point that whenever my character jumps using Mecanim system his model (mesh) goes to air but his attached collider does not.

For jumping I don't apply any force or somethings else. (He does not even have a rigid body component). The jumping process is only done by Mecanim animation jump.

Is there any way to make that collider to move along with the model?

Please note that since I've used character controller to controlling my character, I cannot use "Apply root motion".

# Answer
In animation mesh does not get animated, its the bones which animate and the mesh are deformed or placed according to the bones and skinning information. So the simplest way is to attach the collider to one of its root bone. By trial and error you will find out which bone suits best for your needs :)
> 1 votes

# Answer
Another option would be to use animation curves. You can learn more about them here, as I am not entirely familiar with them.
> 0 votes

---
Tags: collision-detection, unity, mecanim
---