# Question
Title: Monogame - NullReferenceException on Exit();
I'm currently attempting to learn the Monogame system. I have little prior experience in C# (about two weeks of XNA, four years ago) but am reasonably familiar with VB.NET.

Essentially, when calling Game.Exit(), I get the following error: `An unhandled exception of type 'System.NullReferenceException' occurred in MonoGame.Framework.dll`

My main class is this:

```
using System;

namespace MonoTest
{
#if WINDOWS || LINUX
    /// <summary>
    /// The main class.
    /// </summary>
    public static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            using (var game = new Game1())
                game.Run();
        }
    }
#endif
}

```

And the class in which the error occurs is:

```
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

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

        // IMAGES
        private Texture2D background;
        private Texture2D shuttle;
        private Texture2D earth;
        private SpriteFont luna24;
        private int score;

        private AnimatedSprite walker;

        private Texture2D arrow;
        private float angle = 0;
        private int bgTint = 0;

        //Keyboard information
        KeyboardState state;
        KeyboardState oldState; //state from the previous update
        //Mouse information
        MouseState mState;
        MouseState oldMState;

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

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

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

            Texture2D walkerTex = Content.Load<Texture2D>("atlases/SmileyWalk");
            walker = new AnimatedSprite(walkerTex, 4, 4);
            arrow = Content.Load<Texture2D>("entities/arrow");
        }

        /// <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)
        {
            state = Keyboard.GetState(); //get current state of the keyboard
            mState = Mouse.GetState();
            //have an oldState value to compare against to check for presses and ignore holds

            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();
            score++;
            walker.Update();

            if (state.IsKeyDown(Keys.A))
            {
                angle += 0.01f; //rotate the arrow
            }
            if (state.IsKeyDown(Keys.Escape))
            {
                Quit();
                //// Monogame's default initialization process seems to run the game without an instance, but that's impossible.
                //// Can't think of another explanation.

            }
            //if (oldState.IsKeyUp(Keys.A) && state.IsKeyDown(Keys.A))
            //{
            //    bgTint += 1;
            //        if (bgTint > 3)
            //        {
            //            bgTint = 0;
            //        }
            //}
            //// Above is sample of code to check that a button was pressed *this cycle*.

            // If a given button does not exist, it will always appear as released.
            if (mState.LeftButton == ButtonState.Pressed && oldMState.LeftButton == ButtonState.Released)
            {
                bgTint += 1;
                if (bgTint > 3)
                {
                    bgTint = 0;
                }
                Mouse.SetPosition(400, 240);
            }

            base.Update(gameTime);
            oldState = state; //call this at the end of each update loop
            oldMState = mState;
        }

        /// <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);
            Vector2 arrowOrigin = new Vector2(20, 100);

            Vector2 arrowLoc = new Vector2(400, 240);
            Rectangle arrowSource = new Rectangle(0, 0, arrow.Width, arrow.Height);

            spriteBatch.Begin();
            switch (bgTint)
            {
                case 0:
                spriteBatch.Draw(background, new Rectangle(0, 0, 800, 480), Color.White);
                break;
                case 1:
                spriteBatch.Draw(background, new Rectangle(0, 0, 800, 480), Color.Blue);
                break;
                case 2:
                spriteBatch.Draw(background, new Rectangle(0, 0, 800, 480), Color.Green);
                break;
                case 3:
                spriteBatch.Draw(background, new Rectangle(0, 0, 800, 480), Color.Red);
                break;
                default:
                spriteBatch.Draw(background, new Rectangle(0, 0, 800, 480), Color.White);
                break;
            }
            spriteBatch.DrawString(luna24, "Score: " + score, new Vector2(10, 10), Color.Blue);
            spriteBatch.Draw(arrow, arrowLoc, arrowSource, Color.White, angle, arrowOrigin, 1.0f, SpriteEffects.None, 1);

            spriteBatch.End();
            walker.Draw(spriteBatch, new Vector2(mState.X, mState.Y));

            base.Draw(gameTime);
        }

        private void Quit()
        {
            if (this != null)
            {
                Exit(); //this line produces the error
            }
        }
    }
}

```

As may be apparent, this was created using the standard Monogame project template. The code that seems to be causing the issue is the Quit() method.

```
    private void Quit()
    {
        if (this != null)
        {
            Exit(); //this line produces the error
        }
    }

```

Quit() is called in Update() when the escape key is pressed. My understanding is that the NullReferenceException would seem to imply that the object Exit() is being called on has not been initialized, but as everything else in the class works as expected I can't see how this could be the case. The stacktrace is below.

```
   at MonoGame.Framework.WinFormsGamePlatform.Exit()
   at Microsoft.Xna.Framework.Game.Exit()
   at MonoTest.Game1.Quit() in c:\Users\natha\AppData\Local\Temporary Projects\MonoTest\Game1.cs:line 176
   at MonoTest.Game1.Update(GameTime gameTime) in c:\Users\natha\AppData\Local\Temporary Projects\MonoTest\Game1.cs:line 103
   at Microsoft.Xna.Framework.Game.DoUpdate(GameTime gameTime)
   at Microsoft.Xna.Framework.Game.Tick()
   at MonoGame.Framework.WinFormsGameWindow.RunLoop()
   at MonoGame.Framework.WinFormsGamePlatform.RunLoop()
   at Microsoft.Xna.Framework.Game.Run(GameRunBehavior runBehavior)
   at Microsoft.Xna.Framework.Game.Run()
   at MonoTest.Program.Main() in c:\Users\natha\AppData\Local\Temporary Projects\MonoTest\Program.cs:line 18
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

```

A temporary resolution has been found. I was able to resolve the issue by replacing the Exit() call on the current object with System.Environment.Exit(). However, this still leaves the issue of *why* the exception occurred.

# Answer
> 2 votes
I'm no monogame expert, but, you call Exit two times. One in

```
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

```

and one into Quit called here:

```
 if (state.IsKeyDown(Keys.Escape))
            {
                Quit();

```

I suppose the second time is called some resurce used inside exit is at null.

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


# Question
Title: ELO Rating System & Multiple Games Against the Same Player
I've decided to use the ELO rating system for my chess-like strategy game.

