title: Batching in Java (software rendering)

text:
# Question
Title: Batching in Java (software rendering)
I've watched some tutorials on java game development and when they start using spritesheets all they do is get a subimage out of the spritesheet and create a new BufferedImage out of that. Does java do some sort of batching behind the scene when drawing the images like some engines and libraries do? Is it even possible to batch in java, and if so how would I go about doing it?

# Answer
> 0 votes
You don't need to do batching in Java(but if you want to try it here is a link to a usefull link: https://www.youtube.com/watch?v=X6KjDwA7mZg), let me tel you why:

The idea of batching is to draw all models that have the same texture and other data, like vertex data, in batches so that you minimize the amount of binds and unbinds for said data as much as possible, when using APIs like OpenGL or DirectX. So instead of having to bind and unbind the texture add all the other data for every same model, we can simply draw all the models at once, binding and unbind only once the data needed.(IF you haven't understood click on the link above).

In Java this isn't need because your are not bind or unbinding anything. What you can do is, at the beginning of the program load all the sprites from spritesheets and then every time your render to the screen simply draw them using something like a JCanvas. Batching is all about minimizing the amount of bind and unbinds, as mentioned before, so since in Java you do need to bind anything to draw to the screen, batching is useless.

I know this might not have help you a lot do feel free to ask questions

---
Tags: java, spritebatch, software-rendering, batching
---


# Question
Title: How can I make only the hit brick disappear upon collision with the ball in breakout?
I want to make Breakout, but I am having problems destroying the bricks upon collision with the ball, all the bricks disappear upon collision, however, I only want the hit brick to disappear, how can I achieve that? (I am using allegro and C++) The Bricks class:-

```
class Bricks{
public:
int x;
int y;
bool isDestroyed;
ALLEGRO_BITMAP *brick;
}Brickss[40];

```

The draw function:-

```
void draw(){
al_draw_bitmap(background, 0, 0, 0);
al_draw_bitmap(paddle, paddleXPos, paddleYPos, 0);
al_draw_bitmap(ball, ballXPos, ballYPos, 0);
for (int drawBricks = 0; drawBricks < 8; drawBricks++){
    for (Brickss[drawBricks].x = 0; Brickss[drawBricks].x < 1000; Brickss[drawBricks].x += 120){
        Brickss[drawBricks].y = 0;

        if (Brickss[drawBricks].isDestroyed == false){
            al_draw_bitmap(Brickss[drawBricks].brick, Brickss[drawBricks].x, Brickss[drawBricks].y, 0);

        }
    }

    }

al_flip_display();

}

```

The main function:-

```
int main(){
//initialize all what we need in allegro and load all the pictures(background,ball,paddle,bricks)
init();
loadBitmaps();
while (!done){
    al_clear_to_color(al_map_rgb(255, 255, 0));

    ALLEGRO_EVENT ev;
    al_wait_for_event(eventqueue, &ev);
    al_start_timer(timer);
    //motion of the ball
    if (ev.type == ALLEGRO_EVENT_TIMER){
        moveBall();
    }
    //motion of the player
    if (ev.keyboard.keycode == ALLEGRO_KEY_LEFT){
        paddleXPos -= movePaddleX;
    }
    if (ev.keyboard.keycode == ALLEGRO_KEY_RIGHT){
        paddleXPos += movePaddleX;
    }
    //bounce back if the ball hits the paddle
    if (intersects(ball, paddle, ballXPos, ballYPos, paddleXPos, paddleYPos)){
        moveBallX *= -1;
        moveBallY *= -1;
    }
    for (int drawBricks = 0; drawBricks < 8; drawBricks++){
        for (Brickss[drawBricks].x = 0; Brickss[drawBricks].x < 1000; Brickss[drawBricks].x += 120){
            Brickss[drawBricks].y = 0;

            if (intersects(ball, Brickss[drawBricks].brick, ballXPos, ballYPos, Brickss[drawBricks].x, Brickss[drawBricks].y)){

                Brickss[drawBricks].isDestroyed = true;

            }
        }
    }
        //draw everything to the backbuffer
        al_set_target_backbuffer(display);
        draw();
    }
    al_flip_display();
    al_rest(10);

}

```

# Answer
The problem is with how you're using your Bricks class. You're using the same Bricks instance to draw multiple bricks (FYI- a more common convention would be for this class to have a singular name: Brick), so when one of those instances is hit, all of the locations that brick is drawn at disappears. Furthermore, the different instances of Bricks are actually all drawn at the same location\[s\] so when one gets hit, they're all destroyed.

Since your bricks are stationary, consider treating the x and y coordinates as read-only fields, this will prevent you from drawing the same brick in multiple locations.

```
class Brick
{
public:
    // Using getter functions prevents these fields from getting changed outside
    // this class.
    int GetX() { return x; }
    int GetY() { return y; }

    Brick(int x, int y)
    {
        this->x = x;
        this->y = y;
        isDestroyed = false;
        brick = NULL;
    }

    bool isDestroyed;
    ALLEGRO_BITMAP* brick;
private:
    int x, y;
};

```

When iterating through the bricks, you can just iterate through them. Don't try to change their coordinates like you're currently doing in order to draw them in more places. If you want more bricks, just create more Brick objects.

```
// Update
for (int i = 0; i < BRICK_COUNT; i++)
{
    if (intersects(ball, Brickss[i].brick, ballXPos, ballYPos, Brickss[i].GetX(), Brickss[i].GetY())
    {
        Brickss[i].isDestroyed = true;
    }
}

// Draw
for (int i = 0; i < BRICK_COUNT; i++)
{
    if (!Brickss[i].isDestroyed)
    {
        al_draw_bitmap(Brickss[i].brick, Brickss[i].GetX(), Brickss[i].GetY(), 0);
    }
}

```

**Edit:** To answer your additional question on how to actually initialize your Brick array. There's several ways you can do this in C++. You can search for some tutorials on arrays and pointers, these are not game programming specific concepts, but I'll give a brief overview of two options that will keep the coordinates as read-only.

*One*. You can set the positions manually when initializing your array.

```
Brick Bricks[] = { // This can be written after the class declaration as well.
    { 0, 0 }, // This syntax calls the Brick(int x, int y) constructor
    { BRICK_WIDTH, 0 },
    { 0, BRICK_HEIGHT },
    // ....
};

```

*Two*. Doing that isn't really the best design and makes it more difficult to do other things like loading the brick layout from a file or randomly generating it. So instead of a array of Brick, you could use an array of pointers to Brick (Brick\*). This way you can dynamically create the objects during the level initialization.

```
Brick* Bricks[BRICK_COUNT];
for (int i = 0; i < BRICK_COUNT; i++)
{
    // You can decide how you want to compute the coordinates.
    Bricks[i] = new Brick((i % BRICKS_PER_ROW) * BRICK_WIDTH, (i / BRICKS_PER_ROW) * BRICK_HEIGHT);
}

// Because these are now Brick*, you can use the -> operator instead of . to access fields:
Bricks[i]->GetX();

// Because you're allocating objects with the new command, remember to delete
// them when you're done with them.
for (int i = 0; i < BRICK_COUNT; i++)
{
    delete Bricks[i];
}

```
> 1 votes

---
Tags: c++
---


# Question
Title: FPS Crosshair, Should it be drawn on center of the screen or to the forward of bullet spawn point?
so my question is where to draw crosshair? I have some things in my mind like:

1): Draw it on the center of camera(which will stays on the center of screen always), but as my gun is little lower to the camera so my bullets will always hit little lower to the target, but at the same time every FPS draws crosshair on the center(correct me if I am wrong).

2): Draw it to the forward of bullet spawn point so bullets will always be on target. But this also has some issues, player can't just be standing freezed it will move a little so did the gun and in turn crosshair will also move, but I haven't seen any FPS with crosshair moving while player is standing to shoot or even walking plus this will also make the game tough or annoying.

3): Draw the crosshair little lower to the camera(camera.y - difference between camera.y and spawnPoint.y) so the crosshair and bullet spawn point are aligned, but won't it look little weird to have a crosshair little lower to the center of screen.

I had read Shooting the bullet out of the gun instead of the camera, yet keeping it accurate with respect to the reticle

What I get from this is that raycast from camera and fire the bullet in direction where the raycast hits, but the bullet will not be going out from the forward of spawn point and this will look bad. The guy explains something with the animation but I didn't get that point. In GTA V's FPS mode crosshair is being drawn in the center, hands and gun are little low from center so there is no way that gun will hit exactly at the center of crosshair but it does hit and we can see that bullet(not actually bullet, some kind of ray) is getting fired from muzzle of the gun, how do they do it? I am sure there is some kind of trick for that.

I don't know what to do or there are other ways of doing this, any help would be much much appreciated.

My question is similar to the given link but it don't have much information so I am not trying to be duplicate here I am just looking for some more information

Thanks for reading this

# Answer
There are many reasons a designer/programmer would want to draw the crosshair on the exact center of screen, or a little lower. A hybrid system may even be implemented, taking advantage of the properties of these two systems in a game fich of different weapons, vehicles, interactive spots, and so on.

Drawing the crosshair centered or lowered can depend on some design choices:

* **Centered crosshair:** typical style, almost every old FPS game and most modern ones have a centered crosshair. This way the visual range is balanced both horizontally and vertically. This way, when shooting we know the bullet is moving where we are looking at, because its starting position is the same as the camera (our "eyes" in the 3D world). This is a typical choice, as it comes natural for a generic user to focus on the center of the screen when interacting with a computer, and video game players are no exception. Also, if your game has HUD elements on different sides or corners of the screen, having a centered crosshair will let the player keep them under control without extra efforts for their eyes.
* **Lowered crosshair:** drawing the crosshair slightly below to the center of the screen requires the programmer to mind that fired bullets aren't moving straight forward anymore respect to the camera orientation, instead their trajectory is sloped of a certain angle downwards. Having a crosshair below the screen center, means a player has to look a little up in order to still aim in front of him. Also, the visual range changes, as what lies above the horizon line gets actually prioritized than what lies below such line, like weapons, objects, or even your own legs. When it comes to user interface, if you designed the game to have HUD elements on the bottom only, they will be easier to read without losing focus on the crosshair.
* **Hybrid crosshair:** some weapons will sport a centered crosshair, others will have a lowered crosshair. An example is aiming with a rifle vs. aiming from a mounted machine gun. Your choice.

In the Halo series, Halo PC/CE has *always* a centered crosshair, whilst the other titles have a lowered crosshair for weapons, which smoothly moves to the center of the screen when interacting with vehicles or mounted turrets. You can see similar differences in other games, such as Doom 3, Team Fortress 2, Crysis 3, the Battlefield series, the Call of Duty series, and so on.

