# Question
Title: javascript game camera that follows my player
I am experimenting with game developement here but my player disapears my player is alowed to just walk of the screen and never be seen again so i was wondering if someone could help me with adding a camera to my game that folows the player and keeps him centered on the screen but allows him to walk to the wall instead of just stopping here is my game code :)

```
<html>

<body>
    <canvas id="canvas">
        </canvas>
</body>

</html>
<script>
    var audio = new Audio('sounds/theServerRoom.mp3');
    audio.play();

    // Create the canvas
    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    document.body.appendChild(canvas);

    // Background image
    var bgReady = false;
    var bgImage = new Image();
    bgImage.onload = function() {
        bgReady = true;
    };
    bgImage.src = "images/gamemap.png";

    //computer
    var computerReady = false;
    var computerImage = new Image();
    computerImage.onload = function() {
        computerReady = true;
    };
    computerImage.src = "images/computer1.png";
    //hp box
    var hpBoxReady = false;
    var hpBoxImage = new Image();
    hpBoxImage.onload = function() {
        hpBoxReady = true;
    };
    hpBoxImage.src = "images/hpbox.png";
    // player image
    var playerReady = false;
    var playerImage = new Image();
    playerImage.onload = function() {
        playerReady = true;
    };
    playerImage.src = "images/char.png";

    // enemy image
    var enemyReady = false;
    var enemyImage = new Image();
    enemyImage.onload = function() {
        enemyReady = true;
    };
    enemyImage.src = "images/enemy_idle01.png";

    var computer = {
            wifi: true,
            x: 399,
            y: 200
        }
        // Game objects
    var hpBox = {
        restoreHealth: 34,
        x: 300,
        y: 300
    }
    var player = {
        hackingSkill: 10,
        stamina: 7,
        health: 100,
        sprintSpeed: 400,
        weakSpeed: 150,
        speed: 300 // movement in pixels per second
    };
    var enemy = {
        speed: 250,
        viewDistance: 40
    };
    var enemysCaught = 0;

    // Handle keyboard controls
    var keysDown = {};
    addEventListener("keydown", function(e) {
        keysDown[e.keyCode] = true;
    }, false);

    addEventListener("keyup", function(e) {
        delete keysDown[e.keyCode];
    }, false);

    // Reset the game when the player catches a enemy
    var reset = function() {
        player.x = canvas.width / 2;
        player.y = canvas.height / 2;

        // Throw the enemy somewhere on the screen randomly
        enemy.x = 32 + (Math.random() * (canvas.width - 64));
        enemy.y = 32 + (Math.random() * (canvas.height - 64));
    };

    //w is 87
    //a is 65
    //s is 83
    //d is 68
    // Update game objects
    var update = function(modifier) {
        if (87 in keysDown) { // Player holding up
            player.y -= player.speed * modifier;
        }
        if (83 in keysDown) { // Player holding down
            player.y += player.speed * modifier;
        }
        if (65 in keysDown) { // Player holding left
            player.x -= player.speed * modifier;
        }
        if (68 in keysDown) { // Player holding right
            player.x += player.speed * modifier;
        }

        if (
            player.x <= (0)) {
            player.health -= 1;
            console.log('health decreasing');
        }
    }
    if (
        player.y <= (0)) {

        player.health -= 1;
        console.log('health decreasing');
    };

    // Are they touching?
    if (
        player.x <= (enemy.x + 32) &&
        enemy.x <= (player.x + 32) &&
        player.y <= (enemy.y + 32) &&
        enemy.y <= (player.y + 32)
    ) {
        ++enemysCaught;
        reset();
    }

    // Draw everything
    var render = function() {
        if (bgReady) {
            context.drawImage(bgImage, 0, 0);
        }
        if (computerReady) {
            context.drawImage(computerImage, computer.x, computer.y);
        }

        if (hpBoxReady) {
            context.drawImage(hpBoxImage, hpBox.x, hpBox.y);
        }
        if (playerReady) {
            context.drawImage(playerImage, player.x, player.y);
        }

        if (enemyReady) {
            context.drawImage(enemyImage, enemy.x, enemy.y);
        }

        // Score
    };

    function dieEvent() {
        player.health = 100;
    }

    function updateHealth() {
        context.fillStyle = "#FF0000";
        context.fillRect(10, 10, (player.health / 100) * 140, 25);
        context.stroke();
        context.fillStyle = "white";
        context.textAlign = "left";
        context.fillText("Health: " + player.health, 30, 32);
    }

    function updateHackerSkill() {
        context.fillStyle = "green";
        context.textAlign = "left";
        context.fillText("hacker skill: " + player.hackerSkill, 30, 32);
        context.fillStyle = "#FF0000";
        context.fillRect(10, 10, (player.hackerSkill / 100) * 1, 45);
        context.stroke();
    }

    function isNearComputer() {
        if (player.y <= (computer.y + enemy.viewDistance + 23) &&
            player.y >= (computer.y - enemy.viewDistance) &&
            player.x <= (computer.x + enemy.viewDistance + 32) &&
            player.x >= (computer.x - enemy.viewDistance)) {
            console.log("near computer");
            context.fillStyle = "black";
            context.fillRect(0, 0, canvas.width, canvas.height);
            context.stroke();
            context.fillStyle = "green";
            context.font = "24px Helvetica";
            context.textAlign = "left";
            context.textBaseline = "top";
            context.fillText("Welcome to uOS v1.0 ", 20, 10);
            window.setTimeout(500);
            context.fillText("user$> ", 20, 35);

        }

    }

    function isNearHPBox() {

        if (
            player.y <= (hpBox.y + enemy.viewDistance + 64) &&
            player.y >= (hpBox.y - enemy.viewDistance - 64) &&
            player.x <= (hpBox.x + enemy.viewDistance + 64) &&
            player.x >= (hpBox.x - enemy.viewDistance - 64)) {
            console.log("healing!");
            if (player.health <= 100) {
                hpBox.restoreHealth = player.health - 100;
                player.health += hpBox.restoreHealth;
            }

        }

    }

    function moveEnemy() {
        if (
            player.y <= (enemy.y + enemy.viewDistance + 64) &&
            player.y >= (enemy.y - enemy.viewDistance - 64) &&
            player.x <= (enemy.x + enemy.viewDistance + 64) &&
            player.x >= (enemy.x - enemy.viewDistance - 64)) {
            console.log("seen on enemys Y");
            var audio = new Audio('sounds/theWanderer_Scream.m4a');
            audio.play();
            if (player.x >= (enemy.x)) {
                enemy.x -= enemy.speed;
            }
            if (player.x >= (enemy.x)) {
                enemy.x -= enemy.speed;
            }
        }
    }

    function checkWallCollision() {
        if (player.y <= 0) {
            console.log("y")
            player.y += 64;
        }
        if (player.x <= 0) {
            console.log("x")
            player.x += 64;
        }
        if (enemy.y <= 0) {
            console.log("y")
            enemy.y += 64;
        }
        if (enemy.x <= 0) {
            console.log("x")
            enemy.x += 64;
        }
    }

    //   function updateMouseCoords(){
    //           document.onmousemove = function(e){
    //           cursorX = e.pageX;
    //           cursorY = e.pageY;
    //           context.fillStyle = "green";
    //           context.font = "24px WhiteRabbit";
    //           context.textAlign = "left";
    //           context.textBaseline = "top";
    //           context.fillText("x" + cursorX + "y" + cursorY , 20 ,10);
    //
    //       }
    //   }
    //   function drawViewLine(){
    //       var cursorX;
    //       var cursorY;
    //      context.beginPath();
    //     context.moveTo(player.x,player.y);
    //      context.lineTo(cursorX,cursorY);
    //     context.stroke();
    //     console.log("drawing line")
    // }
    function reducedSpeed() {
        player.speed = player.weakSpeed;
    }
    // The main game loop
    var main = function() {
        var now = Date.now();
        var delta = now - then;
        update(delta / 1000);
        context.clearRect(0, 0, canvas.width, canvas.height);
        render();
        updateHealth();
        moveEnemy();

        if (player.health <= 20) {
            reducedSpeed();
        } else {
            player.speed = 300;
        }
        if (player.health <= 0) {
            dieEvent();
        }

        checkWallCollision();
        isNearHPBox();
        isNearComputer();
        //updateMouseCoords();
        //drawViewLine();
        then = now;

        // Request to do this again ASAP
        requestAnimationFrame(main);
    };

    // Cross-browser support for requestAnimationFrame
    var w = window;
    requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

    // Let's play this game!
    var then = Date.now();
    reset();
    main();
</script>
<style>
    @font-face {
        font-family: WhiteRabbit;
        src: url(http://billischill.ddns.net/fonts/whiterabbit.ttf);
        font-weight: normal;
        font-style: normal;
    }

    body {
        margin: 0;
        padding: 0;
    }
</style>

```

could one of you guys please help me :)

# Answer
A quick way to implement camera scrolling on a canvas is by using `context.translate`. It changes the origin-point of the canvas for future draw calls. So when you call \`context.translate(100, 200), for example, everything drawn afterwards will be moved 100 pixels to the left and 200 pixels up. So to always keep the player in the center, call

```
context.save();
context.translate(player.x - canvas.width / 2, player.y - canvas.height / 2);

// ...your drawing code...

context.restore();

```

Restore and save are required because otherwise the translations will accumulate.

By the way, you can also do camera zoom with `context.scale` and camera rotation with `context.rotate`.
> 4 votes

# Answer
You can try implementing this (Camera movement, Draw grid) idea into your game. So the main idea is to only the part that you want to be drawn in relation to the player's position (in my answer linked above I actually turned it into an illusion so as to avoid drawing the player on the much larger background layer).

Now to implement this you would take half the screen from the player's position when clearing the canvas from the main world canvas. Like so:

```
ctx.clearRect(player_position_x - (camera_width/2), player_position_y - (camera_height/2), camera_width, camera_height)