I've implemented the algorithm but I don't really understand it completely (I'm not a maths person)...

I've decided to give starting rank of 1000 for new players, and I use 32 as max increase.

Now for my actual question:

Let's say that player A plays hundreds of games against player B, and player A is much better player (or player A has created a dummy account so that he cheats!).

Do I need to take this in account in any way "manually" or does ELO handle this "automatically"? I mean, ultimately the difference between the two players will be so great that the "cheater" gets only +1 to his rank? So he would possibly have to play LOTS of games to cheat/climb up the ladder this way? Am I correct?

I REALLY wouldn't want to disallow the ladder system completely for friend vs friend (invited matches). And I shouldn't need to: even www.chess.com handles this in some way.

# Answer
I write this answer not being completely certain, what results you desire from your rating system. So I will consider both possible demands. Short answer: I think the ELO system handles the situation you ask about in an arguably favourable way. So I do not think you need to worry about handling any situations "manually".

If two players A and B, with player A being a lot better, play a lot of games against each other (this situation is often prevented by some kind of match making algorithm or authority), the rank of player A will grow fast as long as their rating is close, and will slow down in growing when A wins a lot of games, since the algorithm is expecting him to win with a higher certainty. (And expectation values decide the bonus you actually receive when winning)

So yes using this system will only provide a slow way to cheat. And it is the only logical way this system could work. The system is not primarily designed to reward won games (as in quantity), but to rank players against each other regarding their skill. So wins should and do only change the rankings as much as they differ from the expectations.

If you want the amount a user plays your game to contribute directly to his points (e.g.: rating = 100\*(amount of wins) + 50\*(number of draws) - 75\*(number of losses) + (arbitrary start value)), the ELO rating is not what you are looking for.

Considering friend vs friend games: You can - in principle - use these games to change ratings, for the reasons I have listed above, but should keep in mind that playing against a friend might have a different competitive nature than playing against a stranger. I might not care as much about loosing against a friend or I might care a lot more.

Every case in which one player gives up a game he could have still won, might confuse the ratings, because the winner might not have been the actual better player. Friend vs friend games can be a special case where giving up happens more often, but it is only a special case. If you do not want to worry too much about giving up, rest assured in knowing that "wrong"/"lucky" wins will be corrected in the long run.

Main source: ELO Wikipedia Article, good explanation of the basic principle.
> 2 votes

---
Tags: mathematics, ranking
---


# Question
Title: LibGDX: Scrollpane won't scroll to bottom after adding children to contained table
To my game I want to add a gui element that displays text and textButtons whenever something is happening or it wants you to make a decission (an answer while talking to a person for example). To keep track of your actions you shall be able to scroll it. Similar to text adverntures or dialog boxes in rpgs.

I use Scene2Dui for my GUI, so I put a scrollPane in my GUIs root table. I have methods for adding stuff to the contained table and tell the scrollPane to scroll to the bottom.

In general the idea works, but the thing doesn't scroll to the bottom but only to the bottom of the element I added before the current one. I'm puzzled.

Here's the code, leaving out the skins and styles part:

```
public class TextBox {

ScrollPane box;
Table table;
Label.LabelStyle lStyle;
Skin skin;

TextBox() {

    table.setFillParent(false);

    box = new ScrollPane(table, scrollStyle);

    box.setScrollingDisabled(true, false);
    box.setOverscroll(false, false);
    box.setFillParent(false);

    table.align(Align.topLeft);
    table.row();
}

void writeDecissions(GameEvent[] events) {

    Table tableD = new Table();
    tableD.setFillParent(false);

    if (events != null) {

        for (int i = 1; i < events.length; i++) {

            if (events[i] != null) {

                String s = Character.forDigit(i, 10) + " - "
                        + events[i].getDecision();

                TextButton button = new TextButton(s, style);
                button.getLabel().setWrap(true);
                button.getLabel().setAlignment(Align.left);

                tableD.add(button).width(box.getWidth() - 40).spaceBottom(20).spaceTop(20);

                tableD.row();

            }
        }
    }

    table.add(tableD).align(Align.left).pad(20);
    table.row();

    box.setScrollY(table.getHeight());
}

```

This is the way I test it:

```
public void render(float delta) {
    Gdx.gl.glClearColor(0, 0, 0, 0);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    stage.act();
    stage.draw();

    if (Gdx.input.justTouched()) {
        gui.textBox.writeDecissions(events);
    }

```

I tried box.setScrollY(box.getMaxY) as well as setting overscroll to true (don't really know what that is tough). With the same result.

Finally a screenshot:

Help appreciated.

# Answer
> 3 votes
I found an answer on Stack Overflow.

The thing is I had to call layout() on the scrollPane manually.

The reason: Because the height of a wrapped label is unknown until layout() is automaticaly called while drawing. The maximum Y scroll position remains the same until this happens.

# Answer
> 1 votes
layout() should be called twice, for sure...

From label.setWrap documentation: In some cases the parent of the label will need to layout twice: once to set the width of the label and a second time to adjust to the label's new preferred height.

---
Tags: libgdx, gui
---


title: Know if you're fully utilizing the GPU

text:
# Question
Title: Know if you're fully utilizing the GPU
I render ~17.000 VAOs each frame. 2.840.386 triangles. Only applying texture, nothing else.

I have three computers and the performance across them is not as expected.

* Cheap laptop(i3-4010U & Intel HD 4400) runs at ~20 fps.
* Desktop1(FX-9590 & GT 630) runs at ~65 fps.
* Desktop2(i7-5820k & GTX 970) runs at ~105 fps.

As the game is in a pretty early stage, the only CPU task each frame is to loop through a 3-Dimensional map containing VAO ids, and then render them.

When I look at the CPU Benchmarks and the GPU Benchmarks of my systems, I would expect a much bigger difference between my Desktop2 and the two other systems. The GTX 970's 3D score(8662) is more than 15 times better than the Intel HD 4400's (546), though it only run 5 times as fast. Even more ridiculous the GTX 970's 3D score is ~11 times better than the GT 630's (797), but run 1.6 times faster.

Even without taking the benchmarks into consideration I would still expect bigger difference. When I compare the performance differences in other games(Like GTA V) across my systems, there's a much bigger difference. Therefore I know the problem is my game, and not a hardware/driver related issue.

Am I right that I would expect larger differences between the different systems, if yes: How may I find the issue and how can I solve it?

**Edit:** I've read that GTX 590 is capable of 3.2 Billion triangles/second, where as my game is only able to squeeze ~300 million of a GTX 970.

**Edit 2:** I've tested my desktop1(GT 630) that runs 1080p at 65fps and if I change the resolution to 1 * 1, I only get a performance boost of 20fps(85fps).

# Answer
TL;DR: Your rendering test is very simple with no post-processing so even an integrated GPU has an easy time with it.

---

GPU Benchmarks test many different aspects of a rendering pipeline and gives you back a single simplified number.

GPUs have multiple points that can bottleneck and final render time depends on the worst point of the pipeline.

Some examples of possible bottlenecks:

* Telling the GPU to start drawing (small number of primitives vs large batches)
* GPU rendering mode configuration time (to switch shaders, textures, etc.)
* GPU reading vertices from System RAM vs Video RAM
* Vertex format re-organizing/re-aligning due to GPU DMA limitations
* Vertex shader code processing (size + branches + # of cores)
* pixel shader code processing (size + branches + # of cores)
* texture fetches (amount, size, dependent reads)
* post-processing steps (FBO flush -\> texture -\> pixel shader -\> FBO)
* Memory bandwidth
* cache sizes & organization
* bus bandwidth between CPU\<--\>GPU (in some rare extreme cases integrated GFX can be faster since they share the same cache & memory)
* Triangle to tile draw combining
* fixed point vs floating point shader performance

GPUs can "faceplant" in terms of performance past a certain point on any of those items.

For example, if GPU-Model-A has 8KB of instruction cache for each execution units but runs slightly faster than GPU-Model-B that has 16KB.

Model-A takes 7usec to process a 6KB shader while Model-B that takes 9usec. But if you're using a 12KB shader, Model-B can fit the entire shader it its cache but Model-A has to run it in 2 cache loads, which adds 30usec\* to Model-A's execution, suddenly Model-B runs much faster in comparison.

\*These are made-up numbers, actual numbers vary.

So the artificial benchmark final number depend on how much weight they assign to the score for each part they test and how much load and what type of load they put on the GPU & CPU.

---

In order to figure out which part is the bottleneck you must go through an elimination process where you lighten up the load off of each items and check the performance difference.

For example:

* reducing screen resolution
* disabling post effects
* reducing texture sizes
* reducing shader complexity (while still reading the textures)
* removing dependent texture lookups (while still reading the textures)
* rendering larger batches of triangles to reduce draw calls
* disabling skinning

And check the performance gain of each single item or combination.
> 6 votes

# Answer
Note: While FPS can be safely used to compare values, for measuring differences(for optimizations) you should measure frame times.

There are programs that help you tell whether your application is cpu or gpu limited. One of them is AMD GPU PerfStudio, which as the name suggests is vendor-specific. I am sure NVidia has a similar program too, but I don't know its name. EDIT: I just remembered a basic GPU utilization meter is usually included in overclocking tools and and in the driver settings.

Also you should make sure that the cards are doing the same thing, there are often vendor-specific optimizations or effects that are tuned in relation to the GPU you have, these are usually set in the GPUs control panel. And make sure that the resolutions are the same too as laptops usually have lower resolution and this may strongly affect performance. The true performance of a high-end GPU may only be visible on higher resolutions.

Also bear in mind that the additional speed of a more advanced GPU may only kick in when you are doing more stuff, using more memory, and using more advanced features, which you said you aren't. GPU benchmarks are usually built to attempt to use all features and evenly distribute the work between all GPU blocks.

**We have no way to know if the benchmarks points scale linearly with performance.** The benchmarks may also be tuned to use tessellation and other new features which only recently been optimized in hardware, which will bring new-gen GPUs up-front, while in a simpler setting their power may be almost the same.
> 3 votes

---
Tags: opengl, c++, performance
---


# Question
Title: Unhandled exception at 0x0FE62707 (sfml-system-d-2.dll)
So, turned on my pc today thinking I we're gonna continue making my game but got denied by this error.

Have no idea how to fix it and why it's there at all, I haven't touched my project properties in days.

---

I start my game, he console pops up and just when I can see my games window blink it crashes and gives me this error :

> Unhandled exception at 0x0FE62707 (sfml-system-d-2.dll) in SFML\_Game.exe: 0xC0000005: Access violation reading location 0xCCCCCCD8.

---

It crahes at the 2nd line of SFML code it goes trough, which is :

```
sf::RenderWindow window(sf::VideoMode(1200, 840), "SFML - Box2D Engine 1.0");

```

And the first line being this :

```
sf::Clock deltaClock;

```

---

# Answer
> 1 votes
If *absolutely* nothing changed in your code there could have been a windows DLL update that changed the data addresses slightly exposing a *pre-existing bug* in sfml or elsewhere.

Windows (and other modern OSes) also randomize the address space for security reasons so your executable might happen to run fine one time and crash the next.

You will have to step through the code and look for an uninitialized pointer. Backtracking using breakpoints from the memory exception line.

Just to be safe run a memory tester such as http://www.memtest86.com/ on your system. It's easy and we'll eliminate defective RAM as a possible (even if unlikely) culprit. It's rare but I've had defective RAM before and system can still run "fine" for a surprisingly long time with bad memory.

But most likely it's an uninitialized pointer.

You can also try updating sfml if you're not on the latest version in case it was a bug that was fixed.

---
Tags: c++, sfml, visual-studio
---


# Question
Title: How can I read the smallest mipmap back to the CPU after calling generateMips?
I'm implementing an adaptive tonemapper based on the standard "scale down the luminance map to a 1x1 texture" approach.

This is my code following the rendering of the luminance map:

```
 //Average the luminance map by creating a 1x1 mipmap.
    m_pImmediateContext->GenerateMips(m_lumShaderResourceView);

    m_pImmediateContext->CopyResource(m_cpuLumTex, m_lumTexture);

    float* lumMap;
    D3D11_MAPPED_SUBRESOURCE texture;
    m_pImmediateContext->Map(m_cpuLumTex, 0, D3D11_MAP_READ, 0, &texture);
    lumMap = (float*) texture.pData;
    m_avgLuminance = lumMap[0]; // Should work? ^^;
    m_pImmediateContext->Unmap(m_cpuLumTex, 0);

    float lastLum = m_timedAvgLuminance;
    float currentLum = exp(m_avgLuminance);
    float adaptedLum = lastLum + (currentLum - lastLum) * (1 - exp(-.1 * 0.5));

    m_timedAvgLuminance = adaptedLum;

```

I'd like to read back the calculated average luminance to the CPU for reasons, but what I'm finding is that when I set `m_avgLuminance` to the mapped-back texture, it's grabbing the pixel at 0,0. If the map were a 1x1 texture, this wouldn't be an issue, but it seems I'm not getting the 1x1 texture, but instead the full-sized luminance texture (screen-sized), so what I wind up with is an image tonemapped by the 0,0 pixel instead of the overall average luminance of the scene.

What am I doing wrong here? How can I read the 1x1 generated mip map texture instead of the full-sized texture?

# Answer
You need to map the sub-resource that corresponds to the mipmap level you want.

https://msdn.microsoft.com/en-us/library/windows/desktop/ff476901%28v=vs.85%29.aspx

https://msdn.microsoft.com/en-us/library/windows/desktop/ff476457%28v=vs.85%29.aspx

m\_pImmediateContext-\>Map(m\_cpuLumTex, **(mipmap number here)**, D3D11\_MAP\_READ, 0, &texture);

if your texture is 256x256 that'd be resource 7.

(256 = 1 \<\< **8**, substract 1 for the last 1x1 mipmap =\> #7)
> 1 votes

---
Tags: directx11, mipmaps, rendertexture
---


title: XNA Texture2D Copy Error

text:
# Question
Title: XNA Texture2D Copy Error
I have a static class that I use to build a 3d character and render the results to a RenderTarget2D which I then return.

I'd like to store the results for later use so I need to make a copy of the returned RenderTarget. To do this I\`ve tried both a Quad VertexPrimitive Effect with a tiny copy PixelShaderFunction and a SpriteBatch.Draw.

I think that the Quad render is quicker but no matter how I fiddle, the Quad never seems to get it quite right.

For example, I do use SpriteBatch to pick up a 256\*256 area of a large Texture2D backdrop and Draw that to a RenderTarget2D. But if I then send that directly to the Quad render and put that result back in the same place it almost - but VERY annoyingly not quite - fits back perfectly. Using another SpriteBatch.Draw does give a perfect result but I've convinced myself that it is slower.

So my questions are twofold.

1) Is the Quad UserIndexedPrimitive quicker than the SpriteBatch.Draw for multiple iterations?

and

2) Why can\`t I get the Quad render to give me back the same image when setting it as the Effect sampler via Effect.Parameter..SetValue(RenderTarget)?

As ever, Thanks :) Stoort.

Here is the problem in png form.

The left half is the RenderTarget2D before I use a short user Effect that just does a straight copy using

```
    return tex2D(texture, coord);

```

as the only PixelShaderFunction instruction via a quad with

```
    graphicsDevice.DrawUserIndexedPrimitives<VertexPositionTexture>
                (PrimitiveType.TriangleList, verts, 0, 4, ib, 0, 2);

```

The source and destination width and height are identical as are all the RenderTarget2D settings for both.

As you can see the output on the right is blurred and the top and right lines are wrapped from the opposite sides.

# Answer
> 0 votes
Thanks JonBee your halfpixel offset was just what I was looking for :)

What I did to fix it was this...

When building my quad I add the following Vector3 to each Vertex Position in the VertexPositionTexture\[\] array :-

```
    Vector3 HalfPixelOffset = new Vector3(-0.5f, 0.5f, 0);

```

This worked a charm and I tested it with several different sizes of RenderTarget2D. No changes were needed in the HLSL Effect code. Lovely :)

---
Tags: xna, textures, hlsl, spritebatch
---


title: how is c useful in game development

text:
# Question
Title: how is c useful in game development
I know that C++ is the king in game development especially in the AAA market can anyone tell my how is C helpful I am a Computer Science student in my first year and are they any aspects of C i have to learn in depth? Thanks

# Answer
> 1 votes
C is a subset of C++.

C is small and lean - a manageable subset of C++.

C++ on the other hand is **huge** and can be very confusing, with many questionable features and design decisions. C++ standard is gigantic.

There are quite a few notable industry figures who prefer using C. Majority of professionals use a small and very conservative subset of C++.

My suggestion - **learn how to use C thoroughly** before jumping in with C++11.

There are too many features in C++ that look harmless on the surface, but once you start relying on them they blow in your face - **exploding compile times**, **indecipherable template error messages** \- just to name a few.

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


# Question
Title: How to pitch, yaw, roll, an object like a flight simulator in OpenGL?
I'm working on a college Graphics project using LWJGL (OpenGL in Java). I've done most of the scene but I got a problem in figuring out the jet's orientation.

Here's how I tried it at the very beginning: (After translate it to the desired position)

```
        GL11.glRotatef(xRotation, 1, 0, 0);
        GL11.glRotatef(yRotation, 0, 1, 0);

```

Then I found the I came across the gimbal lock problem? For example: the jet roll 90 degrees to the right, then it pitch up so that it will make a right turn. But if I pitch up 90 degrees first, then roll at some angle, it look like it's Yawing ! It's still rotate along the original X-axis.
**Roll -\> Pitch looks fine.
But Pitch -\> Roll looks BAD.**

Then I tried another way:

```
        GL11.glRotatef(xRotation, 1, 0, (float)Math.tan(Math.toRadians(-yRotation)));
        GL11.glRotatef(yRotation, 0, 1, 0);

```

This time the problem actually inverses! The case I just described is inversed.
**Roll -\> Pitch looks BAD.
But Pitch -\> Roll looks fine.**

I can't even imagine what might happen when I add the Yaw Rotation into this.

The jet should be able to orient at any direction and Roll,Yaw,Pitch should not interfere with each other

I've done lot of research, it appears to me that I have to aggregate the Roll-Pitch-Yaw 3 rotations into one which is represented by **Quaternions**. But I'm really confused about the term. If someone has experience in doing a similar work plz give me some hints(examples are much appreciated!), I'm really really frustrated by this. Thank you !

# Answer
After a whole weekend research and trying, I finally managed it somehow, thanks to *jbridon* on his blog. So **Quaternions** is definitely the way to do it. U may have to use a Point3f to record ur object's coordinates, a Vector3f to represent its motion per frame.
And in each update of rendering, first get ur Euler angles of Roll, Pitch, and Yaw. Then calculate their effect on the **Motion Vector3f**. That's where your object gonna go in the next update.

Here's the tricky point:
You still have to choose a order of XYZ, they do matter but not that bad when using Euler Angles. In my case of a flight simulator, I choose Y-\>X (No Z at the moment) as the order.

Now you want to find out how your Model Coordinates System looks like right now (since you rolled then pitched the object). In my case *jbridon* gives me a way like this: (Mostly his code,so thanks him again)

```
    Velocity.scale((float) Math.cos(perPitch));
    UpDirection.scale((float) Math.sin(perPitch));
    Velocity = Vector3f.add(Velocity, UpDirection, null);
    UpDirection = Vector3f.cross(yDirection, Velocity, null);

    Velocity.normalise();
    UpDirection.normalise();

    yDirection.scale((float) Math.cos(perRoll));
    UpDirection.scale((float) Math.sin(perRoll));
    yDirection= Vector3f.add(yDirection, UpDirection, null);
    UpDirection= Vector3f.cross(yDirection, Velocity, null);

    // Normalize
    yDirection.normalise();
    UpDirection.normalise();

    Vector3f.add(Position, Velocity, Position);

    // here build two quaternion to represent two rotations, then multiply them together
    Quaternion RollQuat = new Quaternion();
    QRoll.setFromAxisAngle(new org.lwjgl.util.vector.Vector4f(v.x, v.y, v.z, perRoll));
    Quaternion PitchQuat = new Quaternion();
    QPitch.setFromAxisAngle(new org.lwjgl.util.vector.Vector4f(yDir.x, yDir.y, yDir.z, -perPitch));

    // Note: we must explicitly multiply out each dQ, not just the total
    Quaternion.mul(ResultQuat, RollQuat, ResultQuat);
    Quaternion.mul(ResultQuat, PitchQuat, ResultQuat);
    ResultQuat.normalise();

```

Then bingo, you're done. You now get the Quaternion that describes the rotation for you. Then you can use multiple ways to apply this to your local coordinates. For example, I use Java OpenGL Math Library's code to transform a quaterion into matrixes for multiplication in my model view. The gimbal lock is avoided in this way.
> 0 votes

---
Tags: opengl, mathematics, rotation, lwjgl, transformation
---


title: Method causes OutOfMemory error

text:
# Question
Title: Method causes OutOfMemory error
If a GameObject in my game has a special ability it triggers it, but I want all the special GameObjects that this GameObject affects to also trigger their abilities, for example if a bomb hits some objects, if these objects are also bombs, trigger them too. I though this would be easy by calling the method that handles all the special abilities recursively, but, as always, it wasn't. Basically what happened is a chain reaction of bullcrap that caused Unity to show an OurOfMemory error. Also makes my PC freeze completely while politely turning all the screens off.

The question is, how can I make it so it triggers all the affected cubes' special abilities, without everything going nuts?

Code:

```
     //Triggers the cube's special ability, if it has any
    private void TriggerSpecialCubeAbility(GameObject specialCube) {
        switch (specialCube.tag) {

            //Destroy all cubes in a radius from the special cube
            case "Bomb":
                TriggerBombAbility(specialCube);
                break;

            //Destroy all cubes of the same color as the special cube
            case "Lighting":
                TriggerLightingAbility(specialCube);
                break;
            default:
                break;
        }
    }

    private void TriggerBombAbility(GameObject specialCube) {
        var nearbyColliders = Physics2D.OverlapCircleAll(specialCube.transform.position, explosionRadius);
        Instantiate(particles[0], specialCube.transform.position, specialCube.transform.rotation);
        Instantiate(particles[1], specialCube.transform.position, specialCube.transform.rotation);

        foreach (var collider in nearbyColliders) {
            if (collider.tag == "Indestructible")
                return;

            var affectedCube = collider.gameObject;
            TriggerSpecialCubeAbility(affectedCube);
            Destroy(affectedCube);
        }

        destroySelectedCubes = true;
        //          Physics2D.gravity *= -1;
        //          Physics.gravity *= -1;
    }

```

# Answer
> 2 votes
First of all, you seem to have a bug in `TriggerBombAbility()`: that `return` should be a `continue`.

Now a quick way to fix your issue of infinite recursion is to devise a way to mark a `GameObject` as no longer triggerable. For instance you could have a `hasBeenTriggered` boolean, defaulting to false, and you set it to true before triggering abilities:

```
       case "Bomb":
            specialCube.hasBeenTriggered = true;
            TriggerBombAbility(specialCube);
            break;

```

Then you only call `TriggerSpecialCubeAbility()` if the ability hasn’t already been triggered:

```
        var affectedCube = collider.gameObject;
        if (!affectedCube.hasBeenTriggered)
        {
            TriggerSpecialCubeAbility(affectedCube);
            Destroy(affectedCube);
        }

```

~~Alternatively, you could put that check in `TriggerSpecialCubeAbility()` itself and do an early exit:~~ Nevermind; this would require a check around `Destroy()`, too, and is therefore more complicated.

---
Tags: unity, gameobject, recursion
---


# Question
Title: How can I calculate the U,V texture coordinates on a disk at infinity given only a view vector and a vector pointing to the disk's center?
I'm using an approach similar to Bruneton's paper on atmospheric scattering for rendering my sky and am trying to extend it to add a textured moon.

Long story short, the paper works by essentially inverting a screen pixel to a world-space vector, then effectively raytracing the sky. To draw the sun, the paper checks the dot product between the sun-vector and pixel view-vector, and gives a "yes hit" or "no not hit" 1 or 0 based on a step function and the angular size of the sun. All of these vectors are unit.

Similarly, I'm doing the same thing to determine if there's a hit on the moon, however unlike the sun, I also now need to determine a texture coordinate. At first I simply subtracted the view vector from the moon vector, normalized the result, then scaled it by the angle between the view and moon vectors. This gives me the correct world-space point, but I'm having a hard time converting this 3-D world space point to a U,V texture coordinate on the intersected moon-disk.

A graphic to illustrate my problem:

My question is this: **Given two unit vectors, how can I calculate a texture coordinate of a point formed by the angle between them?**

# Answer
> 2 votes
Use the dot product function, pseudo-code:

```
vector2 texcoord;

texcoord.x = DotProduct(i1, right) * 0.5 + 0.5;
texcoord.y = DotProduct(i1, up) * 0.5 + 0.5;

```

Where up is a normalized vector pointing at the direction you want for up in your disc / texture. Similarly for right.

i1 should be scaled to match the radius of your disc at unit length. So that i1 will be of unit length when reaching the edge of the disc.

The dot products will give you values between -1 and 1 within the rectangle (texture) area that bounds your disc, larger values beyond it.

The `* 0.5 + 0.5` is there to center the coordinates into your texture so they range from 0 to 1 instead of -1 to 1.

---
Tags: raytracing
---


# Question
Title: Enlarge screen space Texture by set pixel amount
I have a texture shown over the screen using screen space UV's. The Texture is 495x,596x, Screen size is 888,500, but can change. The Texture has a Tile of (3.469775f,1.392644f) to correct for distortion from being stretched to the Screen's size, and has repeat set to Clamped. So basically, I'm showing a Texture of an arbitrary size on screen and using Tile and Offset in the shader to correct for distortion and keep the texture at its original aspect ratio.

Now my problem is I want to Zoom in and out by a set pixel amount in Screen space. So lets say: I need the texture to increase in width by 10 pixels in screen space. What is a formula I can use to recalculate the Tile and Offset so that the texture stays at the same aspect it was but increases by the amount I want it zoomed?

I've been trying things like: 1 Pixel = (1f / Camera.main.pixelWidth). So to zoom by 10 pixels I would go something like Tile.x += (10f * (1f / Camera.main.pixelWidth)); But this doesn't seem quite right, I'm not seeing it increase the Texture by the right number of pixels...

My current function is something like this, but for Zoom = 5f, it's only enlarging by about 2px. AspectRatio = Tiling in the Material and WidthOffset/HeightOffset is just the Offset.

```
public void ZoomOverlay(float ZoomAmount)
{
    AspectRatio.x -= ZoomAmount * (AspectRatio.x / (float)Camera.main.pixelWidth);
    AspectRatio.y -= (ZoomAmount * (AspectRatio.x / (float)Camera.main.pixelHeight)) / 2f;

    WidthOffset += ((ZoomAmount / 2f) * (AspectRatio.x / (float)Camera.main.pixelWidth));
    HeightOffset += ((ZoomAmount * (AspectRatio.x / (float)Camera.main.pixelWidth)) / 2f) / AspectRatio.x;
}

```

# Answer
> 0 votes
The inverse of the texture size corresponds to 1 texel (texture pixel).

pseudo-code:

```
offset.x = (float)borderPixels.x / (float)tex.width;
offset.y = (float)borderPixels.y / (float)tex.height;

tile.x = 1.0f - offset.x * 2;
tile.y = 1.0f - offset.y * 2;

```

where borderPixels is the number of pixels to "remove" around the texture.

This will scale the UV coordinates to cut off the desired number of texels.

After that you can scale the render plane **geometry** to the proper aspect ratio.

---
Tags: unity, graphics-programming
---


title: Direct3D 11 - Mipmap level selection

text:
# Question
Title: Direct3D 11 - Mipmap level selection
When we sample a texture resource through an SSO in HLSL, how is the mip level selected for sampling; assuming the texture resource contains mips?

The SSO has parameters that seem to be concerned with the sampling method, but I can't find any documentation anywhere that states how to actually select a mip level.

Or is it done automatically as a function of the NDC depth value?

Thanks.

# Answer
When using the standard `Sample` method, the automatic MIP level selection is actually quite complex. Assuming standard tri-linear sampling of a 2D texture, two MIP levels are actually sampled. The hardware determines which ones by looking at the texture coordinate arguments of four adjacent pixel shader invocations (referred to as a "quad"), and calculates the difference in `u` and `v` coordinates. The two MIP levels that are selected are the ones such that the average delta in `u` and `v` equate to just over one texel (the coarser level), and the one that the delta equates to just under one texel (the finer level). Using the `uv` coordinates at those two MIP levels, the hardware interpolates between the 8 texels to produce the final output color.

This works well for most cases, but if you have a surface that is nearly parallel to the direction of the camera, the difference between the `u` and `v` deltas is actually quite large, so tri-linear sampling can make things look blurry. This is where anisotropic filtering comes in, which uses a much more complicated formula for choosing the MIP levels.
> 4 votes

# Answer
You can use `SampleLevel` to manually select the mip level. The 3rd parameter specifies the mip level.

Documentation here.
> 1 votes

# Answer
This answer is for selecting a mip level in Direct3D 9 and beyond.

Direct3D 11 has a lot to offer in selecting the mip level.

However, in Direct3D9, which a lot of us still use due to the wide range of platforms it is supported, the trick was to use the

```
SetSamplerState(Index, D3DSAMP_MIPMAPLODBIAS, PCardinal(@Value)^);

```

and

```
SetSamplerState(Index, D3DSAMP_MAXMIPLEVEL, PCardinal(@Value)^);

```

(the above is in Delphi/Object Pascal notation, but is easy to see how it would be in C++)

Say for example you want to use only the 3rd mip level. You should execute:

```
SetSamplerState(Index, D3DSAMP_MAXMIPLEVEL, 3);

SetSamplerState(Index, D3DSAMP_MIPMAPLODBIAS, -1000);

```

The above forces the max mip level to 3 (instead of 0), and then forces the bias to -1000 so that level 3 is always selected.
> 0 votes

---
Tags: directx, directx11, mipmaps
---


title: Is it legal to copy a game's melody?

text:
# Question
Title: Is it legal to copy a game's melody?
Is it legal to remake a videogame e.g. Team Fortress 2 theme song using 8bit style and use it in my own game? Basically, if I keep the melody exactly the same, but remake it from scratch, will I get in trouble?

# Answer
**Looks like it's not legal in most countries if you don't have an explicit permission from copryright owner.**

See this: https://en.wikipedia.org/wiki/Derivative\_work

> **A “derivative work” is a work based upon one or more preexisting works, such as a** translation, **musical arrangement**, dramatization, fictionalization, motion picture version, sound recording, **art reproduction**, abridgment, condensation, or any other form in which a work may be recast, transformed, or adapted. A work consisting of editorial revisions, annotations, elaborations, or other modifications which, as a whole, represent an original work of authorship, is a “derivative work”.

It means, your song will be classified as a "derivative work".

Next, in `17 U.S.C. § 106` (found on same wikipedia page) we have following

> Subject to sections 107 through 122, **the owner of copyright** under this title **has the exclusive rights** to do and to authorize any of the following:
>
> (1) to reproduce the copyrighted work in copies...;
>
> (2) **to prepare derivative works based upon the copyrighted work**;
>
> (3) to distribute copies...of the copyrighted work to the public by sale or other transfer of ownership, or by rental, lease, or lending....
> 4 votes

# Answer
**Yes, you'll probably get in trouble if you're trying to make money.**

According to the USC School of Law:

> The entire corpus of judicial opinions in the area of music copyright infringement dwells on melody as the single most idiosyncratic element of the works in question, and almost entirely the locus of the economic worth of a song. Accordingly, the more melodically similar two works are, the more likely a court will determine that the later created work infringes upon the earlier.

I'm not a lawyer, but you should be especially careful in this. Even if you make it from scratch, a judge could care less how you got it. If have some skill in composing, you could change the melody and add some of your own elements to the song, but if the owner finds out you could be in big trouble. Of course, if you're not trying to make money off of this, the lawyers will probably leave you alone.
> -1 votes

---
Tags: copyright, music
---


# Question
Title: Mismatch between scene view and game view
In my scene view, it looks like the player is correctly lined up with the map. But when I see it in the game view, it's off. You can see the Game view in the top-middle, and the Scene view in the bottom left. The map sprite in the game view seems to be off by one tile. It could be that the collision is off too.

What could be causing it and how can I fix it?

# Answer
> 0 votes
The camera x rotation is not set to zero.

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


# Question
Title: Recursive method causes an OutOfMemory error
If a GameObject in my game has a special ability it triggers it, but I want all the special GameObjects that this GameObject affects to also trigger their abilities, for example if a bomb hits some objects, if these objects are also bombs, trigger them too. I though this would be easy by calling the method that handles all the special abilities recursively, but it wasn't. Basically what happened is a chain reaction of bullcrap that caused Unity to show an OurOfMemory error. Also makes my PC freeze completely while politely turning all the screens off.

The question is, how can I make it so it triggers all the affected cubes' special abilities, without everything going nuts?

Code:

```
     //Triggers the cube's special ability, if it has any
    private void TriggerSpecialCubeAbility(GameObject specialCube) {
        switch (specialCube.tag) {

            //Destroy all cubes in a radius from the special cube
            case "Bomb":
                TriggerBombAbility(specialCube);
                break;

            //Destroy all cubes of the same color as the special cube
            case "Lighting":
                TriggerLightingAbility(specialCube);
                break;
            default:
                break;
        }
    }

    private void TriggerBombAbility(GameObject specialCube) {
        var nearbyColliders = Physics2D.OverlapCircleAll(specialCube.transform.position, explosionRadius);
        Instantiate(particles[0], specialCube.transform.position, specialCube.transform.rotation);
        Instantiate(particles[1], specialCube.transform.position, specialCube.transform.rotation);

        foreach (var collider in nearbyColliders) {
            if (collider.tag == "Indestructible")
                return;

            var affectedCube = collider.gameObject;
            TriggerSpecialCubeAbility(affectedCube);
            Destroy(affectedCube);
        }

        destroySelectedCubes = true;
    }

```

# Answer
> 1 votes
As Fábio Junqueira described, it looks like your problem is this:

```
BombA.Explode()
 - triggers BombB.Explode()
   - triggers BombA.Explode()
     - triggers BombB.Explode()

...and so on until all your memory is used up.

```

If bombs are one-shot, I'd solve this with something like the following:

```
public class Bomb : Monobehaviour
{
   private bool hasExploded = false;

   public void Explode()
   {
      // If we already blew up, don't do it again.
      if(hasExploded)
        return;

      // Time to blow up! Remember that we've blown up.
      hasExploded = true;

      // Do explosion logic here
      // (find nearby items to damage/trigger, self-destruct, etc.)
   }
}

```

# Answer
> 0 votes
When this kind of error happens, its likely there is a infinite recursion loop in your code.

You need to make sure there that `Physics2D.OverlapCircleAll` is not returning the same collider more than once.

If that is not the problem, you can try to to replace the recursive function with a `while` loop

**Edit:**

First make sure that Physics2D.OverlapCircleAll is not returning the same collider more than once. I'm not at home right now to test your code, but by looking at it, it seems that an infinite recursion would happen right here:

```
TriggerBombAbility(cubeA);

//nerabyColliders returns cubeB
var nearbyColliders = Physics2D.OverlapCircleAll(specialCube.transform.position, explosionRadius);

TriggerBombAbility(cubeB);

//nerabyColliders returns cubeA
var nearbyColliders = Physics2D.OverlapCircleAll(specialCube.transform.position, explosionRadius);

TriggerBombAbility(cubeA);

//and this repeats forever....

```

---
Tags: unity, recursion
---


# Question
Title: How to make (or where to get) a half-sphere mesh that textures properly?
I'm making a game in Unity that involves lots of spheres. Said spheres will have lighting applied to them, but will *also* be viewed from only one camera angle. Right now, the **full spheres** look something like this when textured, normal-mapped, and lit:

This is **correct**. The spheres in my game will only be seen head-on, thus I only need to render their top halves.

However, if I use the same material on only **half a sphere** (with a lower resolution, mind you), I get something like this:

(It's not the exact same material, but it's close enough, and shows the same problem.)

This is **incorrect**. The weird part is I only encounter this issue in **compiled builds of the game**; in the editor, the hemisphere is textured exactly as I expect.

At the request of a commentator, here is one of the textures I'm using:

I'm also using it as a normal map.

My question is thus: **how can I make (or where can I find) a hemisphere that can be properly textured, and why does my current hemisphere mesh only render properly in the Unity editor?**

# Answer
> 4 votes
You shouldn't really worry about cutting of the other half of the sphere since Unity doesn't render faces that are looking away anyway. That doesn't solve your problem however. Try to save your sphere as a .blend file. Or if you did that, export it as an .fbx.

If you really want to save resources you should bake(bake texture) your full sphere unto a halfsphere that has had "project from view" unwrap applied. Then you also save texture memory where the biggest performance hit comes from. Forget about saving polygons. Generally they don't matter.

EDIT: I think I figured it out. You used the default Unity Spheres first. But exported the halfspheres from Blender. If that is the case. Then add a fresh "UV Sphere" in blender. Press U and click Sphere projection. Then cut half the faces off. Or better yet, follow my baking advice.

---
Tags: unity, textures, models, 3d-meshes
---


# Question
Title: Using one GLSL shader program for textured and untextured rendering?
Rather than have two separate shaders in my OpenGL code (one for when a texture is bound, one for when none is bound) I usually go for one shader program which handles both. This is my usual fragment shader:

```
#version 330

uniform bool textured;
uniform sampler2D sampler;

in vec4 fColor;
in vec2 tCoord;

out vec4 final_color;

void main()
{
    vec4 texel = vec4(1.0, 1.0, 1.0, 1.0);
    if (textured)
        texel = texture(sampler, tCoord);
    final_color = fColor * texel;
}

```

In a modern OpenGL profile, this compiled but did not output anything but black pixels (alternatively in LWJGL legacy profile, it outputted regular colors if textured == false and textured if textured == true). I don't see any reason that this *wouldn't* work, but what is a method which would work for both textured and untextured fragments?

**EDIT:**

# Answer
> 1 votes
If you don't bind a texture to the slot, the result of sampling is basically undefined (though it's often `vec4(0)`).

To fix your issue, create a white 1x1 texture and assign it to `sampler` when you're using this shader without a texture.

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


title: My Java game fills the system memory

text:
# Question
Title: My Java game fills the system memory
edited. I am writing my first game using LIBGDX.
The issue I'm having is that the system memory completely fills up and then even the swap file starts to grow.
From what I see, the memory fills pretty evenly. So it is not one level that has a huge increase of memory usage. As the game moves from level 1 to 2 and so on, the memory usage just keeps going up by a similar amount each time.
I have every arraylist that I use, make sure that it is empty before the level will be declared done and move on to the next so I'm not sure if it is possible that references to objects are being kept.
I have each level set as its own state that gets called by a game state manager and the old level gets set to null, which I thought would allow the java garbage collector to free it from memory. Perhaps this is not happening though.
Basically how can I free up the memory?
Is declaring a state to null, not the proper way to get the java garbage collector to remove it?
Also is it wrong or bad coding design to have each game level as its own state?

# Answer
> 1 votes
You're not giving us much to go on, but I would start by trying to narrow down where this happens. You should be able to find out something like, for example, the memory definitely does not leak in level 24, but does in level 25. Then start by looking more closely at the code for level 25.

Leaked memory in Java means that you're keeping references to objects, even if you don't know you're keeping them. These are probably hidden someplace, like in an array, or possibly in data that you hand over to libGDX.

Do you use the libGDX memory pools? If so, make sure you're calling `free()` on every object you `obtain()`. Mismatched calls can be really tricky to find. Likewise, make sure you call `dispose()` on all the disposables.

The fact that you're allocating *so much memory* gives us a clue as well. This indicates that you should check any allocations that happen in a loop, (this could fit the case of the memory pool leak), or check for typos in an array sizes, etc.

Your IDE should be able to provide you enough debug information that you can track down which variables are holding all the memory, but that can take a bunch of work with the profiler. If you're not familiar with the profiler, it may be faster/easier to do the search yourself.

---
Tags: java, libgdx
---


title: Creating placement grid in Unity

text:
# Question
Title: Creating placement grid in Unity
I'm fairly new to C# and Unity, so I don't really know much about it.

I want to create an RTS like game where you have a huge grid that the whole world is placed on. Then you can place houses, walls etc on the tiles just like a lot other RTS games (i.e. Age of Empires, Stronghold Series etc).

How would I go about this in Unity? I could imagine having some Terrain/World manager that handles all the models and objects that you can interact with etc. And probably a lot of prefabs too with the different items, soldiers and so.

So if anyone have any smart way of doing this or maybe a link to a tutorial explaining, then the help would be greatly appreciated.

# Answer
> 2 votes
You don't exactly need a grid actually. If you don't need to get information back from tile, you can create a fake tile illusion by "snapping" objects to certain floating points.

For instance, say, you want to have a grid that has placement points on 0, 1, 2, 3 and 4.
Then when the object is at 0.3f, you round it to 0;
and when it is at 0.7f, you round it to 1 (etc.).

This way you will create a snapping effect that gives illusion of a grid.

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


# Question
Title: Reading from txt causes null pointer exception
I'm reading from this text file called beatSheet.txt.

> A: 100 A: 101 A: 102 A: 103 A: 104 A: 105 A: 117 A: 120 A: 122 A: 126 A: 128 A: 129 A: 130 A: 131 A: 133 A: 138 A: 139 A: 140 A: 142 A: 149 A: 15 A: 151 A: 155 A: 156 A: 158 A: 16 A: 164 A: 166 A: 17 A: 172 A: 174 A: 18 A: 180 A: 182 A: 184 A: 188 A: 189 A: 19 A: 32 A: 36 A: 40 A: 45 A: 46 A: 55 A: 56 A: 57 A: 58 A: 63 A: 65 A: 68 A: 70 A: 72 A: 74 A: 79 A: 80 A: 81 A: 82 A: 86 A: 94 A: 95 A: 96 A: 97 A: 98 A: 99 ...(continues for letters s, k, and l)

When I call this method

```
public void openFile(String file) throws IOException{
    FileReader fileToRead = new FileReader("res/"+file);
    BufferedReader bf = new BufferedReader(fileToRead);

    int numLines = readLines(file);

    for(int i = 0; i < numLines;i++){
        if(bf.readLine().contains("A")){
            aList.add(Integer.parseInt(bf.readLine().substring(3)));
        }
        if(bf.readLine().contains("S")){
            sList.add(Integer.parseInt(bf.readLine().substring(3)));
        }
        if(bf.readLine().contains("K")){
            kList.add(Integer.parseInt(bf.readLine().substring(3)));
        }
        if(bf.readLine().contains("L")){
            lList.add(Integer.parseInt(bf.readLine().substring(3)));
        }
    }
    bf.close();
}

```

I get a NullPointerException. Can anyone explain why? This should work.

# Answer
> 3 votes
Every time you call **readLine()** it moves ahead in your file.

So on every loop you're actually **reading 4 to 8 lines** instead of 1. Once you run out of lines to read, readLine() returns null which causes the NullPointerException.

change your loop to:

```
while(true) {
    String str = bf.readLine();

    if(str == null) {
        break;
    }
    if(str.contains("A")){
        aList.add(Integer.parseInt(str.substring(3)));
    }
    ...

```

As to call readLine() only once per loop.

no need for `int numLines = readLines(file);` you'll know you're done when readLine() returns null.

---
Tags: java, file
---


# Question
Title: Texture becomes white box when drawing it?
My problem is that when I try to render my `sf::Sprite` it only renders a white box in my window.

I did some reading on this and couldn't really find anything that helped.

Some said that it's because of the `sf::Texture` variable being in a local scope but mine is in a .h file, which isn't a local scope (I think, at least...)

Someone also mentioned `std::vectors` somehow destroying the `sf::Texture` 's, but my `sf::Texture` is not in a `std::vector`.

However my class which contains `sf::Texture` is a object inside a `std::vector` but I don't know if that matters or not.

---

In my `Sprite.h` I have defined my `sf::Sprite`, `sf::Texture` and `sf::Image` like this :

```
sf::Sprite sprite;
sf::Texture texture;
sf::Image image;

```

and I load an image in like this :

```
if (!image.loadFromFile(PATH))
    std::cout << "Could not load image file : " << PATH << std::endl;

texture.loadFromImage(image);
sprite.setTexture(texture);

```

I render the `sf::Sprite` like this :

```
    for (int i = 0; i < entities.size(); i++)
    {
        entities[i].Draw();
    }

```

Lastly, here's my `std::vector` of my "sprite objects".

```
std::vector<Sprite>entities;
entities.push_back(Sprite(&window, sf::Vector2f(100, 100), 0, "Res/Images/Face.bmp"));

```

---

The picture file is a `.bmp` file, and the path to the file is valid.

---

(I did check both google and this forum for posts like this but none of them helped me.)

# Answer
Your `Sprite` class contains a `sf::Texture` object which is moved by the `std::vector<Sprite>` container.

You're still placing `sf::Texture` inside a `std::vector`, just indirectly.

When the `std::vector` gets resized `Sprite` objects get copied to a new larger buffer at new addresses. But the texture pointer inside `sf::Sprite` still points to the old address where the `sf::Texture` used to be originally.

You can fix this by using an `std::vector<Sprite *>` instead which will copy the pointers to objects rather than the objects themselves.

```
std::vector<Sprite *> entities;

```

and allocate your Sprite objects on the heap as such:

```
entities.push_back(new Sprite(&window, sf::Vector2f(100, 100), 0, "Res/Images/Face.bmp"));

```

(Note the **new** keyword above.)

To destroy:

```
delete entities[i]; // Delete first
entities.erase(entities.begin()+i); // remove from array (std::vector)

```

to draw:

```
for (int i = 0; i < entities.size(); ++i)
{
    entities[i]->Draw();
}

```

(Note the **-\>** operator instead of **.** operator above. And use the prefix operator ++i whenever possible)

This will make sure every `Sprite` object stay in the same spot in memory once created. Only pointers to them get stored inside the `std::vector`.

It also makes adding and removing objects faster as less data is moved around.

You just have to remember to **delete** the `Sprite` objects before erasing the entry in `entities` or you will leak memory.
> 1 votes

---
Tags: c++, sprites, sfml
---


title: Why is my game freezing?

text:
# Question
Title: Why is my game freezing?
Ok here is what I have done. I have made a simple test game where you move a character around. I built it and installed the app onto 2 different devices (as it will be a multiplayer game later).

*Phone1* \- Samsung Galaxy S4 (Android version 4.4 kit kat I know I need to update it)

*Phone2* \- LG G Stylo (Android version 5.1 lollipop)

My SDK - I have android 6.0 (API 23) installed everything up to date.

*Phone1* plays it flawlessly no errors. *Phone2* plays it until it freezes at random times. Not much going on in the scene as far as graphics. I kept it pretty simple.

Some debugging I did was to check the logcat. No errors are shown! The only thing I notice is that the frames just stop. So I go to developers options on both phones and check the box that allows you to see every update. I find out that after a while *Phone2* stops updating the games frames, which freezes it. It is no longer calling `Update()`. *Phone1* keeps running perfectly no crash yet.

What am I doing wrong? I am guessing it's a version issue but I don't know where to go from here.

# Answer
You can try attaching MonoDevelop ( http://docs.unity3d.com/Manual/AttachingMonoDevelopDebuggerToAnAndroidDevice.html ) to your device and hope that it can break when the game freeze and tell you where the hang is but this does not always work.

If that does not work you're in for a good old session of "printf" debugging (in the case of unity it's Debug.Log() ) and hope that:

* the issue is somewhere surrounded by c# code
* not deep within a native plugin
* not within Unity
* that Debug.Log() does not change timing in a way that prevent the issue from happening making it impossible to narrow down the issue.

You're going to have to put Debug.Log() calls around parts of the code you suspect might hang and keep narrowing it down until you find the exact spot that hangs. (Yes, this is probably going to take a while.)

And make a backup of your project first, it'll be easier to revert the mess of Debug.Log() that will be added once the issue if found (hopefully).

For example:

```
void Update() {
    Debug.Log("MainHero Update() Begin");

    ... the hero code

    Debug.Log("MainHero Update() End");
}

```

And look at the log for a Begin without an End when it hangs, then once you find the function that hangs you can narrow it down by adding Debug.Log()s inside it between parts of the code.

You'll have to check every functions until you've found the line of code that causes these hangs.

Which may not even be in the C# code. It could be somewhere in a native thread such as the sound or networking.

Another thing you can try is remove Google Play and/or sound and/or anything else you can think of and keep going by elimination until it doesn't freeze anymore. (Again, make a backup of your project first.)
> 3 votes

---
Tags: unity, android, performance
---


title: Creating a Slide-Up Menu

text:
# Question
Title: Creating a Slide-Up Menu
How can I create a menu that slides up while "un-fading" as illustrated in this video?

As you can see in the video, the menu also falls down a bit in the end which gives it a realistic feel. I really have no idea on how to approach this, and searching the web did not help either.

Any help is appreciated.

# Answer
> 2 votes
You can animate just about anything in Unity. Fade effects are generally just the animation of the UI item's alpha color.

https://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/animate-anything

http://forum.unity3d.com/threads/changing-a-new-ui-images-alpha-value.289755/

---
Tags: c#, unity, gui, menu
---


# Question
Title: How to Access MouseLook In Unity 5 with JavaScript
I'm following a tutorial to make a horror game. In the 8th tutorial I got stuck with the Mouselook option, he is using an other version of unity and I'm using Unity 5.

In Unity 4, MouseLook was a script attached to FPController, but in Unity 5, MouseLook has changed to become a part of FPController Script (in C#) as an object.

Now I need to access that, how to do that?

The file I am using is here: http://ryandome.weebly.com/ *(named pausemenu.js)*

And the error is in line 238 where it's unable to get the FPS controller's Mouselook option:

```
firstPersonControllerCamera = gameObject.Find("First Person Controller").Find("FirstPersonController");
print(firstPersonControllerCamera);
mainCamera = gameObject.FindWithTag("MainCamera").GetComponent("MouseLook");
firstPersonControllerCamera.enabled = false;
mainCamera.enabled = false;

```

# Answer
> 1 votes
To disable the Mouselook for a pause menu it surely doesn't matter if you disable the fps controller script instead of just the Mouselook script so you could try doing that using similar code to what's already there.

Instead of getting the fps camera and then the mouse look component you could get the fps controller script and then disable that.

# Answer
> 0 votes
The MouseLook is still a separate script in Unity 5. Search for MouseLook in the hierarchy. It's written in c#, but it's fairly simple.

---
Tags: javascript, unity
---


# Question
Title: Unity animation won't play on trigger. What do I do to fix it?
Ok so I added a play animation line to my trigger script. I made an animation, added it to the trigger object, attached the animation to the trigger, and tested. The target goes to the trigger as it should, deletes the trigger, but the animation never plays. So I check the console, and it's telling me "The AnimationClip 'MazeDoorClose' used by the Animation component 'SuckInTarget' must be marked as Legacy." so I do that, but now the trigger activates before the target gets there, and there is still no animation playing!

I know this sounds confusing so in an attempt to make it easier to understand I made a short video . Sorry for the crappy quality, but hey it's free. Here is the code:

```
using UnityEngine;
using System.Collections;

public class SuckIn : MonoBehaviour
{

    public Transform target;
    public float speed;
    public string ObjectWithTagToBeDestroyed;
    public string ThingToAnimate;

    void Update()
    {
        float step = speed * Time.deltaTime;
        target.position = Vector3.MoveTowards(target.position, transform.position, step);
    }

    void OnTriggerEnter(Collider coll)
    {
        if (coll.gameObject.tag == "Ball")
        {
            Destroy(GameObject.FindWithTag(ObjectWithTagToBeDestroyed));
            GetComponent<Animation>().Play(ThingToAnimate);
        }
    }

}

```

Before you ask yes the animation is on the object as it should be, and as Unity told me to do I marked it as a legacy animation. Any ideas what am doing wrong?

# Answer
> 1 votes
I'm not quite sure how to solve the legacy issue but I can recommend a different way to tackle your problem.

Instead of trying to play the animation directly use a parameter on the Animator Controller to trigger it. Here is a video released by Unity that trains you on creating them. This is very worth learning it is more robust and will give you greater control in the long run.

Regarding how to call it in your script, if you used a trigger (for a one time call) then you would type:

```
GetComponent<Animator>().SetTrigger("MyTriggerName");

```

Let me know if you have more questions on how to get this setup after watching the video/reading the documentation.

# Answer
> 0 votes
You have the animation to start as awake checked accidentally. Use the **debug** menu in the upper options panel in the inspector to see all the animation options.

---
Tags: animation, unity
---


# Question
Title: How do I determine the look-at vector of a free-look camera?
I'm trying to create a free-look camera with DirectX 10.

I've figured out how to get the directions for forward and back and left to right. However, I don't know how to rotate the look-at vector of my view matrix around the camera position so as to rotate in-place. How can I do this?

# Answer
You need to rotate around the X axis to have "up-down rotation", Z axis if you want "roll rotation", and Y if "left-right" rotation. Rotate the "front" (or look at vector) and "up" vector around the desired axes. Make sure to rotate those vectors before translating the camera. If you applied your rotation and translation then recreate the view matrix with those values.
> 1 votes

# Answer
some link to crunch the math side if you want to prepare a one matrix that rotates about the 2 angles at once:

http://inside.mines.edu/fs\_home/gmurray/ArbitraryAxisRotation/

Otherwise I personally do it this way:

```
void ThisApplication::UpdateClient0Positions(void)
{
    if (AbsoluteValueFl(RotateCamera.y) > D3DXToRadian(120))
        RotateCamera.y = D3DXToRadian(120) * Sign(RotateCamera.y);

    Direction.x = (float)( sin(RotateCamera.x) * cos(RotateCamera.y) );
    Direction.y = (float)( sin(RotateCamera.y) );
    Direction.z = (float)( cos(RotateCamera.x) * cos(RotateCamera.y) );

    up.x = (float)( sin(RotateCamera.x) * sin(RotateCamera.y) * -1 );
    up.y = (float)( cos(RotateCamera.y) );
    up.z = (float)( cos(RotateCamera.x) * sin(RotateCamera.y) * -1 );

    if (Active[STRAFE_LEFT])
    {
        TravelCamera.x -= (float)(cos (RotateCamera.x) * g_CameraSpeed * FrameTime);
        TravelCamera.z += (float)(sin (RotateCamera.x) * g_CameraSpeed * FrameTime);
    }
    else if (Active[STRAFE_RIGHT])
    {
        TravelCamera.x += (float)(cos (RotateCamera.x) * g_CameraSpeed * FrameTime);
        TravelCamera.z -= (float)(sin (RotateCamera.x) * g_CameraSpeed * FrameTime);
    }

    if (Active[GO_FORWARD])
    {
        TravelCamera.x += (float)(Direction.x * g_CameraSpeed * FrameTime);
        TravelCamera.y += (float)(Direction.y * g_CameraSpeed * FrameTime);
        TravelCamera.z += (float)(Direction.z * g_CameraSpeed * FrameTime);
    }
    else if (Active[GO_BACKWARD])
    {
        TravelCamera.x -= (float)(Direction.x * g_CameraSpeed * FrameTime);
        TravelCamera.y -= (float)(Direction.y * g_CameraSpeed * FrameTime);
        TravelCamera.z -= (float)(Direction.z * g_CameraSpeed * FrameTime);
    }

    if (Active[JUMP])
    {
        TravelCamera.x += (float)(up.x * g_CameraSpeed * FrameTime);
        TravelCamera.y += (float)(up.y * g_CameraSpeed * FrameTime);
        TravelCamera.z += (float)(up.z * g_CameraSpeed * FrameTime);
    }
    else if (Active[CROUCH])
    {
        TravelCamera.x -= (float)(up.x * g_CameraSpeed * FrameTime);
        TravelCamera.y -= (float)(up.y * g_CameraSpeed * FrameTime);
        TravelCamera.z -= (float)(up.z * g_CameraSpeed * FrameTime);
    }

    D3DXMatrixLookAtLH (&MatView, &D3DXVECTOR3(TravelCamera.x, TravelCamera.y, TravelCamera.z),
                                  &D3DXVECTOR3(TravelCamera.x + Direction.x,
                                               TravelCamera.y + Direction.y,
                                               TravelCamera.z + Direction.z),
                                  &up);
    g_pD3DDevice->SetTransform (D3DTS_VIEW, &MatView);
}

void ThisApplication::ReadMouse(void)
{
    RotateCamera.x += MouseStt.lX * g_Sensitivity * 0.005f;
    RotateCamera.y -= MouseStt.lY * g_Sensitivity * 0.005f;
}

```

The MouseStt comes from direct input get device state, updated by frame basis (therefore the traveled distance is accumulated correctly for the delta time, by the driver).
> 0 votes

# Answer
> I've figured out how to get the directions for forward and back and left to right.

This means that you are on a home stretch Just take a cross-product of your forward & right vectors to get the rotation axis. Then construct the rotation around axis quaternion and use it to rotate your view vector either by rotation matrix or just by multiplication of a vector and quaternion.

Hope this helps

P.S. looks like you can directly plug that rotation axis to **XMMatrixRotationAxis** method. P.P.S. for a first person camera like in most FPS games you don't have to take a cross-product, instead just use the constant \<0, 0, 1\> axis.
> 0 votes

---
Tags: c++, directx, camera, rotation
---


# Question
Title: Java 2D Game Development - Best Performance With Rendering
I have seen two different rendering methods. One of them is rendering multiple bufferedImages like g.drawImage(image1 to imagexxx, x, y). Like in my game I have to render, on each tick, 880 buffered images. This is very bad. I have a good computer but my max fps is 140. There should be another way to get better performance.

The second way is drawing one single bufferedImage and setting its pixels to RGB from the other bufferedImages.

What is the best way? Is there another way to get better performance?

# Answer
> 1 votes
I personally would prefer the second method, because it allows you to manipulate the one buffered image, that you're using, so you can, for example apply filters and do some post processing with it. Also you can set a fixed resolution for your game and do some scaling.

I hope that helped at least a bit

---
Tags: java, 2d, rendering, performance
---


# Question
Title: How to convert OpenCV camera capture to Irrlicht texture without killing fps?
I am looking to include images captured from the users webcam into my application so I've been looking into using OpenCV to capture from the webcam and then render it in Irrlicht. I've created a basic app to test and I'm doing this in my main loop to capture and convert to ITexture\* to render onto a cube.

```
    if( cv::waitKey(50) >= 0 ) break;
    capture >> camera_frame;

    if( ! camera_frame.empty() )
    {
        unsigned char *tex_buf = (unsigned char*)frame_tex->lock();
        unsigned char *frame_buf = camera_frame.data;
        // Convert from RGB to RGBA
        for(int y=0; y < camera_frame.rows; y++) {
            for(int x=0; x < camera_frame.cols; x++) {
                *(tex_buf++) = *(frame_buf++);
                *(tex_buf++) = *(frame_buf++);
                *(tex_buf++) = *(frame_buf++);
                *(tex_buf++) = 255;
            }
        }
        frame_tex->unlock();

        //cube->setMaterialTexture(0, driver->getTexture("../../media/t351sml.jpg"));
        cube->setMaterialTexture(0, frame_tex);
        cube->setMaterialFlag(video::EMF_LIGHTING, false);

    }

...

```

It works.... BUT... the framerate drops to about 4fps.

Yes, it probably could have been done slightly more efficiently, but it's a massive drop in framerate for something so simple.

Is there another way to do this that won't kill the framerate?

# Answer
> 1 votes
Try this (the suggested modifications are in the comments in the code):

```
if( cv::waitKey(50) >= 0 )
    break;
capture >> camera_frame;

if( ! camera_frame.empty() )
{
    unsigned char *tex_buf = (unsigned char*)frame_tex->lock();
    unsigned char *frame_buf = camera_frame.data;
    // Convert from RGB to RGBA
    for(int j=0; j < camera_frame.rows*camera_frame.cols; j++) {

        *(tex_buf) = *(frame_buf);
        *(tex_buf+1) = *(frame_buf+1);
        *(tex_buf+2) = *(frame_buf+2);
        *(tex_buf+3) = 255;
        frame_buf +=3;
        tex_buf +=4;
        // remove accumulator because when product with row*cols it huge time
        // and merge x loop & y loop in one that remove more asm count operation
    }
    frame_tex->unlock();

    //cube->setMaterialTexture(0, driver->getTexture("../../media/t351sml.jpg"));
    cube->setMaterialTexture(0, frame_tex);
    cube->setMaterialFlag(video::EMF_LIGHTING, false);

}

```

---
Tags: c++, irrlicht
---


# Question
Title: What is the more appropriate way to implement a health bar in iOS?
I'm building a game a pokemon like rpg game in iOS using Swift. I'm currently in the process of making graphics and is in the dilemma of either just using a health bar blank and dynamically changing the length of a health bar or should I instead use intervals (100percent.png, 90percent.png) to represent damage? Which way is more appropriate to conserve memory and is more efficient?

# Answer
Generally, I wouldn't think the efficiency of drawing your health bar would be a bottleneck in your game. If it is, you should figure out why by profiling your code and seeing where the slowdown is.

Having said that, you could just make it a rectangle that you fill in and then it takes no texture memory. It may not look as cool, but if you're concerned about the amount of memory you're using, it's very efficient. It also allows you to make the health any value between the minimum and maximum, so you aren't constrained to just 10% intervals.

If you still want to use textures, you could also look into compressed textures. I'm not sure whether or not iOS supports them and if so which types of compression, but if you're concerned about size, that may be a reasonable option.
> 2 votes

---
Tags: ios
---


# Question
Title: How to handle gun position while running and aiming in an FPS
In an FPS, when a character runs, from the view of another character, the gun moves, and similarly when the character aims down sight. Are the views from the third person and from the first person actually showing the same gun position? I feel like it would be tricky to that happen and have it look natural from both perspectives.

# Answer
The gun position is not the same when viewed from the FPS player perspective than from the 3rd other players perspective.

This is due to the fact that both of these views need to look "realistic". And there is no magic potion to make the look and feel applicable for both of them.

In the first-person-view, you *rarely* see the character's body, so what the player sees is only the hands and the gun, tuned so that it has a look and feel realistic.

And the 3d artists can work with the models that you see in 3rd person so that they too look realistic.
> 1 votes

---
Tags: models, skeletal-animation, first-person-shooter
---


# Question
Title: Is it legal to use other game's title word in my game's name?
Is it legal to use e.g. the word "Fortress" in my game’s title?

There is a game called *Team Fortress* and I think it’s trademarked. I’m thinking of replacing the word "Team" with another word and using that name in my game (with an intent to make money).

Would I get in trouble?

# Answer
Usual disclaimer: I am not a lawyer and in this site questions about these issues have to be always taken as ideas, thoughts or experiences, never as technical advice.

That said, it's good that in your question you use both the tags "copyright" and "trademark", because indeed your question in the end touches the difference between these two. I say that because a game's title can be trademarked, while the asset's of games can be copyrighted. At the same time, the concept or the gameplay of a game is a more difficult matter. For a nice quick guide/discussion to that, including some points that are very directly related to your question, see the article "Video Games and the law: Copyright, Trademark and Intellectual Property".

---

Now, let me briefly address particular issues raised by your question.

First of all, certainly words in themselves are not trademarked per se. Second, if you take the title of a game and change it *enough*, you *certainly can* be safe from issues regarding the trademark of the original game's title. The problem is that how much is "enough" is something that can't be determined a priori. Therefore, there is always risk (and consider that the problem of being sued is not only loosing, but even before that, wasting time and resources on the matter).

However, your main problem does not seem to even be the infringement of the trademark of another game's title, but rather you being afraid of copyright infringement since by your comment to other answers you seem to plan to fully copy the gameplay of a copyrighted game and just modify your version's title to avoid having your gameplay-copy from being sued.

Here things are more dubious. On the one hand, the US Copyright office says that:

> Copyright does not protect the idea for a game, its name or title, or the method or methods for playing it. Nor does copyright protect any idea, system, method, device, or trademark material involved in developing, merchandising, or playing a game. Once a game has been made public, nothing in the copyright law prevents others from developing another game based on similar principles. Copyright protects only the particular manner of an author’s expression in literary, artistic, or musical form.

On the other hand, this is a bit too vague for making one feel safe. In fact, the interpretations at the Courts have been diverging quite bit. There is an excellent article on Gamasutra, from 2013, that discusses that: "Clone Wars: The Five Most Important Cases Every Game Developer Should Know".

Therefore, copying the title and copying the whole game mechanics are two different things that are not necessarily related. I mean, even if your title isn't considered to be infringing the trademark of another game's title, your game fully copying another game's gameplay can put you into trouble. Even if your game's title is 100% different (but of course if the title is also similar, it will be used as additional evidence of you desiring fully copying the copyrighted game).

And when I say that it can put you into trouble, I mean the following. Although game ideas and game concepts in general can not be copyrighted, the problem is two-folded:

a) if your game calls enough attention from the original game's company, considering the law is a bit dubious here, they might try their luck and sue you because fighting at the courts is proportionally much more of a burden for you than for a big company.

b) again, since things definitions and rules are a bit too vague in the case of gameplay, game concepts and game ideas, you always incur in the risk of courts deciding that you went too far and really copied the original game just disguising that. After putting a lot of your time and resources on making the game, just that risk is often too big since all your efforts would be at a loss.

Hope it helps!
> 15 votes

# Answer
No, it's not illegal to use words from another trademark. Police won't visit you, and you won't have to go to jail, even if you outright use the same trademark.

**However**, holders of any trademark can decide to sue you, either to make you stop using the name, to make you give them a share of the income from the game, to make you acquire a license from them for further use of the name, to compensate them for damage done to their brand, or any combination of those.

Their chances to win the case increase if their case is stronger and/or if they have more lawyers. The case for them is strongest if the name is very similar to your trademark (e.g. squad fortress), the trademarked object is similar (e.g. you make a capture the flag 3D shooter with comic-like graphics), and the 2 products actually compete with each other. Further details depend on jurisdiction.

Once they win the case and you refuse to pay them and/or the court, you might be doing something illegal and should worry about police and jail.

Cases where anyone sues you do not have to have any merit at all to succeed. As soon as the cost for defending is significantly higher than the cost of the settlement, most people settle. Case in point: http://www.pcgamer.com/rebellion-sues-stardock-for-using-its-name-in-sins-of-a-solar-empire-rebellion.
> 6 votes

# Answer
I think too much emphasis is made on legal use of trademark. The bottom line is that you may be sued for just about anything. The best way not to be sued is for your game not to become popular. If Minecraft was just as unsuccessful as the games it copied its gameplay from, then it would probably not have problems from Bethesdas paranoia. If you need legal advice go for a lawyer, but keep in mind that the bigger blip you are on the radar the higher likelihood of being sued for just about anything.
> 4 votes

# Answer
I think you can use this word as long as your game (and gameplay) has nothing to do with team fortress.

You should avoid something too similar like "squad fortress" for exemple.

It depends on the company that hold the trademark. For exemple, Mojang (minecraft) had troubles for putting a dragon as final boss in their game while Bethesda was releasing Skyrim (a game where you have to figth dragons).
> 2 votes

---
Tags: trademark
---


# Question
Title: Does all box2d bodies have collision detection?
What I want to know is if both b2-static and dynamic bodies have automatic collision detection.

And how do I tell box2D what it should do when it collides with a specific body?

# Answer
> 1 votes
You should follow some tutorials as you are learning Box2D. Every body in Box2D has collision detection unless disabled. There are many way of checking collisions, here they're explained well:
http://www.iforce2d.net/b2dtut/collision-anatomy

Also do some research please, things like this can be easily found on Google or even here.

---
Tags: c++, box2d
---


title: LibGDX - Map Boundaries

text:
# Question
Title: LibGDX - Map Boundaries
## Synopsis

Well, I'm making a little top-down JRPG and today I was like 'Yeah, I'm gonna bust out this whole map collision thing!'. I failed.

## Problem

So I went on the internet and looked up 'LibGDX Tiled Map Collision Detection' and found a really neat post about Map Objects so I added in a map object layer and did all that biz and came out with this little method to ensure the player can move freely around the map but at the same time can't exit it but each time I've tried it ends up with a horrible result such as the player moving off the screen. The latest error is that the player gets stuck doing a walk animation and can't move anywhere else!

## Code

```
package com.darkbyte.games.tfa.game.entity.entities;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.objects.RectangleMapObject;
import com.badlogic.gdx.math.Rectangle;
import com.darkbyte.games.tfa.game.entity.Entity;
import com.darkbyte.games.tfa.game.entity.SpriteSheet;
import com.darkbyte.games.tfa.game.world.map.MapManager;
import com.darkbyte.games.tfa.render.Batch;
import com.darkbyte.games.tfa.render.Camera;

public class Player extends Entity {

    // The constructor for the player class
    public Player(String name, SpriteSheet spriteSheet) {
        super(name, spriteSheet);
        direction = Direction.DOWN;
        collisionBox = new Rectangle(x, y, 64, 64);
    }

    // A flag to see if the player is moving
    private boolean isMoving;
    // The variable that holds the state time
    private float stateTime;

    // The player's walking animations
    private Animation[] walkAnimations = {
            spriteSheet.getAnimation(8, 8, 1 / 16f),
            spriteSheet.getAnimation(9, 8, 1 / 16f),
            spriteSheet.getAnimation(10, 8, 1 / 16f),
            spriteSheet.getAnimation(11, 8, 1 / 16f) };
    // The player's static frames
    private TextureRegion[] staticFrames = {
            spriteSheet.getTexture(8, 0),
            spriteSheet.getTexture(9, 0),
            spriteSheet.getTexture(10, 0),
            spriteSheet.getTexture(11, 0) };

    // The render code for the player
    @Override
    public void render() {
        // Makes the camera follow the player
        Camera.setCameraPosition(x, y);
        Batch.getGameBatch().setProjectionMatrix(Camera.getCamera().combined);

        // Updates the state time
        stateTime += Gdx.graphics.getDeltaTime();

        // Gets the player's direction, if the player's moving, it sets the
        // current frame to the frame that would be played at the current moment
        // based on the state time
        // If the player isn't moving, it sets the current frame to the static
        // frame associated to the direction
        switch (direction) {
        case UP:
            if(isMoving) {
                currentFrame = walkAnimations[0].getKeyFrame(stateTime, true);
            } else
                currentFrame = staticFrames[0];
            break;
        case LEFT:
            if(isMoving) {
                currentFrame = walkAnimations[1].getKeyFrame(stateTime, true);
            } else
                currentFrame = staticFrames[1];
            break;
        case DOWN:
            if(isMoving) {
                currentFrame = walkAnimations[2].getKeyFrame(stateTime, true);
            } else
                currentFrame = staticFrames[2];
            break;
        case RIGHT:
            if(isMoving) {
                currentFrame = walkAnimations[3].getKeyFrame(stateTime, true);
            } else
                currentFrame = staticFrames[3];
            break;
        }
    }

    // The tick code for the player
    @Override
    public void tick() {
        // The object to represent the bounds of the land on the map
        RectangleMapObject land = (RectangleMapObject) MapManager.getCurrentMap().getMap().getLayers().get("collision").getObjects().get("land");

        // Checks if the player is within the bounds of the map
        if(land.getRectangle().contains(collisionBox)) {
            // If the player is moving but the arrow keys aren't pressed, sets isMoving to false
            isMoving = (isMoving && (Gdx.input.isKeyPressed(Keys.W) || Gdx.input.isKeyPressed(Keys.UP)
                    || Gdx.input.isKeyPressed(Keys.A) || Gdx.input.isKeyPressed(Keys.LEFT)
                    || Gdx.input.isKeyPressed(Keys.S) || Gdx.input.isKeyPressed(Keys.DOWN)
                    || Gdx.input.isKeyPressed(Keys.D) || Gdx.input.isKeyPressed(Keys.RIGHT)));

            // Checks to see if the arrow / WASD keys are pressed and moves the
            // player in the correct direction at the speed of 1.5 pixels/tick
            // (45/second)
            // It also sets the players state to moving and corresponds it's
            // direction to the key pressed
            // Doesn't move if opposing keys are pressed
            if(Gdx.input.isKeyPressed(Keys.W) || Gdx.input.isKeyPressed(Keys.UP)) {
                if(!(Gdx.input.isKeyPressed(Keys.S) || Gdx.input.isKeyPressed(Keys.DOWN))) {
                    direction = Direction.UP;
                    y += 1.5f;
                    isMoving = true;
                }
            }

            if(Gdx.input.isKeyPressed(Keys.A) || Gdx.input.isKeyPressed(Keys.LEFT)) {
                if(!(Gdx.input.isKeyPressed(Keys.D) || Gdx.input.isKeyPressed(Keys.RIGHT))) {
                    direction = Direction.LEFT;
                    isMoving = true;
                    x -= 1.5f;
                }
            }

            if(Gdx.input.isKeyPressed(Keys.S) || Gdx.input.isKeyPressed(Keys.DOWN)) {
                if(!(Gdx.input.isKeyPressed(Keys.W) || Gdx.input.isKeyPressed(Keys.UP))) {
                    direction = Direction.DOWN;
                    y -= 1.5f;
                    isMoving = true;
                }
            }

            if(Gdx.input.isKeyPressed(Keys.D) || Gdx.input.isKeyPressed(Keys.RIGHT)) {
                if(!(Gdx.input.isKeyPressed(Keys.A) || Gdx.input.isKeyPressed(Keys.LEFT))) {
                    direction = Direction.RIGHT;
                    x += 1.5f;
                    isMoving = true;
                }
            }
        } else {
            if(!isMoving) {
                // If the player's just spawned puts the player to the map's spawn point
                x = MapManager.getCurrentMap().getPlayerSpawnX();
                y = MapManager.getCurrentMap().getPlayerSpawnY();
            } else { // If not, it just moves them back till they're no longer out of the map
                if(x > (land.getRectangle().getX() + land.getRectangle().getWidth())) x -= 1.5;
                if(y > (land.getRectangle().getY() + land.getRectangle().getHeight())) y -= 1.5;
            }
        }

        // Synchronises the collision box with the player's x and y position
        collisionBox.x = x;
        collisionBox.y = y;
    }

    // Returns if the player is moving
    public boolean isMoving() {
        return isMoving;
    }
}

```

Can you guys make it so that when he reaches the border that he stops but he can still keep moving!

Thanks for reading!

# Answer
> 1 votes
Try it this way :

First of all, create this four variables:
`boolean left,right,up,down;`
The next thing you wanna do is to create these variables:
`boolean canleft,canright,canup,candown;`
Now use four collision-boxes instead of one, one one the left side, one on the right, one on the upside and finally one on the downside of your character.
When you check for collision, set at the beginning all the canleft, canright and so on variables to true, and if there is a collision with the left collision box of your character, set canleft to false and the same for all the other boxes.
Now to your keyevents: set left to true, when the key for left is pressed, set it to false if it is released, same for up,down and right.
The last step you wanna do, is moving: Only move your character to the left, if canleft and left are true, the same is for right, up and down.

I hope you get the idea and that I could help at least a bit... Comment below if you need any further explanation

---
Tags: java, collision-detection, libgdx, tilemap
---