Here, in **(1)** there's the classic centered crosshair: when looking straight forward, the player's *pitch* angle (whether he's looking upwards/downwards) is equal to 0 degrees, as one would expect. Then, in **(2)** we have a lowered crosshair. Now, if the player wants to aim again in front of him, he has to look a little up just like in figure **(3)**.

But there's another more important reason this crosshair stuff is a thing, and it's related to the question you linked. One may ask:

> *How can I shoot bullets out from the camera, yet pretending they come from the gun barrel?*

The player shoots at what he's looking at. That's why most weapons spawn bullets at the camera position instead of the tip of the gun. Yet, we must pretend bullets are still fired from the weapon.

We can achieve this by using a lowered crosshair, in combination with good character animations. A generic FPS biped consists of a character and a weapon. Look at the following image (Halo helps again):

Red is camera, blue is weapon. In figure **(1)**, we have a centered crosshair and a horizontal rifle, so we should adjust weapon and arms orientation to reflect the direction of fired bullets. Alternatively, we can move the weapon closer to the head, simulating the act of aiming to reduce the distance between starting position of bullets and gun barrel.

On the other hand, in figure **(2)** the camera sports a lowered crosshair. The resulting effect is that the fired bullet will move so close to the gun barrel that they seem coming from there! We can do even better: draw the bullet only after it moves over the gun barrel, as the fire coming out from the gun will complete the whole effect. When doing this, it's good animating arms and head accordingly to the current direction the camera is looking at. Also, reducing the angle difference between bullets direction and weapon direction on the model, will give you a better result as the bullet is actually moving on a straight line trajectory. The closer the camera (the model head) to the weapon held, the better the final result.
> 7 votes

# Answer
Posting an answer to point out that there are other options.

In some games (though I can't think of specific titles right now) you may notice the crosshair is projected out from the weapon's line of fire, similar to a laser sight. This is highlighted when you walk up to a wall and the crosshair moves dramatically, because the weapon barrel is far closer to the wall and therefore the offset is more noticeable. I imagine most VR first-person games with crosshairs would use this effect, but some non-VR games do too. This technique would make the crosshair accurate because it's projected from the weapon.

I'm not sure if this technique is used in many games, but you could also have the weapon's firing angle adjust to the place that the crosshair is aiming - Project the crosshair straight out from the camera, and then adjust the weapon's displayed angle and aiming direction to point at the place the crosshair has 'hit'. This would mean that the crosshair becomes accurate by virtue of it being the target point for the weapon. You may want to have some boundaries for the weapon's angle though, so it doesn't angle itself so
> 1 votes

---
Tags: first-person-shooter, ui-design
---


# Question
Title: Bullet Physics Applying Torques Effects not noticeable
I am applying torques to a rag doll in order to make it move/walk.

For some reason, I am unable to view any effects when I use a call to rigidbody to apply torques even though these torques are pretty large i.e in the hundreds of Nm.

When I start the simulation, the doll just falls and the torques don't seem to have any effect. When I apply torque impulses however, there is a huge effect and the rag doll blows up because the angular velocity component becomes large that my velocity damping factor multiplies it and the torque impulse becomes huge.

I seem to notice effects of the torque though when I pause the simulation and then resume it after some time.

Am I missing something when I am trying to applying torques? I know that when applying torque, it accumulates the torque value rather than updating the angular velocity directly.

I'm applying torques at every internal tick callback.

I'd be happy to supply necessary code.

Thank you all.

# Answer
> -1 votes
The way I solved this was to apply the torques during the pre-tick callback for bullet physics.

---
Tags: physics, bullet-physics, torque
---


# Question
Title: Is it possible to design a multiplayer game which can be played from different devices?
I want to design a online multiplayer game for all gaming devices e.g. Desktop PC, Internet browser, Android phones, Android tablets, iPhone, iPad, XBOX 360 etc. Now my main requirement is that, I want all devices can be used to play the game in multiplayer mode together i.e. One player can be connected using PC another using Android phone and other may be with iPhone or iPad.

My doubts are:

1. How to make all devices to connect to common game server?
2. What will be the logic for graphics and texture because all devices screen will be of different aspect ratio?

# Answer
Short answer: Yes.

Long answer: You almost certainly aren't ready for that, and a sole developer would be folly to undertake such an enormous project anyway.

Connecting to a common server is not too big of an issue. All the devices you mention communicate with common servers on a regular basis (via HTTP anyway). The server doesn't have to know anything about what OS the client is running. Network communication is, for the most part, device agnostic. Once you have electricity on the wire, it doesn't matter who sent it or what's on the other end.

About your doubt with the "logic for graphics and texture", if you think that the aspect ratio is your primary concern, you are woefully misinformed and likely don't understand the technology. The devices you listed do not have common graphics hardware nor do they even use a common coding language. Some can run many, some can run only one. That being said, it would be possible to have them all run something that appears to look the same. However, you'd have to maintain multiple code bases to support just the hardware you mentioned, not including the "etc.".

Just based on your question, you seem to be a very new developer. I think your ambition is great, but you may want to start smaller. See what actually goes into the development of a game for one platform. Then decide if you actually want to expand that to multiple devices.
> 18 votes

# Answer
Is it possible? Yes. Is it a good idea? No, for various reasons that involve trying to balance the game for the many different input devices.

As for the difficulties in actual development, most modern game engines are purpose built to be able to port the same game to PC, xbox, playstation, mobile devices, and macs without too much trouble aside from controls and optimization.
> 0 votes

# Answer
Is it possible? Yes, but it will be very difficult, from a programming standpoint, as has already been addressed.

From a design standpoint, I cannot imagine a game that would be enjoyed by people on such varying devices. Most console and PC gamers play more action-y games than mobile games, and if your game is a multiplayer action game console and PC gamers are at a *huge* advantage since they have greater input control. If it is a puzzle game, it probably will not be worth the time it takes to implement on consoles, since your largest demographic will be mobile. Party games, while usually a great genre for multiple devices, are usually played entirely on a console or entirely on mobile devices. Perhaps strategy or RPG games would be played by both platforms, but again, the input difference is important.

To summarize, make sure you consider who your actual audience *is* before you try to port the game to a new platform.
> 0 votes

# Answer
Of course you can but there are problems you wouldn't like to run through, different platforms has diferent architectures, different memory structure, different float point, different byte length, etc. So probably your code will not work as expected os simply, output different things in each platform.

If you are working in a "high precision math" (anything that's not super mario) game you probablly will end with a messy code that doesn't work more than where it was focused to, this is why MAC and PC players can't play together, because the float point and machine arch is not the same.

You would have to sanitize your code, design your architecture, test and debug for each platform, using a middle server is a must, you can't simply connect an UNIX an a Windows machine by UDP and hope it to work, unless you want to do the middle-ware part in the client (i think it's an error).

Anyways, xBox360 development is pretty straight forward, but PS3 had a weird-as-f\*** processor that did everything really hard, you would need to be an expert to know how your functions and networking will work in both, pc and there. I bet you aren't yet.

Building a game that runs in every device is not impossible tho, you can use Unity3D, UDK or other pre-build engines and just try to set up the whole thing, with documentation and try-catch you will make it work, but I wouldn't even think about building it from scratch or even release a quality product unless I had a team of developers, a good self with books about networking, archs, protocols, optimization, etc and an expert in each platform.
> 0 votes

---
Tags: game-design, multiplayer, browser-based-games, cross-platform, xbox360
---


# Question
Title: Can't add inspector variables to script?
So I just added this script to my project : https://www.assetstore.unity3d.com/en/#!/content/11278 Since this script only draws the lines on gizmos, I wanted to add a LineRenderer, so that I can draw the lines also in GameView. So I simply wrote :

`public LineRenderer lr;`

But this variable never appears in my inspector, can anybody explain me why this happens and how I could fix it?

# Answer
> 2 votes
The script BezierCurveEditor is overwriting the GUI Layout of the component because of this line right at the top of file : `[CustomEditor(typeof(BezierCurve))]`

Adding a line renderer prop to the OnEnable and OnInspectorGUI fixes the issue.

```
SerializedProperty colorProp;
    void OnEnable()
    {
    linerendereProp = serializedObject.FindProperty("lr");
}
public override void OnInspectorGUI()
    {
        serializedObject.Update();

        EditorGUILayout.PropertyField(linerendereProp);
}

```

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


title: Is this shader can exist in Unity?

text:
# Question
Title: Is this shader can exist in Unity?
'Front' and 'back' are all SpriteRenderer.

Do you have a Shader these things that will be present in the Unity?

# Answer
> 3 votes
You dont need a shader for this. Setting the Order in Layer of the Back sprite render toa higher value that the Order in Layer of the Fron sprite renderer makes sure that Back renders in front of Front in 2d space, regardless of the position in 3d space.

---
Tags: unity, shaders
---


# Question
Title: Unity c# - NullReferenceException: Object reference not set to an instance of an object
This is driving me crazy. I am new to C# and I always get this error when playing while it seems like a very simple code.

I get the error at this line NullReferenceException: Object reference not set to an instance of an object.

HealthText.text = health.ToString();

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

public class damageHandler : Photon.MonoBehaviour {
    public int health = 10;
    public Text HealthText;
    public Text nameText;

    void Start(){
    //  HealthText.text = health.ToString();
    //  nameText.text = PhotonNetwork.playerName;
    }

    void OnTriggerEnter2D(){
        TakeDamage();
    }

    public void TakeDamage(){
        health --;
        HealthText.text = health.ToString();
    }

    void Die() {
        Destroy(gameObject);
    }

    void Update(){
        if (health <= 0){
            Die();
        }
    }
}

```

# Answer
> 2 votes
This looks like you have forgotten to assign the HealthText variable in the editor (drag and drop the text component to your script).

Also, make sure to read the post linked by liggiorgio in his comment.

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


title: Adding network support

text:
# Question
Title: Adding network support
I am trying to implement a simple game "Bulls and cows" in c#. It is a final project of my university course about design patterns. The target of the game is simple - try to guess the opponent number.

http://github.com/snoward/BullsAndCows

I try to follow the MVC and dependency injection patterns. My problem is that I don't know what part of my program should be responsible for network connection. Is this a part of controller work?

I think that the best way is to create a new instance of network controller as server for my game. And then user choose UI to use (console or window). So, network controller must observe user's UI to update game model state.

# Answer
> 2 votes
In a classic MVC world, the networking is split into a controller and a view component.

Network **input** is a **controller**, because it processes commands which then result in changes to the model.

The network **output** is a **view**, because it translates the model changes which are happening in your game into a network protocol. This is not much different from translating the model changes into pixels or console text.

Both the network controller and the network view depend on the same network connection, which is a dependency you should inject when you instantiate them.

When you follow these patterns, then it becomes very easy to implement different kinds of multiplayer, because the controllers and views used by a remote player, a local player or an AI player can all interact with the game through the same interfaces.

---
Tags: c#, networking, design-patterns, mvc, dependency-injection
---


# Question
Title: How can I fix this code to spawn multiple types of enemies on the same point with the Corona SdDK?
I have this code to spawn a simple enemy outside the window:

```
local function spawnGrupo1()
  local color01 = display.newImage("assets/img/enemigos/blue.png")
  color01.x = 40
  color01.y = -50
  physics.addBody( color01,{density = 5.0, friction = 0.0, bounce = 0} )
end

timer.performWithDelay( 1000, spawnGrupo1, 0)

```

But I want to be able to spawn multiple enemies from that point, and I can't figure it out.

I tried this, but it doesn't work:

```
local function spawnGrupo1()
  local numero = math.random(1, 3)

  if numero == 1 then
    local color01 = display.newImage("assets/img/enemigos/blue.png")
  end
  if numero == 2 then
    local color01 = display.newImage("assets/img/enemigos/yellow.png")
  end
  if numero == 3 then
    local color01 = display.newImage("assets/img/enemigos/red.png")
  end
  color01.x = 40
  color01.y = -50
  physics.addBody( color01,{density = 5.0, friction = 0.0, bounce = 0} )
end

timer.performWithDelay( 1000, spawnGrupo1, 0)

```

How can I approach the problem?

# Answer
*I'm assuming you have issues with the scope of the variable since you simply say 'It doesn't work'.*

I'm not familiar with Lua, but I'd go with something like this:

```
local function spawnGrupo1()
  local numero = math.random(1, 3)
  local color01

  if numero == 1 then
    color01 = display.newImage("assets/img/enemigos/blue.png")
  end
  if numero == 2 then
    color01 = display.newImage("assets/img/enemigos/yellow.png")
  end
  if numero == 3 then
    color01 = display.newImage("assets/img/enemigos/red.png")
  end

  color01.x = 40
  color01.y = -50
  physics.addBody( color01,{density = 5.0, friction = 0.0, bounce = 0} )
end

timer.performWithDelay( 1000, spawnGrupo1, 0)

```

In your implementation, each `color01` is local the the `if` bloc. By declaring it outside of the `if` blocs like it's been done above, you make sure that it is the same variable that will be used in the `addBody` function call.

You can read a bit more about the concept of scope in lua here.
> 0 votes

---
Tags: lua, corona-sdk
---


title: Process of writing to the depth texture

text:
# Question
Title: Process of writing to the depth texture
In openGL, let's say I output one single point from the vertex shader with this value

```
gl_Position = vec4(2.0,3.0,5.0,7.0);

```

what exact math operations happen to "z" after leaving the vertex shader?
what will be the end value of that depth texel?

# Answer
After all of your transformations are applied (rotations, perspective transformations, etc.), all of the coordinates are divided by *w* (the fourth value in the `gl_Position` vector) to determine **Normalized Device Coordinates,** NDC. In other words NDC = *(x/w, y/w, z/w)*

The *x, y,* and *z* coordinates in NDC space are in the range \[-1..1\] if they are in the clip region. The *x* and *y* coordinates are used for the viewport transformation. The *z* coordinate is linearly transformed into the range \[0..1\] and is used for depth calculations. This last step depends on the values set by glDepthRange: 0=near and 1=far are the default values.

This is detailed in the OpenGL red book, and here.
> 1 votes

# Answer
If I remember correctly, `z` (as well as `x` and `y`) will be divided by `w`.

Then, everything outside of `-1..1` will be culled.

And then, resulting value will be mapped to `0..1` (or to whatever range you selected with `glDepthRange()`).

In case of default range, full formula would be `depth = z / w / 2 + 0.5`.
> 0 votes

# Answer
after setting

```
glDepthRange(n, f);

```

Full formula:

```
finalDepth = (gl_Position.z/gl_Position.w)*(f-n)*0.5+(f+n)*0.5

```

Bonus:
Every other answer out there about depth buffer always assumes the use of projection matrix, this matrix is a waste of space, time and precision, of the 16 floats that it has only 2 are really needed, the "field of view" and the "screen ratio".
OpenGL makes the precision worst by not giving us control of that math formula of final depth value.
> -3 votes

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


# Question
Title: OpenGL flat shading of non-planar polygons using TBOs
I'm trying to implement flat shading for non-planar polygons (using a single normal vector per polygon) based on *buffer textures*, but I can't seem to figure out how to set up things correctly. The approach is as follows —

* I render n-gons using `GL_TRIANGLE_FAN`. Everything is stored index-based, so I use `glDrawElements()`. To know where one n-gon ends and the next one starts, I use the *primitive restart* approach.
* In the fragment shader, one has access to `gl_PrimitiveID`. In the rendering process, each n-gon is split into `(n-2)` triangles, each triangle has a unique `gl_PrimitiveID`.
* Each triangle can be linked back to its original n-gon as follows. Let's consider a mesh consisting of a pentagon, a triangle and a quad (in that order). The data stored in the first *buffer texture* is `0,0,0,1,2,2`. The pentagon (index `0`) is rendered as three triangles, the triangle (index `1`) is of course rendered as a single triangle, and the quad (index `2`) is rendered as two triangles. Using `gl_PrimitiveID`, the n-gon index can be obtained.
* Finally, there is a second *buffer texture* which contains one normal vector per original n-gon. The indices in the other buffer texture (i.e., `0`, `1` and `2` in the example) can be used to obtain the right normal vectors for each triangle.

Ok, to create the buffer textures, I use

```
GLuint faceIndexBuffer, faceIndexTexture, faceNormalBuffer, faceNormalTexture;

glGenBuffers(1, &faceIndexBuffer);
glBindBuffer(GL_TEXTURE_BUFFER, faceIndexBuffer);
glBufferData(GL_TEXTURE_BUFFER, sizeof(unsigned int)*FaceIDs.size(), FaceIDs.data(), GL_DYNAMIC_DRAW);

glGenTextures(1, &faceIndexTexture);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_BUFFER, faceIndexTexture);
// Unsigned integers (uint)
glTexBuffer(GL_TEXTURE_BUFFER, GL_R32UI, faceIndexBuffer);

glGenBuffers(1, &faceNormalBuffer);
glBindBuffer(GL_TEXTURE_BUFFER, faceNormalBuffer);
glBufferData(GL_TEXTURE_BUFFER, sizeof(QVector3D)*FaceNorms.size(), FaceNorms.data(), GL_DYNAMIC_DRAW);

glGenTextures(1, &faceNormalTexture);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_BUFFER, faceNormalTexture);
// RGB floats (vec3)
glTexBuffer(GL_TEXTURE_BUFFER, GL_RGB32F, faceNormalBuffer);