```

This will draw a box around the player and center him/her onto the screen. So you do this each frame the player moves.

Just check the answer mentions above for more info.
> 0 votes

---
Tags: javascript, camera, html-canvas, html
---


# Question
Title: how to change floor sprite in unreal engine
I have started a 2D side scrolling game in Unreal Engine from the menu when you start a new game. The basic environment loads up and it works but I don't know how to change the floor sprites and player sprites. Please Help.

# Answer
A Paper2D sprite is simply a plane with a material. Have you tried changing the material on your sprites?

https://docs.unrealengine.com/latest/INT/Engine/Paper2D/Sprites/
> 1 votes

---
Tags: sprites, unreal-4, unreal
---


title: Map with media texture not packaging

text:
# Question
Title: Map with media texture not packaging
I have a simple map with a Big-sphere and a pawn inside it. I use media texture and media player to play 360 video on it. But when I try to package it for windows-64 it fails while it tries to cook the map.

Yes all the videos are copied to Content/Movies first and then imported to UEProject as asset later.

This is very crucial to our project. One of our developer have already started to build the solution in Unity just in case if packaging issue does not resolve with media player in unreal.

Please help!

# Answer
> 0 votes
There seem to be some problems with media textures, file formats and memory size:

https://answers.unrealengine.com/questions/378202/media-texture-not-showing-in-umg-after-packaging.html

Please paste the packaging failure message, it should help identify the problem.

---
Tags: unreal-4, unreal, 360-video
---


# Question
Title: how to dent & deform damaged objects in unreal engine?
I am trying to simulate damages in cars using unreal engine when a body collides with it like it is done in this video - https://vimeo.com/162729920

I am trying to do it in the first person shooter game template, so that i can shoot projectiles at the object. but the object just moves and doesn't dent. I tried creating a destructible mesh but that cause the object to break down into pieces. I want it to dent when i apply a force to it. Could someone point me in the right direction?

# Answer
> 1 votes
Softbody physics is definitely an option, although it requires a special engine build that contains Nvidia Flex (https://github.com/NvPhysX/UnrealEngine/tree/FleX \- you will need to be allowed to view the UE4 github as well). But it's not the best option.

Another option is to use the Runtime Mesh Component plugin; when a projectile hits a vehicle part, a new mesh is dynamically created from the hit vehicle part, your code deforms the new mesh how you want, then it is shown on the vehicle.

Making your vehicle from multiple meshes that all have the same root position, lets you use either dynamically-deformed meshes OR predeformed static meshes. These two methods would be my suggestions.

---
Tags: rendering, 3d-meshes, unreal-4, destructables
---


title: Single-face, Multi-plane geometry?

text:
# Question
Title: Single-face, Multi-plane geometry?
I'm just getting started with 3D so I'm not sure what's this is called. If I move a point in a polygon out of alignment with the other points in the polygon, such that is would be on a separate plane, what do you call it? What are the implications of doing so? Should this be avoided? Does this affect CPU? rendering? Is this universally supported by hardware and WebGL?

In my example, I have essentially turned a square plane into two triangular planes, creating a "v" in the middle of a cube. It appears that both triangles belong to a single face on the cube.

# Answer
> 1 votes
There may be a more specific term I'm not aware of, but I'd just refer to that as a non-planar polygon. You do want to avoid that for real-time rendering (not all video cards support that nicely) which is why many game engines automatically triangulate the mesh; a triangle is always planar after all.

In other words, you don't necessarily need to care about that as a 3D artist, because the code will handle it automatically.

---
Tags: 3d, blender
---


title: Drawing roads on heightmaps

text:
# Question
Title: Drawing roads on heightmaps
I've been running into walls for the past week or so on my toy project in UE4. My goal is to draw procedural roads on a procedural landscape (eventually getting to intersections and buildings). The landscape is generated with libnoise and the roads are generated with a slightly modified version of the algorithm found here.

But I'm having issues draping the roads on the landscape and I can't find any straightforward algorithmic way of doing it. You can see my problem below: the geometry of the road intersects the geometry of the landscape.

In short, given:

* The landscape index buffer
* The landscape vertex buffer
* Every road segment's `X,Y,Z` coordinate

How do I modify the underlying vertex/index buffer so that the landscape "wraps around" the roads?

# Answer
> 2 votes
I would suggest modifying the engine to expose the Landscape functions. Then add a button to the Landscape tool palette, to force a terrain rebuild after placing roads. Terraim rebuild routine could look at the manual painting mechanisms, to see how to correctly modify vertex position.

This is not a trivial matter indeed.

Without this, I feel the best solution is to make the road always above terrain level, then fill around the road with static meshes so it avoids "floating mesh" issues.

# Answer
> 1 votes
When you place a road, you need to subdivide it into triangles based on the terrain triangles under it.

Let's forget the y axis for a moment, and do things as if they were in 2d.

First of all, get the AABB of the road, extend it in each direction a bit to avoid not checking some terrain triangles.

Next you need to get every triangle that at least partially intersects with the road. If your terrain is out of squares, then this is going to be very easy. If it isn't, then use AABBs once again. You don't need to make sure the triangle intersects with the road, you just need the triangles that could intersect with it.

Now you want to get intersection points of the triangle edges and the road's edges. Take the intersection points and add them to a list. If a corner of a triangle is inside the road, add that one too.

Now, you have the intersection points, make them line up with the terrain and use a triangulisation algorithm to convert it into polygons. The result should perfectly line up with the terrain.

# Answer
> 0 votes
Obviously no one correct answer for this. I worked on a game at Sony where we had to solve this exact problem. One solution is that you'll develop a strategy where you generate road geometry that follows the procedural geometry at the triangle level, possibly even down to computing split triangles, then give it some thickness and a curb.

---
Tags: unreal-4, heightmap, algorithm
---


# Question
Title: Why doesn't the current player on the server spawn after a new client connects?
I have a running server that can change maps. When a client joins the server, it automatically loads the scene because the server uses `ServerChangeScene ()` to change the scene.

The problem is that the client does spawn the objects on the server, but it spawns them on the first scene it loads into. How can I make it spawn the objects on the actual scene it loads into?

# Answer
> 0 votes
So I fixed my own problem. The reason the server does not spawn the players for the other clients *is* that the objects are spawned on the first scene instead of the actual scene the client needs to load. The solution to my problem was to make sure the clients are set unready before loading the new scene, and then set them ready once they load the new server. Use methods like `NetworkServer.SetAllClientsNotReady()` and `ClientScene.Ready()`

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


title: Help with a snake like movement

text:
# Question
Title: Help with a snake like movement
I am looking for an algorithm that moves an object at a regular speed in a snake-circular like movement. This movement should look pseudo-random and smooth, later on I am going to add other body parts, but so far this is the essential.

My try so far has consisted in having a random value t that chages each frame:

t= Random.Range(t-20f,t+20f);

and according to it I was employing a direction. The result should be more directions that are smoothly different, so that the movement itself is smooth.

I would score the solution with 7/10, and moreover, it doesn't describe like short circles, but rather larger ones and the negative result is that the object exits the scene quite fast.

What is your algorithm solution? On the internet I found solutions where the player moves the head of the snake, but here the object acts like an autonomous object.

# Answer
I would recommend using the wander algorithm. You can find a code sample here and here.

This is the result of Rusildo's answer::
> 1 votes

---
Tags: unity, movement
---


# Question
Title: Missing Reference exception when accessing a GameObject in Unity
I have been making a C# script that attacks the player in Unity. However, with the following code I got the following error message:

> "The object of type 'GameObject' has been destroyed but you are still trying to access it.

Here is my code:

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

public class attackPlayer : MonoBehaviour {

    GameObject Enemy;
    GameObject Player;

    void Start ()
    {
        Enemy =  GameObject.FindWithTag ("Enemy");
        Player = GameObject.FindWithTag ("Player");
    }

    void Update ()
    {
        var heading = Enemy.transform.position.x - Player.transform.position.x;
        if (heading > 0.0f && heading < 5.0f)
        {
            Explode ();
        }
    }

    void Explode()
    {
        var exp = GetComponent <ParticleSystem>();
        exp.Play ();

        Destroy (gameObject,exp.main.duration);
        Destroy(Player);
    }

    void OnCollisionEnter2D (Collision2D col)
    {
        if (col.gameObject.tag == "Player")
        {
            Explode ();
        }
    }
}

```

# Answer
> 1 votes
In `Explode`, you destroy the `Player` game object. In `Update`, you calculate the distance between the enemy and the player: `var heading = Enemy.transform.position.x - Player.transform.position.x;`. This calculation still references the player, which is destroyed in `Explode`.

I'm not very familiar with Unity techniques on handling this, but I could see that one solution is to set `Player = null;` after calling `Destroy(Player);` and checking if `Player` is not `null` in `Update` before doing the calculation.

---
Tags: unity
---


# Question
Title: Creating a Simple Puzzle resolution Algorithm
I develop a (really) simple puzzle game that asks you to join a point A to a B (enter/exit) using a ball and mechanisms that you can rotate to give the correct direction to the ball in order to join the exit.

**Here is screenshots of a simple level, showing clearly the purpose of the game:**

1) New level started, the mechanisms are rotated in a random way:

2) Level is completed, all the mechanisms are rotated properly to give the ball the right path to join the exit:

**Question:**

How can I create an algorithm allowing me to automatically generate levels by taking into account the rotations and leaving only one possibility for the player to complete the level?

I'd also like to add more complexity by adding more mechanisms (to create creating difficulty levels).

I don't think it's necessary to talk about tech, but I'm using C# and Unity.

Let me know if you need more information.

Thank you!

# Answer
> 1 votes
Backtracking.

1. Place a mechanism which aims at the goal from a random direction and a random distance. Have it face randomly so the ball needs to come from either the right or the left to get directed to the goal.
2. Then another one at a random distance which aims at the previously placed mechanism's input, again with its own input randomly facing right or left.
3. Repeat step two. The number of iterations depends on the desired difficulty.
4. Place the start so it faces the last placed mechanism. You now have a solved puzzle.
5. (optional) place some more random mechanism which aim at the opposite of the output of a random one of the existing mechanisms. These are "red herrings" which are not needed to solve the puzzle and only serve the purpose to confuse the player.
6. Then rotate each rotator into a random direction so the player has to guess how to rotate them.

---
Tags: puzzle, algorithm
---


# Question
Title: Proper way of loading Image/Texture Sprites on GameScreen in LibGDX?
Good day everybody I'm new to this framework **LibGdx**. I need advice/suggestion for my game.Is it okay if I load my images in a single class? I'm a beginner and start learning LibGdx. I already coded my game screen and it works perfectly as I expected. My concern is how about the performance of this in other device? I don't know how to implement `Assetmanager`.

Here is my code it works fine but I think it is not the proper way of loading images. Any suggestion help are much appreciated :)

