title: TileMap collision detection

text:
# Question
Title: TileMap collision detection
I'm currently working on a project in XNA and I'm trying to implement collision detection but can't wrap my head around how exactly i'm going to do it.

I'm using the Tiled application to create my maps, exporting to a .tmx file and then reading in and drawing through my program.

Here is my main game1.cs code:

```
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System;
using System.Xml.Linq;

namespace tutorial
{
    /// <summary>
    /// This is the main type for your game.
    /// </summary>
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        private SpriteFont font;
        private int frames;
        Tile[,] tileset;

        private Texture2D background;
        Character player;
        bool playOnce;
        KeyboardState state = Keyboard.GetState();
        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()
        {
            ScreenManager.Instance.Initialize();
            ScreenManager.Instance.Dimensions = new Vector2(800, 480);
            graphics.PreferredBackBufferWidth = (int)ScreenManager.Instance.Dimensions.X;
            graphics.PreferredBackBufferHeight = (int)ScreenManager.Instance.Dimensions.Y;
            graphics.ApplyChanges();
            playOnce = true;
            // TODO: Add your initialization logic here
            base.Initialize();
            tileset = getTileset();
        }

        public Tile[,] getTileset()
        {
            XDocument xml = XDocument.Load("Content/map3.tmx");
            int mapWidth = int.Parse(xml.Root.Attribute("width").Value);
            int mapHeight = int.Parse(xml.Root.Attribute("height").Value);
            int tilecount = int.Parse(xml.Root.Element("tileset").Attribute("tilecount").Value);
            int columns = int.Parse(xml.Root.Element("tileset").Attribute("columns").Value);

            string IDarray = xml.Root.Element("layer").Element("data").Value;
            string[] splitArray = IDarray.Split(',');

            int[,] intID = new int[mapWidth, mapHeight];

            for (int x = 0; x < mapWidth; x++)
            {
                for (int y = 0; y < mapHeight; y++)
                {
                    intID[x, y] = int.Parse(splitArray[x + y * mapWidth]);
                }
            }

            int key = 0;
            Vector2[] sourcePosition = new Vector2[tilecount];
            for (int x = 0; x < tilecount / columns; x++)
            {
                for(int y = 0 ; y < columns; y++)
                {
                    sourcePosition[key] = new Vector2(y * 32, x * 32);
                    key++;

                }
            }

            Texture2D sourceTex = Content.Load<Texture2D>("level/Tiles_32x32");

            Tile[,] tiles = new Tile[mapWidth, mapHeight];
            for (int x = 0; x < mapWidth; x++)
            {
                for (int y = 0; y < mapHeight; y++)
                {
                    if (intID[x, y] != 0)
                    {
                        tiles[x, y] = new Tile(new Vector2(x * 32, y * 32),
                                            sourceTex,
                                            new Rectangle((int)sourcePosition[intID[x, y] -1].X, (int)sourcePosition[intID[x, y] -1].Y, 32, 32)
                                            );
                    }

                }
            }
                return tiles;
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            ScreenManager.Instance.LoadContent(Content);
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            font = Content.Load<SpriteFont>("Score");
            background = Content.Load<Texture2D>("Sprites/background");

            player = new Character(new Vector2(300, 100));
            player.LoadContent(Content);
            int numberOfSongs = 14;
            Song[] bgMusicList = new Song[14];
            bgMusicList[0] = Content.Load<Song>("music/FirstStepMaster");
            bgMusicList[1] = Content.Load<Song>("music/FloralLife");
            bgMusicList[2] = Content.Load<Song>("music/CavaBien");
            bgMusicList[3] = Content.Load<Song>("music/AboveTheTreetops");
            bgMusicList[4] = Content.Load<Song>("music/amoria");
            bgMusicList[5] = Content.Load<Song>("music/BlueWorld");
            bgMusicList[6] = Content.Load<Song>("music/GoPicnic");
            bgMusicList[7] = Content.Load<Song>("music/HighlandStar");
            bgMusicList[8] = Content.Load<Song>("music/LetsMarch");
            bgMusicList[9] = Content.Load<Song>("music/Nightmare");
            bgMusicList[10] = Content.Load<Song>("music/SleepyWood");
            bgMusicList[11] = Content.Load<Song>("music/Subway");
            bgMusicList[12] = Content.Load<Song>("music/UponTheSky");
            bgMusicList[13] = Content.Load<Song>("music/WhenTheMorningComes");
            Random r = new Random();
            int rInt = r.Next(0, 3);
            int currentSong = rInt;
            if(MediaPlayer.State != MediaState.Playing)
            {
                if(playOnce)
                {
                    playOnce = false;
                    currentSong++;
                    if(currentSong >= numberOfSongs)
                        currentSong = 0;
                 }
            MediaPlayer.Play(bgMusicList[currentSong]);
            }

            if(MediaPlayer.State == MediaState.Playing)
            {
                playOnce = true;
            }

            // 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)
        {
            frames++;
            state = Keyboard.GetState();
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();
            ScreenManager.Instance.Update(gameTime);
            player.Update(gameTime);

            //------ATTEMPT AT BASIC COLLISION DETECTION-----------
            foreach(Tile t in tileset)
            {
                if(t != null)
                {
                    //Rectangle tile = t.getRect();
                    if (player.getPos().Y < t.getPos().Y)
                    {
                        float x = player.getPos().X;
                        float y = player.getPos().Y;
                        y += 2;
                        Vector2 newPos = new Vector2(x, y);
                        player.setPos(newPos);
                    }
                }

            }

                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.CornflowerBlue);

            spriteBatch.Begin();
            foreach (Tile t in tileset)
            {
                if(t != null)
                    t.Draw(spriteBatch);
            }
            //spriteBatch.Draw(background, new Rectangle(0, 0, 800, 480), Color.White);
            spriteBatch.DrawString(font, "Frame: " + frames, new Vector2(10, 10), Color.White);
            ScreenManager.Instance.Draw(spriteBatch);
            player.Draw(spriteBatch);
            spriteBatch.End();
            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }
    }
}

```

As you can see by my awful attempt at collision detection, i'm a bit lost:

```
//------ATTEMPT AT BASIC COLLISION DETECTION-----------
        foreach(Tile t in tileset)
        {
            if(t != null)
            {
                //Rectangle tile = t.getRect();
                if (player.getPos().Y < t.getPos().Y)
                {
                    float x = player.getPos().X;
                    float y = player.getPos().Y;
                    y += 2;
                    Vector2 newPos = new Vector2(x, y);
                    player.setPos(newPos);
                }
            }

        }

```

I understand the concept, and that both X and Y have to overlap to trigger a collision, but right now i'm basing everything off the position of the player and the position of the tile when I feel like I should be doing it from the dimensions of the rectangle encumbering the tile/player and whether those corners overlap.

I figure there has to be some calculations regarding the dimensions of the tile and dimensions of the player in respect to their current position and whether they intersect however my brain is turning to mush trying to figure this out. Any help would be appreciated.

# Answer
Here is some code that I pulled up for you from my XNA coding days. This is how I would handle collisions with XNA. This method works strictly with Rectangle colliders.

The first function I will show you is to get the intersection depth between two Rectangles:

```
public static float GetHorizontalIntersectionDepth(Rectangle rectA, Rectangle rectB)
{
    // Calculate half sizes.
    float halfWidthA = rectA.Width / 2.0f;
    float halfWidthB = rectB.Width / 2.0f;

    // Calculate centers.
    float centerA = rectA.Left + halfWidthA;
    float centerB = rectB.Left + halfWidthB;

    // Calculate current and minimum-non-intersecting distances between centers.
    float distanceX = centerA - centerB;
    float minDistanceX = halfWidthA + halfWidthB;

    // If we are not intersecting at all, return (0, 0).
    if (Math.Abs(distanceX) >= minDistanceX)
        return 0f;

    // Calculate and return intersection depths.
    return distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
}

```

Since the vertical intersection calculation is slightly different, here is the function to grab that depth as well:

```
public static float GetVerticalIntersectionDepth(Rectangle rectA, Rectangle rectB)
{
    // Calculate half sizes.
    float halfHeightA = rectA.Height / 2.0f;
    float halfHeightB = rectB.Height / 2.0f;

    // Calculate centers.
    float centerA = rectA.Top + halfHeightA;
    float centerB = rectB.Top + halfHeightB;

    // Calculate current and minimum-non-intersecting distances between centers.
    float distanceY = centerA - centerB;
    float minDistanceY = halfHeightA + halfHeightB;

    // If we are not intersecting at all, return (0, 0).
    if (Math.Abs(distanceY) >= minDistanceY)
        return 0f;

    // Calculate and return intersection depths.
    return distanceY > 0 ? minDistanceY - distanceY : -minDistanceY - distanceY;
}

```

With these functions, you can determine how deep an intersection between two rectangles are. This is important as we need to know this information in order to correct our position in our collision response.

The next method, is a "helper" function that will calculate the depth between two rectangles based on the direction you are looking to check:

```
private bool TileIntersectsPlayer(Rectangle player, Rectangle block, Direction direction, out Vector2 depth)
{
    if (direction == Direction.Vertical) {
        depth = new Vector2(0, GetVerticalIntersectionDepth(player, block));
    } else if (direction == Direction.Horizontal) {
        depth = new Vector2(GetHorizontalIntersectionDepth(player, block), 0);
    }

    return depth.Y != 0 || depth.X != 0;
}

```

With this helper method, we will now be able to handle the collision handling and response with this function:

```
private bool HandleCollisions(Direction direction)
{
    bool collides = false;

    // Whatever method you use to get a list of tiles to check against
    // A quad tree structure here would be beneficial to query
    List<Land> land = GetListOfLandTilesToCheck();

    // process tiles and check if we are colliding with them
    foreach (Land l in land)
    {
        // Calculate how deep the intersection is
        Vector2 depth;
        if (l.Rectangle.Intersects(Rectangle))
        {
            if (TileIntersectsPlayer(Rectangle, l.Rectangle, direction, out depth))
            {
                // Adjust position for collision response
                Position += depth;
                collides = true;
            }
        }
    }
    return collides;
}

```

And then finally, you need to handle your movement and collision checks one-axis at a time in order for this method to work. In your update method you would have something like this:

```
// Process Y axis
Velocity.Y += Gravity.Y * elapsed * Mass;
Position.Y += Velocity.Y * elapsed;

// Handle vertical collision that may have occured
HandleCollisions(Direction.Vertical);

// Process X Axis
Velocity.X += Speed * elapsed;
Position.X += Velocity.X * elapsed;

HandleCollisions(Direction.Horizontal);

```
> 1 votes

---
Tags: xna, xna-4.0
---


# Question
Title: Need some help with Unity 2d animation controller
So my animations don't transition right. I have a 2d top down prototype project and animations for 4 directional movement and an idle position. Right now i have the movement set up so the right animation activates when the player moves in one of 4 directions. problem is that the walking animation does not stop when the player stops, it doesn't transition over to the idle animation.

My animation controller looks like this:

The parameter between the animations are an integer that signals which direction needs to play, from 0 to 3. I have been messing around with a speed float parameter, but I don't really know how to get it to work.

```
if (Input.GetKey (KeyCode.D))
        {
            GetComponent<Rigidbody2D>().velocity = new Vector2(moveSpeed,GetComponent<Rigidbody2D>().velocity.y);
            animator.SetInteger("Direction", 2);
            animator.SetFloat("MoveSpeed", 0);
        }

        if (Input.GetKey(KeyCode.A))
        {
            GetComponent<Rigidbody2D>().velocity = new Vector2(-moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
            animator.SetInteger("Direction", 0);
            animator.SetFloat("MoveSpeed", 0);
        }

        if (Input.GetKey(KeyCode.W))
        {
            GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, moveSpeed);
            animator.SetInteger("Direction", 1);
            animator.SetFloat("MoveSpeed", 0);
        }

        if (Input.GetKey(KeyCode.S))
        {
            GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, -moveSpeed);
            animator.SetInteger("Direction", 3);
            animator.SetFloat("MoveSpeed", 0);
        }

```

Here is my movement code if it helps.

If I'm missing something important that you need to help me, please tell me.

# Answer
From what I can get from that picture and your code, I can understand that your transition from "Any State" to, for example, "walk\_left" is when Direction is 0, right? Problem is that you're not setting the Direction value to another value when you stop holding the key, so it keeps going back to "walk\_left" over and over again, so of course it's never going to get to idle. What you can do is, either create another animator parameter that tells the Animator when you're walking, for example a isWalking bool. Or use another value for when you're not walking, -1, 4, whatever you want.

Then, in the transitions to idle use that new value as the condition. If using the boolean, remember to check that isWalking is true before transitioning to any of the walking states, and that isWalking is false when you need to transition to the idle states.

As for how to know when you stopped walking you can use something like this:

```
if (Input.GetKeyUp(KeyCode.A) || Input.GetKeyUp(KeyCode.W) || Input.GetKeyUp(KeyCode.S) || Input.GetKeyUp(KeyCode.D))
    {
        GetComponent<Rigidbody2D>().velocity = new Vector2(0f, 0f);
        animator.SetInteger("Direction", 4);
        animator.SetFloat("MoveSpeed", 0);
    }

```
> 1 votes

# Answer
I handled one of mine as follows:

```
int direction=0; //0,1,2,3=N,E,S,W
bool walking = false;
...
if(Input.GetKeyDown(KeyCode.A))
{
    direction=3;
    walking=true;
}
if(Input.GetKeyDown(KeyCode.S))
{
    direction=2;
    walking=true;
}
if(Input.GetKeyDown(KeyCode.D))
{
    direction=1;
    walking=true;
}
if(Input.GetKeyDown(KeyCode.W))
{
    direction=0;
    walking=true;
}
if(Input.GetKeyUp(KeyCode.A) || Input.GetKeyUp(KeyCode.S) || Input.GetKeyUp(KeyCode.W) || Input.GetKeyUp(KeyCode.D))
{
    walking=false;
}

```

This allowed direction to stay at the last value, so the character stayed facing the same way. The idle sprite sheet is chosen based on direction, and if walking is false, it did not play the animation, just showing the first frame. It also allowed my animation controller to be very simple, with state change dependent on "direction", and animation play based on "walking".
> 0 votes

---
Tags: unity, c#, 2d, animation
---


# Question
Title: Three levels deep composition (player<-character<-spell), with preset character+skill sets
So I'm creating a rather generic strategy game similar to Warcraft or League of Legends, which needs to have:

* a `Player` class for representing the users playing the game
* a `Character` class for the character the user is controlling (champions in LoL, heroes in Warcraft)
* a `Spell` class for the spells each character has

Also, each player can own multiple characters, but only one can be active at a time (for now at least...)

So the design issue I'm having is with defining the characters and spells:

I want there to be "presets", similar to how Warcraft and LoL have predefined sets of heroes/champions + spells, i.e. you don't get to choose which spells you want for your character, but you choose a character and it has its own unique spells. And multiple people can pick the same character, in which case they have the same spells too, just on different levels.

First I thought to just create `Character` and `Spell` classes, but it's not that simple, since I want it to be easy to define new characters, and defining a character isn't as simple as just creating a new object like this:

```
char = Character(name='Warrior', spells=[...])

```

Since I want every player who wants to play "Warrior" to have the same set of spells (every warrior should have `FireBall` spell while mages have `FrostBolt`, for example) and same name (Warrior), but different instances.

How should I define something like this? I'm using Python 3.5, but any generic design pattern to solve this is more than welcome.

# Answer
This looks like a job for the Flyweight Pattern! (Closely related to the Type Object pattern)

Here you separate the concept of a character *archetype* from the instance of the *character* itself.

You might for instance have a `CharacterArchetype` class that stores anything that doesn't change from one instance of a given character to another, things like:

* Character name
* Base stats
* Spell list
* Animation set
* Sound set
* List of visual skins
* etc.

Your `Character` class then holds a reference to its archetype, along with anything that can vary between instances:

* Controlling player (if it needs to know this)
* Current HP / energy meter(s)
* Modified stats (eg. if under the effect of a buff, debuff, or status effect)
* Spell cooldowns
* Movement state
* Visual representation (using a particular skin)
* etc.

You can spawn many character instances referencing the same read-only archetype data, without redundantly repeating the definition of "Warrior" or "Mage" every time you need a new instance.

Your archetypes would likely be defined in one or more data files so they're easy to edit, especially if you're working in a team with character/combat designers who might not be best-suited to working in code directly.
> 3 votes

---
Tags: architecture, python, design-patterns, data-structure, oop
---


title: SECTR sectors & global state