```

where

```
QVector<unsigned int> FaceIDs;
QVector<QVector3D> FaceNorms;

```

Neither `FaceIDs` nor `FaceNorms` contains any data when the above code is run. To update the actual data, I use

```
glBindBuffer(GL_TEXTURE_BUFFER, faceIndexBuffer);
glBufferData(GL_TEXTURE_BUFFER, sizeof(unsigned int)*FaceIDs.size(), FaceIDs.data(), GL_DYNAMIC_DRAW);

glBindBuffer(GL_TEXTURE_BUFFER, faceNormalBuffer);
glBufferData(GL_TEXTURE_BUFFER, sizeof(QVector3D)*FaceNorms.size(), FaceNorms.data(), GL_DYNAMIC_DRAW);

```

The other data (vertex information, i.e. coordinates and normals, and indices) are stored as VBOs and IBOs, wrapped in a VAO.

Relevant part of the fragment shader —

```
layout(binding = 0) uniform samplerBuffer primIdToFaceId;
layout(binding = 1) uniform samplerBuffer faceNormals;

int faceIndex = int(texelFetch(primIdToFaceId, gl_PrimitiveID).x);
vec3 norm = texelFetch(faceNormals, faceIndex).xyz;

```

Note that I use bindings in the shader, so I shouldn't have to use e.g.

```
uFaceIDs = glGetUniformLocation(ShaderProg->programId(), "primIdToFaceId");
glUniform1i(uFaceIDs, 0);
uFaceNorms = glGetUniformLocation(ShaderProg->programId(), "faceNormals");
glUniform1i(uFaceNorms, 1);

```

Unfortunately, something is apparently not set up in the correct way, because I don't obtain the right normals. This is the relevant logging information (Buffer 4 corresponds to the first TBO containing indices, Buffer 5 to the second one, containing normals) —

```
→ Log: QOpenGLDebugMessage("APISource", 131185, "Buffer detailed info: Buffer object 4 (bound to GL_TEXTURE_BUFFER, usage hint is GL_STATIC_DRAW) will use VIDEO memory as the source for buffer object operations.", "NotificationSeverity", "OtherType")
→ Log: QOpenGLDebugMessage("APISource", 131185, "Buffer detailed info: Buffer object 5 (bound to GL_TEXTURE_BUFFER, usage hint is GL_STATIC_DRAW) will use VIDEO memory as the source for buffer object operations.", "NotificationSeverity", "OtherType")

```

when creating/updating data, and

```
→ Log: QOpenGLDebugMessage("APISource", 131185, "Buffer detailed info: Buffer object 4 (bound to NONE, usage hint is GL_DYNAMIC_DRAW) will use VIDEO memory as the source for buffer object operations.", "NotificationSeverity", "OtherType")

```

when rendering. **This last line here indicates what might be wrong, the first TBO is not bound anymore?** What am I overlooking?

# Answer
Fixed it! One of the TBOs is filled with *unsigned* integers, therefore `usamplerBuffer` has to be used instead of `samplerBuffer`

```
layout(binding = 0) uniform usamplerBuffer primIdToFaceId;
layout(binding = 1) uniform samplerBuffer faceNormals;

```

Some debugging and results. Using

```
fColor = vec4(0.0, mod(gl_PrimitiveID,256)/255, 0.0, 1.0);

```

in the fragment shader results in

Note that in this setting, each triangle in an original n-gon has its own colour —

Using

```
fColor = vec4(0.0, mod(faceIndex,256)/255, 0.0, 1.0);

```

results in

Now all triangles in an n-gon share the same colour. Finally, using the code from the original post, we get the intended flat shading effect —

\[Edit\] I still get the

```
→ Log: QOpenGLDebugMessage("APISource", 131185, "Buffer detailed info: Buffer object 4 (bound to NONE, usage hint is GL_DYNAMIC_DRAW) will use VIDEO memory as the source for buffer object operations.", "NotificationSeverity", "OtherType")

```

message, though it appears to be harmless.
> 5 votes

---
Tags: opengl, qt
---


# Question
Title: Blender, Exporting to Collada, Assimp and Normal Maps
I have a simple model that uses a diffuse and a normal map - in this case just two textures applied to the same material, where for the normal map I uncheck all the options in the "Influence" section in Blender and check the option for "Normals". Inside Blender the normal map is used correctly, but when I export the file to collada and try to load it with OpenAssimp, the normal map doesn't show up in the material.

Also, the Collada file doesn't seem to mark the normal map as something special, it's just listed as another image under (there's no reference to it being a normal map, and there is no bump effect in library\_effects).

Do I need to activate some special option in blender to make sure the normal shows up in the collada file?

Notes: AssimpView doesn't load the normal map either, but when I export as 3DS it shows the normal map correctly - too bad I can't use 3DS since it doesn't support bones.

# Answer
Open the .dae file in a text editor. Search for:

```
<bump>