```
public class IngamedayOne implements Screen ,InputProcessor {
final MyGdxGame game;
// Constant rows and columns of the sprite sheet
private static final int FRAME_COLS = 5, FRAME_ROWS = 1;
private boolean peripheralAvailable;
private static final float ACCELERATION     = 20f;
// Objects used
Animation<TextureRegion> walkAnimation; // Must declare frame type (TextureRegion)
Texture  left_paw,right_paw,progressbar_background,progressbar_knob,pause,meter,open_box;
Texture carpet,desk,plants,square_carpet,pauseImg,pause_cancel,retry,dayselect_img,household_select,back_to_main_menu;

SpriteBatch spriteBatch;
Sprite catsprite,sprite_shoes,sprite_plant,sprite_ball,dogsprite;
private  Texture Background1,Background2,Background3;
float yMax, yCoordBg1, yCoordBg2,yCoordDesk;
final int BACKGROUND_MOVE_SPEED = -200;

ImageButton left_paw_btn,right_paw_btn,pause_btnDialog,pause_btn_exit,retry_btn,dayselect_btn,select_household,back_to_main_menu_btn;
Image pauseImg_text;
Viewport viewport;
private Stage stage;
// A variable for tracking elapsed time for the animation
float stateTime;
private TextureRegion myTextureRegion;
TextureRegion textureRegion;
private TextureRegionDrawable myTexRegionDrawable;
private boolean isPause;
private Group pauseGroup;
Texture cat,dog;

private float yPosition = -40;
//Screen Size
OrthographicCamera camera;
float catSpeed = 50.0f; // 10 pixels per second.
float catX;
float catY;
float x=0,y=0;

public IngamedayOne(final MyGdxGame game) {
    this.game = game;
    Gdx.input.setCatchBackKey(false);
    Gdx.graphics.setContinuousRendering(false);
    Gdx.graphics.requestRendering();
    stage = new Stage(new StretchViewport( 720, 1280));
    camera = new OrthographicCamera(1280 ,720);
    camera.update();

    camera.setToOrtho(false, 720, 1280);
    camera.translate( 1280/2, 720/2 );
    Gdx.input.setInputProcessor(stage);
    spriteBatch = new SpriteBatch();
    viewport = new StretchViewport(720, 1280);
    Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

    // Load the sprite sheet as a texture
    cat = new Texture(Gdx.files.internal("cat.png"));
    catsprite = new Sprite(cat);
    catX=300;
    catY=0;

    dog = new Texture(Gdx.files.internal("equip/Dog.png"));
    dogsprite = new Sprite(dog);
    dogsprite.setPosition(20,580);

    Gdx.input.setInputProcessor( this);
    peripheralAvailable = Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer);
    int orientation = Gdx.input.getRotation();
    Input.Orientation nativeOrientation = Gdx.input.getNativeOrientation();

    viewport = new StretchViewport(720, 1280);
    Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    //Display Items
    carpet = new Texture("equip/carpet2.png");
    desk = new Texture("equip/Desk.png");
    open_box = new Texture("equip/open box.png");

    square_carpet = new Texture("equip/Carpet.png");

    plants = new Texture("equip/Plants.png");
    sprite_plant = new Sprite(plants);

    sprite_shoes = new Sprite(new Texture("equip/Shoes.png"));
    sprite_shoes.setPosition(260,580);

    sprite_ball = new Sprite(new Texture("equip/Basketball.png"));
    sprite_ball.setPosition(260,300);
    // Progressbar
    progressbar_background = new Texture("progression_map.png");
    progressbar_knob = new Texture("cat_head.png");
    //pause
    pause = new Texture("pause.png");
    myTextureRegion = new TextureRegion(pause);
    myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
    pause_btnDialog = new ImageButton(myTexRegionDrawable); //Set the button up
    pause_btnDialog.setPosition(580,1150);

    stage.addActor(pause_btnDialog); //Add the button to the stage to perform rendering and take input.
    Gdx.input.setInputProcessor(stage);
    pause_btnDialog.addListener(new ChangeListener() {
        public void changed (ChangeEvent event, Actor actor) {
            System.out.println("Pause Button Pressed");
            //Show Pause Screen menu
            pause();
        }
    });
    stage.addActor(pause_btnDialog);
    meter = new Texture("meter.png");
    //background
    Background1 = new Texture(Gdx.files.internal("floor.png"));
    Background2 = Background1;
    yMax = -1270;
    yCoordBg1 = yMax*(-1);
    yCoordBg2 = 0;
    yCoordDesk = 0;

    // Use the split utility method to create a 2D array of TextureRegions. This is
    // possible because this sprite sheet contains frames of equal size and they are
    // all aligned.

    TextureRegion[][] tmp = TextureRegion.split(cat, cat.getWidth() / FRAME_COLS, cat.getHeight()/ FRAME_ROWS);
    // Place the regions into a 1D array in the correct order, starting from the top
    // left, going across first. The Animation constructor requires a 1D array.
    TextureRegion[] walkFrames = new TextureRegion[FRAME_COLS * FRAME_ROWS];
    int index = 0;
    for (int i = 0; i < FRAME_ROWS; i++) {
        for (int j = 0; j < FRAME_COLS; j++) {
            walkFrames[index++] = tmp[i][j];
        }
    }

    // Initialize the Animation with the frame interval and array of frames
    walkAnimation = new Animation<TextureRegion>(0.200f, walkFrames);
    // Instantiate a SpriteBatch for drawing and reset the elapsed animation
    // time to 0
    spriteBatch = new SpriteBatch();
    stateTime = 0f;

    //left_control
    left_paw = new Texture(Gdx.files.internal("left_paw.png"));
    myTextureRegion = new TextureRegion(left_paw);
    myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
    left_paw_btn = new ImageButton(myTexRegionDrawable); //Set the button up
    left_paw_btn.setPosition(10,25);

    stage.addActor(left_paw_btn); //Add the button to the stage to perform rendering and take input.
    Gdx.input.setInputProcessor(stage);

    left_paw_btn.addListener(new InputListener(){
        @Override
        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("Left Button Pressed");
            //Start Animation
        }
        @Override
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
            return true;
        }
    });
    stage.addActor(left_paw_btn);
    //right_control
    right_paw = new Texture(Gdx.files.internal("right_paw.png"));
    myTextureRegion = new TextureRegion(right_paw);
    myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
    right_paw_btn = new ImageButton(myTexRegionDrawable); //Set the button up
    right_paw_btn.setPosition(517,25);

    stage.addActor(right_paw_btn); //Add the button to the stage to perform rendering and take input.
    Gdx.input.setInputProcessor(stage);
    right_paw_btn.addListener(new InputListener(){
        @Override
        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("Right Button Pressed");
            //Start Animation
            stateTime += Gdx.graphics.getDeltaTime(); // Accumulate elapsed animation time
            camera.update();
        }
        @Override
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
            return true;
        }
    });
    stage.addActor(right_paw_btn);
}
public enum State
{
    PAUSE,
    RUN,
    RESUME,
    STOPPED
}
private State state = State.RUN;
@Override
public void show() {
}
@Override
public void render(float delta) {
    // clear previous frame
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Clear screen
    stateTime += Gdx.graphics.getDeltaTime(); // Accumulate elapsed animation time
    yCoordBg1+= BACKGROUND_MOVE_SPEED * Gdx.graphics.getDeltaTime();
    yCoordBg2 = yCoordBg1 + yMax;  // We move the background, not the camera
    yCoordDesk = BACKGROUND_MOVE_SPEED * Gdx.graphics.getDeltaTime();
    if (yCoordBg1 <= 2) {
        yCoordBg1 = yMax*(-1);
        yCoordBg2 = 0;
    }
    spriteBatch.begin();
    if(this.state==State.RESUME);
    stateTime += Gdx.graphics.getDeltaTime();
    TextureRegion currentFrame = walkAnimation.getKeyFrame(stateTime, true);
    spriteBatch.setProjectionMatrix(camera.combined);

    spriteBatch.draw(Background1, 0,yCoordBg1);
    spriteBatch.draw(Background2, 0,yCoordBg2);
    //spriteBatch.draw(square_carpet,150,2,408,800);
    //spriteBatch.draw(carpet,230,980,250,260);
    //sprite_shoes.draw(spriteBatch);
    spriteBatch.draw(open_box,490,690);
    sprite_ball.draw(spriteBatch);
    dogsprite.draw(spriteBatch);
    spriteBatch.draw(currentFrame,catX,catY); // Draw current frame at (50, 50)
    // spriteBatch.draw(desk,10,1150,160,260);
     //spriteBatch.draw(plants,500,700,200,260);
    spriteBatch.draw(meter,190,990);
    spriteBatch.draw(progressbar_background,20,1170);
    spriteBatch.draw(progressbar_knob,18,1170);

        //Moving player on desktop
        if (Gdx.input.isKeyPressed(Input.Keys.LEFT))
            catX -= Gdx.graphics.getDeltaTime() * catSpeed;
        if (Gdx.input.isKeyPressed(Input.Keys.RIGHT))
            catX += Gdx.graphics.getDeltaTime() * catSpeed;
        if (Gdx.input.isKeyPressed(Input.Keys.UP))
            catY += Gdx.graphics.getDeltaTime() * catSpeed;
        if (Gdx.input.isKeyPressed(Input.Keys.DOWN))
            catY -= Gdx.graphics.getDeltaTime() * catSpeed;
        //Mobile acceleration
        if (Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer)) {
            catX -= Gdx.input.getAccelerometerX();
            catY += Gdx.input.getAccelerometerY();
        }
    if (catY > Gdx.graphics.getHeight() - 100) {
        catY = Gdx.graphics.getHeight() - 100;
    }
        if (catX < 0) {
            catX = 0;
        }
        if (catX > Gdx.graphics.getHeight() - 250) {
            catX = Gdx.graphics.getHeight() - 250;
        }
    if(this.state==State.RESUME) {
        switch (state) {
            case RUN:
                //do suff here
                break;
            case PAUSE:
                break;
            case RESUME:
                break;
            default:
                break;
        }
    }
    spriteBatch.end();
    stage.act(); //acting a stage to calculate positions of actors etc
    stage.draw(); //drawing it to render all
}
// Check if Polygon intersects Rectangle
// Check if Polygon intersects Circle
private boolean isCollision(Polygon polygon, Circle c) {
    float[] vertices = polygon.getTransformedVertices();
    Vector2 center = new Vector2(c.x, c.y);
    float squareRadius = c.radius * c.radius;
    for (int i = 0; i < vertices.length; i += 2) {
        if (i == 0) {
            if (Intersector.intersectSegmentCircle(new Vector2(
                    vertices[vertices.length - 2],
                    vertices[vertices.length - 1]), new Vector2(
                    vertices[i], vertices[i + 1]), center, squareRadius))
                return true;
        } else {
            if (Intersector.intersectSegmentCircle(new Vector2(
                    vertices[i - 2], vertices[i - 1]), new Vector2(
                    vertices[i], vertices[i + 1]), center, squareRadius))
                return true;
        }
    }
    return false;
}
@Override
public void resize(int width, int height) {
    viewport.update(width, height);
    camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);
}
@Override
public void pause() {
    this.state = State.PAUSE;
    pauseGroup = new Group();
    Image semiTransparentBG=new Image(new Texture(Gdx.files.internal("backgroundimage.png")));
    // setSize(Size of screen) and make it semi transparent.
    pauseGroup.addActor(semiTransparentBG);
    //create all other pause UI buttons with listener and add to pauseGroup
    //cancel
    pause_cancel = new Texture(Gdx.files.internal("pausemenu/exit.png"));
    myTextureRegion = new TextureRegion(pause_cancel);
    myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
    pause_btn_exit = new ImageButton(myTexRegionDrawable); //Set the button up
    pause_btn_exit.setPosition(550,1130);

    stage.addActor(pause_btn_exit); //Add the button to the stage to perform rendering and take input.
    Gdx.input.setInputProcessor(stage);
    pause_btn_exit.addListener(new InputListener(){
        @Override
        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("Cancel Button Pressed");
            resume();
        }
        @Override
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
            return true;
        }
    });
    stage.addActor(pause_btn_exit);
    pauseGroup.addActor(pause_btn_exit);

    pauseImg = new Texture(Gdx.files.internal("pausemenu/pause_text.png"));
    myTextureRegion = new TextureRegion(pauseImg);
    myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
    pauseImg_text = new Image(myTexRegionDrawable); //Set the button up
    pauseImg_text.setPosition(260,970);
    pauseGroup.addActor(pauseImg_text);

    //retry
    retry = new Texture(Gdx.files.internal("pausemenu/retry.png"));
    myTextureRegion = new TextureRegion(retry);
    myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
    retry_btn = new ImageButton(myTexRegionDrawable); //Set the button up
    retry_btn.setPosition(200,700);

    stage.addActor(retry_btn); //Add the button to the stage to perform rendering and take input.
    Gdx.input.setInputProcessor(stage);
    retry_btn.addListener(new InputListener(){
        @Override
        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("Button Pressed");
            //resume
            game.setScreen(new IngamedayOne(game));
        }
        @Override
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
            return true;
        }
    });
    stage.addActor(retry_btn);
    pauseGroup.addActor(retry_btn);
    //Day Select
    dayselect_img = new Texture(Gdx.files.internal("pausemenu/day_select.png"));
    myTextureRegion = new TextureRegion(dayselect_img);
    myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
    dayselect_btn = new ImageButton(myTexRegionDrawable); //Set the button up
    dayselect_btn.setPosition(180,490);
    stage.addActor(dayselect_btn); //Add the button to the stage to perform rendering and take input.
    Gdx.input.setInputProcessor(stage);
    dayselect_btn.addListener(new InputListener(){
        @Override
        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
            System.out.println(" Button Pressed");
            game.setScreen(new SelectDiffculty(game));
        }
        @Override
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
            return true;
        }
    });
    stage.addActor(dayselect_btn);
    pauseGroup.addActor(dayselect_btn);
    //House Select
    household_select = new Texture(Gdx.files.internal("pausemenu/household_select.png"));
    myTextureRegion = new TextureRegion(household_select);
    myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
    select_household = new ImageButton(myTexRegionDrawable); //Set the button up
    select_household.setPosition(180,300);

    stage.addActor(select_household); //Add the button to the stage to perform rendering and take input.
    Gdx.input.setInputProcessor(stage);
    select_household.addListener(new InputListener(){
        @Override
        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
            System.out.println(" Button Pressed");
            //resume
            game.setScreen(new SelectHouseHold(game));

        }
        @Override
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
            return true;
        }
    });
    stage.addActor(select_household);
    pauseGroup.addActor(select_household);
    //Back to main menu
    back_to_main_menu = new Texture(Gdx.files.internal("pausemenu/back_to_main_menu.png"));
    myTextureRegion = new TextureRegion(back_to_main_menu);
    myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
    back_to_main_menu_btn = new ImageButton(myTexRegionDrawable); //Set the button up
    back_to_main_menu_btn.setPosition(40,80);
    stage.addActor(back_to_main_menu_btn); //Add the button to the stage to perform rendering and take input.
    Gdx.input.setInputProcessor(stage);
    back_to_main_menu_btn.addListener(new InputListener(){
        @Override
        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
            System.out.println(" Button Pressed");
            //resume
            game.setScreen(new MainScreen(game));
        }
        @Override
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
            return true;
        }
    });
    stage.addActor(back_to_main_menu_btn);
    pauseGroup.addActor(back_to_main_menu_btn);
    stage.addActor(pauseGroup);
}

@Override
public void resume() {
    this.state = State.RESUME;
    pauseGroup.remove();
}
@Override
public boolean keyDown(int keycode) {
    return true;
}
@Override
public boolean keyUp(int keycode) {
    return false;
}
@Override
public boolean keyTyped(char character) {
    return false;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    return false;
}

@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
    return false;
}

@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
    return false;
}

@Override
public boolean mouseMoved(int screenX, int screenY) {
    return false;
}

@Override
public boolean scrolled(int amount) {
    return false;
}
@Override
public void hide() {
}

@Override
public void dispose() { // SpriteBatches and Textures must always be disposed

}

}

```