text:
# Question
Title: SECTR sectors & global state
For our game we decided to give SECTR (https://www.assetstore.unity3d.com/en/#!/content/15356) a try. SECTR loads scenes additively into the main scene, which enables us to work on it concurrently. It also unloads scenes when they aren't used.

Time is very important in our game and objects have to perform actions at a certain time or have to be in a certain state at a time. We decided to have those actions/events local to the sector. So now when the sector is unloaded, we lose the current progress of our action/event.

What is a good way to save this progress and how could we apply differences in time between unloading and loading to this progress? How do we handle events happening while the sector is unloaded?

The obvious solution is to use global state for these events, but we'd like to keep it local to the sectors.

# Answer
> 1 votes
You have three requirements here:

* Sectors can be unloaded
* Time-based interactions keep running everywhere
* Interactions are executed locally within each sector

You may satisfy any two, but not all three:

* If sectors can be unloaded and their interactions keep running, then those interactions must be executed elsewhere, outside of the sector itself.
* If interactions run locally in each sector and must keep running, then you can't unload any sectors with time-based scripts running.
* If interactions run locally and you unload sectors, then time-based interactions will sometimes stop running for unloaded sectors.

So, what compromises can we choose?

You could write an editor pre-processor script that, on run/build, scans all of your scenes and logs any time-based scripts in each, using this to build a data model that can execute time-based interactions in a GameObject that's never unloaded. It can communicate with objects that are currently loaded or when they load in, synchronizing them to the state of this global model. That lets you keep the convenience of authoring your interactions locally in each sector, while it can still execute globally even when sectors are unloaded.

Or, depending on the nature of your events, you might be able to save a timestamp when a given sector was last unloaded and, when it's next loaded, have all its scripts read the elapsed time and fast-forward their state, retroactively accounting for everything that "happened off-screen." This fast-forwarding can become complicated though, and won't allow you to handle interactions or propagation between sectors, or events that need to raise some signal the moment they occur.

---
Tags: unity
---


title: How does XNA/MonoGame project 3d to 2d?

text:
# Question
Title: How does XNA/MonoGame project 3d to 2d?
I am trying to figure out how XNA is actually projecting a 3d world space coordinate to screen space.

I decompiled the MonoGame framework and copied the CreateLookAt und CreatePerspectiveFieldOfView methods of Matrix and multiplied thereafter 3 vectors like XNA does:

First multiply each position with world, then multiply resultig new vector4 with view and then the new resulting vector4 finally by projection.

```
      public static Vector2<T> Project(Vector3<T> source, Matrix4x4<T> world, Matrix4x4<T> view, Matrix4x4<T> projection, int width, int height)
    {
        Vector4<T> worldPosition = world * new Vector4<T>(source.X.ParseToNumeric<T>(), source.Y.ParseToNumeric<T>(), source.Z.ParseToNumeric<T>(), 1);
        Vector4<T> viewPosition = view * worldPosition;
        Vector4<T> position = projection * viewPosition;

        var X = position.X.ParseToNumeric<T>();
        var Y = position.Y.ParseToNumeric<T>();
        var Z = position.Z.ParseToNumeric<T>();

        return new Vector2<T>((X / Z) + width / 2, (Y / Z) + height / 2);

    }

```

Because (0,0,0) would be the center of the screen I added to the corresponding X and Y coordinates width and height divided by 2. Just because it made sense I divided finally the xy components by z.

The result is sobering:

I used following matrices:

```
      basicEffect.World = Matrix.Identity;
        basicEffect.View = Matrix.CreateLookAt(new Vector3(0, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 1, 0));
        basicEffect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 0.1f, 1000.0f);

```

And these points:

```
            vertices[0] = new VertexPositionColor(new Vector3(0, 0, 2), Color.Red);
        vertices[1] = new VertexPositionColor(new Vector3(1, 0, 2), Color.Red);
        vertices[2] = new VertexPositionColor(new Vector3(0, 1, 2), Color.Red);

```

Do you know why this happens?

# Answer
> 1 votes
MonoGame and XNA use a drawing API (such as OpenGL or DirectX), these operate on coordinates between -1 and 1, and they convert the output to device coordinates after everything is calculated (before the fragment shader basically), that's why your triangle is so big on the second image.

To make the triangle look correct, you need to multiply the 2d coordinates you get as a result with the width and height of the window.

---
Tags: xna, 3d, monogame, projection
---


# Question
Title: Tiled deferred shading without compute shader
I'm building a deferred renderer and since I want to support a large amount of lights in the scene I've had a look at tiled deferred shading.

The problem is that I have to target OpenGL 3.3 hardware and it doesn't support GLSL compute shaders.

Is there a possibility to implement tiled deferred shading with normal shaders?

# Answer
> 1 votes
You can sort of fake it with a pixel shader, but it requires an extra pass. I don't claim this is a great approach, BUT it will work:

Create two low-res render targets - say, 1/8th of your framebuffer size - and render each of your lights. Render to the first target, with the second bound to a sampler. In your PS, sample the second target, set a bit in the result corresponding to the light's ID, and write it to the first (gl\_Color, output var or whatever). CPU side, swap the two targets and repeat for each light.

When you're done, you'll have a texture where every texel has a bit set for the lights that touch it.

This isn't nearly as flexible as using compute, especially async compute, but it'll take some pressure off of the lighting pass.

# Answer
> 0 votes
Yes, you can. The issue is performance. The main benefit of tiling is that it enables the use of compute shaders so that you can short circuit your rendering logic and avoid unnecessary calculations.

There's no reason you can't do the same thing without compute shaders but the problem is that you will have much less pleasing performance. Which makes it kind of pointless.

So if you want to use tiled deferred shading then it's probably better to use separate deferred shading implementations for versions of ogl that support compute shaders and the ones that don't.

---
Tags: opengl, deferred-rendering, deferred-shading
---


# Question
Title: libgdx UI coordinate consistency in a scaled window
I'm having an issue that I'm sure boils down to something simple that I've missed: The UI Graphics can't handle a window resize. Either the graphics get stretched, or the placement is incorrect.

For now I'm working with just one UI element consisting of a Sprite, until i've gotten the project to render properly. Its position is defined in a Settings-class when the asset is loaded:

```
    touchpadBG = new Sprite(assets.get("ui/joystick_background.png", Texture.class));
    touchpadBG.setCenter(Settings.touchpadPositionX, Settings.touchpadPositionY);

```

... and drawn like so:

```
batch.setProjectionMatrix(gameCam.combined);
batch.begin();
// Draw the gameworld. This is done without any issues.

batch.setProjectionMatrix(uiCam.combined);
touchpadBG.draw(batch);

batch.end();

```

uiCam is defined like this:

```
    this.uiCam = new OrthographicCamera(Settings.windowSize_X, Settings.windowSize_Y);
    uiCam.translate(Settings.windowSize_X / 2, Settings.windowSize_Y / 2, 0);
    uiCam.update();
    uiViewport = new FitViewport(Settings.windowSize_X, Settings.windowSize_Y, uiCam);
    uiViewport.apply();

```

I've experimented with different viewports (and no viewport), and while correct placement happens at first, resizing the window will result in the UI element being drawn in the wrong position, stretched, or both.

I then suspected my resize/update methods being off, but I can't find anything wrong:

```
public void resize(int w, int h) {
    uiViewport.update(w, h);
    update();
}

public void update() {
    aspectRatio = (float)Gdx.graphics.getHeight() / (float)Gdx.graphics.getWidth();
    uiCam.update();
    gameCam.update();
}

```

Any ideas where I'm going wrong with this? If my post is missing a relevant part of my code, leave a comment, and I'll edit it in.

# Answer
Fixed it. For starters, I was using the wrong viewport. Changing `uiViewport` to a `ScreenViewport` fixed the scaling issue. Apart from that, I had overlooked the fact that I didn't `apply()` the new viewport after resizing.

uiCam and uiViewport is now created like this:

```
this.uiCam = new OrthographicCamera(Settings.windowSize_X, Settings.windowSize_Y);
uiCam.translate(Settings.windowSize_X / 2, Settings.windowSize_Y / 2, 0);
uiCam.update();
uiViewport = new ScreenViewport(uiCam);
uiViewport.apply();

```

Resize and update methods:

```
public void resize(int w, int h) {
    uiViewport.update(w, h, true);
    uiViewport.apply();
    update();
}

public void update() {
    uiCam.update();
    gameCam.update();
}

```

Works like a charm: Touchpad stays in the correct position, and it's rever stretched.
> 0 votes

---
Tags: libgdx, rendering, gui, projection
---


# Question
Title: UE4 crashing after compiling, anyway to fix?
I'm working on a small game project and made a completely noob mistake and don't have a back up. Well, after compiling my most recent c++ code, the engine crashed. And now every time I try to reopen it it just crashes. I opened up the Visual Studio files and commented out the code. Is there a way to compile this to the project and get it to open again? I really don't want to have to remake the entire level.

# Answer
You can rebuild the engine *from* the Visual Studio project files. Just open the `.sln`, find the `.vcxproj` corresponding to your game, right-click it, and pick "Build." "Rebuild" will clean and rebuild the project if you want to be safe (this will take longer).
> 4 votes

---
Tags: c++, unreal-4, visual-studio
---


# Question
Title: How to achieve 'forward' movement (into the screen) using Cocos2D?
I'm interested in creating a 2.5D first-person shooter (like Doom) and I currently don't understand how to implement the player moving forward. The player will also be able to browse around the world (left, right, up, down) via gyroscope control. I plan to only use 2D sprites and no 3D models.

My first attempt was to increase the scale of layers to make it appear as if the player was moving toward the objects but I'm not sure how to make it seem as if the player is passing around the objects (instead of running into them).

If there are extensions that I should take a look at (like Cocos3D), please let me know. Thanks for the help!

# Answer
> 1 votes
Your solution, thus-far, implies you are already calculating depth to determine the scale factor needed to simulate perspective. To make objects move "behind" the camera, test that same depth when you draw them and do not draw objects whose depth indicates they should be behind the camera.

```
 if (object.sceneDepth >= 0) object.Draw();

```

Re:

> (like Doom)

I recommend going 3D, although I can't recommend any specific extensions. I would not avoid using 3D because of a perceived learning curve.

Doom and many other games use animated "billboards" to quickly approximate 3D. A billboard is simply a textured quad that always faces the camera. As the billboard rotates, the texture displayed on it can be animated to reflect the camera's new location and perspective. This allows you to render in "3D" while only actually rendering 4 vertices.

So, to answer your question, while you are able to render 2D sprites at different depths into the screen, it would be complicated, at best, to splice that together into something "like Doom".

If you look at the textures for Doom, you will find that every pose, for every creature was pre-rendered. When you move "behind a monster", the billboard is turned to face you, and the front-view monster texture is replaced with the rear-view monster texture. They were all 2D textures, drawn on 2D squares, oriented in 3D space.

Grass and trees are sometimes rendered with only one texture, but it is obvious because the trees can be easily noticed turning to face you. Their use is also evident in games where the grass becomes visible and appears to "stand up" when the camera gets close.

# Answer
> 0 votes
I know this is kind of a cop-out, but I bet you can get a lot out of the Doom source code on github: https://github.com/id-Software/DOOM

It has spurred more than a couple Doom-likes and at the very least is maintained well enough that you could emulate a lot of the implementation there and still be very original. Even if you don't have linux to compile it on, it's a great starting point for this kind of project.

# Answer
> 0 votes
If you're really reluctant to go into full-on 3D programming, I would suggest looking into **raycasting**. A very good explanation of this technique (coded in Javascript) can be found on this webpage.

Raycasting is pretty simple, mathematically. A raycaster's in-game camera will send out abstract "rays" that are meant to collide with solid objects in the environment. Upon collision, the engine receives the distance from the camera to the collision point, then renders a vertical subslice of the target texture, scaled down in proportion to how far away it was.

Due to the nature of a raycasting renderer, the camera / player itself can have full 360-degree motion and floating-point positional coordinates, even if your environment is defined as a discrete 2D array. This can help you with your need for the player to feel like he/she is moving around objects, rather than into them.

# Answer
> -1 votes
I experimented with a simple raycaster for Cocos2d-x. Check out the write-up with links to video and source here:

http://discuss.cocos2d-x.org/t/making-a-first-person-game-using-cocos2d-x/

---
Tags: mathematics, cocos2d-iphone, cocos2d, first-person-shooter, 2.5d
---


# Question
Title: How to implement 3d maneuver gear physics in unity?
I am trying to create a attack on titan styled game for a school project. I am not new to programming, but I am new to game development. I couldn't find any resources for this, hence I am posting it here.

How do I go about implementing 3d maneuver gear physics from attack on titan anime?

**What is it?**

In case you don't know, here's a brief link about 3d maneuver gear.

A brief commentary about 3dMG

It's basically a grappling hook based system (similar to what you would find in a spiderman game), but it has different components to it, which makes it quite complex to think about.

**My Approach so far**

I have seen tutorials on how to use hooks in unity and stuff, but it would be great if someone could give me a general idea as to how to even start with this kind of thing. I would appreciate your answer, even though it is not unity specific.

The idea is to have two points on the character, from where we fire the ropes. These ropes could simply be graphics (or unity's RaycastHit). And then we would also need information about the hook "hit point". Once we know that, we just reel in ourselves towards that. However the problem is that I don't know how to use momentum etc to effect the character's movement. Also since it's not just one rope(like a spiderman's game), but two, it's even difficult to think as to how would the movement be if user uses only left hook, or right hook or both. Also there is this gas aspect, which would propel you further and it should also be taken into account, along with momentum that we would carry.

So any general idea would be greatly appreciated.

# Answer
I think the components you are looking for are Rigidbody for an object which maintains momentum and the SpringJoint to model the ropes. Spring joints can stretch and will then exert a force which retracts the connected object. This can be used to propel it forward.

You can add multiple spring-joints to an object which connect it to other objects. When you have one joint connecting the character to building A and one connecting the character to building B, both of their forces will apply and the character will move to where the equilibrium lies.

A directional acceleration which doesn't come from the springs (the "propelling gas") can be implemented by adding a force to the rigidbody.
> 1 votes

---
Tags: unity, c#, physics, rotation
---


# Question
Title: How to turn the car when pressing left or right key
I am new to canvas and developing a game where a car moves straight and now I want to turn the car to anti clockwise when the left key is pressed and clockwise when right key is pressed.

Currently I am trying with

```
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");

 function drawSprite(image, x, y, scale = 1,angle = 0){
    ctx.setTransform(scale, 0, 0, scale, x, y); // set scale and center of sprite
    ctx.rotate(angle);
    ctx.drawImage(image,- image.width / 2, - image.height / 2);
    ctx.setTransform(1,0,0,1,0,0); // restore default transform
                                   // if you call this function many times
                                   // and dont do any other rendering between
                                   // move the restore default line
                                   // outside this function and after all the
                                   // sprites are drawn.
}
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
    heroReady = true;
};
heroImage.src = "images/car.png";
  if (37 in keysDown) { // Player holding left
  drawSprite(heroImage, hero.x, hero.y, scale = 1,angle = 90);
}

```

But this does not work at all.I only want the car to be turned and not the screen.Any help is appreciated. My source code: working pen In case the above code is not enough you may look into to the below one game.js

```
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 1024;
canvas.height = 1024;
document.body.appendChild(canvas);
function drawSprite(image, x, y, scale = 1,angle = 0){
    ctx.setTransform(scale, 0, 0, scale, x, y); // set scale and center of sprite
    ctx.rotate(angle);
    ctx.drawImage(image,- image.width / 2, - image.height / 2);
    ctx.setTransform(1,0,0,1,0,0); // restore default transform
                                   // if you call this function many times
                                   // and dont do any other rendering between
                                   // move the restore default line
                                   // outside this function and after all the
                                   // sprites are drawn.
}
// Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
    bgReady = true;
};
bgImage.src = "http://res.cloudinary.com/dfhppjli0/image/upload/v1491958481/road_lrjihy.jpg";

// Hero image
var heroReady = false;

var heroImage = new Image();
heroImage.onload = function () {
    heroReady = true;
};
heroImage.src = "http://res.cloudinary.com/dfhppjli0/image/upload/c_scale,w_32/v1491958999/car_p1k2hw.png";

//Second Taxi
var heroReady3 = false;
var heroImage3 = new Image();
heroImage3.onload = function () {
    heroReady3 = true;
};
heroImage3.src = "images/taxi3.png";

var heroswitchobj = false;
var heroSwitch = new Image();
heroSwitch.onload = function () {
    heroswitchobj = true;
};
heroSwitch.src = "images/taxi9.png";

var heroswitchobj3 = false;
var heroSwitch3 = new Image();
heroSwitch3.onload = function () {
    heroswitchobj3 = true;
};
heroSwitch3.src = "images/taxi9.png";

/*
for(i=0;i<3;i++){

var str="heroReady";
var strImage="heroImage";

str=str1.concat(i);
var str = false;
var heroImage = new Image();
heroImage.onload = function () {
    heroReady = true;
};
heroImage.src = "images/taxi.png";

}
*/

// Monster image
var monsterReady = false;
var monsterImage = new Image();
monsterImage.onload = function () {
    monsterReady = true;
};
monsterImage.src = "http://res.cloudinary.com/dfhppjli0/image/upload/v1491959220/m_n1rbem.png";

var monsterReady3 = false;
var monsterImage3 = new Image();
monsterImage3.onload = function () {
    monsterReady3 = true;
};
monsterImage3.src = "http://res.cloudinary.com/dfhppjli0/image/upload/v1491959220/m_n1rbem.png";

var monsterReady9 = false;
var monsterImage9 = new Image();
monsterImage9.onload = function () {
    monsterReady9 = true;
};
monsterImage9.src = "http://res.cloudinary.com/dfhppjli0/image/upload/v1491959220/m_n1rbem.png";

var monsterReady12 = false;
var monsterImage12 = new Image();
monsterImage12.onload = function () {
    monsterReady12 = true;
};
monsterImage12.src = "http://res.cloudinary.com/dfhppjli0/image/upload/v1491959220/m_n1rbem.png";

// Game objects
var hero = {
    speed: 256 // movement in pixels per second
};
var hero3 = {
    speed: 256 // movement in pixels per second
};
var herochange = {
    speed: 256 // movement in pixels per second
};
var hero3change = {
    speed: 256 // movement in pixels per second
};
function drawRotated(degrees){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.save();
    ctx.translate(canvas.width/2,canvas.height/2);
    ctx.rotate(degrees*Math.PI/180);
    ctx.drawImage(image,-image.width/2,-image.width/2);
    ctx.restore();
}

var monster = {};
var monster3 = {};
var monster9 = {};
var monster12 = {};

var monstersCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
    keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function (e) {
    delete keysDown[e.keyCode];
}, false);
var count=0;
// Reset the game when the player catches a monster
var reset = function () {

    hero.x = canvas.width / 2;
    hero.y = canvas.height / 2;

    hero3.x = canvas.width / 1.5;
    hero3.y = canvas.height / 1.5;

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

    monster3.x = 32 + (Math.random() * (canvas.width - 64));
    monster3.y = 32 + (Math.random() * (canvas.height - 64));

    monster9.x = 32 + (Math.random() * (canvas.width - 64));
    monster9.y = 32 + (Math.random() * (canvas.height - 64));
    monster12.x = 32 + (Math.random() * (canvas.width - 64));
    monster12.y = 32 + (Math.random() * (canvas.height - 64));
};

var reset_monster_only= function (s) {

if(s==1){

}
/*        if(heroswitchobj){
        ctx.drawImage(herochange, hero.x, hero.y);

        }

        if(heroswitchobj3){

        ctx.drawImage(herochange3, hero3.x, hero3.y);
        }
*/

    monster.x = 32 + (Math.random() * (canvas.width - 64));
    monster.y = 32 + (Math.random() * (canvas.height - 64));

    monster3.x = 32 + (Math.random() * (canvas.width - 64));
    monster3.y = 32 + (Math.random() * (canvas.height - 64));

    monster9.x = 32 + (Math.random() * (canvas.width - 64));
    monster9.y = 32 + (Math.random() * (canvas.height - 64));
    monster12.x = 32 + (Math.random() * (canvas.width - 64));
    monster12.y = 32 + (Math.random() * (canvas.height - 64));
};

var angleInDegrees=0;

// Update game objects
var update = function (modifier) {

        hero.y -= hero.speed * modifier;
        hero3.y += hero3.speed * modifier;

    if (38 in keysDown) { // Player holding up
        hero.y -= hero.speed * modifier;
        hero3.y += hero3.speed * modifier;
    }
    if (40 in keysDown) { // Player holding down
        hero.y += hero.speed * modifier;
        hero3.y -= hero3.speed * modifier;
    }
    if (37 in keysDown) { // Player holding left

        //ctx.clearRect(0,0,canvas.width,canvas.height);
        //ctx.save();

     drawSprite(heroImage, x, y, scale = 1,angle = 90)
       //drawRotated(angleInDegrees);
        //hero.x=hero.y;
        //hero.y=hero.y-32;
        //hero.x -= hero.speed * modifier;
        //hero3.x += hero3.speed * modifier;
    }
    if (39 in keysDown) { // Player holding right
        //hero.x += hero.speed * modifier;
        //hero3.x -= hero3.speed * modifier;
    }

    // Are they touching?
    if (
        hero.x <= (monster.x + 32)
        && monster.x <= (hero.x + 32)
        && hero.y <= (monster.y + 32)
        && monster.y <= (hero.y + 32)
    ) {
        ++monstersCaught;
        reset_monster_only(1);
    }

if (
        hero3.x <= (monster.x + 32)
        && monster.x <= (hero3.x + 32)
        && hero3.y <= (monster.y + 32)
        && monster.y <= (hero3.y + 32)
    ) {
        ++monstersCaught;
        reset_monster_only(2);
    }

   if (
        hero3.x <= (monster3.x + 32)
        && monster3.x <= (hero3.x + 32)
        && hero3.y <= (monster3.y + 32)
        && monster3.y <= (hero3.y + 32)
    ) {
        ++monstersCaught;
        reset_monster_only(3);
    }

if (
        hero.x <= (monster3.x + 32)
        && monster3.x <= (hero.x + 32)
        && hero.y <= (monster3.y + 32)
        && monster3.y <= (hero.y + 32)
    ) {
        ++monstersCaught;
        reset_monster_only(4);
    }

if (
        hero.x <= (monster9.x + 32)
        && monster9.x <= (hero.x + 32)
        && hero.y <= (monster9.y + 32)
        && monster9.y <= (hero.y + 32)
    ) {
        ++monstersCaught;
        reset_monster_only(5);
    }

if (
        hero3.x <= (monster9.x + 32)
        && monster9.x <= (hero3.x + 32)
        && hero3.y <= (monster9.y + 32)
        && monster9.y <= (hero3.y + 32)
    ) {
        ++monstersCaught;
        reset_monster_only(6);
    }
    if (
        hero.x <= (monster12.x + 32)
        && monster12.x <= (hero.x + 32)
        && hero.y <= (monster12.y + 32)
        && monster12.y <= (hero.y + 32)
    ) {
        ++monstersCaught;
        reset_monster_only(7);
    }

if (
        hero3.x <= (monster12.x + 32)
        && monster12.x <= (hero3.x + 32)
        && hero3.y <= (monster12.y + 32)
        && monster12.y <= (hero3.y + 32)
    ) {
        ++monstersCaught;
        reset_monster_only(8);
    }

if (hero3.x >= (canvas.width)   || hero3.y >= (canvas.height)) {

        reset();
    }
if (hero.x >= (canvas.width) || hero.y >= (canvas.height)) {

        reset();
    }

};

// Draw everything
var render = function () {
    if (bgReady) {
        ctx.drawImage(bgImage, 0, 0);
    }

    if (heroReady) {
        ctx.drawImage(heroImage, hero.x, hero.y);
        ctx.drawImage(heroImage, hero3.x, hero3.y);
    }

    if (monsterReady) {
        ctx.drawImage(monsterImage, monster.x, monster.y);
        ctx.drawImage(monsterImage3, monster3.x, monster3.y);
        ctx.drawImage(monsterImage9, monster9.x, monster9.y);
        ctx.drawImage(monsterImage12, monster12.x, monster12.y);
    }

    // Score
    ctx.fillStyle = "rgb(250, 250, 250)";
    ctx.font = "24px Helvetica";
    ctx.textAlign = "left";
    ctx.textBaseline = "top";
    ctx.fillText("Points: " + monstersCaught, 32, 32);
};

// The main game loop
var main = function () {
    var now = Date.now();
    var delta = now - then;
setTimeout(update(delta/1000), 10000);
    //update(delta / 1000);
    render();

    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();

```

Edit:I updated the working pen and the main objective I am trying is to get the car moved whenever it is turned left or right

# Answer
You have to save the context of the canvas and reload it after you draw the sprite:

```
ctx.save();
// Rotate the canvas and draw the sprite here
ctx.restore();

```

You also don't need to reset the transform if you do this.

Additional notes:

You don't need to reference `requestAnimationFrame` with `window.requestAnimationFrame`. Everything in the window object is available globally.
> 1 votes

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


title: Overuse of Canvas in Unity3D

text:
# Question
Title: Overuse of Canvas in Unity3D
I'm currently trying a new approach on a Card Game in Unity.

To capsuling my `Card Prefab` i have a root GameObject with the `Canvas Component`.

I'm highly count on the Canvas behavior which should render things after the main scene rendering.

> Elements on a canvas are rendered AFTER scene rendering, either from an attached camera or using overlay mode.

Before i further proceed, i want to know if there are any disadvantage of this, when my Game Logic approximately generate 100-200 of this GameObjects?

Should the `Canvas Component` not be overused in Unity?

# Answer
> 2 votes
Canvas is rendered in the "RenderOverlay" call in he render pipeline. If we are talking about screen overlay the canvas is simply rendered in 2D space over anything previously rendered, which always happens last. I'm not entirely sure why this was in your question?

The advantage of Canvas is that it can render multiple sprites in one go, if and only if their states are the same. The batching technique is mostly useful if you're drawing lots of things to the screen. I'm assuming that each canvas is holding its own buffer for vertices ( I can't be too sure about it but as John Hamilton stated, it suggest to be the case ). I'm not entirely sure if 100-200 canvases will help you with performance Per se.

The mesh of the canvas is build dynamically by pushing vertex data to the buffer based on their screen coordinates, size and scaling, this is done cpu side which is then uploaded to the GPU, so there is a bit of work involved for your computer.

So ideally if you have a layout that doesn't change, you want to keep that in a separate canvas so that the buffer doesn't have to be rebuild and uploaded. Likewise if you have moving parts you want to keep those in a separate canvas as well.

Going back to your 100-200 canvases, I'm not really seeing the advantage here by giving your moving objects several canvases. If my assumption is correct about canvases managing their own buffers, you're creating a lot of them, and it is also safe to assume these buffers are created bigger to accommodate at least a couple of sprites. You're wasting memory and you're doing a lot more calls to the gpu to update the data.

It isn't clear if those canvases have static layouts or moving parts either.

You have to test some of this yourself. Use the Frame debugger ( or RenderDoc) to see what is going on when objects are rendered and what buffers are created.

---
Tags: unity, unity-ui, card-game
---


# Question
Title: Identify objects of the same type from each other, even between game restarts?
So I have a simple `Character` class:

```
class Character:

    def __init__(self, type, level, health, items=None):
        self._type = type
        self.level = level
        self.health = health
        self.items = items if items is not None else []

    def __getattr__(self, attr):
        return getattr(self._type, attr)

```

And a `CharacterType`:

```
class CharacterType:

    def __init__(self, name, max_level, max_health):
        self.name = name
        self.max_level = max_level
        self.max_health = health

    def new(self, *args, **kwargs):
        return Character(type=self, *args, **kwargs)

```

This allows me to easily spawn multiple instances of the same character type:

```
t_dragon = CharacterType('Dragon', 30, 2080)
t_mage = CharacterType('Mage', 100, 610)

dragon0 = t_dragon.new()
dragon1 = t_dragon.new(health=437)  # Damaged one
mage0 = t_mage.new(level=50)

```

But now I need to store these into a database table, and be able to somehow identify the character's type. I can't create a separate table for each type, since these types will be manageable by designers through JSON and thus new types can be added dynamically and old types be removed. So as it stands now, the above characters would populate the `character` table like so:

```
 id | level | health | type_identifier
----+-------+--------+-----------------
 0  | 0     | 2080   | ????
 1  | 0     | 437    | ????
 2  | 50    | 610    | ????

```

I would *highly* prefer if there's a solution which doesn't require the designers to have to come up with an unique ID themselves, so while something like this would work, where the designer comes up with an unique ID:

```
{
    "name": "Dragon",
    "max_level": 30,
    "max_health": 2080,
    "unique_id": "#dragon_2017-04-12"
}

```

and keeps it even if they change the character's `name`, it's very bothersome to have to maintain something like this in the JSON itself.

How can I get a string/integer/value to identify the character types (Python objects) from each other, in a consistent manner between server restarts, without the designer having to manually come up with an unique ID?

# Answer
I would suggest using GUID \- it is widely used and pretty much every language/lib has an implementation, python included.

A common practice is to express it as hexadecimal string, possibly also truncate generated GUID to a shorter one (whether that is wise depends on particular case). You can also consider using GUID in conjunction with a "friendly" name, an alias that can be set manually.

An alternative would be to use hash, it is not trivial to create good hash function however - especially in context of game objects, where even for duplicates different hash might be needed.
> 1 votes

---
Tags: python, databases, gameobject, objects
---


# Question
Title: Can I clip a collection of geometry to render only inside a particular worldspace volume?
I am making a VR app in Unity. I have a giant map that I want to display on a virtual table. The map is too large to fit on the table, and I cannot change its size. (It is a third party asset, and does not easily have that capability.)

How can I tell the camera not to render the parts of the map that fall off of the table? Perhaps something along the lines of:

```
Camera.DoNotRender(new Vector3(100, 0, 0));

```

I have been looking into using some `MonoBehaviour` messages such as `OnPreRender`, `OnRenderObject`, etc. But I do not know which one can help me, if any. Ideally, the pixels behind the non-rendered pixels should be rendered, but that is not my priority.

The map is made up of 100s of little renderers:

How can I have my Camera not render specific world space pixels?

# Answer
One way to do this is with the `clip` function in a shader, which aborts rendering of a pixel if it fails a particular condition.

This lets you create custom-shaped clipping regions, but it has a downside: by the time you reach the clip test, most of the work of rasterizing the object is already done, so you end up paying a significant amount for the invisible portions of the model that don't actually get drawn in the end.

Be sure to profile this to determine whether it's an issue in your particular application - it might not be. If it is, there are some additional tricks you can use with depth, stencil, and off-screen buffers to exclude some of the redundant geometry.

---

**Edit:** a neat trick I've just learned is if you introduce a `NaN` or infinity into a vertex position, you can abort rendering of triangles using that vertex. So this can let you do some of this clipping per-vertex instead of solely per fragment, saving some rasterization costs.

```
v.vertex.x /= step(outOfBounds, 0.1f);

```

You need a margin like that `0.1f` there that's bigger than your typical triangle - otherwise you can have a vertex outside your clipping margin abort a whole triangle that's partly inside the clipping volume.

Note that this doesn't seem to be an officially documented feature, just something GPUs tend to do 'cause how else are they going to render that triangle? ;)

---

Here's an example shader using this approach - use something like this on your map material to achieve the clipping:

```
Shader "Custom/ClipVolume" {
    Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0

        // Expose parameters for the minimum x, minimum z,
        // maximum x, and maximum z of the rendered volume.
        _Corners ("Min XZ / Max XZ", Vector) = (-1, -1, 1, 1)
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200

        // Allow back sides of the object to render.
        Cull Off

        CGPROGRAM

        #pragma surface surf Standard fullforwardshadows
        #pragma target 3.0

        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
            float3 worldPos;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;

        // Read the min xz/ max xz material properties.
        float4 _Corners;

        void surf (Input IN, inout SurfaceOutputStandard o) {

            // Calculate a signed distance from the clipping volume.
            float2 offset;
            offset = IN.worldPos.xz - _Corners.zw;
            float outOfBounds = max(offset.x, offset.y);
            offset = _Corners.xy - IN.worldPos.xz;
            outOfBounds = max(outOfBounds, max(offset.x, offset.y));
            // Reject fragments that are outside the clipping volume.
            clip(-outOfBounds);

            // Default surface shading.
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
            o.Albedo = c.rgb;
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = c.a;
        }
        ENDCG
    }
    // Note that the non-clipped Diffuse material will be used for shadows.
    // If you need correct shadowing with clipped material, add a shadow pass
    // that includes the same clipping logic as above.
    FallBack "Diffuse"
}

```

Here's what it looks like on Unity's "Ethan" model:

And here it is using the triangle aborting trick above to remove some of the excess geometry outside the clipping volume:
> 6 votes

# Answer
Using Stencils is another simple option

Stencil lets you use a "mask" to define where the shader is rendered. This is incredibly flexible and easy to modify in the editor.

here's unity's documentation

https://docs.unity3d.com/Manual/SL-Stencil.html

To use it, you'll need to put this in the "mask" shader

```
Stencil{
    Ref 1
    comp always
    Pass replace
}

```

and then this in the map render shader

```
Stencil{
    Ref 1
    comp Equal
    Pass keep
}

```

This way only pixels viewed "through" the mask will be rendered.
> 1 votes

---
Tags: unity, 3d, shaders, rendering, transparency
---


# Question
Title: How to set a Label position after a timer ends, in a repetitive structure?
I have this fragment of code. It moves a pawn on a board.

```
while(i<end)
{
    try
    {
        Thread.sleep(1000);
    }
    catch (Exception e)
    {
       System.out.println(e);
    }
    Label.setBounds(x+i, y, xsize, ysize);
    i++;
}

```

My problem: The Label gets set only once, after all the time(`end` seconds) passes.

Also tried:
1:

```
while(i<end)
{
    for(int v;v<9999999;v++);
    Label.setBounds(x+i, y, xsize, ysize);
    i++;
}

```

2:

```
while(i<end)
{
    for(int v;v<9999999;v++)
    {
        Label.setBounds(x+i, y, xsize, ysize);
    }
    i++;
}

```

With same result.

# Answer
> 0 votes
This ain't a simple task. First: i am not sure which Java Framework for windows (awt, Swing, JavaFX) you are using. Since i personally am most confident with JavaFX, i will refer to JavaFX in my answer.

Java does not repaint its interface every X miliseconds, but whenever the main thread is idle. As long as your application DOES stuff, it won't repaint, and won't show progress. So if you update your label within a loop, only the last label text will actually be repainted once the loop ends.

You could circumvent that by using a thread. A thread is like a second little program, more or less independent from the main "loop" of your application. But usually, only the main thread is allowed to change interface elements, so a second thread should not be allowed to modify the GUI from within the thread.

So how do you update the label? The answer ain't exactly simple. And it depends heavily on your framework. The basic answer is: do calculations in a separate thread, and make your GUI update from the main thread. In javaFX you could **bind** the label's text to a variable and change that variable in your second thread. Some classes, like the progressBar (fantasy name, the real class name is somewhat different) also have special calls that allow to bind it to a Task's progress property.

For further info on this for JavaFX see here: http://docs.oracle.com/javafx/2/threads/jfxpub-threads.htm

A good starting point for swing is here: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/

overall, this area is kinda difficult, but once you get the hang of it, you can build nice, responsive applications. It's definately worth learning.

# Answer
> 1 votes
> Read the section from the Swing tutorial on Concurrency for more information on why this happens.

Using `javax.swing.Timer` I modified the code to this form:

```
int delay = 1000;

ActionListener taskPerformer = (ActionEvent evt) ->
{
    Label.setBounds(x+1, y, xsize, ysize);
    if(condition)
    {
        timer.stop();
    }
};

timer = new Timer(delay, taskPerformer);
timer.setRepeats(true);
timer.start();

```

It now works as intended.

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


# Question
Title: Unity 5 - Manually zooming/scaling in and out of an image with a text layer while still retaining text sharpness when zoomed?
I have a section in my scene where I have an image on a layer, as a child of this layer I have a load of text objects. I need the ability to zoom in and out of the image (it's a technical drawing, so necessary to zoom in and out), so I have set up a simple Scale of the image itself (via Playmaker) and applied the zoom in to a button and the zoom out to another button. When zoomed out, the image Scale is set to the default 1 and when zoomed in it goes to Scale 3. It works perfectly. I have also added a 'Scroll Rect' to the parent canvas, this enables me to click and scroll around the image when it is zoomed in - this also works perfectly.

However the main problem I have is that while the image looks fine zoomed in (the original image is a large size, so looks fine even when scaled up to Scale 3) - the text does not look good when scaled. It is essentially just 'zooming' in on the text and therefore the bigger it gets, the worse it looks.

Text is set to 'Best Fit' - it has to be this way due to the fact I have dynamic translations on the text, so the text needs to stay within its specified area and shrink if necessary.

Ideally I would like the text size to scale in line with the image scale - ie. if the text is size 10 when zoomed out, then it should be size 30 when zoomed x3 (as opposed to a scaled size 10) - is this possible? The text must stay in the exact same position relative to the image, as text is placed at specific points on the drawing. The text also needs to be able to be scrolled in exact line with the image (hence why I have it as a child of it, so it follows nicely).

Canvas is set to 'Screen Space - Overlay' with 'Scale with Screen Size' and 'height' at 1 (works perfectly across the game like this).

Screenshots attached...

**Canvas**

**Text**

Any help would be appreciated.

Thanks in advance

Unity 5.3.5 PC/Mac Standalone only

# Answer
> 3 votes
I've dealt with this before, and the simplest solution (which is also kind of a hack, so beware) was to scale the text transforms by the inverse of the maximum zoom, and multiply their font size by the maximum zoom. This will cause Unity to render a higher-resolution font texture that will look better when zoomed in.

Example: Your maximum zoom amount is 3x. Set the scale of all text transforms to 0.33333. Set their font size to (3 * original font size). So, for a text component that originally had the font size 10, the new font size is 30.

---
Tags: unity, text, ui-design
---


# Question
Title: How to change the color of an image when getting points
Currently I have a car game which I give points when a car touches the monster.Now extra to that I also wanted to change the color of the car or replace the car image with a different color car image when it is touching the monster.

So where I give point is

```
monsters.array.forEach(monster => {
            if(monster.isTouching(this)){
                monster.reset();
                monstersCaught += 1;
            }
        });

```

So now when I give point I also want to change the color of the car. Any help is appreciated.My pen for the game :pen

# Answer
> 1 votes
If you only have 1 car image, you can use javascript to give the car a css property `hue-rotate()` to change its color.

If you have multiple car images with different colors, you can simply change the `src` attribute using javascript to point to the new car image.

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


# Question
Title: How do I run code in sync without interrupting the main() method?
I have three activities:

1. Attack
2. Troops Training
3. Gathering Resources

I want to attack and train troops while I am gathering resources. I want these activities to run in sync.

Here is an example of one of my functions:

```
for (int x=100; x<=0; x--)
{
   sleep(50);
   playerFood += 10;
}

```

How do I make functions run in sync with each other?

# Answer
> 2 votes
You might not need parallel execution for this at all. Many actions in games that seem to play out simultaneously are in fact being stepped sequentially. It's just that we only see the updated state once they've all been advanced, so it appears they're progressing in parallel.

As long as we arrive at the new state in time to present a new rendered frame to the player 30, 60, or more times each second, then the exact order in which the events were processed doesn't matter (or at least shouldn't matter, if we've planned our dependencies right and avoided creating order-of-update bugs for ourselves)

This is called the Game Loop Pattern \- Robert Nystrom's book on such patterns does a great job explaining and motivating this pattern, so I highly recommend giving it a read.

In your case, your logic might look like this:

```
int Main() {
  while(exit == false) {
     Update_Game_State();
     Render_Frame();
     sleep(50);
  }
  return 0;
}

```

Where your update function works through each system that needs to be advanced and ticks it forward one step:

```
void Update_Game_State() {
   playerFood += 10;

   troopsTrained += 1;

   Process_Attacks();

   // etc.
}

```

If you want your harvesting/training/attack events to run at different frequencies, then you can maintain a list of ongoing events and the next timestamp when they need to occur. Your update loop can then walk the list, updating the events whose time has come and skipping anything that's still pending for the future.

There are more sophisticated game loops possible too. Glenn Fielder's "Fix Your Timestep" article outlines some popular best practices.

If you prefer to write code in a different style, where each system looks like it's running uninterrupted in parallel, but without the complications of thread synchronization, you can look into Coroutines. These are methods that can suspend their execution state midway through to let other code take a turn, then resume where they left off. I wrote about using threads vs coroutines in the context of Unity here, and similar principles will apply in other environments.

---
Tags: c++
---


# Question
Title: How to display custom UnityEvents in the editor?
I recently stumbled upon the UnityEngine.Events.UnityEvent class, and it seemed pretty cool so I started using it in a project.

Then I decided that I wanted to add some parameters to the event using its generic variants, like so:

```
[System.Serializable]
public class BarkEvent<GameObject> : UnityEvent<GameObject> {}

public class MyOtherClass : MonoBehavior {
    public BarkEvent<GameObject> bark;
    // ... Other stuff ...
}

```

But now it doesn't show up in the editor, making it harder to wire up my subscribers. Is there a way to make unity events with extra arguments show up in the Unity editor?

# Answer
> 1 votes
@JohnHamilton is right. Because Unity can't serialize generic types in the inspector (not easily, workarounds exist I think), your event won't be displayed. The purpose of inheriting from the UnityEvent type is to get rid of the generic type and be able to serialize it in order to be shown in the inspector.

Your event is "designed" to handle GameObjects only, thus, you don't have (and should not) specify the `GameObject` type between the chevrons.

```
[System.Serializable]
public class BarkEvent : UnityEvent<GameObject> {}

public class MyOtherClass : MonoBehavior {
    public BarkEvent bark;

    public void YourFunction()
    {
         if( bark != null )
             brak.Invoke( gameobject ) ;
    }
}

```

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


title: How do I render Hindi text in Libgdx?

text:
# Question
Title: How do I render Hindi text in Libgdx?
How do I render Hindi text in Libgdx using any font? For example, I want to render the word *"प्रकार"*.

Here is what I have, so far:

```
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;

public class MyGdxGame extends Game
{
    SpriteBatch spriteBatch;
    BitmapFont font;
    OrthographicCamera camera;
    String text, text1;
    private byte[] myBytes = { (byte) 0xe0, (byte) 0xa4, (byte) 0xa8,
            (byte) 0xe0, (byte) 0xa4, (byte) 0xbf, (byte) 0xe0, (byte) 0xa4,
            (byte) 0xb6, (byte) 0xe0, (byte) 0xa5, (byte) 0x89, (byte) 0xe0,
            (byte) 0xa4, (byte) 0xa4 };
    private String myName = new String(myBytes, Charset.forName("UTF-8"));
    private String hindiStr = "ँंःअआइईउऊऋऎएऐऍऒओऔऑकखगघङचछजझञटठडढणतथदधनऩप"
            + "फबभमयय़रऱलळऴवशषसहािीुूृॆेैॅॊोौॉ़्।०१२३४५६७८९INV";

    @Override
    public void create()
    {
        camera = new OrthographicCamera();
        camera.setToOrtho(false, 400, 640);
        spriteBatch = new SpriteBatch();

        FreeTypeFontGenerator generator
                = new FreeTypeFontGenerator(Gdx.files.internal("font/mangal.ttf"));
        FreeTypeFontGenerator.FreeTypeFontParameter parameter
                = new FreeTypeFontGenerator.FreeTypeFontParameter();

        // +FreeTypeFontGenerator.DEFAULT_CHARS; The characters the font should contain
        parameter.characters = hindiStr;
        parameter.size = 15;

        font = generator.generateFont(parameter);
        font.setColor(1.0f, 0.0f, 0.0f, 1.0f);

        generator.dispose();

        text = "शुभ प्रभात";
        text1 = "आप का स्वागत है";
    }

    @Override
    public void render()
    {
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        Gdx.gl.glClearColor(1, 1, 0, 1);

        spriteBatch.setProjectionMatrix(camera.combined);

        spriteBatch.begin();
        font.draw(spriteBatch, "सूक्ष्मजीवों के विभिन्न प्रकार ", 10, 30);
        font.draw(spriteBatch, myName, 10, 100);
        spriteBatch.end();
    }

    @Override
    public void resize(int width, int height)
    {
        camera.setToOrtho(false, width, height);
    }

    @Override
    public void dispose()
    {
        font.dispose();
        spriteBatch.dispose();
    }
}

```

# Answer
We can use "Chanakya" font for render the Hindi Text in correct way. Download the chanyaka.ttf from hera :

http://indiatyping.com/index.php/download/199-chanakya-font

After installing the font . You should encode your Hindi text using the coverter :

http://indiatyping.com/index.php/font-converter/unicode-to-chanakya-font-converter

Once converted the text, simply copy it to your destination and you should be good to go.
> 1 votes

---
Tags: android, libgdx, rendering, fonts
---


title: Controlling Instantiation

text:
# Question
Title: Controlling Instantiation
I have an problem where I instantiate a GameObject and it keeps on instantiating a million times over, even though I put the line of code under the start function.

I am trying to have the player collide with the coin(then a point is added to your score) , then the coin deletes itself and then re-instantiates at a random coordinate, but I cant get past the initial instantiation.

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

public class Coin : MonoBehaviour {
public GameObject coins;
Vector2 randomPosition;
public UIScript _UIScript;

// Use this for initialization
void Start () {
    _UIScript = GameObject.FindWithTag("UI").GetComponent<UIScript>();
    randomPosition = new Vector2(Random.Range(-8f, 8), Random.Range(-4f, 4f));
    Instantiate(coins, randomPosition, Quaternion.identity);
}

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

}
private void OnTriggerEnter2D(Collider2D coinCollision)
{
    switch(coinCollision.tag)
    {
            case "Player":
            collisionWithPlayer();
            break;
    }
}
private void collisionWithPlayer()
{
    _UIScript.highScore = _UIScript.highScore + 1;
    Object.Destroy(coins);
}
}

```

# Answer
*Expanding my comment.*

Well I'm not an expert with Unity, but here is what I notice.

If your variable `public GameObject coins` contains game objects of type `Coin`, and that `Start` is called when the object is instantiated, you have an infinite loop of creation of objects because `Start` will call `instantiate`, which will have `Start` called on the newly created object, which call `instantiate`, which will have `Start` called on the newly created object, *which call `instantiate`, which will have `Start` called on the newly created object, which call `instantiate`, which will have `Start` called on the newly created object, which call `instantiate`, which will have `Start` called on the newly created object, which call `instantiate`, which will have `Start` called on the newly created object, which call `instantiate`, which will have\[...\].*

Maybe you could put the call to instantiate in `collisionWithPlayer` instead, just before calling `Object.Destroy(coins);`, like such:

```
public class Coin : MonoBehaviour {
    public GameObject coins;
    public UIScript _UIScript;

    // Use this for initialization
    void Start () {
        _UIScript = GameObject.FindWithTag("UI").GetComponent<UIScript>();
        Vector2 randomPosition = new Vector2(Random.Range(-8f, 8), Random.Range(-4f, 4f));
        // Instead of setting the position of the next object here, set the position of this
        // object on its Start
        transform.SetPositionAndRotation(randomPosition, Quaternion.identity);
    }

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

    private void OnTriggerEnter2D(Collider2D coinCollision)
    {
        switch(coinCollision.tag)
        {
            case "Player":
                collisionWithPlayer();
                break;
        }
    }

    private void collisionWithPlayer()
    {
        _UIScript.highScore = _UIScript.highScore + 1;
        // Create the new object here, and let it position itself in its start method.
        Instantiate(coins);
        Object.Destroy(coins);
    }
}

```

Now I wouldn't say this is *the* way to do it (as I said, I'm not an expert with Unity), but this could probably do what you need.
> 6 votes

---
Tags: unity
---


# Question
Title: Is it possible to use Google Play Service on a game not published on Google Play?
I'm developing a game for a local Android market but for the leaderboard I'm using Google Play Services. I wanted to know whether it's possible for people to use my leaderboard without publishing on Google Play and just on that local Android market.

Problem is I got Leaderboard up and running with the GPGS but only testers can use it and I think for others be able to use it has to be out of beta and published, please correct me if I'm wrong.

Best, idn

# Answer
I think not, **some times ago it was possible using it on iOS apps** (and hence it was possible using also elsewhere), but now they deprecated the API.

I think they have no particular incentive on getting it work on other platforms but Google Play.

So basically **you have the following choice:**

1. implement your server infrastructure for your simple game
2. use the service only for Android games published in Play Store.

The service relies on remote communication, that means that theorically it is possible to get it working almost anywhere, in practice that is hard to do, and not the best maintenable option.

I think that's a smart move because most programmers to avoid problems will just stick on using it on Play Store.
> 2 votes

---
Tags: google-play-services
---


# Question
Title: Possible Framerate Problem using Pygame?
This is the first game I've ever tried to make using Pygame and I am running into some issues displaying the player character and the enemy characters. I have a "main" game file and other files that are imported into it.

Here is a picture of what I mean

So yeah. They images seem to leave behind their former selves and just keep going. Never mind that yes the dog is the one from Undertale and the cat is Pusheen lol. I will post my main code and the supporting imported files.

Here is the main game file::

### Main Game File

```
import pygame, sys, math, random
import time
# from pygame import *
from globals import *
from Start import *
from instructions import *

def main():
    pygame.init()
    FPSCLOCK = pygame.time.Clock()
    startScreen()
    displayInst()
    while True:
        #displays instructions.png on game
        for event in pygame.event.get():
            keyE = pygame.event.get(KEYUP)
            if event.type == pygame.QUIT:
                terminate()
            if event.type == pygame.KEYDOWN:
                # while True:
                DISPLAYSURF.fill(WHITE)
                runGame()
                if event.key == pygame.K_ESCAPE:
                    terminate()

def runGame():

    invulnerable = False   # if the player is invulnerable
    invulnerableStart = 0
    gameOverMode = False   # if the player has lost
    gameOverStartTime = 0  # time the player lost
    winMode = False        # if the player won
    INVULTIME = 2

    dogObjs = []  #stores all dog objects in the game
    # cameraX and cameraY are the top left of where the camera view is
    cameraX = 0
    cameraY = 0

    dogObjs = [] # stores all the non-player objects
    foodObjs = [] # stores all the food objects

    playerObj = {'surface': pygame.transform.scale(HungryCat, (STARTSIZE, STARTSIZE)),
                 'facing': RIGHT,
                  'size' : STARTSIZE,
                  'x': HALF_WINWIDTH,
                  'y': HALF_WINHEIGHT,
                  'health': MAXHEALTH}

    moveLeft = False
    moveRight = False
    moveUp = False
    moveDown = False

    while True:  # main game loop

        if invulnerable and time.time() - invulnerableStart > INVULTIME:
            invulnerable = False

        for dObj in dogObjs:
            # move all the dogs
            dObj['x'] += dObj['moveX']
            dObj['y'] += dObj['moveY']

            if random.randint(0,99) < DIRECTIONCHANGE:
                dObj['moveX'] = getRandomVelocity()
                dObj['moveY'] = getRandomVelocity()
                if dObj['moveX'] > 0:  # faces right
                    dObj['surface'] = pygame.transform.scale(TScaryDog, (dObj['width'], dObj['height']))
                else:  # faces left
                    dObj['surface'] = pygame.transform.scale(ScaryDog, (dObj['width'], dObj['height']))

        # go through all objects and see if any need to be deleted
        for i in range(len(dogObjs) -1, -1, -1):
            if isOutsideActiveArea(cameraX, cameraY, dogObjs[i]):
                del dogObjs[i]

        # if there are not enough dogs, make more
        while len(dogObjs) < NUMDOGS:
            dogObjs.append(makeNewDog(cameraX, cameraY))

        # adjusts the cameras X and Y if they are beyond the allowed camera slack value
        playerCenterX = playerObj['x'] + int(playerObj['size'] / 2)
        playerCenterY = playerObj['y'] + int(playerObj['size'] / 2)
        if (cameraX + HALF_WINWIDTH) - playerCenterX > CAMERASLACK:
            cameraX = playerCenterX + CAMERASLACK - HALF_WINWIDTH
        elif playerCenterX - (cameraX + HALF_WINWIDTH) > CAMERASLACK:
            cameraX = playerCenterX - CAMERASLACK - HALF_WINWIDTH
        if (cameraY + HALF_WINHEIGHT) - playerCenterY > CAMERASLACK:
            cameraY = playerCenterY + CAMERASLACK - HALF_WINHEIGHT
        elif playerCenterY - (cameraY + HALF_WINHEIGHT) > CAMERASLACK:
            cameraY = playerCenterY - CAMERASLACK - HALF_WINHEIGHT

        # draw all dogs
        for dObj in dogObjs:
            dObj['rect'] = pygame.Rect(dObj['x'] - cameraX,
                                          dObj['y'] - cameraY,
                                          dObj['width'],
                                          dObj['height'])
            DISPLAYSURF.blit(dObj['surface'], dObj['rect'])

        # draw the player
        flashIsOn = round(time.time(), 1) * 10 % 2 == 1
        if not gameOverMode and not (invulnerable and flashIsOn):
        # and not flashIsOn:
            playerObj['rect'] = pygame.Rect( (playerObj['x'] - cameraX,
                                                playerObj['y'] - cameraY,
                                                playerObj['size'],
                                                playerObj['size']) )
            DISPLAYSURF.blit(playerObj['surface'], playerObj['rect'])

        # draws the health meter
        healthMeter(playerObj['health'])

        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()

            elif event.type == KEYDOWN:
                if event.key in (K_UP, K_w):
                    moveDown = False
                    moveUP = True
                elif event.key in (K_DOWN, K_s):
                    moveUp = False
                    moveDown = True
                elif event.key in (K_LEFT, K_a):
                    moveRight = False
                    moveLeft = True
                    if playerObj['facing'] != LEFT:
                        playerObj['surface'] = pygame.transform.scale(THungryCat, (playerObj['size'], playerObj['size']))
                    playerObj['facing'] = LEFT
                elif event.key in (K_RIGHT, K_d):
                    moveLeft = False
                    moveRight = True
                    if playerObj['facing'] != RIGHT:
                        playerObj['surface'] = pygame.transform.scale(HungryCat, (playerObj['size'], playerObj['size']))
                    playerObj['facing'] = RIGHT
                elif winMode and event.key == K_RETURN:
                    return

            elif event.type == KEYUP:
                # stop moving the players
                if event.key in (K_LEFT, K_a):
                    moveLeft = False
                elif event.key in (K_RIGHT, K_d):
                    moveRight = False
                elif event.key in (K_UP, K_w):
                    moveUp = False
                elif event.key in (K_DOWN, K_s):
                    moveDown = False

                elif event.key == K_ESCAPE:
                    terminate()

        if not gameOverMode:
            # actually move the player
            if moveLeft:
                playerObj['x'] -= MOVERATE
            if moveRight:
                playerObj['x'] += MOVERATE
            if moveUp:
                playerObj['y'] -= MOVERATE
            if moveDown:
                playerObj['y'] += MOVERATE

            # check for collision with dogs
            for i in range(len(dogObjs)- 1, -1, -1):
                dgObjs = dogObjs[i]
                if rect in dgObjs and playerObj['rect'].colliderect(dgObjs['rect']):
                    # this means a collision has occured

                    if dgObjs['width'] * dgObjs['height'] <= playerObj['size']** 2:
                        playerObj['size'] += int((dgObjs['width'] * dgObjs['height'])** 2) + 1
                        del dogObjs[i]

                        if playerObj['facing'] == LEFT:
                            playerObj['surface'] = pygame.transform.scale(HungryCat, (playerObj['size'], playerObj['size']))
                        if playerObj['facing'] == RIGHT:
                            playerObj['surface'] = pygame.transform.scale(THungryCat, (playerObj['size'], playerObj['size']))

                        if playerObj['size'] > HOWBIG:
                            winMode = True

                    elif not invulnerable:

                        invulnerable = True
                        invulnerableStart = time.time()
                        playerObj['health'] -= 1
                        if playerObj['health'] == 0:
                            gameOverMode = True
                            gameOverStartTime = time.time()

        else:
            # game is over, show "game over" screen
            gameOverScreen = pygame.image.load('gameOver.png')
            DISPLAYSURF.blit(gameOverScreen, (0,0))
            if time.time() - gameOverStartTime > GAMEOVERTIME:
                return # end the current game

        # check if player has won
        if winMode:
            WinScreen = pygame.image.load('Win.png')
            DISPLAYSURF.blit(WinScreen, (0,0))

        pygame.display.update()
        FPSCLOCK.tick(FPS)

def healthMeter(currentHealth):  # draws the players health bar
    for i in range(currentHealth):
        pygame.draw.rect(DISPLAYSURF, RED, (15, 5 + (10 * MAXHEALTH) - i * 10, 20, 10))
    for i in range(MAXHEALTH):
        pygame.draw.rect(DISPLAYSURF, WHITE, (15, 5 + (10 * MAXHEALTH) - i * 10, 20, 10), 1)

def getRandomVelocity():
    speed = random.randint(DOGMINSPEED, DOGMAXSPEED)
    if random.randint(0, 1) == 0:
        return speed
    else:
        return -speed

def makeNewDog(cameraX, cameraY):
    dog = {}
    generalSize = random.randint(5, 25)
    multiplier = random.randint(1,3)
    dog['width'] = (generalSize + random.randint(0,10)) * multiplier
    dog['height'] = (generalSize + random.randint(0,10)) * multiplier
    dog['x'], dog['y'] = getRandomOffCameraPos(cameraX, cameraY, dog['width'], dog['height'])
    dog['moveX'] = getRandomVelocity()
    dog['moveY'] = getRandomVelocity()
    if dog['moveX'] < 0:  # faces right
        dog['surface'] = pygame.transform.scale(ScaryDog, (dog['width'], dog['height']))
    else:  #dog is facing left
        dog['surface'] = pygame.transform.scale(TScaryDog, (dog['width'], dog['height']))
    return dog

    def getRandomOffCameraPos(cameraX, cameraY, objWidth, objHeight):

        cameraRect = pygame.Rect(cameraX, cameraY, WINWIDTH, WINHEIGHT)
        while True:
            x = random.randint(cameraX - WINWIDTH, cameraX + (2 * WINWIDTH))
            y = random.randint(cameraY - WINHEIGHT, cameraY + (2 * WINHEIGHT))

            objRect = pygame.Rect(x,y, objWidth, objHeight)
            if not objRect.colliderect(cameraRect):
                return x, y

    def isOutsideActiveArea(cameraX, cameraY, obj):
        # Return False if camerax and cameray are more than
        # a half-window length beyond the edge of the window.
        boundsLeftEdge = cameraX - WINWIDTH
        boundsTopEdge = cameraY - WINHEIGHT
        boundsRect = pygame.Rect(boundsLeftEdge, boundsTopEdge, WINWIDTH * 5, WINHEIGHT * 5)
        objRect = pygame.Rect(obj['x'], obj['y'], obj['width'], obj['height'])
        return not boundsRect.colliderect(objRect)

    if __name__ == '__main__':
        main()

```

Thanks for taking the time to look at this and let me know if I need to upload anything else. Thanks!!

# Answer
> 1 votes
You need to clear the screen at the start of each frame. So, put `DISPLAYSURF.fill((0, 0, 0))` at the start of your game mainloop (which you oddly seem to have two).

Currently you clear the screen before calling `runGame`, but then `runGame` takes over the mainloop, so the screen won't be cleared in `main` again.

You really want to just have one main loop, where you start with polling for events, the update all your objects, after which you clear the screen, then render all your objects, and finally flip the window buffer.

---
Tags: graphics-programming, pygame
---


title: Shadow map sample is weird

text:
# Question
Title: Shadow map sample is weird
I'm attempting to implement Shadow mapping in opengl/GLSL and have encountered a problem with sampling the shadow map itself.

I have confirmed that the shadow map is correctly rendered:

However, when I attempt to sample it in my shader, the output is always zero (or appears to be zero).

My vertex shader:

```
#version 430
// Some drivers require the following
precision highp float;
layout (location = 0)in vec3 MSVertex;
layout (location = 4)in vec2 MSTexCoord;

out xferBlock
{
    vec3 VSVertex;
    vec2 VSTexCoord;
} outdata;

void main()
{
    outdata.VSVertex = MSVertex;
    outdata.VSTexCoord = MSTexCoord;
    gl_Position = vec4(MSVertex,1.0);
}

```

And my fragment shader:

```
#version 430 core
// Some drivers require the following
precision highp float;

layout (location = 0) uniform sampler2D positionMap;
layout (location = 1) uniform sampler2D normalMap;
layout (location = 2) uniform sampler2D colourMap;
layout (location = 3) uniform sampler2D specularMap;
layout (location = 4) uniform sampler2D glowMap;
layout (location = 5) uniform sampler2DShadow shadowMap;

struct DirLightData
{
    vec4 colour;
    float intensity;
    vec4 direction;
};
uniform mat4 ShadowTransform;
uniform DirLightData dirLight;
out vec4 colour;
uniform vec3 WSCamPos;
in xferBlock
{
    vec3 VSVertex;
    vec2 VSTexCoord;
} indata;

vec3 computeLight(vec3 Ldirection, vec3 Vdirection, vec3 Lcolour, vec3 normal, float Lintensity, float specular)
{
    vec3 diffCol = Lcolour * max(0.0,dot(normalize(normal),-Ldirection));
    vec3 reflectVec = normalize(reflect(Ldirection,normal));
    float specFactor = max(dot(reflectVec,Vdirection),0);
    float specPow = pow(specFactor,specular*255.0);
    vec3 specCol = Lcolour * specPow;
    return (diffCol+specCol)*Lintensity;;
}
float computeOcclusion(vec4 shadowCoords)
{
    float vis = 1.0;
    vec3 coord = vec3(shadowCoords.xy,shadowCoords.z/shadowCoords.w);
    float depth = texture( shadowMap, coord);
    if (  depth < coord.z );
    {
        vis = 0.5;
    }
    return depth;
}
void main()
{
    vec4 pcolour = texture(positionMap, indata.VSTexCoord).rgba;
    vec4 ncolour = texture(normalMap, indata.VSTexCoord).rgba;
    vec4 dcolour = texture(colourMap, indata.VSTexCoord).rgba;
    vec4 scolour = texture(specularMap, indata.VSTexCoord).rgba;
    vec4 gcolour = texture(glowMap, indata.VSTexCoord).rgba;
    vec4 shadowCoord = ShadowTransform * pcolour;
    float visibility = computeOcclusion( shadowCoord );
    vec3 vToEye = WSCamPos - pcolour.xyz;
    vToEye = normalize(vToEye);
    vec3 outColour = vec3(0.0,0.0,0.0);

    outColour = computeLight(dirLight.direction.xyz,vToEye,dirLight.colour.rgb,ncolour.rgb,dirLight.intensity,scolour.r);
    colour = vec4(visibility*(dcolour.rgb*outColour),1.0);

}

```

I have confirmed that the lighting, sans shadow map, works just fine. I've also tried defining the shadow map as a regeular sampler2D, and using `float depth = texture( shadowMap, coord.xy);`, with the same results.

After some additional research, I found that:

```
    vec3 coord = vec3(shadowCoords.xy,shadowCoords.z/shadowCoords.w);
    float depth = texture( shadowMap, coord);

```

is actually a depth comparison, of the world space coordinates, transformed to the light's perspective, which (if I understand it correctly) returns 1.0 or 0.0, indicating if the fragment passes or fails the depth comparison.

In this case, the fragment always fails the comparison.

To get a better idea, I output the z component of the transformed world space coordinates:

As you can see, it looks like there are some minor discrepencies in the z value.

I'm not sure how to fix this. Perhaps it is related to how I created the depth attachment?

```
glGenFramebuffers(1, &m_FBOName);
glBindFramebuffer(GL_FRAMEBUFFER, m_FBOName);

// Depth texture. Slower than a depth buffer, but you can sample it later in your shader
glGenTextures(1, &m_DepthTexture);
glBindTexture(GL_TEXTURE_2D, m_DepthTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_DepthTexture, 0);

```

# Answer
> 1 votes
The issue was that I had to change the occlusion function in my shader to:

```
float computeOcclusion(vec4 shadowCoords)
{

    vec3 coord = vec3(shadowCoords.xy,shadowCoords.z/shadowCoords.w);
    float depth = texture( shadowMap, coord);
    return depth;
}

```

And, I had to add `glCullFace(GL_FRONT)` to the client code, right before I started rendering to the depth texture, as without it, small accuracy discrepancies like the one's in the image caused everything to be in shadow.

---
Tags: opengl, glsl, shadow-mapping
---