```

If its just called `<bump>`, change it to:

```
<bump bumptype="NORMALMAP">

```

Then, below your material type, and above `</technique>`, paste the following and replace with your normal texture name. In context, it should look like this:

```
</phong>
<extra>
  <technique profile="FCOLLADA">
    <bump bumptype="NORMALMAP">
      <texture texture="example_Normal_jpg-sampler" texcoord="UVMap"/>
    </bump>
  </technique>
</extra>
</technique>

```

:)
> 1 votes

---
Tags: blender, collada, assimp
---


title: Using GrabPass for 2D water reflection?

text:
# Question
Title: Using GrabPass for 2D water reflection?
I'm trying to achieve some neat 2d water reflection effect with Unity, something like this:

What I've managed to accomplish so far:

The problem is GrabPass captures the entire screen but I really want to control precisely what area of the screen will be captured.

Is it feasible with GrabPass? (I'd rather not use a new camera for a rendertexture).

Is that even the right approach?

# Answer
> 0 votes
Using a Grab Pass can work, in 2d. But what you need to do is project the texture into screen space.

Here is the code you should use:

```
float4 reflectionTex = tex2D(_GrabTexture, float2(IN.screenPos.x, 1-IN.screenPos.y)/IN.screenPos.w).xyzw);

```

# Answer
> 1 votes
2D Water Reflection can achieve results like that. I did it first for a friend who wanted exactly the same effect that you described and that is looking like Kingdom. I did not used GrabPass but a specific render texture instead. The result is then applied on a screen aligned quad, flipped, Y clipped and distorded. I do not know which one is performing better but I suspect they should be close.

---
Tags: unity, shaders
---


# Question
Title: Unity3D - Android build has no Internet Access
I'm having trouble connecting to the internet in an Android build. I created a simple program that checks if there is an connection. Also I set in 'Edit \> Project Settings \> Player' the Internet Access to Require. But there is still no sign of connection in the app. Does anyone know what the problem is? Thank in Advance!

```
public class CheckInternet : MonoBehaviour {

    private bool isInternet = false;
    public Text ConnectedText;
    public Text IntText;
    int i = 0;
    // Use this for initialization
    void Start () {

    }

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

        StartCoroutine (TestInternet());
        IntText.text = i++ + "";
        if (isInternet) {
            ConnectedText.text = "Connected";
        } else {
            ConnectedText.text = "Not Connected";
        }
    }

    IEnumerator TestInternet(){
        WWW internet = new WWW("www.google.com");
        yield return internet;
        if(internet.error!=null)
            isInternet=false;
        else
            isInternet=true;

    }
 }

```

Source

In the Play-Modes it had internet access:

And in the Android Build it has not Internet Access:

# Answer
> 1 votes
I was stuck at this for hours, but I came up with a solution. In case anyone's still stuck at this, here it is:

Unity on Android, or Android itself doesn't seem to like URL's without the protocol.

The fix is to add the protocol before the URL, for example your `www.google.com` would probably become `http://www.google.com` or `https://www.google.com`.

The error is explained perfectly in the `WWW.error` variable, that's what I didn't check.

---
Tags: unity, android
---


title: Updating GameObject Position in Unity 5

text:
# Question
Title: Updating GameObject Position in Unity 5
I have a simple Sprite called `Player` that has the follow components (Transform, Sprite Renderer, Box Collider 2D, Rigidbody 2D, Player Controller Script). In my Player Controller script I want to update the player's position when a key is pressed.

```
using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

    Vector2 playerPos;

    // Use this for initialization
    void Start () {

        playerPos = gameObject.transform.position;

    }

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

        if (Input.GetKey("d")) {

            playerPos = new Vector2(playerPos.x + 0.2f, playerPos.y);

        }

    }
}

```

This script is attached to my gameobject but whenever I press or hold down the 'd' key, nothing happens to the player. Does anyone know how to fix this?

# Answer
Vector2 is a C# struct, which is a **value type**. That means when you assign a Vector2 to a variable, or pass it as an argument/return value, you're *copying the value* of the Vector2 — **not** passing around a *reference* to it.

So when you say

`playerPos = gameObject.transform.position;`

You are *copying* the player's current position into `playerPos`