# Answer
> 2 votes
I would recommend you use Assetmanager because that way when the application exits and you call manager.dispose() it automatically releases all resources you loaded.

Example from the wiki Assetmanager

```
AssetManager manager = new AssetManager();

```

This sets up a standard AssetManager, with all the loaders libgdx has in store at the moment. Let's see how the loading mechanism works.

Loading a specific asset is simple:

```
 manager.load("resource path/mytexture.png", Texture.class);
manager.load("resource path/myfont.fnt", BitmapFont.class);
manager.load("resource path/mymusic.ogg", Music.class);

```

So far we only queued assets to be loaded. The AssetManager does not yet load anything. To kick this off we have to call AssetManager#update() continuously, say in our ApplicationListener#render() method:

```
    public MyAppListener implements ApplicationListener
        {
        public void render()
        { if(manager.update()) {
        // we are done loading, let's move to another screen!
        }

    // display loading information
float progress = manager.getProgress() ... left to the reader ...
    }
    }

```

If you want to block and make sure all assets are loaded you can call:

```
manager.finishLoading();

```

Getting assets is also easy as 1 2 3

```
manager.get("resource path",classtype);

```

Example

```
Texture texture = manager.get("resource path/mytexture.png",Texture.class);

```

Disposing of the manager is also easy yust call

```
manager.dispose(); // gets rid of all the assets

```

Hope this helps and take a look at the wiki PS made this on my phone.

# Answer
> 0 votes
You can load your stuff in same class but it's not a good practice, I advice you to use LoadingScreen to load your assets.

This page explains how to create simple LoadingScreen.

This page very well explains how to use `AsssetManager`

---
Tags: java, android, libgdx, asset-management
---


title: Unet how to control child gameobject?

text:
# Question
Title: Unet how to control child gameobject?
I'm currently getting into the Unity networking system called unet. I have a child of the local player authority, the weapon. The weapon (PlasmaCannon\_left and right) have a script handling firing, because weapons can be replaced, and have different firing intervals, this seemed to me to be the easier way. However, they won't fire.

Hierarchy:

(simplified) Weapon Code:

```
public void Start() {
    Debug.Log("Weapon Spawned.");
    if (isLocalPlayer) {
        Debug.Log("Weapon set as local player");
    }
}

public void Update() {
    if (isLocalPlayer) {
        if (firingTimer <= firingInterval){
            firingTimer += Time.deltaTime;
        }
        if (firingTimer >= firingInterval) {
            if (Input.GetButton("Fire1") && firingMode == FiringMode.Primary) {
                CmdFire();
            }
            if (Input.GetButton("Fire2") && firingMode == FiringMode.Secondary) {
                CmdFire();
            }
        }
    }
}

[Command]
public void CmdFire() {
    Debug.Log("Firing Bullet.");
}

```

I am getting the "Weapon Spawned." log message, but nothing inside `isLocalPlayer` conditions is happening even though I have added a `networkidentity` component and set `Local Player Authority` to true.

Like I said, I'm still learning so I have no clue what's going wrong here.

# Answer
> 0 votes
for some reason `isLocalPlayer` is not inherited from its parent, the gameobject also did not have client authority, i solved it by calling a function in the `PlayerController` to actually fire the bullet, only using variables used in the weapon/bullet objects.

# Answer
> 0 votes
```
if (isLocalPlayer) {
    Debug.Log("Weapon set as local player");
}

```

This wont work if it is a child of the gameobject with local authority (the network manager recognizes the parent gameobject as the local player).

Instead, try checking "if" the gameobject is a child of the gameobject recognized as the local player. Using your example...

```
    if (!gameObject.transform.parent.gameObject.GetComponent<NetworkIdentity>().isLocalPlayer)
    {
        Debug.Log("Weapon set as local player");
    }

```

Now see if the debug message is displayed. Note: For anyone else coming across the net, just replace the debug message with "return;" as you would normally using that function.

---
Tags: unity, debugging, unet
---


# Question
Title: How would you implement and differentiate between input actions and input states?
Im currently trying to setup my game and Ive started to implement input. It works like this:

I have an `Input` class who notifies the `InputMapper` whenever some key is pressed (or released or whatever). This InputMapper gets the keys pressed and returns an `Action` or a `State` depending on the current `InputContext` (Action and State are enums) (I used this article to get idea of how it should work).

**`Action` here represents one-time actions like `Jump` while `State` represents continuous things like `move_right`.**

I now attach an `InputListener`to the `InputMapper`, which gets the `Action` or `State` whenever pressed.

In the game I use an **entity-component-system**. I have a `ControlComponent`, which should have variables that dictate what an entity should do and a `KeyBoardSystem`, which should set these variables. `ControlComponent` is then used by things like `WalkSystem` or `JumpSystem`.

**My question now is: How would you implement these States and Actions in an entity-component-system?** I know that States could be represented by booleans in the ControlComponent, but Actions? They could be events, but the ControlComponent doesnt (shouldnt?) have any method or know about the systems that use it.

Any help is appreciated.

# Answer
What's the harm in allowing the input state for both actions & state to be managed by the input system directly and you merely expose methods for querying this state from other systems?

Your `JumpSystem` registers the `Jump` action with the `InputSystem`. Perhaps the registration is also accompanyed by the default key for `SPACE`. As a step in your game's startup, you load the player's mappings from a file to override the default input mappings with their custom ones.

At some future frame, your `PlayerControllerSystem` queries the `InputSystem` and checks whether the *JUMP* action is active. If the answer is true, then the player controller system initiates the jump sequence. This might include setting some booleans in the player controller component.

At the end of the frame, the `InputSystem` clears all actions and sets them back to inactive while leaving the current active status for *States* as-is so that carries over to the next frame.

In other words, I'm advocating polling input rather than pushing it. Why?

When input is pushed, now each system interested in input should cache those values so that later on when those systems update their state, they can react to that input. They shouldn't react to the input prior to because each system in the game loop typically must update in a deterministic order.

By polling input instead, we avoid having to force systems to maintain input state when it would be dispatched at the top of the game loop. Systems interested in current input state can obtain it when its needed for calculations and furthermore it allows that state to be cleared/managed cleanly from frame to frame.

**UPDATE**

I don't believe it makes sense to separate things like keyboard, mouse, and joystick into something called a *system* because these are technically *input devices* which should be managed by a system responsible for *input*.

That is why I mentioned an `InputSystem`, of which your `InputMapper` is a component of. The mapper is ultimately responsible for turning input events into actions or state changes.

Next, I mentioned `PlayerControllerSystem` because this is where input actions and state changes are translated into game world reactions. This system knows how to to turn the jump action trigger into a series of changes to game objects so that jump occurs. This might imply applying a boolean value on a component or coordinating the jump animation with the animation system and the movement/force needed to jump with the physics/movement systems.

Just like components, make sure not to create systems that are equally too granular in nature unless there really is a legit reason to do so.

This is a simplified example of my own engine:

```
class PlayerControllerSystem {
public:
  PlayerControllerSystem(InputSystem* pInput) {
    // Register an action in the category 'Movement' called 'Jump'
    // Assign the action to respond to the default key SPACE.
    mJumpAction = pInput->registerAction( "Movement", "Jump", Input::KC_SPACE );

    // Register a state in the category 'Movement' called 'Move Forward'
    // Assign the state to respond to the default key W.
    mForwardState = pInput->registerState( "Movement", "Move Forward", Input::KC_W );
    ....
  }

  void update(const FrameEvent& evt) {
    if ( mJumpAction.isActive() ) {
      // initiate jump
    }
    if ( mForwardState.isActive() ) {
      // handle forward movement
    }
  }
}

```

As you can see, I am not using events nor the observer pattern here. I believe its more efficient to simply have the input system gather and set state rather than dispatch to callbacks. There are most definitely places in your game loop where both synchronous and asynchronous events are useful, but I honestly do not believe that it makes sense to use them for input.

The system above shows how it tells the input system when the spacebar is pressed, toggle the mJumpAction as active. Internally, the input system maintains a data structure that relates `Input::KC_SPACE` as an action with the name `Jump` and category `Movement`.

What is the importance of this name/category? I use it to manage a tree display of category and named key mapping options users can change in a GUI screen inside the game.

During the update loop of that system, it uses the `mJumpAction` and `mForwardState` variables to check whether they're toggled.

Now your implementation of the input system might not return anything to the calling system if you'd rather not have variables. If so, all you simply need to do during the update loop would be to do something like:

```
if ( pInputSystem->isActionActive( "Jump" ) ) {
  // do jump logic
}

```

I prefer the variable approach for two reasons:

1. I avoid having to use strings to lookup things during the update loop.
2. I can have the input system return the same action/state should multiple systems register the same named/key-combo configuration and save memory.

Lastly, the input system registration could also be written to accept a sequence of values allowing for console game type reactions, like:

```
`A`, `A`, `B`, `Up`, `Down`, `Left`, `Right`.

```

Much like how the input system determines when the key/state has been activated and sets it accordingly, the same holds true for sequences.
> 0 votes

---
Tags: libgdx, input, entity-system, entity-component, artemis
---


# Question
Title: Finding out the "width" and "height" of my screen after projection added
In a 2d game, doing collisions with the edges of your screen is easy. Your textures are a 1:1 mapping of your screen resolution because your verities are too.. if your x position is \> than ( screen width / 2 ) then you have hit the edge of your screen and shouldn't be able to escape it.

**How do you solve the same problem once your game is in 3d coordinates?**

*I've tried the following but I'm missing something, the output is far too large. I'm expecting a number like 6.0 instead I'm getting 41.0 because I'm multiplying 25 or so by 1.5*

```
float Window::width = 1920.0f;
float Window::height = 1080.0f;

float PlayingFrame::cameraPosition = -1.0f;
float PlayingFrame::fov = 45;
float PlayingFrame::defaultPlayDistance = 25.0f; // how far back my player is pushed into the frustrum... mainly for scaling.
float PlayingFrame::defaultFrameWidth = 0.0f; // I want to know how far my scaled player can go left / right until he hits the edge of the viewable screen
float PlayingFrame::defaultFrameHeight = 0.0f; // same as above but with top / bottom
float PlayingFrame::nearFrustrum = 1.0f;

float PlayingFrame::GetWorldSpaceHeight( float distance )
{
    float a = PlayingFrame::nearFrustrum + abs(PlayingFrame::cameraPosition) + distance;
    float o = 1.0f + tan(PlayingFrame::fov * 0.5);
    return a * o;
}

float PlayingFrame::GetWorldSpaceWidth(float distance)
{
    float a = PlayingFrame::nearFrustrum + abs(PlayingFrame::cameraPosition) + distance;
    float o = 1.0f + tan(PlayingFrame::fov * 0.5);
    return a * o;
}

```

Fyi, distance coming in as a parameter is actually set to 25.0f at the moment, I was trying to think ahead

It may help to see the actual problem I'm having... I basically want 2d characters in a 3d world so I can do cool rotation things.. but I cannot figure out how to know when my character has hit the edge of the viewable screen:

https://www.youtube.com/watch?v=A-jcnFfLu6c

---

I'm going to tell this story more thoroughly:

I originally made a 2D game. I had vertices for my background filling up 1920 x 1200:

```
const VERTEX World::vertices[ 4 ] = {
    { -960.0f, -600.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f },    // side 1 screen coordinates centred
    { 960.0f, -600.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f },
    { -960.0f, 600.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f },
    { 960.0f, 960.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f }
};

```

I applied Orthographic projections to my vertices and obviously it came out lovely on my screen! my 1920 x 1200 texture mapped perfect to my full screen app. beautiful.

Same goes with all of my players and enemies etc, I had vertices like:

```
const VERTEX Player::vertices[ 4 ] = {
    { -64.0f, -32.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f },    // side 1 screen coordinates centred
    { 64.0f, -32.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f },
    { -64.0f, 32.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f },
    { 64.0f, 32.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f }
};

```

this image was 128 x 64... and so was my texture, so it mapped perfectly... it fit on the screen as if it were 1:1 mapped... spot on!

**The problem**

I wanted to make my game 3D... so I now applied a **perspective fov left hand projection** and a camera... rather than the orthographic projection which allowed it to be 2D:

I set up a camera like so:

```
XMVECTOR vecCamPosition = XMVectorSet( 0.0f, 0.0f, PlayingFrame::cameraPosition, 0 );
XMVECTOR vecCamLookAt = XMVectorSet( 0.0f, 0.0f, 0.0f, 0.0f );
XMVECTOR vecCamUp = XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f );
matView3D = XMMatrixLookAtLH( vecCamPosition, vecCamLookAt, vecCamUp );

```

I set up a projection like so:

```
matProjection = XMMatrixPerspectiveFovLH(
    XMConvertToRadians( PlayingFrame::fov ),                              // the field of view
    Window::width / Window::height,  // aspect ratio
    PlayingFrame::nearFrustrum,                                                           // the near view-plane
    100.0f );                                                        // the far view-plan

```

I did not change my vertices but I added a z of 1.0f to my objects with just a simple translation... The issue (and I guess you already realise this) was that my **textures / vertices were HUGE**... I either had to scale all of my objects by some *roughly correct size* with a scaling transformation, or change my vertices (and this is what I did in the end) to something more like this:

```
const VERTEX Player::vertices[ 4 ] = {
    { -1.0f, -0.5f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f },    // side 1 screen coordinates centred
    { 1.0f, -0.5f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f },
    { -1.0f, 0.5f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f },
    { 1.0f, 0.5f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f }
}

```

Both choices are killing me. Choice 1 meant I had to scale all of my collisions aswell, and both choice 1 and 2 meant I had to estimate how scaled they should be. so much so that my original 1920 x 1200 background I put back into orthographic projection coz I could not get it to scale well...

The last and most frustrating issue is that I have NO IDEA how to calculate where the borders of my screen are...

What is the usual approach to this?

# Answer
you can try to project the screen borders back into the scene. In rendering projection matrices are invertable, because depth isn't thrown away. so you can use (matProjection\*matCamera)⁻¹\*v to project a point from screen coordinates back to world coordinates. the vertices \[1 -1 0 1\] \[1 1 0 1\] \[1 1 1 1\] \[1 -1 1 1\] are the quad that is on the right border of the screen. used in the formula above and you a a quad in world coordinates that you can use for collision.
> 1 votes

# Answer
Use the projection matrix like that:

```
D3DXMatrixPerspectiveFovLH( &matProjPerPlayer, D3DXToRadian( (FOV) ),
                     CanvasX / CanvasY , Near, Far );

```

And it will get the vector to the border, if camera looks at the z coordinate

```
D3DXVECTOR3 v;
v.x = 1 / matProjPerPlayer._11 ;
v.y = 1 / matProjPerPlayer._22 ;
v.z = 1 / matProjPerPlayer._33 ;

```

I think that you can multiply with camera object matrix to calculate the width of field of view of the camera. (And Multiply with your distance.)
> 1 votes

---
Tags: c++, matrix, directx11
---


# Question
Title: is it possible to generate the walkable area based on an image in a 2D isometric game?
I have hand drawn isometric background looked at about 35-40 degrees.

How to set walkable areas at such image?

Is it possible to use a black ("not white") and white color map sketch and set white areas to be walkable?

Or is there some other way to do it easily?

On this image, black areas represent walls at some height seen at some angle.

I also have more complex maze-like dungeon drawn:

I have searched quite some time but didn't find some satisfactory answer specific to my need.

# Answer
I suggest that you place invisible "boxes" on the black area and then check for collision. I have drawn a few boxes where you could check for collision.
> 1 votes

# Answer
Yes, drawing a pixel collision map like that is possible. There are 3 issues tough:

* If the walkable area gets too tight, rounding errors and frame based collision detection will allow players to get into corners they cannot ever get out of again. They get stuck. This is relatively easy to avoid if you keep shapes simple and walking spaces big.
* Pathfinding is trickier the more obstacles there are. with pixel-based collision detection, every pixel is an obstacle.
* You may want people to "slide" alongside walls. This isn't really possible with a pixel based collision map.
> 1 votes

---
Tags: unity, 2d
---


title: Limitation on irandom() of game maker?

text:
# Question
Title: Limitation on irandom() of game maker?
I have three objects. All of them in the create event contain an action each (execute a piece of code):

**obj\_r01** =\> `r01=0;`

**obj\_r02** =\> `r02=0;`

**obj\_r03** =\> `r03=0;`

**Image (to clarify what I have tried to explain)**:

So far so good, but I have one more object that modifies the variables of these other three: `obj_control`

The **obj\_control** contains two events: **create** and **draw**.

**crete event** (obj\_control):

```
obj_r01.r01=irandom(9);
obj_r02.r02=irandom(9);
obj_r03.r03=irandom(9);
```

**draw event** (obj\_control):

This event contains three actions, precisely three "execute a piece of code":

**piece one**:

`draw_text(x,y,obj_r01.r01);` =\> **applies to obj\_r01**

**piece two**:

`draw_text(x,y,obj_r02.r02);` =\> **applies to obj\_r02**

**piece three**:

`draw_text(x,y,obj_r03.r03);` =\> **applies to obj\_r03**