(You can skip the `gameObject` at the front, since the MonoBehaviour's transform getter does the same thing)

Everything you do after that is just *modifying this copy* — you never assign it back to the player transform to actually move the player.

If you want to move the player to the new location, you need to assign the value back to the player's transform:

`transform.position = playerPos;`
> 2 votes

# Answer
You want something like:

`var player = GameObject.Find("Player");`

Then

`player.transform.position = new Vector2(playerPos.x + 0.2f, playerPos.y)`

Check this out: http://answers.unity3d.com/questions/642405/continuous-movement.html

Describes: Moving in one direction continuously and then move the opposite direction continuously when you press a button.
> 1 votes

---
Tags: unity, movement
---


# Question
Title: Conditional Variables in Scriptable Objects
While using `ScriptableObjects`, how can I make some variables conditional?

*Example Code:*

```
[System.Serializable]
public class Test : ScriptableObject
{
      public bool testbool;
      public string teststring;
      public int testint;
}

```

**Goal:** When `testbool == true` then `teststring` is available to edit, when `testbool == false` then `testint` is available to edit while the other one is "*grayed out*".

# Answer
> 6 votes
The Editor-friendly path is a "custom inspector". In Unity API terms, this means extending the Editor class.

Here is a working example, but the doc link above will walk you through a lot of the details and additional options:

```
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(Test))]
public class TestEditor : Editor
{
    private Test targetObject;

    void OnEnable()
    {
        targetObject = (Test) this.target;
    }

    // Implement this function to make a custom inspector.
    public override void OnInspectorGUI()
    {
        // Using Begin/End ChangeCheck is a good practice to avoid changing assets on disk that weren't edited.
        EditorGUI.BeginChangeCheck();

        // Use the editor auto-layout system to make your life easy
        EditorGUILayout.BeginVertical();
        targetObject.testBool = EditorGUILayout.Toggle("Bool", targetObject.testBool);

        // GUI.enabled enables or disables all controls until it is called again
        GUI.enabled = targetObject.testBool;
        targetObject.testString = EditorGUILayout.TextField("String", targetObject.testString);

        // Re-enable further controls
        GUI.enabled = true;

        targetObject.testInt = EditorGUILayout.IntField("Int", targetObject.testInt);

        EditorGUILayout.EndVertical();

        // If anything has changed, mark the object dirty so it's saved to disk
        if(EditorGUI.EndChangeCheck())
            EditorUtility.SetDirty(target);
    }
}

```

Keep in mind that this script uses Editor-only APIs, so it must be placed in a folder named Editor. The above code will turn your inspector into the following:

That should get you rolling until you are more comfortable with Editor scripting.

# Answer
> 3 votes
```
[System.Serializable]
public class Test : ScriptableObject
{
    private bool testbool;
    public string teststring;
    public int testint;

    public string TestString
    {
        get
        {
            return teststring;
        }
        set
        {
            if (testbool)
                teststring = value;
        }
    }
}

```

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


title: Drawing a level in SFML (C++)

text:
# Question
Title: Drawing a level in SFML (C++)
So in an attempt to move out of the console environment I have set up an SFML poject in Visual Studio. I am currently trying to draw a stage from a vector within a vector (Matrix?), and the results are not exactly what I was hoping for.

First i tried mapping out everything as '0's representing empty space, changing the top and bottom vector to '1's, representing objects, thus drawing what essentially would be a rectangle covering the bottom and a rectangle covering the top, everything inbetween ignored.

```
bool stage::load()
{
 vector<int> tempvec;
 for (int i = 0; i != 30; i++)
 {
    for (int j = 0; j != 40; j++)
    {
        tempvec.push_back(0);
    }
    hitbox.push_back(tempvec);
    tempvec.clear();
 }

 for (int i = 40 - 1; i != -1; i--)
 {
    hitbox[29][i] = 1;
 }
 for (int i = 30 - 1; i != -1; i--)
 {
    hitbox[i][0] = 1;
 }
 return true;    //Will use this more efficently once I get the function to work
}

```

So this is how I set up the stage variable-wise, hitbox being defined as:

```
vector <vector<int>> stage::hitbox;

```

I then try to map out the individual blocks, so every time it finds a '1' in the vector, it should print out a square (quad).

```
vector<VertexArray> tilesetrender;
VertexArray tmp(Quads, 4);
tmp.resize(4);

level.load();
for (int y = level.hitbox.size() - 1; y >= 0; y--)
{
    for (int x = level.hitbox.at(y).size() - 1; x >= 0; x--)
    {
        switch(level.hitbox[y][x])   //Switch case allows me to expand on this function in the future
            {
            case 1:
                tmp[0].position = Vector2f(y * 20 - 10, x * 20 - 10);
                tmp[1].position = Vector2f(y * 20 - 10, x * 20 + 10);
                tmp[2].position = Vector2f(y * 20 + 10, x * 20 + 10);
                tmp[3].position = Vector2f(y * 20 + 10, x * 20 - 10);
                tilesetrender.push_back(tmp);
            }
    }
}

```

With all the variables created, I proceed to draw the level.

```
for (int count = tilesetrender.size() - 1; count >= 0; count--)
{
    renderWindow.draw(tilesetrender.at(count));
}

```

And what I get is this...  The vertices being white, and the background being red. As I have said, I hoped for drawing two rectangles, one at the top and one at the bottom. I have no real idea regarding what part of my code is causing the error, but I've played around with the position commands the most, to no avail.

Thanks in advance.

EDIT: Code partially corrected (Thanks Alayric), thus rendering this image instead:  White being the vertices, red the background and blue the player (previously not visible). Although it is a whole lot better, something is still incorrect, as the upper rectangle does not reach all the way, and the lower rectangle does not mirror the upper. I do belive the main problem has been solved, and thus I am able to continue on my own.

# Answer
> 1 votes
Switch statements are supposed to be surrounded by curly braces.

```
switch(level.hitbox[y][x]) {
    case 1:
        tmp[0].position = Vector2f(y * 20 - 10, x * 20 - 10);
        tmp[1].position = Vector2f(y * 20 - 10, x * 20 + 10);
        tmp[2].position = Vector2f(y * 20 + 10, x * 20 + 10);
        tmp[3].position = Vector2f(y * 20 + 10, x * 20 - 10);
        tilesetrender.push_back(tmp);
}

```

What you wrote is equivalent to:

```
switch(level.hitbox[y][x]) {
    case 1:
        tmp[0].position = Vector2f(y * 20 - 10, x * 20 - 10);
}
tmp[1].position = Vector2f(y * 20 - 10, x * 20 + 10);
tmp[2].position = Vector2f(y * 20 + 10, x * 20 + 10);
tmp[3].position = Vector2f(y * 20 + 10, x * 20 - 10);
tilesetrender.push_back(tmp);

```

# Answer
> 2 votes
Unfortunately, I don't have enough reputation to add a comment to your original post. Here is my go at a partial answer!

Here is where you populate the top row with 30 white boxes.

```
for (int i = 30 - 1; i != -1; i--)
 {
    hitbox[i][0] = 1;
 }

```

It looks like your boxes are 20x20 because

```
tmp[0].position = Vector2f(y * 20 - 10, x * 20 - 10);

```

**My honest guess is that the screen is wider than you expect. In the first block, change the loop delimiter to something higher than 30. 30x20 = 600. Your window may be larger than 600 pixels, or you may have a misconfigured OpenGL or SFML viewport to be wider than you expect**.

As an unrelated style tip, I would suggest you change your loop header to something more readable, ie:

```
for(int i = 30; i >= 0; i--)

```

or \`for(int i = 0; i \< 30; i++)

These two ways of writing the loop header make it more readily apparent that you are counting up/down from 30, rather than saying "I'm gonna start at 30-1, and go to -1." -1 is a weird number unless you're checking for an invalid array index.

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


title: Shadows in html5 canvas game

text:
# Question
Title: Shadows in html5 canvas game
I'd like to ask for reference. I met an article about how to cast shadows in games. I'm using html5 canvas (currently without webgl) with javascript for my projects.

The article mentioned above is located at http://willyg302.wordpress.com/2012/11/04/2d-visibility/.

I was thinking if this method is possible to employ with canvas (without webgl) and javascript?

More precisely, I have few shapes drawn on canvas some of them are complex made by arc and similar methods. Thus I don't have a simpel way how to describe one shape with an equation where I can store only a few parametrs (i.e. circle is described as centerX, centerY, radius with these I can easily draw it but with more complex shapes I don't have such information) therefore I thought about storing the whole canvas data by pixels with context.getImageData.data, then using method described in the article (polar transformation, ..., back to cartesian system) and putting the whole scene into canvas with canvas.putImageData method.

But before actually applying this I'd like to ask if it's even possible with canvas (no webgl) and javascript to create shadows dynamically (light source moving across the screen) this way without heavy fps loss (I can imagine this method works pretty good for still objects but the moment when I need to do it each time a light source moves I'm not sure if javascript + canvas can handle this in reasonable time, especially when I found information that putImageData and getImageData are quite slow)?

Or if anyone has tried to create dynamic shadows in different way in html5+js I'd appreciate your suggestions about these as well (I do it currently in similar way as is described in http://ncase.me/sight-and-light/, though I'm experiencing some troubles with concave shapes :( ).

This is getting awfully long, I hope I explained myself well enough.

Thank you very much for any advice you can share and I'm sorry that my post grew so large, although I'm asking just one question.

EDIT: Forgot to mention, I'm looking only for 2d solution.

# Answer
Well, that's a tricky question but I'll start from the beginning.

* Get/Put imageData is faster than you think, but if you want to do it in a efficient way I'd recomend you to build a double buffer and rasterize your shapes in it (here's a double buffer module I wrote, have a peek).
* Strange shapes' shadowing is as hard to do as rectangles shadowing, you only need to set a light point, then raycast it (raycast module i wrote, maybe it will help you to find out how to do it) and get the angle of the shadows for each object, then, thinking in objects as 3D and having the light point's 3D coords, project the object's shadow into the floor in said angle from it's bottom.

Usually, 2D games use baked shadows though, as it's easier to manage and implement than dynamic shadows.

If you want to do dynamic shadows, I'd recommend you to build everything in 3D and then render it by projection, I built a 3D rasterizer for vanilla 2D canvas that could help you, it renders 3D triangulated meshes in 2D canvas by projection, I have a updated version with dynamic shadowing and some other stuff, tell me if you are interested and I'll upload it later, and yes, it works in a good FPS rate, but you can't use the canvas render API for this purpose since you have to manage pixels.

Good luck.
> 1 votes

# Answer
I've thought about this for a while, I have have done a bit of research on this topic. Other than using a framework and writing super complex/long code, there are two options that I can think of:

1. use shadowblur
2. use radial/linear gradients

http://www.w3schools.com/tags/canvas\_createradialgradient.asp

Another option is to use alpa colors to draw various levels of darkness such as squares or circles:

```
context.save();
context.globalAlpha = 0.5;
context.fillStyle = "#000000";
// draw a whole ton of shapes with 50% transparency with a black color...
context.restore();

```
> 0 votes

---
Tags: javascript, html5, html-canvas, shadows
---


title: Sprite update issue

text:
# Question
Title: Sprite update issue
I'm currently implementing Box2D with LIBGdx and i'm having issue on update, as you can see on this video : https://www.youtube.com/watch?v=D3Nph6yftTQ whenever my player move or the camera move the sprites are updated badly. Currently i'm setting the sprite like that :

http://codepaste.net/7jujr3

Do you have any idea why the sprite is moving like that ? Thanks

# Answer
I fixed it by changing the main update loop and i followed this ordrer

* Input
* Physics (World & Bodies)
* Camera (position & update)
* Graphics
* Box2D Renderer (if neeeded)
> 0 votes

---
Tags: java, libgdx, sprites
---


# Question
Title: glViewport and single-pass cubemap rendering
This question is related to another question of mine on StackOverflow.

The problem I'm facing is that while I'm rendering to a cubemap in a single pass using a geometry shader (like I show in my other question) only the positive X face of the cube map actually gets rendered.

Using NSight I could see that actually also my negative X face is being rendered (with the right color looking to the pixel history), but then it results to be completely black, like if the fragment is discarded.

Doing some tests, I've found that this problem may be due to a `glViewport` call that I do when I bind the framebuffer of the destination cube map as the rendering target. My destination cube map is a 256x256 pixels cube map (every face is 256x256 pixels wide) and calling `glViewport(0, 0, 256, 256)` doesn't work (it renders only the positive X face like I said befare), but calling `glViewport(0, 0, 181, 181)` and below (with width and height less than 181) also the negative X face is rendered. Every call to `glViewport` passing width and height more than 181 doesn't work.

Could this be a driver problem? I'm facing this problem ONLY when rendering to the cube map bound to the framebuffer as `GL_TEXTURE_CUBE_MAP` target, if I bind every face with `GL_TEXTURE_CUBE_MAP_POSITIVE_X, ...` as target and draw to it there's no problem.

---

UPDATE

This is my geometry shader (this handles only the positive and negative X faces):

```
#version 330 core

layout(points) in;
layout(triangle_strip, max_vertices = 8) out;

out vec3 frag_textureCoord;

void main()
{
    const vec4 positions[4] = vec4[4] ( vec4(-1.0, -1.0, 0.0, 1.0),
                                        vec4( 1.0, -1.0, 0.0, 1.0),
                                        vec4(-1.0,  1.0, 0.0, 1.0),
                                        vec4( 1.0,  1.0, 0.0, 1.0) );

    // Positive X
    gl_Layer = 0;
    gl_Position = vec4(-1.0, -1.0, 0.0, 1.0);
    frag_textureCoord = vec3(1.0,  1.0, -1.0);
    EmitVertex();

    gl_Position = vec4( 1.0, -1.0, 0.0, 1.0);
    frag_textureCoord = vec3(1.0,  1.0,  1.0);
    EmitVertex();

    gl_Position = vec4(-1.0,  1.0, 0.0, 1.0);
    frag_textureCoord = vec3(1.0, -1.0, -1.0);
    EmitVertex();

    gl_Position = vec4( 1.0,  1.0, 0.0, 1.0);
    frag_textureCoord = vec3(1.0, -1.0,  1.0);
    EmitVertex();
    EndPrimitive();

    // Negative X
    gl_Layer = 1;
    gl_Position = vec4(-1.0, -1.0, 0.0, 1.0);
    frag_textureCoord = vec3(-1.0,  1.0, -1.0);
    EmitVertex();

    gl_Position = vec4( 1.0, -1.0, 0.0, 1.0);
    frag_textureCoord = vec3(-1.0,  1.0,  1.0);
    EmitVertex();

    gl_Position = vec4(-1.0,  1.0, 0.0, 1.0);
    frag_textureCoord = vec3(-1.0, -1.0, -1.0);
    EmitVertex();

    gl_Position = vec4( 1.0,  1.0, 0.0, 1.0);
    frag_textureCoord = vec3(-1.0, -1.0,  1.0);
    EmitVertex();
    EndPrimitive();
}

```

This is how I create the destination cubemap and its framebuffer:

```
// Destination cube map creation
glGenTextures(1, &_destinationCubeMapTextureID);
glBindTexture(GL_TEXTURE_CUBE_MAP, _destinationCubeMapTextureID);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

for (size_t face = 0; face < 6; face++)
    glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + (unsigned int)face, 0, GL_RGBA16F, 256, 256, 0, GL_RGBA, GL_FLOAT, nullptr);

glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, 8);
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);

glBindTexture(GL_TEXTURE_CUBE_MAP, 0);

// Destination depth map creation
glGenTextures(1, &_destinationDepthCubeMapTextureID);
glBindTexture(GL_TEXTURE_CUBE_MAP, _destinationDepthCubeMapTextureID);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

for (size_t face = 0; face < 6; face++)
    glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + (unsigned int)face, 0, GL_DEPTH_COMPONENT24, 256, 256, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, nullptr);

glBindTexture(GL_TEXTURE_CUBE_MAP, 0);

// Destination framebuffer creation
glGenFramebuffers(1, &_destinationFrameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, _destinationFrameBuffer);

glFramebufferTexture(GL_FRAMEBUFFER, attachment, _destinationCubeMapTextureID, 0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, _destinationDepthCubeMapTextureID, 0);

glDrawBuffers(1, &drawBuffer);

```

This is basically how I bind the cubemap framebuffer to draw and how I send the draw command:

```
void BindTextureTarget()
{
    glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _destinationFrameBuffer);

    glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _destinationCubeMapTextureID, 0);
    glViewport(0, 0, 256, 256);
}

...
glUseProgram(programID);

BindTextureTarget();

glClear(GL_COLOR_BUFFER_BIT);
glClearColor(0.0, 0.0, 0.0, 0.0);

pointVertexArray.Enable();
glDrawArrays(GL_POINTS, 0, 1);

```

# Answer
First of all, please put a simple version of your code here so I can fix it for you.

But for now, there is lots of reason you can't render correctly in your cube map:

* Early use of texture (use flush and finish to make sure your using a completed frame buffer)
* Maybe your texture and frame buffer format are mismatched.

There is lots of other problematic things that might be your answer, but I must see your code first.

And I must say something else that your way of writing geometry shader, is not very recommended, if you put code in your question i can help you with that too.
> -1 votes

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


# Question
Title: How to calculate the outcome of a battle?
My game's war system is pretty straightforward, so I will give you a brief overview. You assign soldiers to commanders, and you also assign equipment. Equipment being weapons (e..g: rifles, pistols, etc ...) and vehicles (e.g.: tanks).

If a commander has 10,000 weapons in their inventory, and they only have 5,000 soldiers, then there will be 5,000 **unused** weapons in the commanders inventory. These unused weapons will not have any affect on the battle, but are still at risk to be lost during the fight (so it would actually be rather unwise for the player to assign that many weapons).

If a commander has 1,000 tanks **\- tanks require 3 soldiers -** in their inventory, then the commander will need at least 3,000 soldiers to be able to use every single tank in battle.

If there are **more soldiers** than there are weapons and vehicles, then there will be some soldiers who are not assigned a vehicle or weapon, and so they will fight with their base/default stats.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Now for the actual mechanic that I seem to be struggling with:

Every soldier, weapon, and tank only has two variables that are used or considered in battle: **attack & power**.

Say a tank has 70 attack and 100 defense, and a rifle has 15 attack and 0 defense. These stats will be ADDED to the soldier's base stats.

Assuming that there is only the **attacker's** commander vs. the **defender's** commander of a city, no external forces or variables, I could simply calculate one commander's total combined attack & power, and if it's greater than the other commander, then I should declare him the winner.

Whether this is the best method for this I'm not sure yet.

But my current question is, *how do I determine losses*? How do I determine how many soldiers, weapons, and tanks either commander has lost during the fight?

# Answer
> 1 votes
First, your suggestion that a simple comparison of the forces should determine the outcome of the battle is completely historically accurate. Most battles are determined by the relative strengths of the forces going into the conflict. In the rare event of a weaker side winning, due to good fortune or good generalship, it will be spoken about more often, giving the wrong impression that this is a common event.

It seems to me there are two ways to calculate losses:

**"Game world"** Frequently in the world of gaming it seems to me that the losers are wiped out entirely. Each battle is thus a fight to the death for the opposing forces.

**"Real world"** In the real world, a battle might be lost, but (and this really depends on many things) in many cases about 90% of the manpower survives, from ancient to modern times. Some wars have seen 50% of ground troops killed (but far less for artillery and other branches) but this is after they have participated in many battles, or the insane over-the-top policies of World War I trench warfare.

When it comes to taking a city, it really depends on whether or not the city is in a siege situation. This was much more common in the fortified towns of medieval times. Part of the reason why the World War II battles of Stalingrad and Berlin are so famous is their dramatic quality - both involved a siege situation with no escape for the defenders. This, however, is not the normal fare, and retreat from a city is much more common with most of your troops intact.

Before making a suggestion of how to calculate the matter it is important to know how the game play occurs. It sounds like a simple calculation is made and there is no time passing for the players during a battle. If there was time passing (a battle 'in progress' as it were) then one side could pull out as they see how the battle is going. That does not seem to be how your game goes.

How many survive ("real world" now) depends on whether or not the defending troops can get out if they lose, which is normally the case. Also, a general will suffer greater losses if they think the battle is worth more, or they just bloody well want to beat the other guy, so this is a possible user setting you might consider going into the battle ('enthusiasm'?).

Calculate the attacker's total attack force and and the defender's total defense force. If it is a fight to the death (the simplest calculation) the loser ends up with 0, and it is not unreasonable to say that the winner's remaining resources adds up to the original difference between the two. Lets say the winner has 10000 points worth of material left over (whether attacking or defending). You have three choices:

1. Distribute evenly based on the proportions of the forces going in. If half of the winner's points when they went into the battle were tanks, then half of them are left over.
2. Distribute randomly: it does not matter how many were tanks entered the fray, but be careful that no more than this number comes out!
3. Distribute based on opposing forces. If 100,000 tank attack points met 70,000 tank defender points and the defenders lost, then 30,000 points worth of tanks remain to the victor. BUT! The attackers may have lost the overall battle, so this is trickier to implement.

I tend towards the last one, though I frequently make life more difficult for myself! The first is the most straightforward.

Finally, if it is not a fight to the finish, then any of these choice can be applied to a *proportionate* loss in each sides forces. How about deciding the winner the same way (simply comparing forces, this is presumably fine if each side does not know how many the other is investing). Defenders have a certain advantage (as long as they can run away in the event of a loss) but you already reflect this in the attack/defense point awarded to each element. This is where I would argue with your awarding 0 defense points to a rifle. In fact, if dug in, a rifle has more defense value than attack value. Ask the snipers left behind to help troops evacuate a lost city!

This nod to the real world, where each battle is not a wipe-out, is also easy to calculate. Perhaps 90% survival is too slow for your game (or maybe it means the games are not stupidly short!?!?), but you could experiment with other proportions - winners retain 75% of forces, losers retain 60% (losers would normally retreat before being overrun or surrendering). Then apply one of the three methods listed above to the remaining forces.

The only way to really test the correctness of the proportions you choose is by trying it out by playing the game with those numbers. The wipe-out approach could ruin games with only a few cities, but might simplify games with dozens of cities. In the proportionate approach, retaining 90% of forces each time might be too slow, but too low might as well have a wipe-out. Also, if both sides only lose the same proportion (say 50%) this is really a loss for the greater force which has lost more (though this is frequently the case - see here).

I hope this has been of some use.

# Answer
> 0 votes
i'd take a "decimate" approach. Since you know the exact power and quantity of both sides you could simply get the "succesfull rate" for each point, will explain.

if i had 1000 soldiers in each side but the first side had some weapons (100), then whe would have 2500 pts vs 1000pts. Then, we could know that, for every second side "hit", the first side would hit 2.5 times. so, since our base (soldiers) is 1000 for both sides, at the end og the battle first side would still having 600 units (1000 - (1000 / 2.5)) and second side would be erradicated.

About the riffle/tank lost, i would make kind of "estimation" approach, say we have the situation said above. then we would have 1 riffle for each 10 soldiers, so, when we lose 10 soldiers we have to remove 1 riffle, that means that, in the case above, the would be 40 lost riffles. But this is not "accurate" since soldiers can take up lost's friend's guns and use themselfs or a lucky grenade could put 2 or 3 rifflemen out of combat, so i would randomizate it with an "error", so, if the "average" that we lose 1 riffle for each 10 soldiers, lets say that, in this actual battle will be lost Random( (soldiers / rifles) * 0.8, (soldiers / rifles) * 1.2).

So we would have a random number in a thight enough range.

Hope it helped

---
Tags: game-mechanics
---


# Question
Title: Streaming webcam via websocket performance issues (Code included)
I finally figured out, how I can stream my webcam, but I'm getting not the best performance. In low resolutions it's working fine, but as soon as I turn the resolution up, the performance gets worse. I think Unity can't handle the decoding in that quality and speed so that the game is getting slowed down. Here is my Code :

```
Texture2D screenshot = new Texture2D(Screen.width, Screen.height, TextureFormat.ARGB32, false);
screenshot.ReadPixels(new Rect(0,0,Screen.width,Screen.height),0,0);
screenshot.Apply();
ws.Send(System.Convert.ToBase64String(screenshot.EncodeToJPG(quality)));

```

Hopefully there is something to improve.

# Answer
There are 2 things that I think might make this run faster:

1) Limit the number of images you're attempting to send (e.g. the FPS) (Unity is single threaded, so everything you do has an impact on performance)

2) Make the resulting JPG smaller by scaling the image before Base64 encoding it

There are a number of ways to reduce the frame rate, but possibly the easiest is to use a Coroutine. If you also use WaitForSeconds then you'll be able to limit the frame rate to whatever you need. Something like the following will give you a stream of about 30FPS:

```
IEnumerator SendScreenshot()
{
    // Change this to affect frame rate
    yield return new WaitForSeconds(0.33f);

    Texture2D screenshot = new Texture2D(Screen.width, Screen.height, TextureFormat.ARGB32, false);
    screenshot.ReadPixels(new Rect(0,0,Screen.width,Screen.height),0,0);
    screenshot.Apply();
    ws.Send(System.Convert.ToBase64String(screenshot.EncodeToJPG(quality)));
}

```

You may find this still slows things down a little, as it will still be executing in the main Unity thread. If that's still not acceptable performance wise, you can try scaling the image down, before sending it over the network.

Hope this helps :-)
> 1 votes

---
Tags: textures, unity, websocket, streaming
---


# Question
Title: How can I apply Perlin noise to generating an asteroid from cubic voxels?
I know I can use Perlin noise to generate randomised terrains, but for my current project i want to generate random *asteroids* of non-uniform length, width depth etc.

My first thought was to apply Perlin noise to a sphere, but i do not know how i would apply this with cubes space in a grid nor did i know whether it would make the asteroids appear *random* enough, my current assumption was they would all be relatively spherical still.

Is Perlin noise still the best method to be using for terrain not on a single plane?

# Answer
Here is how you can blend data of noise and gradient together, in 3D. This should provide you with asteroid style shapes.

First, our container to store the Data:

```
public class MapData {

    public float[,,] Data;
    public float Min { get; set; }
    public float Max { get; set; }

    public MapData(int width, int height, int depth)
    {
        Data = new float[width, height, depth];
        Min = float.MaxValue;
        Max = float.MinValue;
    }
}

```

We init this data container as follows:

```
blendData = new MapData (Width, Height, Depth);