The objects are arranged as follows in the room:

**In execution this is what happens:**

The value of r01 is randomized, but that of r02 and r03 is not. **I also tried to modify the obj\_control creation event code to**:

```
randomize();
obj_r01.r01=irandom(9);
randomize();
obj_r02.r02=irandom(9);
randomize();
obj_r03.r03=irandom(9);
```

However the result does not change. With this I could only suspect that the `irandom ()` function can only create a storable random value, would it solve such a problem?

---

**EDIT 1:**

I tried putting randomize() only at the beginning of the code as suggested to me by **@Philipp** and **@DH.**:

```
randomize();
obj_r01.r01=irandom(9);
obj_r02.r02=irandom(9);
obj_r03.r03=irandom(9);
```

**But there was no change in the result.**

I also did a test to be sure if the value was not even being randomized or if the values of r02 and r03 were being randomized to 0 and for that I modified their values in the creation of each object:

In obj\_r02:

`r02=10`

In obj\_r03:

`r03=100`

The result:

The first value (not surprisingly) was randomized, but the second and third values were not. **Thus it is clear that the randomization is not being made or that the draw event is occurring before the radomization of r02 and r03**.

# Answer
The random number generator used by GameMaker is not a true random number generator. It is a **pseudo**random number generator (or short: PRNG). A PRNG will return a sequence of numbers which *look* randomly, but are actually a deterministic sequence. The sequence of numbers a PRNG generates depends on its initial state, the so-called **seed value**. When you initialize a PRNG with the same seed, it will generate the same sequence.

That means that when you want each run of a game to be an unique experience, you need to use a different seed value for the PRNG for each run. As a developer you usually don't care where that value comes from, just that it isn't the same you already used. Game Maker's `randomize` function has the purpose to re-seed the random number generator with a new seed which is unlikely to be the same as the last time the game was run. I don't know what that function does exactly "under the hood" to achieve that, but it likely calculates the seed value from various entropy sources, like the current time, user input, etc. When you call `randomize` multiple times, those entropy sources might not have changed, so you re-initialize it again with the same seed. That means the PRNG will return the same sequence.

That means you generally should call `randomize()` exactly once: when the game starts. Then just call `irandom(n)` when you need a random number and it should return a different random number each time (or the same number... with a chance of one in `n`). So your game initialization function would look like this:

```
randomize();
obj_r01.r01=irandom(9);
obj_r02.r02=irandom(9);
obj_r03.r03=irandom(9);

```
> 2 votes

# Answer
A complement to @DMGregory comment is the real use of `randomize()`.

It's supposed to set the seed, and there is no need to do it more than once as already noted, but also, as said here

> Please note, that when using the random number functions in GameMaker: Studio the initial seed is always the same, as this makes tracing errors and debugging far easier. Should you wish to test with true random, you should call this function at the start of your game.

So, not calling will wield the same results over the runs. The best case is to just call once, at the start of the game, and never call it again to make it "truly" random.
> 2 votes

---
Tags: game-maker, random
---


# Question
Title: ArgumentNullException from SpriteBatch.Draw trying to get a Texture2D from a jagged array
first time on here. So I'm trying to make a tile based game in Monogame using some 2D arrays and spriteBatch.draw absolutely refuses to retrieve a Texture2D from an array, or something else is wrong with my code which I'm sure is the case.

Here's some of the samples. Excuse the ugliness, still kind of beginning MonoGame.

Tile class:

```
class Tile {

    #region Init

    private Texture2D _gfx;
    private Vector2 _pos;
    private BoundingBox _bb = new BoundingBox();

    public Texture2D Graphic {
        get {
            return _gfx;
        }set {
            _gfx = value;
        }
    }

    public Vector2 Position {
        get {
            return _pos;
        }
        set {
            _pos = value;
        }
    }

    #endregion

    #region Constructors

    public Tile() { } //Empty constructor

    public Tile(Vector2 position) {
        Position = position;
    }

    public Tile(Texture2D graphic) {
        Graphic = graphic;
    }

    public Tile(Texture2D graphic, Vector2 position) {
        Position = position;
        Graphic = graphic;
    }

    #endregion

}

```

TileManager Class:

```
class TileManager {

    #region Methods

    public static Tile[,] createBoard(int width, int height, Texture2D graphic, float offset) {

        Tile[,] tArray = new Tile[width, height];

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                tArray[x, y] = new Tile(new Vector2(x * offset, y * offset), graphic);
            }
        }

        return tArray;

   }

    public static Tile getTileAt(Tile[,] tile_array, int x, int y) {
        return tile_array[x, y];
    }

    #endregion

}

```

and of course the whole main class:

```
public class Game1 : Game {
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    Texture2D floor;
    Texture2D wall;
    Color myColor;

    Tile newTile;
    Texture2D newTexture;

    Tile[,] mainBoard;

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

    /// <summary>
    /// Allows the game to perform any initialization it needs to before starting to run.
    /// This is where it can query for any required services and load any non-graphic
    /// related content.  Calling base.Initialize will enumerate through any components
    /// and initialize them as well.
    /// </summary>
    protected override void Initialize() {
        // TODO: Add your initialization logic here

        mainBoard = TileManager.createBoard(10, 10, floor, 25f);

        base.Initialize();
    }

    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    protected override void LoadContent() {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        floor = Content.Load<Texture2D>("floor");
        wall = Content.Load<Texture2D>("wall");

        // TODO: use this.Content to load your game content here
    }

    /// <summary>
    /// UnloadContent will be called once per game and is the place to unload
    /// game-specific content.
    /// </summary>
    protected override void UnloadContent() {
        // TODO: Unload any non ContentManager content here
    }

    /// <summary>
    /// Allows the game to run logic such as updating the world,
    /// checking for collisions, gathering input, and playing audio.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Update(GameTime gameTime) {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();

        base.Update(gameTime);
    }

    /// <summary>
    /// This is called when the game should draw itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Draw(GameTime gameTime) {
        GraphicsDevice.Clear(Color.Black);

        spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);

        for (int x = 0; x < 10; x++) {
            for (int y = 0; y < 10; y++) {
                spriteBatch.Draw(mainBoard[x, y].Graphic, mainBoard[x, y].Position, Color.White);
                // Fist argument is null no matter what?
            }
        }
        spriteBatch.End();
        base.Draw(gameTime);
    }
}

```

Thanks in advance.

Edit: Here are some things I tried

-Making content "Copy if newer" and "Always Copy"

-Put "mainBoard" in loadContent

-using Tiles Graphic only constructor in tileManager

Edit2:

Fixed it! I just had to put mainBoard AFTER the loading the floor and wall graphics in LoadContent.

# Answer
> -1 votes
Fixed it! I just had to put mainBoard AFTER the loading the floor and wall graphics in LoadContent.

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


title: Issues with UBO data alignment

text:
# Question
Title: Issues with UBO data alignment
I'm trying to implement an OpenGL deferred renderer, in order to process multiple lights.

I have a structure defined in both C++ and GLSL that defines a simple point light, thus: C++

```
struct LightData
{
    glm::vec4 colour;
    glm::vec4 position;
    glm::vec4 attenuation;
    float intensity;
};

```

GLSL:

```
struct LightData
{
    vec4 colour;
    vec4 position;
    vec4 attenuation;
    float intensity;
};

```

Upon examination, using `sizeof(LightData)`, I find that the size of the C++ struct is 52 bytes, which makes sense. (3x 16 bytes, plus 4 bytes, plus 3x 4 bytes padding for memory alignment)

However, given that I am writing a deferred renderer to work on multiple lights, I populate a GL Uniform Buffer with an array of such structs, and access them like so:

```
layout (std140) uniform PointLights
{
    LightData points[MAX_NUM_POINT_LIGHTS];
};

```

Upon examination of the data on the GPU, using Nsight, I find that after the first light, all following light structs are accessed differently as if the alignment is off. From examining the offsets of the struct members in Nsight, it seems that the light struct in GLSL is padded up to 64 bytes in size, causing it to read values from the incorrect memory address

```
                    C++ offset              GLSL offset
0    vec4 colour;           0                       0
0    vec4 position;         16                      16
0    vec4 attenuation;      32                      32
0    float intensity;       36                      48
1    vec4 colour;           52                      64
1    vec4 position;         68                      80
1    vec4 attenuation;      84                      96
1    float intensity;       100                     112

```

How would I go about fixing this discrepancy so that the data is retrieved from the correct memory address?

# Answer
> I find that the size of the C++ struct is 52 bytes, which makes sense. (3x 16 bytes, plus 4 bytes, plus 3x 4 bytes padding for memory alignment)

Your calculations here are wrong.

16 + 16 + 16 + 4 is 52, so your value of 52 bytes *excludes* the 3x4 padding bytes.

If we include the pad bytes we get: 16 + 16 + 16 + 4 + (3x4), or 64, which is the correct value.
> 0 votes

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


# Question
Title: FPS - How to handle accuracy with red dot sight on guns
I have a gun which you can aim down the red dot sight. If you are moving while aimed down sight, there is some bobbing that comes into play. The arms are bobbing, not the camera itself.

Currently when the player fires their gun, I fire a ray from the center of the camera and check for a hit on a player.

The problem is, if the player is aiming and moving, the red dot is bobbing(since the arms are) but because the camera isn't, the ray always fires down the center which doesn't line up with the red dot. It Doesn't feel right in gameplay.

I was hoping someone may have some ideas to offer on how to handle this..

# Answer
The pragmatic solution would be to not fire from the camera but to fire from the weapon model instead... at least when the player is in aim mode. When the player is not aiming with the weapon, the line of fire might be set off, which might seem a bit strange. Also, your gameplay is now affected a lot by your animation design, which gets cumbersome to balance.

What many games are doing instead is always having a random bullet spread, but make the intensity of the spread different depending on the current state of the player-character.

When you calculate a bullet trajectory, change the pitch and yaw by a random value. Use a small random value when the player is standing and aiming and a much larger random value when the player is running and firing from the hip. The bullets still won't land exactly where the gun is pointing at that moment. Instead the bullets will be spread all over the place, which is likely what the player expects to happen.
> 1 votes

---
Tags: unity, first-person-shooter
---


# Question
Title: Two UBO's end up containing the same data
I have two separate UBO's for different types of lights (for a light stage in a deferred rendering system).

These are defined as follows:

```
//Pointlight UBO
m_pointLightBlockIndex = glGetUniformBlockIndex(shader.getShaderHandle(), "PointLights");
glGetActiveUniformBlockiv(shader.getShaderHandle(), m_pointLightBlockIndex, GL_UNIFORM_BLOCK_DATA_SIZE, &m_PointLightBlockSize);
glUniformBlockBinding(shader.getShaderHandle(), m_pointLightBlockIndex, 0);

//Spotlight UBO
m_splBlockIndex = glGetUniformBlockIndex(shader.getShaderHandle(), "SpotLights");
glGetActiveUniformBlockiv(shader.getShaderHandle(), m_splBlockIndex, GL_UNIFORM_BLOCK_DATA_SIZE, &m_SpotLightBlockSize);
glUniformBlockBinding(shader.getShaderHandle(), m_splBlockIndex, 0);

//create the buffers
glGenBuffers(1, &m_SLBuffer);
glGenBuffers(1, &m_PLBuffer);

glBindBuffer(GL_UNIFORM_BUFFER, m_SLBuffer);
glBufferData(GL_UNIFORM_BUFFER, sizeof(SpotLightData)*m_MaxSpots, nullptr, GL_DYNAMIC_DRAW);

glBindBuffer(GL_UNIFORM_BUFFER, m_PLBuffer);
glBufferData(GL_UNIFORM_BUFFER, sizeof(LightData)*m_MaxPoints, nullptr, GL_DYNAMIC_DRAW);

glBindBuffer(GL_UNIFORM_BUFFER, 0);

```

To populate the UBO's I use the following:

```
void LightUniformBuffer::updatePointLights(int numLights, const LightData * data)
{
    glBindBuffer(GL_UNIFORM_BUFFER, m_PLBuffer);
    glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(LightData)*numLights, data);
    glBindBuffer(GL_UNIFORM_BUFFER, 0);
}

void LightUniformBuffer::updateSpotLights(int numLights, const SpotLightData * data)
{
    glBindBuffer(GL_UNIFORM_BUFFER, m_SLBuffer);
    glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(SpotLightData)*numLights, data);
    glBindBuffer(GL_UNIFORM_BUFFER, 0);
}

```

And finally to bind them:

```
void LightUniformBuffer::bindPointLights()
{
    glBindBufferBase(GL_UNIFORM_BUFFER, m_pointLightBlockIndex, m_PLBuffer);
}

void LightUniformBuffer::bindSpotLights()
{
    glBindBufferBase(GL_UNIFORM_BUFFER, m_splBlockIndex, m_SLBuffer);
}

```

These buffers are represented as arrays of lights in GLSL, like so:

```
layout (std140) uniform PointLights
{
    LightData points[MAX_NUM_POINT_LIGHTS];
};

layout (std140) uniform SpotLights
{
    SpotLightData spots[MAX_NUM_POINT_LIGHTS];
};

```

Now, when I populate the buffers and use the shader, I found, through using Nsight, that both buffers are using the same set of data, i.e. the spotlight buffer is filled with point light data, and so is useless.

Why is this happening, and how can I fix it?

# Answer
> 0 votes
I figured out the problem:

`glUniformBlockBinding(shader.getShaderHandle(), m_pointLightBlockIndex, 0);` Requires a unique binding location for each buffer, so if I defined an enum like so:

```
enum bufferType
{
    Spotlight = 0,
    PointLight = 1
};

```

I can set each one like so:

`glUniformBlockBinding(shader.getShaderHandle(), m_pointLightBlockIndex, PointLight);` `glUniformBlockBinding(shader.getShaderHandle(), m_splBlockIndex, Spotlight);`

Because I was using the number 0 instead, they were pointing to the same memory addresses.

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


# Question
Title: Normal mapping soft question: What could this be?
So I'm trying to implement tangent space normal mapping. I bind the uniforms, load the attributes, set the shaders, and out comes this:

This happens on the sides only, and not when in direct light. I'm pretty sure it's matrix related, but could it be I'm mapping the tangent values incorrectly? Has anyone seen something like this before? Or have a hunch what it could be?

UV screenshot, it's a cube, turned into a sphere, and each side is separated. The final object shows no seams on the top or bottom, but rather on each side.

Update: When I order the tangents according to UVs, I get a much cleaner result, but some areas/sides still get an inverted normal. I'm not sure why this is, or how to fix it. It happens on each side, so it is as if the sides get inverted normals.

# Answer
I found 3 problems, and by solving them, I get this:

A seemingly seamless planet with working shaders. But what is the problem?

The tangents I was generating were mapped to each vertex, in the parser, when in fact, they describe the direction of the normal\_map in relation to the UV. Making a tangent per UV value, and indexing them together with the UVs (UV 1,2,3.. and Tangent 1,2,3..) removed the seams, but that was not all.

The second thing I found, was that I was crossing the normal and tangent in the wrong order, when finding the bitangent of vertex\_normal/tangent for the tbn matrix, like so:

```
vec3 n = normalize(normalmatrix * vertex_normal);
vec3 t = normalize(normalmatrix * vec3(vertex_tangent));
     t = normalize(t-dot(t,n)*n);  //Gramm-Schmidt process
vec3 bitangent = normalize( cross( n, t ) ); //these were t,n

```

Which was messing slightly with shadows, but not as much as this:

```
mat3 tbn = transpose(mat3(t,bitangent,n)); //why transpose??

```

Apparently I should have been transposing my tbn matrix all along, proving how little of this I actually understand.

Either way, the transpose function is cheap (apparently), and I guess this is the place to call it. I dont quite understand it tbh.
> 2 votes

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


# Question
Title: Design/Architecture of a game waiting room
I have some experience in creating singleplayer games, but for a new project I want to implement also a multiplayer.

I can imagine what kind of information (position, textureId, ...) i have to send over the network. But hey, I can't figure out how I "could" represent a game waiting room. Which means :

1. One player creates a new game (What happens here?Does the server code calls a new instance of the game, but does not start the game yet???)
2. The player, who created the game then either waits for additional players(in maximum 4) or he starts a solo game (Should my game has something like a value for `currentPlayers` ? Or is this managed by server code?)
3. Also can you explain what exactly server code means? Which common functions should it handle (in context of creating a game room)?
4. How can I make sure, that other players can also start new games

As you can see I am a complete beginner to networking, but i do know about TCP and UDP, but the only thing i have done with it was a simple echo server... What am i looking for are simple pseudocodes oder examples, but please explain briefly.

# Answer
> 1 votes
I accomplished what you describe in a previous project using a game state machine, and a network class for both server and client.

Have an abstract base class **GameState**, and derive a few states from it:

* MenuState
* LobbyState
* PlayingState

And another abstract class **Network**, and derive a couple of more classes:

* Server
* Client

The base Network class contains a list of players.

You will need some kind of StateManager class that handles a stack of states. You begin by pushing the MenuState onto the state stack as the program starts. The user then navigates to the menu option for creating a server or joining a server, and you push the lobby state once the connection is established.

```
void Game::CreateServer( const string& name )
{
  mNetwork = new Server(name);
  if( mNetwork ){
    StateManager.PushState( new LobbyState() );
    // Some game loop will then use the current state to render the lobby, etc.
  }
}

void Game::JoinServer( const string& hostname )
{
  mNetwork = new Client(hostname);
  if( mNetwork ){
    StateManager.PushState( new LobbyState() );
  }
}

```

Players joining/leaving must be managed:

```
void Server::PlayerConnected( PlayerID id )
{
  mPlayers.push_back(id);
  BroadcastPlayerConnected(id);
}

void Client::PlayerConnected( PlayerID id )
{
  // This is called when client receives server broadcast of player connecting.
  mPlayers.push_back(id);
}

```

The server should also be able to receive chat messages if you choose to support that, and "ready up" messages, character selection, and whatever else you choose for the lobby UI, so the server records the information and then broadcasts it to all connected clients, who then replicate the server's information.

Then when the host wishes to start the game, you simply push the PlayingState, and then pop it off once the game is done to return to the lobby.

```
void Game::Start()
{
  StateManager.PushState( new PlayingState() );
  // Game loop should handle loading, gameplay etc. using the current state.
  mNetwork->Update( Network::GameStarted ); // Server implementation broadcasts game started event.
}

void Game::Stop()
{
  StateManager.PopState();
  mNetwork->Update( Network::GameEnded );
}

```

Keep in mind this is just a rudimentary example, and you will certainly have to consider more design work than this. I'm just laying out the groundwork.

---
Tags: networking
---


title: How do i put XMMATRIX inside XMFLOAT4X4

text:
# Question
Title: How do i put XMMATRIX inside XMFLOAT4X4
I'm currently trying to move my weapon with the camera. To do this i'm creating a vector (`tempVect`) where i load how much the camera has moved compared to the weapon (in the code behind is just filled with random values to test it). `TempTranslation` is the `XMMATRIX` where the translation is stored. result is `the XMMATRIX` that comes out from the multiplication of `tempMatrix` and tempTranslation. `mPistolWorld` is an `XMFLOAT4X4` that is going to be loaded into the "world" variable to make the `world * view * proj` matrix. Now that i have `result` how can i load it into `mPistolWorld` ?

```
XMVECTOR tempVect = XMVectorSet(0.2f, 0.2f, 0.2f, 0);

    tempTranslation = XMMatrixTranslationFromVector(tempVect);

    XMMATRIX tempMatrix = XMLoadFloat4x4(&mPistolWorld);

    XMMATRIX result = XMMatrixMultiply(tempMatrix, tempTranslation);

```

# Answer
> 2 votes
You should be able to update the mPistolWorld XMFLOAT4X4 variable using:

```
XMStoreFloat4x4(&mPistolWorld, result);

```

https://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx\_sdk.storing.xmstorefloat4x4(v=vs.85).aspx

---
Tags: directx11, matrix, c++
---


title: Visualize BoxCast

text:
# Question
Title: Visualize BoxCast
Im trying to find a way to visualize, and Edit the Physics2D.BoxCast from the Editor.

I wrote the methods below to visualize the BoxCast, and edit in the editor:

```
public Rect Box;
 private void OnDrawGizmos()
 {
     Gizmos.color = Color.magenta;
     Gizmos.matrix = Matrix4x4.TRS(transform.position + (Vector3) Box.position, transform.rotation, Vector3.one);
     Gizmos.DrawWireCube(Vector2.zero, Box.size);
 }

 private void Update()
 {
     var hits = Physics2D.BoxCastAll(transform.position + (Vector3) Box.position, Box.size,
         transform.eulerAngles.z, Vector2.right, 0, 1 << LayerMask.NameToLayer("Player"));
     foreach (var hit in hits)
         Debug.Log(hit.transform.name);
 }

```

It works fine, but when I edit the object rotation I get this problem: https://i.stack.imgur.com/mtQN3.jpg

I can fix it easily, putting just transform.position, instead of transform.position + (Vector3)Box.Position. But if I do it, i will not be able to edit the Raycast position.

So, how I can solve this?

# Answer
> 1 votes
Try using `Box.center` instead of `Box.position`. From the docs for `Rect.position`:

> This is the same as min, except that setting it will move the rectangle rather than resize it.

Both `Physics2D.BoxCastAll` and `Gizmos.DrawWireCube` expect you to provide a center point and a size. Right now, your box-cast is being centered at the minimum of the rectangle. If you use `Box.center` instead, then your gizmos should show the correct rectangle and your box cast should match it.