```

Now, if you already have your generated noise, and gradient maps, you can blend them as follows:

```
// first pass - blend gradient values
for (var x = 0; x < Width; x++) {
    for (var y = 0; y < Height; y++) {
        for (var z = 0; z < Depth; z++) {

        // Get gradient values
        float gradValue1 = (float)NoiseMap.Get (nx, ny, nz);
        float gradValue2 = (float)GradientMap.Get (nx, ny, nz);

        // Multiply
        float blendValue = gradValue1 * gradValue2;

        // keep track of the max and min values found
        if (blendValue > blendData.Max) blendData.Max = blendValue;
        if (blendValue < blendData.Min) blendData.Min = blendValue;

        blendData.Data[x,y,z] = blendValue;
    }
}

```

Doing so will give you some pretty crazy values, so we are going to want to normalize these in order to provide an easier way to work with this data in the future:

```
// secondary pass to normalize the blended values
for (var x = 0; x < Width; x++) {
    for (var y = 0; y < Height; y++) {
        for (var z = 0; z < Depth; z++) {
            blendData.Data[x,y,z] = (blendData.Data[x,y,z] - blendData.Min) / (blendData.Max - blendData.Min);
        }
    }
}

```

Render this data, and you should see a asteroid style shape emerge.
> 0 votes

---
Tags: procedural-generation, perlin-noise
---


# Question
Title: How to create a repeating gif style imagery for a game tutorial dialog
I want to create a gif style video that shows up in a tutorial window using Unity. How can I make this? Do I record the thing I want to show and then put it in a texture?

Example:

# Answer
> 1 votes
Whole sprite animation with PNG sequence in mecanim is one way to go and loop the animation with delay for repetitive showcase. \[Will take more asset space\]

Or you can animate all small pieces in mecanim and loop it with delay for repetitive showcase. \[Will need less asset space\]

# Answer
> 1 votes
Since it appears that what you are doing is tutoring people in game mechanics, an elegant solution presents itself:

Use the game mechanic you're tutoring.

If the architecture of your game allows it, create a scaled game board that is set up in a useful tutorial state, allowing a player to either trigger the mechanic as they would in game (with some kind of indicator, like a glowing square in this case, if necessary), and with a button named 'Show me!' that has a computer player do the action, triggering the game mechanic.

If the architecture of your game *doesn't* support making a scaled board like this, consider replacing the popups with tutorial levels instead, where the RNG is cooked to give the desired assets to the players to complete the tutorial (as applicable).

**Edit:**

As an alternative, nix the tutorial all together and throw the player into the deep end, keeping track of what game mechanics they've triggered and seen.

Whenever a new game mechanic is discovered, instead of a pop up, slide in a bumper with a brief explanation of what just happened; if possible while the action is still going on, pausing the view and letting the player absorb the information at their own pace until dismissal of the bumper.

---
Tags: unity
---


# Question
Title: Disabling object OnCollisionEnter and Enabling it On Collision exit
I have two objects that when they collide disable another gameobject. The problem is that I only want to have the other game object disabled while the two objects are touching and that I want to have it enabled again as soon as the two objects are no longer touching. My script is below:

```
using UnityEngine;
using System.Collections;

public class DestroyObject : MonoBehaviour {

public GameObject ObjectToDestroy;
public GameObject TheObject;
public GameObject Player;

void OnCollisionEnter(Collision col)    {
    if (col.gameObject == TheObject) {
        ObjectToDestroy.SetActive (false);
    }
}
}

```

# Answer
I fixed this issue as I noticed a simple mistake that I made when I was trying to fix this myself. Here is the whole piece of code.

```
using UnityEngine;
using System.Collections;

public class DestroyObject : MonoBehaviour {

public GameObject ObjectToDestroy;
public GameObject TheObject;
public GameObject Player;

void OnCollisionEnter(Collision col)    {
    if (col.gameObject == TheObject) {
        ObjectToDestroy.SetActive (false);
    }
}

void OnCollisionExit(Collision col) {
    if (col.gameObject == TheObject) {
        ObjectToDestroy.SetActive (true);
    }
}
}

```
> 0 votes

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


# Question
Title: Any way to load/execute scripts (game-logic) included in a post-release DLC (Unity3D AssetBundles) on iOS since it seems its not allowed?
We are making a game where players will be granted access to new levels every week and these new levels will probably be downloaded from our server as Unity Asset Bundles The only issue is, as mentioned here , ios and other app stores dont allow loading/executing of scripts this way even if they allow you to load these newer asset bundles without doing the full update cycle. So really we need to know how game-logic scripts, etc can be executed for the new levels that are going to be released via Asset Bundles and downloaded from our server. Our server will be authoritative btw. I am sure there is a way since big game publishers are able to do post-release DLC and really, thats what we are after too - Just more regularly, whilst being in-line with app store regulations. Our usual workflow until now was just publish and then release a big update months down the line. Not every week.

# Answer
> 2 votes
Many games are data driven, and apple is fine with you downloading data from your servers which changes the behavior of the game, adds content, etc. If you can't do with data what you need to do, you have to put out a new exe that exposes new features to data, that will let you do more without executable patching. Rinse and repeat.

# Answer
> 1 votes
It's actually not that uncommon to release new "downloadable" content with a mandatory patch which is rolled out to all users through the normal app updating system and then just unlock it when the user paid for it.

---
Tags: unity, ios, client-server
---


title: Evaluate 2D point in a 3D triangle?

text:
# Question
Title: Evaluate 2D point in a 3D triangle?
Given three points, (x1, y1, z1) (x2, y2, z2) (x3, y3, z3)

and given a point "A" at (x, y), how would I find "A'", at (x, y, z)?

# Answer
Depending on the library or technology you are working with - things can get easier. But it is *almost always* good to understand the maths behind this stuff. Have a look at the line through plane equations on Wikipedia.
> 0 votes

---
Tags: algorithm, coordinates, interpolation
---


# Question
Title: Does AddForce continue to add force indefinitely?
Does the AddForce method continue add velocity to an object forever? Does it need to be limited by another line of code?

Sorry if it is too broad or too simple; I am completely new to programming and Unity, as well as 3D development.

# Answer
> 5 votes
`AddForce` will apply a force for the current update cycle. The force is applied to the RigidBody for that update cycle, then cleared. **At the beginning of each physics step, the forces are zero**. Then the forces for gravity, friction and calls to `AddForce` are summed up and added to the RigidBody.

Assuming the forces added to the object don't cancel each other out, there will be a resulting velocity change. If force is continually applied, the velocity can reach infinity. But unless you're applying infinite force, the force will not reach infinity, because it's applied and cleared each physics step.

You do not need to 'negate' a force after it's been applied to stop it from being applied.

# Answer
> 1 votes
Force is applied continuously along the direction of the force vector. Specifying the ForceMode mode allows the type of force to be changed to an Acceleration, Impulse or Velocity Change. Force can be applied only to an active Rigidbody. If a GameObject is inactive, AddForce has no effect.

Taken directly from here. Maybe read more on that website. It has some good answers.

# Answer
> 1 votes
It depends on how you add it. If you add it once on some callback, for example, or button press\release event, then it will be added once.

This once applied force, will affected by other things, like friction for example, which over a period of time will render that applied force value to zero (by decreasing it's every physics update).

If you apply it constantly in update function of your character controller, yes, you'll be adding force infinitely.

---
Tags: c#, unity, movement, vector
---


# Question
Title: HLSL SetVertexShader Texture2DArray Sample
I want to do some texture samples in the vertex shader, but it seems this cannot be done in the same was as when using the Pixel shader.

The code is basically..

```
Texture2DArray   gTexture;

VS()
{
    gTexture.Sample(samPoint, float3(x, y, z)
}

PS()
{
    gTexture.Sample(samPoint, float3(x, y, z)
}

technique11 main
{
   pass P0
   {
      SetVertexShader(CompileShader(vs_4_0, VS()));
      SetGeometryShader(NULL);
      SetPixelShader(CompileShader(ps_4_0, PS()));
   }
}

```

The PS() will compile and work fine but I also need to do this sort of thing in VS().

When putting this code in the VS() I get: Error X4532 cannot map expression to vs\_4\_0 instruction set ....

I have done some googling and it looks like you can sample a texture in the VS but I cant get enough detail together to make this work.

Any help on this would be good.

Just for reference: I am using DirectX11 VS2015

# Answer
You can not Sample a texture in vertex shader with regular sampling. You should use SampleLevel and sample a specific mip level of the texture with it. This is because you don't have screen space derivatives (ddx and ddy) in the vertex shader. In the pixel shader those are used to determine the mip level. You can also use texture.Load.
> 2 votes

---
Tags: shaders, textures, directx11, hlsl
---


# Question
Title: Monitor external window events with SDL2
I'm trying to render my game (SDL2, C++) in a Windows Form application (C#) using C++/CLI to interface with my underlying C++ code. The purpose of the form is to create an editor which can monitor/adjust/interact with the game, however the game is also executable without the form.

To do this I'm using the **SDL\_CreateWindowFrom** function (which takes the handle to the form panel). This works fine for actually rendering to the panel, however I'm not receiving any events when calling **SDL\_PollEvents**. When I use **SDL\_WaitEvent** instead I do receive **SDL\_SYSWMEVENT**'s but this isn't ideal (as this means my renderer will be stalled while waiting for events AND I would have to process raw windows message events (e.g. **WM\_KEYDOWN**)).

Is there a way to allow SDL to receive (particularly important: input) events from an external window? Is there a way to override the **WndProcHandler** that SDL uses? Or is there an entirely different approach I should be taking?

Thanks a lot!

# Answer
This is *probably* not the approach you want to take. Normally this kind of "render my engine into a HWND" technique accomplishes input handling by having the other HWND's process (the C# application in this case) send the relevant events back to your engine process via some kind of backchannel, such as a socket connection. It's generally an easier-to-deal-with technique.

---

That said, if you're set on monitoring the events directly, look into `SetWindowsHookEx`. That function allows you to inject a hook function that is called with before (`WH_CALLWNDPROC`) or after (`WH_CALLWNDPROCRET`) they have been processed by the target windows `WNDPROC`. You need to give the function a hook type (one of the two previous constants) and a hook function, which must look like:

```
LRESULT CALLBACK HookFunction(int code, WPARAM wparam, LPARAM lparam);

```

Your hook function will be called with the appropriate window message and parameters as given in the hook function signature. Be aware that your placement of the hook before or after the target window procedure impacts how you must handle the resulting messages, as the window may or may not have done things to reflect state differently based on whatever its own `WNDPROC` wants to do. You also may not be permitted to take action when your hook is called (if the code is negative, you must immediately invoke and return the value of `CallNextHookEx`.

Also, you'll need to put your hook code into shared memory since you're not hooking something in your own thread, and you'll need to be aware of the bitness (32 or 64) of both processes, because they have to match.

Overall it can be a bit tricky to deal with. There are some good posts on StackOverflow about using `SetWindowsHookEx` in various ways, such as this one dealing with the shared memory issue.

---

Since you control all the code involved here (as I understand it), I think you should avoid the trouble of `SetWindowsHookEx` and go with a socket-based approach. Alternatively you can create a control in the C++/CLI interop layer that talks directly to your engine code and manually pumps events for it using a variant of an `Application.Idle` event listener. That may require some rejiggering of how your engine's core loop is coupled to `SDL_PollEvents` though, so it's hard to say for sure how much work is involved without seeing more of your code.
> 1 votes

---
Tags: c++, sdl2, windows-forms, winapi, c++cli
---


# Question
Title: Control Unity Game loop to sync with external hardware/software
We would like to run the Unity Game Loop in sync with external hardware and applications running on a different computer. We want to arrive at something that work similar (but does not have to be identical to this).

1. Receive remote TCP packet with a list of new locations (etc.) for GameObjects \[For low latency, would we put this in a FixedUpdate loop, set at a high Hz?\] \[Is this best done in a \[Manager Singleton\]?\]
2. Send these updates from this "singleton" to all game objects \[One way might be to just have the object pick up the data in the Update cycle, which would happen after the fixedUpdate is done\]. \[Is a better idea to forget about the gameloop, and just use C# events to broadcast the updates to the gameobject attached scripts?\] Each GameObject will then update its location
3. Once all is stable (step #2 is completely done by all objects), we need to do measurements (scene read only) (with Raycast and LineCast) from each object to each other to see what is occluded and what is visible \[Can we rely on LateUpdate to run afterwards, or should we avoid the game loop\] \[How do we know that all gameobjects have finished updating?\]
4. Finally we need to post the visibility results back via a TCP packet.

The overall goal here is to make all four steps run as fast (back-to-back) as possible, Best would be to be able to speed up the frame rate (or slow it down) based on when each phase is done. But we can live with a fixed 60Hz if needed.

Other questions, have to do with the Async nature of TCP (or UDP) clients inside of Unity, and the issues of not being able to use the API from a separate thread (e.g. the async results of the TCP receive\]. Has anyone pointers to solutions to that?

We need no help writing the code, but the internal execution model of Unity3D at this level of detail is not clear in the manuals.

We think this has wide applicability for VR, AR, and various robot co-sync with games.

# Answer
> 0 votes
As @DMGregory points out, there are some very elegant ways to chain Coroutines to guarantee syncrhornization points at phases of computation (even with a large swarm of "virtually seperate threads" of execution running in each gameObject.

I encorage folks to read: http://forum.unity3d.com/threads/the-truth-about-fixedupdate.231637/

as well as: How to not freeze the main thread in Unity?

By using Update() and waitForEndOfFrame() for my tcp work and putting the rest in co-routines and lastDone, I can effecting seperate the 4 phases the computation and get about 1500FPS of externally clocked simulation, SWIL work done. I am impressed.

```
public class Tools
{
    public static string timeStamp()
    {
        return string.Format("{0} - {1:H:mm:ss.ffffff}", Time.time, System.DateTime.Now);
    }
}

public class TargetScript : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(CoDo());
    }
    void Update()
    {
        Debug.Log(string.Format("{0}: {1} update: {2}", Time.frameCount, gameObject.name, Tools.timeStamp()));
    }
    IEnumerator CoDo()
    {
        while (true)
        {
            yield return null;
            Debug.Log(string.Format("{0}: {1} codo: {2}", Time.frameCount, gameObject.name, Tools.timeStamp()));
        }

    }
    void LateUpdate()
    {
        Debug.Log(string.Format("{0}: {1} late:   {2}", Time.frameCount, gameObject.name, Tools.timeStamp()));
    }
    IEnumerator Done()
    {
        while (true)
        {
            yield return new WaitForEndOfFrame();
            Debug.Log(string.Format("{0}: {1} done: {2}", Time.frameCount, gameObject.name, Tools.timeStamp()));
        }
    }
}

```

# Answer
> 2 votes
That's not really how Unity works, you're not intended to directly control the `FixedUpdate` or `Update` or `LateUpdate` methods (but you can write your own methods). Also, `FixedUpdate` is named the way it is because it's supposed to run at a fixed timestep. Running it once whenever a network message comes in defeats the purpose of it being a fixed update.

Additionally you can't really run 20 or so methods "in parallel". Even spawning threads for each method is only going to have some wait while others are processed. If you're just looking for a on-command line-of-sight tester, Unity probably isn't the best technology choice. You'd be better off writing something without the overhead of an entire engine.

---
Tags: unity
---


# Question
Title: Box2D shape/fixture position vs. body position
I load my rectangular shapes from a simple Tiled level into libGDX and want to create a physics world out of it via Box2D and attach sprite assets for rendering.

I get the tiled object layer and iterate over it, create the objects and add it to the world:

```
    BodyDef bdef = new BodyDef();
    bdef.type = BodyDef.BodyType.DynamicBody;
    FixtureDef fdef = new FixtureDef();
    Shape shape;
    Sprite sprite = null;
    for(MapObject mo : layer.getObjects())
    {
       if (mo instanceof RectangleMapObject)
       {
         shape = getRectangle((RectangleMapObject) mo);
         sprite = new Sprite(box_texture, 0, 0, box_texture.getWidth(), box_texture.getHeight());
       }
       fdef.shape = shape;

       Body body = world.createBody(bdef);
       body.createFixture(fdef);

       if (sprite != null) {
             body.setUserData( sprite );
       }

        shape.dispose();
    }

    private Shape getRectangle(RectangleMapObject rectangleObject)
        {
            System.out.println("Loading rectangle from map file");

            Rectangle rectangle = rectangleObject.getRectangle();
            PolygonShape polygon = new PolygonShape();
            Vector2 size = new Vector2((rectangle.x + rectangle.width * 0.5f) / Config.PIXEL_PER_METER,
                    (rectangle.y + rectangle.height * 0.5f ) / Config.PIXEL_PER_METER);
            polygon.setAsBox(rectangle.width * 0.5f / Config.PIXEL_PER_METER,
                    rectangle.height * 0.5f / Config.PIXEL_PER_METER,
                    size,
                    0.0f);
            return polygon;
        }

```

The Box2D Debug Renderer shows everything fine. So, this works for Box2D.

But now I want to render the attached sprite for those object.

In render() I do it like:

```
    Gdx.gl.glClearColor(0, 0, 0.2f, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    handleInput();

    world.step(delta, 6, 3);

    // set camera to follow player
    gameCamera.position.set(
            player.getPosition().x * Config.PIXEL_PER_METER + Config.WIDTH / 4,
            Config.HEIGHT / 2,
            0
    );

    gameCamera.update();

    if(Config.DEBUG)     // move B2D camera with player
    {
        B2DCamera.position.set(
                player.getPosition().x + (Config.WIDTH / 4 / Config.PIXEL_PER_METER),
                (Config.HEIGHT/ 2 / Config.PIXEL_PER_METER),
                0
        );

        B2DCamera.update();
    }

sb.setProjectionMatrix(gameCamera.combined);
sb.begin();
            world.getBodies(tmp);
            for(Body b : tmp)
            {
               if(b.getUserData() != null && b.getUserData() instanceof Sprite)
               {
                        Sprite sprite = (Sprite) b.getUserData();
                        sprite.setPosition( b.getPosition().x * Config.PIXEL_PER_METER - sprite.getWidth() / 2, b.getPosition().y * Config.PIXEL_PER_METER - sprite.getHeight() / 2);
                        sprite.setRotation(b.getAngle() * MathUtils.radiansToDegrees);
                        sprite.draw(sb);
                    }
                }
sb.end();

if(Config.DEBUG)
   b2dr.render(world, B2DCamera.combined);

```

But the sprite rendering seems to be at the wrong place. While the Box2D debug draw is fine, the sprites are heavily off. I debugged it, and the box2d body position seems to be wrong. It's not a Pixel/Meter conversion issue, the values are not THAT wrong as far as I see, but also not just a rectangle length (more like randomly somewhere far away). I didn't set the body position explizitely, but implicitely via the recangle shape of the fixture. I thought that's sufficient. And DebugDraw was fine with that.

So, when I set the position of the body explicitly like this when creating the physics world:

```
bdef.position.x = mo.getProperties().get("x", Float.class) / Config.PIXEL_PER_METER;
bdef.position.y = mo.getProperties().get("y", Float.class) / Config.PIXEL_PER_METER;

```

and remove the position of the fixture like that:

```
polygon.setAsBox(rectangle.width * 0.5f / Config.PIXEL_PER_METER, rectangle.height * 0.5f / Config.PIXEL_PER_METER);

```

it seems to work well. Since it seems to be much easier for me to deal with shape and fixture positions than setting body position, I'd like to understand what's going wrong in my first run.

So, when I don't set the body position explicitly (but only the fixtures position via shape), why is the Box2D DebugRendering fine, where the sprites are not ? The Sprites draw on body's x/y pos, and this is not set correctly as far as I can see. But looking at the source of the DebugRenderer, it's also using body.getPosition() ? So I would expect this is also not working. But it does.

Any idea would be helpful. Maybe I just don't understand the concept of fixture position and body position ?

# Answer
> 1 votes
The fixture position in box2d is in relation to the body position. So if you set your fixture to be at (5, 5) the body is still at (0, 0) and if you then move the body to (1, 0), the fixture will then draw at (6, 5).

It looks like you are getting your sprite position from the Body position, not the fixture position in the original method. In the second one, you are setting the body, and leaving the fixture centered on it, so the sprites draw correctly.

---
Tags: libgdx, box2d, tiled
---


# Question
Title: How to add constant force to player with sperical gravity planet.?
I have a planet and character. My player move perfect around planet with pressing key like 'w','s','a and 'D'. I want to move my player on every frame with same force around sphere. I try plane surface constant force code like this `this.rigidbody.AddForce ( 3f,3f,3f);`, when start playing game this code work fine but after some movement it stop my player on specific position of planet. I want to use this code for 3D sphere.

Any one can help me how can add constant force to my player on 3d sphere.?

I want add constant force to player when game start. I don't want any kind of planet's orbits, because my player is moving on all over the planet.

I try below link but it did not working for me. How can i accurately simulate orbits in unity.?

**Here is my Sctipts**

**PlayerController.cs**

```
using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

public float moveSpeed = 10;
public Vector3 moveDir;
Rigidbody rigidbody;
// Update is called once per frame3

void Start(){
    rigidbody = GetComponent<Rigidbody> ();
}
void Update () {

    moveDir = new Vector3 (Input.GetAxisRaw("Horizontal")  ,0,Input.GetAxisRaw("Vertical"));
}
void FixedUpdate(){

    rigidbody.MovePosition (rigidbody.position + transform.TransformDirection(moveDir) * moveSpeed * Time.deltaTime);

 }
}

```

**FauxGravityBody.cs**

```
using UnityEngine;
using System.Collections;

[RequireComponent (typeof (Rigidbody))]
public class FauxGravityBody : MonoBehaviour {

public FauxGravityAttractor attractor;
public Transform myTransform;
Rigidbody rigidbody;

// Use this for initialization++
void Awake(){

    this.rigidbody = GetComponent<Rigidbody> ();

}
void Start () {
    myTransform = transform;
    rigidbody.useGravity = false;
    rigidbody.constraints = RigidbodyConstraints.FreezeRotation;
}

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

    attractor.Attract (myTransform);
  }
}

```

**FauxGravityAttractor.cs**

```
using UnityEngine;
using System.Collections;

public class FauxGravityAttractor : MonoBehaviour {

public float gravity = -10;
public void Attract(Transform body){

    Vector3 gravityUp = (body.position - transform.position).normalized;
    Vector3 bodyUp = body.up;

    body.GetComponent<Rigidbody>().AddForce (gravityUp * gravity);
    Quaternion targetRotation = Quaternion.FromToRotation (bodyUp, gravityUp) * body.rotation;
    body.rotation = Quaternion.Slerp (body.rotation, targetRotation, 50 * Time.deltaTime);
  }
}

```

I am working with this scripts, If any one help me? then please.

# Answer
> 1 votes
There is the Faux gravity system in Unity and it works with jumping as well. TThis is the youtube link - https://m.youtube.com/watch?v=gHeQ8Hr92P4&fulldescription=1&client=mv-google&gl=ZW&hl=en. The download link for the unity project seems to be dead though. Ive uploaded the project to my mediafire account. I'l also add it to github when i get on a PC. link - http://www.mediafire.com/download/o7w7mogd6w3a4jc/Faux\_Gravity\_Example.7z

Edit 1: Adding constand force- In order to add a constant force to the player object, in the Player Controller script, edit the update method. Replace all the code in update with this

`moveDirection = new Vector3(1,0,1);`

I suggest you take a look at some basic C# tutorials before jumping into Unity. If this is for a school project or assignment, you wont learn much doing things this way. good luck.

---
Tags: unity, c#, 3d, rigidbody, physics
---