---
Tags: unity, physics, matrix, raycasting
---


# Question
Title: Unity: Simple “pass through” geometry shader
I would like to implement a geometry shader that does nothing, just for the purpose of learning and to go ahead with that and do something useful with it.

I currently have:

* A compute shader creating "particles".
* A vertex shader doing the transformation
* A fragment shader...

This is the shader file:

```
StructuredBuffer<float3> particles;

struct fsInput {
    float4 pos : SV_POSITION;
};

fsInput vert(uint id : SV_VertexID)
{
    fsInput fsIn;
    float3 worldPos = particles[id];
    fsIn.pos = mul(UNITY_MATRIX_VP, float4(worldPos, 1.0f));
    return fsIn;
}

//[maxvertexcount(1)]
//void geom(point fsInput p[1], inout TriangleStream<fsInput> output)
//{
//  fsInput fsOut = (fsInput) 0;
//  fsOut.pos = p[0].pos;
//  output.Append(fsOut);
//}

float4 frag(fsInput fsIn) : COLOR
{
    return float4(1.0, 0.2, 0.2, 1);
}

```

I'm drawing my particles with this call:

```
Graphics.DrawProcedural(MeshTopology.Points, NUM_PARTICLES);

```

In my understanding, which is quite limited due to the perfect documentation of geometry shaders, my geometry shader should do nothing. Just forward the points to the fragment shader. However, if I use that shader (comment in those lines), I wont see my particles anymore. Without the geometry shader, I can see every particle.

So the first question is, where is the error? The second question is: Can I, starting with points and using the geometry shader, go from points to a, for example, cube? Or should I do it in the compute shaders? But if so, which MeshTopology should I use to draw the data from the compute shader as Cube, Sphere, etc...?

Thank you for help!

# Answer
> 2 votes
It looks like the problem is that you're using a TriangleStream. You've marked it as maxvertexcount(1) which means that you can't actually draw anything, because a triangle with one vertex isn't a triangle. Try using a PointStream as your output type.

A GeometryShader with a TriangleStream can be used to output two triangles that are facing the screen in order to draw billboards for particles, but if you really want an identity geometry shader, the output type must be the same as the input type.

---
Tags: unity, shaders, hlsl, geometry-shader
---


# Question
Title: How can I minimize visual clutter in an ASCII rougelike game?
I'm currently designing an old-school rouguelike, similar to games like Nethack or Dwarf Fortress. While I love the ASCII graphical style they employ (which my game will also employ), they also suffer from visual clutter, caused by the large amount of text usually present on the screen at any given time. The graphical style of my game without clutter-reducing improvements will effectively be identical to that of Dwarf Fortress's:

I've thought up a few things which could potentially alleviate this problem, but they're probably not enough:

* Separate the UI rendering and game rendering into separate "layers".
* Apply a unique color filter to each layer to visually separate them.
* Tone down the use of ASCII characters, and instead opt for solid coloring in some places when possible.

How can I minimize this visual clutter?

# Answer
You want an ASCII based aesthetics, but not exactly because you want to have less clutter. How far do you deviate from the classical aesthetics of Dwarf Fortress et.al. is up to you.

Consider that Dwarf Fortress will look very different if you use custom fonts, or if you use a viewer that uses tilesets:

Of course, those have the limitation that they need to preserve the characters that will appear in text in the game. You don't have that limitation.

---

If you don't want to move to tile graphics, I suggest to do the following:

1. Use colored backgrounds

I'm taking the NetHack example from Wikipedia:

```
                                        ------------
                                      ##....._.....|
                                        |...........#          ------
                                       #...........|           |....|
                   ---------------   ###------------           |...(|
                   |..%...........|##########               ###-@...|
                   |...%...........###    #                 ## |....|
                   +.......<......|       ###              ### |..!.|
                   ---------------          #              #   ------
                                            ###          ###
                                              #          #
                                           ---.-----   ###
                                           |.......|   #
                                           |........####
                                           |.......|
                                           |.......|
                                           ---------

```

If you replace each "." with a white space with silver background, and each "#" with a gray background, you get this:

2. Use emoji / special fonts

I have used emoji to replace the objects in the map. I had adjust spacing manually to prevent the text to break aligment as the emoji font isn't monospace... that shouldn't be a problem for you if you place objects in a different layer.

3. Box-drawing

By using Box-drawing characters we can get the following result:

---

If you are thinking that that's not text... well, there I didn't use images or draw lines. Just text, font, color and a few space tweaks. Here is my evidence:

```
p{line-height:12pt;margin:0;border:0;padding:0;font-family:"Courier New";color:black}
span{font-size:12pt;font-family:"Courier New";color:black}
```

```
<p><span>
┌──────────┐</span></p>
<p><span>
<span style="background:gray"> </span><span style="background:gray"> </span><span style="background:silver;letter-spacing:-1.8pt;">     </span><span style="background:silver"></span><span style="background:silver">
</span>│</span></p>
<p><span>
│<span style="background:silver">           </span><span style="background:gray"> </span>          ┌────┐</span></p>
<p><span>
<span style="background:gray"> </span><span style="background:silver">           </span>│           │<span style="background:silver">    </span>│</span></p>
<p><span>         ┌──────────────┐
<span style="background:gray"> </span><span style="background:gray"> </span><span style="background:gray"> </span>└──────────┘           │<span style="background:silver"> </span><span style="background:silver;letter-spacing:-4.6pt">  </span><span style="background:silver"></span>│</span></p>
<p><span>         │<span style="background:silver;letter-spacing:-3.75pt">  </span><span style="background:silver">☠</span><span style="background:silver">           </span>│<span style="background:gray"> </span><span style="background:gray"> </span><span style="background:gray"> </span><span style="background:gray"> </span><span style="background:gray"> </span><span style="background:gray"> </span><span style="background:gray"> </span><span style="background:gray"> </span><span style="background:gray"> </span><span style="background:gray"> </span>               <span style="background:gray"> </span><span style="background:gray"> </span><span style="background:gray"> </span><span style="background:silver"> </span><span style="background:silver"></span><span style="background:silver;letter-spacing:-2.8pt">   </span>│</span></p>
<p><span>         │<span style="background:silver;letter-spacing:-2.5pt">   </span><span style="background:silver">☠</span><span style="background:silver">
</span><span style="background:gray"> </span><span style="background:gray"> </span><span style="background:gray"> </span>    <span style="background:gray"> </span>                 <span style="background:gray"> </span><span style="background:gray"> </span> │<span style="background:silver">    </span>│</span></p>
<p><span>         <span style="background:silver"></span><span style="background:silver;letter-spacing:-2.17pt">       </span><span style="background:silver"></span><span style="background:silver">
</span>│       <span style="background:gray"> </span><span style="background:gray"> </span><span style="background:gray"> </span>              <span style="background:gray"> </span><span style="background:gray"> </span><span style="background:gray"> </span> │<span style="background:silver;letter-spacing:-2.7pt;">  </span><span style="background:silver;"></span><span style="background:silver"> </span>│</span></p>
<p><span>
└──────────────┘         <span style="background:gray"> </span>              <span style="background:gray"> </span>   └────┘</span></p>
<p><span>
<span style="background:gray"> </span><span style="background:gray"> </span><span style="background:gray"> </span>          <span style="background:gray"> </span><span style="background:gray"> </span><span style="background:gray"> </span></span></p>
<p><span>
<span style="background:gray"> </span>          <span style="background:gray"> </span></span></p>
<p><span>                                 ┌──<span style="background:silver"> </span>────┐   <span style="background:gray"> </span><span style="background:gray"> </span><span style="background:gray"> </span></span></p>
<p><span>
│<span style="background:silver">       </span>│   <span style="background:gray"> </span></span></p>
<p><span>
│<span style="background:silver">       </span><span style="background:silver"> </span><span style="background:gray"> </span><span style="background:gray"> </span><span style="background:gray"> </span><span style="background:gray"> </span></span></p>
<p><span>
│<span style="background:silver">       </span>│</span></p>
<p><span>                                 │<span style="background:silver">       </span>│</span></p>
<p><span>
└───────┘</span></p>
```

Of course, how that looks may change depending on what fonts are available on the browser, on what zoom the user is viewing, etc... you shouldn't have that problem in XNA.
> 2 votes

---
Tags: 2d, graphics, gui
---


# Question
Title: LibGDX search for file types in local file system
I'm building a system that allows users to upload files to LibGDX's local directory to play them in the game. How can I search recursively through the local file system for a specific file type and return all returned files?

# Answer
You could use `Files.walk()` along with `filter()`. Thus if you wanted to get all PNG images, then you could do:

```
Path path = Paths.get(Gdx.files.getLocalStoragePath());

try {
    List<Path> files = Files.walk(path)
        .filter(filePath -> !Files.isDirectory(filePath) &&
                            filePath.toString().toLowerCase().endsWith(".png"))
        .collect(Collectors.toList());
}
catch (IOException ex) {
    ex.printStackTrace();
}

```

The example starts searching from `Gdx.files.getLocalStoragePath()` continuously searching all subdirectories for any file ending with `.png`.

It might be important to include `!Files.isDirectory(filePath)` as technically someone could name a directory `test.png`.
> 1 votes

---
Tags: libgdx, scene2d, file
---


# Question
Title: In LibGDX, how might I make an object orbit around a position?
I need an object, which would be a circle, made with ShaderRender, to orbit around a specified point. In LibGDX is there a method or something that would allow me to accomplish this? If not, could you please provide a code example?

# Answer
If you wish for an object to orbit around a specified point in two dimensional space, you want to use some trigonometric functions. Here is an example method to calculate an objects position in an orbit:

```
class OrbitUtilities {
   /* currentOrbitDegrees: the degrees around the orbit that the satellite is(can greater that 360(361 would be equivalent to 1))
    * distanceFromCenterPoint: the distance in world units from the center point that the satellite is
    * centerPoint: the vector of the center point of the orbit system
    */
    public Vector2 calculateOrbit(float currentOrbitDegrees, float distanceFromCenterPoint, Vector2 centerPoint) {
        float radians = Math.toRadians(currentOrbitDegrees);

        float x = (Math.cos(radians) * distanceFromCenterPoint) + centerPoint.x;
        float y = (Math.sin(radians) * distanceFromCenterPoint) + centerPoint.y;

        return new Vector2(x, y);
    }
}

```
> 6 votes

# Answer
you need to keep the angle of the object (alpha) , declare float alpha =0, then in render method do something like this

```
x = Math.cos(alpha*MathUtils.DegreesToRadians)* distance;
y = Math.sin(alpha* MathUtils.DegreesToRadians )* distance;
alpha++;
sprite.setPosition(x,y);

```
> 0 votes

---
Tags: libgdx, mathematics, rotation, physics
---