# Question
Title: 2d coordinates vs x/y screen positioning
I have a 2d top-down view tile map game, that generates random color tiles (water colors) as you move the character. I've been positioning elements on screen using the x/y coords (finding a way to generate new tiles as the player moves was no picnic, but I did it).

My problem is that I want to establish an actual map-level coordinate system, so the player knows where they are. I'd prefer to just count a first "spawn" area as `0,0` and then count from there.

How should I handle doing that? The problem with x/y is that it's relative to the window frame. I have code that detects when the character reaches the edge of the window, and it "freezes" the player, and moves the map instead.

Whatever system I use, I'll need to be able to add code that can check for other nearby entities.

# Answer
Screen coordinates (SC) should be derived from world coordinates (WC). So if the player is in WC space at 2000, 3000, and the screen is only 640x480, a quick modulo will tell you what coordinate the player is relative to the fixed-screen system you mentioned. So, the SC in the example I have setup is therefore

```
2000 % 640 = 80
3000 % 480 = 120

```

So your SC are now 80, 120. This will always generate you a "grid" as broken up by the screen resolution. You can substitute the resolution of your screen with instead the square area of your grid. So if you have 10x15 tiles of 20px by 20px each, then the math is pretty simple.

To have the coordinate system start at 0, 0 where the player is, the screen coordinates would need to be shifted to allow 0, 0 be the center of the screen (instead of the top-left corner, which is what would happen if you used modulo). So feel free to adjust as necessary. Otherwise no other fancy mathematics is necessary. Just remember that modulo in Java does not work in the most convenient way. If you wanted -4 % 5 to return 4, you should do the following

```
newX = Math.abs(-4) % 5;
if(-4 < 0)
    newX *= -1;

```

This will preserve the modulo rules we want and keep the negative the way it should. I believe otherwise Java just returns 0 for all negative numbers when used with modulo.
> 3 votes

---
Tags: java, 2d, coordinates
---


title: GUI Library for MonoGame

text:
# Question
Title: GUI Library for MonoGame
Is there any GuiLibrary available, which works with MonoGame? I know there are some GUI Libraries for XNA but I assume most will not work with MonoGame.

Even simple stuff like Buttons and Inputfields would help me...

Thanks.

# Answer
I asked myself the exact same question a few weeks ago. Unfortunately, I didn't find anything that suited my needs but what I did find might help.

Here are a few XNA GUI projects I've found that might be compatible with MonoGame. I'm not really sure which ones are better than others and I haven't really tried them, but I've collected a few options.

Sorry, I don't have enough rep to post hyperlinks.

xWinForms (sourceforge.net/projects/xwinforms/)

XNA Simple GUI (simplegui.codeplex.com)

Window System for XNA (wsx.codeplex.com)

Squid (www.ionstar.org)

Ruminate XNA 4.0 GUI (xnagui.codeplex.com)

Nuclex Framework (nuclexframework.codeplex.com)

CEGUI# (sourceforge.net/projects/ceguisharp/) a port of CEGUI (http://www.cegui.org.uk)

MQuickGUI (www.ogre3d.org/tikiwiki/tiki-index.php?page=MQuickGUI) made for the Ogre / Mogre engine but could be adapted to XNA.

Xpf by Red Badger (red-badger.com/blog/2012/07/05/xpf-to-be-open-sourced/) - An implementation of WPF for mobile devices. It looks good but I can't see a way to download it. It was announced to be open sourced on 5 July 2012 but I don't think that has happened yet.
> 8 votes

# Answer
NuclearWinter works with MonoGame.
> 5 votes

# Answer
One option that you have is GWEN port for the .Net if you don't mind writing the MonoGame adaptation layer. The original C++ library is written by Garry Newman. The layer is easy to create, and there are plenty of examples available in the code base.

While GWEN might not be outright better than other GUI libraries, it has following advantages:

* Simple
* Easy to theme
* Has quite many controls available
* It is not a framework, rather a library
* Doesn't rely on XML or any other kind of markup

On the other hand, I've found out following downsides:

* It may not be as flexible as other GUI libraries
* It does not come with ready made layout managers
* No XML
> 4 votes

# Answer
This should've been a comment to @craftworkgames comment but it doesn't seem to be possible.

I wanted a GUI system for mobile games, I favor code simplicity, easy composition and, last but one of the most important, community / documentation / developer activity (improving the framework or just promoting it). From the link he posted, the ones that I liked more were:

* CraftworkGUI, he's own framework, it's really close to what I was searching for
* XNA Simple GUI (simplegui.codeplex.com)
* Xpf by Red Badger. I liked this one more for the potential, haven't actually tried it yet. You can find this one on Github.

Researching for this has been really tedious and boring, but from what I've seen, I wish CraftworkGUI grows to be a good solution for mobile GUI dev.
> 2 votes

---
Tags: monogame
---


title: 3D Distortion Effect

text:
# Question
Title: 3D Distortion Effect
I'm trying to make a distortion effect similar to this:

However I'm not making a 2d screen space effect. I'm applying it to a 3d scene and I want it to be placed IN the world, so it can be blocked by other 3D objects. I know the general method for doing this is as a post-process effect applied to a 3D sphere, however I can't find any code/equations that work for that case. All the ones I've found assume you're given a 2d point and a radius.

The 2d point is easy to calculate from a 3d point but getting the radius of a 3d sphere projected into 2d space... seems extremely complicated. How can I achieve this kind of outwards-push effect in a 3d space?

# Answer
> 3 votes
**Algorithm**

Assuming your current centre is e.g. wherever the mouse cursor currently is, for ease of understanding...

For each source pixel:

* Create `pushVector`, a vector passing through the centre and the source pixel position.
* Store its magnitude as `distanceFromCentre`, then normalise the vector.
* Apply some function used to produce `pushMagnitude` from length `distanceFromCentre`. This should result in 0 for any pixel that lies on the lens' radius (`distanceFromCentre` == `lensRradius`), and a large amount for any pixel which is very close to the centre (`distanceFromCentre` ≈≈ `0`). The function used to map `distanceFromCentre` -\> `pushMagnitude` is up to you, but I suspect a tangent function would give a spherical look.
* `pushVector` = `normalisedVector` * `pushMagnitude`.
* `finalPosition` = `centre` \+ `pushVector`; plot your source pixel colour here.

**Magnitude function**

You need to map your input range for `tan`, correctly. As you know, `tan` maps to 0 at 0 degrees and infinity at 90 degrees. This refers to the edge of your circle and the centre, respectively: While a pixel exactly on the radius does not shift at all, any vector exactly at the centre of the lens could not be pushed outward in any given direction (i.e. we could not choose a `pushVector` for it), hence infinity. This means that you need to remap your `distanceFromCentre` which ordinarily lies in range `0->r` to a new range `0->90 degrees`.

**Practicalities**

A pixel / fragment shader can be used for this; sometimes it is easier to get a feel for the basic algorithm in something like Processing or Flash first, and then translate it into a shader kernel... just a thought.

Remember that you do not have to process the whole screen, only the bounding box that will contain your lens-effect radius.

\** Pseudocode \**

```
distanceFromCentre = pushVector.magnitude(); //range to 0->1 for ease of manipulation

fractionDistanceFromCentre = distanceFromCentre / lensRadius;
fractionDistanceFromRadius = 1 - fractionDistanceFromCentre; //reverse the mapping
pushMagnitude = tan(fractionDistanceFromRadius * PI / 2); //radians; or 90 degrees

pushVector.normalise();
pushVector *= pushMagnitude;
plotPosition = centre + pushVector;
plotAt(plotPosition); //draw the pixel at it's final position.

```

# Answer
> 1 votes
If I'm not wrong, this can be done using shaders.

The actual effect your showing in the example is a 2D effect, so can you achieve the exact same effect in a 3D world? Maybe, but again, it's a effect done after rendering.

In order to actually block it by another object, this would require a more advanced algorithm. I suggest learning how to do this effect in the game using shaders but not worrying about overlapping the effect. Then look into Ray Casting and use a similar algorithm to detect whether to apply the effect to each pixel. Either way, the effect will be slow.

---
Tags: directx, shaders, hlsl, graphic-effects, fragment-shader
---


# Question
Title: Android/OpenGL ES2: How do I set fragment shader value using C;
This should be easy So I am using the following to create a fragment shader.

```
 GLbyte fShaderStr[] = "precision mediump float;"
    "void main()                                \n"
    "{                                          \n"
    "  gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); \n"
    "}                                          \n";

```

I then render a circle (collection of lines) the circle comes our red. If I change the code to...

```
GLbyte fShaderStr[] = "precision mediump float;"
    "void main()                                \n"
    "{                                          \n"
    "  gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0); \n"
    "}                                          \n";

```

The circle is now purple. My question is how do I control this dynamically? So for example when I receive an input I toggle the two colors?

I tried...

```
GLbyte vShaderStr[] = "attribute vec4 vPosition;   \n"
            "attribute vec4 inColor;   \n"
    "uniform mat4 Projection;   \n"
    "varying vec4 fragColor;   \n"
    "void main()                 \n"
    "{                           \n"
    "   gl_Position = Projection * vPosition; \n"
    "   fragColor = inColor; \n"
    "}                           \n";

GLbyte fShaderStr[] = "precision mediump float;"
    "varying vec4 fragColor;                   \n"
    "void main()                                \n"
    "{                                          \n"
    "  gl_FragColor = fragColor; \n"
    "}\n";

void initColor(){
    LOGD("Initing Color");
    GLfloat vVertices[] = { 1.0f, 0.0f, 0.0f, 1.0f };
    glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, vVertices);
}

```

However, this doesn't seem to work as the circle is now black.

# Answer
> 2 votes
You can try adding:

```
glEnableVertexAttribArray(1);

```

before your call to **glVertexAttribPointer**.

Basically any attribute is disabled by default, so you may have to enable it first. See this.

**Edit**

msell comment made me realize that you probably want the circle to be of single color, in that case yes, you need uniforms. Attributes are a property of vertices, so you would use attributes when you want to paint different vertices with different colors. Also, in that case you would need to specify a color for each vertex, so your **vVertices** array would need to have 4 floats for each vertex you are going to draw.

**How to do it**

The function you need is in the family of glUniform and most likely is **glUniform4f** because you want to set a color that is represented by 4 floats. You should declare your color in the **fragment shader** as a uniform:

```
uniform vec4 inColor;

```

Then in your application code you would do:

```
GLint location = glGetUniformLocation(program, "inColor");
glUniform4f(location, 1.0f, 0.0f, 0.0f, 1.0f);

```

**Little explanation**

Usually it doesn't make sense to derive the value of a **varying** solely from **uniforms** in the vertex shader; the reason is that **uniforms** are *uniform* across all possible vertices shaded during the current draw call. The **varyings** are varying in the sense that the vertex shader computes their value for each vertex of a triangle, and then the interpolation units on the graphic card constructs all the intermediate values corresponding to the generated fragments. Since a **uniform** value is the same for each vertex, each fragment would get the same value. That is, if you use a **uniform** to decide in the vertex shader that all vertices are purple, the interpolator will generate all the shades of purple between purple and purple, that is, purple.

Instead, if you specify colors as **attributes** it is necessary to generate all intermediate shades across the triangle, so it makes sense to assign the **attribute** to the varying.

**Reference**

**Square**

You need 6 positions:

```
-1.0, -1.0, 0.0
+1.0, -1.0, 0.0
-1.0, +1.0, 0.0
-1.0, +1.0, 0.0
+1.0, -1.0, 0.0
+1.0, +1.0, 0.0

```

And two colors, spread over two triangles:

```
1.0, 0.0, 0.0, 1.0 // Red
1.0, 0.0, 0.0, 1.0 // Red
1.0, 0.0, 0.0, 1.0 // Red
0.0, 1.0, 0.0, 1.0 // Green
0.0, 1.0, 0.0, 1.0 // Green
0.0, 1.0, 0.0, 1.0 // Green

```

And then use a call like:

```
glDrawArrays(GL_TRIANGLES, 0, 6);

```

---
Tags: android, opengl-es
---


# Question
Title: Can we develop a game for iPhone on Windows platform?
Is it possible by any means to have a game developed for iPhone using the iPhone sdk on Windows?

# Answer
> 4 votes
Though it is against Apple's policy, you can install OS X into a virtual machine and develop an app that way. And if you can manage it, you technically *can* write the code and such on a Windows machine; it is, of course, only text. But the compiler, SDK, etc. is completely OS X-only.

You can also look into other ways to make iPhone games, such as the Unity engine, or Flash (I know at one point they compiled to iPhone games, I think they have since discontinued that)

# Answer
> 3 votes
See this question on stackoverflow.com.

Even if there's some way to do it with virtual machines, jailbroken phones and so on, I can't believe the hassle would be worth it. The time you spend dealing with all the issues is time that you won't have to improve the game.

If you're using a cross-platform development environment like Unity, you'll be able to do most of the development on Windows, but you'll still need a Mac in order to deploy to the phone for testing or release. (And testing on the device is vital: a finger on a touch screen is not like a mouse pointer on a window.)

It's not as if you need a powerful machine to develop an iPhone game: a Mac Mini for $699 will do just fine.

# Answer
> 3 votes
I'd recommend looking into Mono. It allows you to write .NET apps on your iPhone/iPad.

# Answer
> 1 votes
I was looking for a solution to develop apps on Windows. In the end I bought a Mac mini and I am glad I did. The Mac and the develop tools are working just fine. The time I saved figuring out configuring Windows/Virtual machines/OSX and so on I spent on actually developing Apps.

# Answer
> 1 votes
Airplay SDK claims to allow you to develop in Visual Studio on a Windows PC. I have not tried it out, so no idea how well it works.

# Answer
> 1 votes
The Adobe AIR SDK 3.3 allow you to build iOS app on windows platform: http://helpx.adobe.com/flash-player/release-note/developer-relese-notes-11\_3.html

However, you have to code your app/game in ActionScript but you can extends the AIR SDK functionality through Adobe Native Extension (ANE).

# Answer
> 0 votes
Marmalade is a good engine which can easily be integrated with Visual Studio. So you can develop for iOS, Android, Bada, WebOS, Windows etc. from single code. You would need a Mac to upload the ipa file though, but i guess it'll be easier since you only need it once. I am using it so I can tell you it works good and now with version 6.0 you can also develop in HTML5 using phonegap API.

# Answer
> 0 votes
You can use a computer simulator like VirtualBox and just upload the mac's source code files and download XCode of the app store.

---
Tags: iphone, windows
---


title: .NET in Windows ME

text:
# Question
Title: .NET in Windows ME
So I'm used to work with C# and I recently started studying C++. So I have a Vista computer, which I'm using right now, but I also have an old Windows Millennium Edition Computer, and I also wanna work with it. It has a Visual Studio, but when I try to open it, it says that the computer can't start the program. There's no C# nor C++ nor anything installed, I tried but it wasn't compatible. So what I'm asking for is:

**.NET Software Development Kit**

**It has to be compatible with Windows ME. It also needs to be installed with an offline setup (My ME computer only supported Internet by cable phone or something, and I don't have it)**

Is it possible?! If so, how to get it?

**Thanks for the time**

# Answer
> 1 votes
In some ways, your question is analogous to trying to run a Super Nintendo game on the original NES. If you have limited OS features, you should probably not try to develop using a high-overhead, modern framework (designed for modern OS features.) I wonder why you want to use .NET at all.

Regardless, your question made for a fun little research project, so here's what I found.

For the old computer, you might want to abandon the .NET idea. You can wipe it, install linux, and learn to write C++ by doing everything the hard way. Make games that are fun without using managed code. Then when you've mastered the language features, you can buy modern hardware and marvel at how much it simplifies everything.

---
Tags: c++, c#, windows, .net
---


# Question
Title: Detecting if "Wall" To The Left or Right Of Player Unity3D
I am working on a 3D Platformer in Unity3D and I need to prevent the player from going through walls. The movement for my player works like this:

(A bird-eye-view representation)The areas the player can move a divided into layers. He can slide into the 2nd, 1st , or 3rd layers. The player is not a rigid-body, and is controlled using a character controller. To move the player into these layers I simply increase his Z-Axis. Currently if my player is behind the wall he will slide directly into it. How can I determine if there is a wall to the left of the player in Unity 3D? If so, I simply wont allow the user to move to the layer until they have steered clear of the obstacle. Does anyone have any suggestions of what I should do?

# Answer
You can use function CharacterController.Move to detect collision to the wall. if you don't want to use Move then you can cast a ray with Raycast to check if wall close enough to stop your character or let him move ;)
> 1 votes

---
Tags: unity, collision-detection, unityscript
---


title: Building a tessellated texture

text:
# Question
Title: Building a tessellated texture
In games like Minecraft the textures such as grass when lined up side-by-side it looks like one big perfect texture. When I make a texture it's never even and you can see the different blocks. How do the textures kinda tessellate with each other?

# Answer
What you're looking for is something called "seamless" textures.

Here are some tutorials for popular image editing programs:
> 6 votes

# Answer
The reason for this effect is that the left side of the texture meats up with the right side of the texture perfectly. And so do the top and bottom.

In most textures there is a pattern, shape, or gradient that makes them interesting to look at. When you place another copy of the tile next to it, you will have pixels from the beginning of the texture directly next to pixels from the end of the previous instance. The problem occurs when those pixels do not line up in a logical way, and shapes/patterns are cut short. The solution is to make sure that both edges of the texture can meet in a logical way.

To create this effect it is necessary to design the texture properly. For simple textures (like grass or dirt), one can simply cut the image down the center, swap the halves (now the pixels from the center, which line up, are on at the edges) then smooth out the new center line. Then repeat along the other axis. Note that in a simple texture any bold area or pattern will be very obvious when you look at many of them tiled, which is generally an undesirable effect.

For complex textures, you will need to put more work into planning to make sure that edges meet up correctly. For instance, a pattern of circles must be designed such that any circle that meets the edge has its remainder on the opposite side of the texture, so that it will look whole when another instance is tiled next to it.
> 1 votes

---
Tags: 2d, textures, tessellation
---


title: Monogame Windows 8 Phone

text:
# Question
Title: Monogame Windows 8 Phone
I have monogame 3.0.1 (latest stable) installed on a Windows 8 Pro machine. I can create a new Windows Phone 8 project (Monogame template) and deploy to the emulator and an actual device with no problems.

However after successfully getting a screen of cornflour blue I wanted to display a simple image. I know the content pipeline is something that doesnt work but I wanted to display a simple PNG.

For this, I tried:

Adding a Content folder. Adding a simple PNG (test.png) to the content folder. Set the build to "Content" and ensure it was set to "Copy if newer". Then added the following code.

```
texture = Content.Load<Texture2D>("test");

```

And in the draw, draw it out. However , I get a NotImplementedException when I try to deploy this.

Out of the box, how do I draw a simple texture/sprite to the screen?

# Answer
> 1 votes
@Barry MonoGame does not currently generate \*.xnb files, but it CAN actually consume them. So if you have an existing \*.xnb file add it instead of the png, following the same steps you mentioned in your post and it should work.

# Answer
> 0 votes
When using PNG files or other resources directly you need to specify the file extension when you load it with the content manager. So in your case, try this:

```
texture = Content.Load<Texture2D>("test.png");

```

I know this works on Android. I assume it works the same way on other platforms.

---
Tags: monogame, windows-phone-8
---


# Question
Title: Relative mouse tracking stick mouse to center of screen
I wrote this code to handle relative mouse movements,

```
        public override void Update(GameTime gt)
        {
            _lastmousestate = _mousestate;
            _mousestate = Mouse.GetState();
            if(LockMouse)
                Mouse.SetPosition(EntityGame.Viewport.Width/2,EntityGame.Viewport.Height/2);
            Point distance = new Point(_lastmousestate.X - _mousestate.X, _lastmousestate.Y - _mousestate.Y);
            Cursor.Position = new Point(Cursor.Position.X - distance.X, Cursor.Position.Y - distance.Y);
        }

```

`Cursor` is the cursor drawn to the screen to track the mouse. When running this code my mouse sticks to the center of the screen and won't move. However, the X,Y values change for a second before resetting back to the center of the screen.

Any ideas?

EDIT: Setting LockMouse to false causes the mouse and cursor to act perfectly fine although it is not bound to the window.

EDIT2: Here is the MouseHandler code, not much to see here just me setting it up so you can bind mouse buttons easier.

```
using System;
using EntityEngineV4.Engine;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace EntityEngineV4.Input.MouseInput
{
    public class MouseHandler : Service
    {
        public CursorEntity CursorEntity;
        private static MouseState _mousestate;
        public static MouseState MouseState {
            get { return _mousestate;}
        }
        private static MouseState _lastmousestate;
        public static MouseState LastMouseState {
            get { return _lastmousestate;}
        }

        public bool LockMouse = false;

        public MouseHandler (EntityState stateref) : base(stateref)
        {
            CursorEntity = new CursorEntity(stateref, stateref, "CursorEntity", this);
            stateref.AddEntity(CursorEntity);
        }

        public override void Update(GameTime gt)
        {
            _lastmousestate = _mousestate;
            _mousestate = Mouse.GetState();
            if (_lastmousestate == _mousestate) return; //The mouse was the same, no need to do anything.
            if(LockMouse)
                Mouse.SetPosition(EntityGame.Viewport.Width/2,EntityGame.Viewport.Height/2);
            Point distance = new Point(_lastmousestate.X - _mousestate.X, _lastmousestate.Y - _mousestate.Y);
            CursorEntity.Position = new Point(CursorEntity.Position.X - distance.X, CursorEntity.Position.Y - distance.Y);
        }

        public override void Draw(SpriteBatch sb)
        {
        }

        public Point GetPositon()
        {
            return new Point(_mousestate.X, _mousestate.Y);
        }

        public void SetPositon(Point p)
        {
            Mouse.SetPosition(p.X, p.Y);
        }

        public void Flush()
        {
            _lastmousestate = _mousestate;
        }

        public bool IsMouseButtonDown(MouseButton mb)
        {
            switch(mb)
            {
            case MouseButton.LeftButton:
                return _mousestate.LeftButton == ButtonState.Pressed;
            case MouseButton.MiddleButton:
                return _mousestate.MiddleButton == ButtonState.Pressed;
            case MouseButton.RightButton:
                return _mousestate.RightButton == ButtonState.Pressed;
            case MouseButton.XButton1:
                return _mousestate.XButton1 == ButtonState.Pressed;
            case MouseButton.XButton2:
                return _mousestate.XButton2 == ButtonState.Pressed;
            }
            throw new Exception("MouseButton does not exist!");
        }

        public bool IsMouseButtonPressed (MouseButton mb)
        {
            switch (mb)
            {
            case MouseButton.LeftButton:
                return _mousestate.LeftButton == ButtonState.Pressed && _lastmousestate.LeftButton == ButtonState.Released;
            case MouseButton.RightButton:
                return _mousestate.RightButton == ButtonState.Pressed && _lastmousestate.RightButton == ButtonState.Released;
            case MouseButton.MiddleButton:
                return _mousestate.MiddleButton == ButtonState.Pressed && _lastmousestate.MiddleButton == ButtonState.Released;
            case MouseButton.XButton1:
                return _mousestate.XButton1 == ButtonState.Pressed && _lastmousestate.XButton1 == ButtonState.Released;
            case MouseButton.XButton2:
                return _mousestate.XButton2 == ButtonState.Pressed && _lastmousestate.XButton2 == ButtonState.Released;
            }
            throw new Exception("MouseButton does not exist!");
        }

        public bool IsMouseButtonUp(MouseButton mb)
        {
            switch(mb)
            {
            case MouseButton.LeftButton:
                return _mousestate.LeftButton == ButtonState.Released;
            case MouseButton.MiddleButton:
                return _mousestate.MiddleButton == ButtonState.Released;
            case MouseButton.RightButton:
                return _mousestate.RightButton == ButtonState.Released;
            case MouseButton.XButton1:
                return _mousestate.XButton1 == ButtonState.Released;
            case MouseButton.XButton2:
                return _mousestate.XButton2 == ButtonState.Released;
            }
            throw new Exception("MouseButton does not exist!");
        }

        public bool IsMouseButtonReleased (MouseButton mb)
        {
            switch (mb)
            {
            case MouseButton.LeftButton:
                return _mousestate.LeftButton == ButtonState.Released && _lastmousestate.LeftButton == ButtonState.Pressed;
            case MouseButton.RightButton:
                return _mousestate.RightButton == ButtonState.Released && _lastmousestate.RightButton == ButtonState.Pressed;
            case MouseButton.MiddleButton:
                return _mousestate.MiddleButton == ButtonState.Released && _lastmousestate.MiddleButton == ButtonState.Pressed;
            case MouseButton.XButton1:
                return _mousestate.XButton1 == ButtonState.Released && _lastmousestate.XButton1 == ButtonState.Pressed;
            case MouseButton.XButton2:
                return _mousestate.XButton2 == ButtonState.Released && _lastmousestate.XButton2 == ButtonState.Pressed;
            }
            throw new Exception("MouseButton does not exist!");
        }
    }

    public enum MouseButton
    {
        LeftButton, RightButton, MiddleButton, XButton1, XButton2
    }
}

```

# Answer
> 0 votes
Figured it out.

You have to ignore the last mouse state when the mouse is locked and just set it to the center of the screen like so.

```
            public override void Update(GameTime gt)
        {
            Flush();
            _mousestate = Mouse.GetState();

            if (LockMouse)
            {
                int lockx = EntityGame.Viewport.Width/2;
                int locky = EntityGame.Viewport.Height/2;

                //After we get our states, we can reset the Mouse with no problems!
                SetPosition(lockx, locky);
                Point distance = new Point(lockx - _mousestate.X, locky - _mousestate.Y);
                CursorEntity.Position = new Point(CursorEntity.Position.X - distance.X, CursorEntity.Position.Y - distance.Y);
            }
            else
            {
                //Calc our distance and add it to our cursor.
                Point distance = new Point(_lastmousestate.X - _mousestate.X, _lastmousestate.Y - _mousestate.Y);
                CursorEntity.Position = new Point(CursorEntity.Position.X - distance.X, CursorEntity.Position.Y - distance.Y);
            }
            CursorEntity.Update(gt);
        }

```

---
Tags: xna
---


# Question
Title: why is Lua so important ( frequently used ) in game development
I have written some small games for fun myself, but never used Lua myself.

I have seen people discussing Lua's use in games everywhere.

The question is: What benefit can I get from using Lua in game development?

Can someone explain this a little bit to me?

# Answer
Lua is a pretty well developed scripting engine that is flexible and easy to integrate to your games, and is already supported in many game engines, for instance:

**2D**

* Agen (Lua; Windows)
* Blitwizard (Lua; Windows, Linux, Mac)
* Corona (Lua; Windows, Mac; iOS/Android)
* EGSL (Pascal/Lua; Windows, Linux, Mac, Haiku)
* Grail Adventure Game Engine (C++/Lua; Windows, Linux, MacOS X (SDL))
* LÖVE (Lua; Windows, Linux, Mac)
* MOAI (C++/Lua; Windows, Linux, Mac; iOS, Android; Google Chrome (Native Client))

**2.5D**

**3D**

Source: https://stackoverflow.com/questions/5053134/what-is-a-good-game-engine-that-uses-lua

And as MJP says from gamedev.net:

> Using a scripting language was/is very popular for games for a few reasons:
>
> 1. Most scripting languages are much more high-level than C++ (which just about all commercial games use), and can be used much more readily by gameplay or level designers.
> 2. The portions of a game written in scripting languages can be modified while the game is running, without having to restart or recompile. This is important if the people working on the scripted portions don't have access to the compilation tools, or if compilation takes a long time.
> 3. C++ has no built-in reflection capabilities.

Source: http://www.gamedev.net/topic/520284-why-use-luascripting/
> 10 votes

---
Tags: software-engineering, cocos2d-x, scripting, lua
---


title: How to add a feel of depth?

text:
# Question
Title: How to add a feel of depth?
I have several mountain models drawing in the background. See actual screenshot here:

At the very back, you see those grey mountains. Although they are so much in background, it still doesn't seem "in the background".

How can I add a feel of depth to those mountains? I would like see them as far far away.

**This is how it looks now, thanks to DarenW**

# Answer
> 19 votes
The spikey intense orange objects are pushing in front of everything. In visual arts, distance is indicated by:

* Paler colors. Just changing your intense orange/rust color to be less saturated will help loads.
* Lighter colors. blending object's natural color with sky color or with a bland light color such as light gray or a pale sky blue. Related to this: if any objects are black or very dark, they'll pop up nicely in front of a light background. Light objects may need some help such as strong shading, a few dark features, or outlining.
* Out of focus (slightly), assuming the viewer is meant to focus on nearby objects. For a realistic scene, only slightly out of focus. But consider artistic style - you could use severe blurring. I've seen games like that, and it's kinda fun visually, but it'll work only if you also use paler/lighter colors.
* Loss of detail. Even if the background features are in focus, less contrast of and even elimination of fine-scale details such as cracks, bumps, texture.
* The opposite of loss of detail for distance objects: sharpen edges, fine-scale detail texture of nearby objects. You could even add outlining using an edge detector. In animations from old-time saturday morning cartoons to the newest anime, it is often the case that foreground characters have strong well-modulated linework while background art is colored regions only, no special treatment of boundaries. Of course, this involves choice of artistic style.
* Perspective clues such as long or meandering objects that progress from far to near, such as a river or pipeline or a row of buildings or towers heading away, shrinking with distance. But without the other cues, such a thing may not "sit" right in the apparent 3D space.

For far away objects which will always be shown far away, production effort may be minimized by making the original image assets pale, light, and blurred appropriately. Then no extra run-time compositing effort will be needed.

Although you're working in digital arts, there's a ton of accumulated wisdom in the traditional media world of fine art. I visit wetcanvas.com for that, and also https://graphicdesign.stackexchange.com/ because I like the SE way of doing Q&A.

# Answer
> 17 votes
* Make them less sharp
* Implement parallax when moving the camera
* Add some haze
* Add other objects near them to give perspective on their size (like cloud caps).
* Add objects of known size (like trees) spreading into the distance and still in front of the mountains
* Add foothills around their base

# Answer
> 1 votes
The most important aspect of making mountains appear distant is to make them closer to the color of the sky. If you take a picture of snowcapped mountains that look distant, and use a color picker on the white snow, you will usually find it is actually a pretty strong blue. Mountains that are orange covered with a blue overlay will still look orange by contrast with the blue sky.

# Answer
> 0 votes
1. The further away things get, the more out of focus or blurry they get.
2. The further away things are, the "lighter" they become.

# Answer
> 0 votes
Haze is your best friend. You have three levels of DoF in your image: The path, first row of mountains, second row of mountains.

Magic happens on the second row of mountains where they should get some edge blur, less detail, some highlight coming off the bottom and get in color value with the sky. If you could get some Z fog in there that would be good.

Google some "landscape haze" and deconstruct it carefully.

Also take a look at http://www.youtube.com/watch?v=CgogMP-kbA0

There is a PSD plugin that can generate Depth map out of single photo so that can help you as well http://www.kolor.com/neutralhazer-haze-remover-photo-photoshop-plugin.html

---
Tags: art
---


# Question
Title: Realistic 3D Collision Detection Implementation
I understand how box collision, sphere collision, and other such collisions work. However, how would one implement realistic 3D collisions? That is, objects would interact with one another as they would in real life. For example, take a rod and a torus. Assume that the thickness of the rod is smaller than the hole in the torus. With simple collision systems, as far as I know, inserting the rod into the hole of the torus would result in a collision detection. In reality, no collision would take place. Hopefully, that explains what I am looking for.

# Answer
You can compound various primitives together to add accuracy to your collision model. For instance in your torus example, you could have a bounding box or sphere around the entire model but then also have a sphere that just encompasses the torus' hole. Then the algo would go: if rod is in box but not in holeSphere, then it's colliding, else if rod is in box and holeSphere, it is not colliding.

You can often use a few basic primitives (planes, rays, boxes, spheres) together to get an acceptable level of accuracy.

Definitely get 'Real time collision detection' by Chtister Ericsson,.
> 2 votes

---
Tags: collision-detection
---


# Question
Title: Car licensing if real cars appear in FMV cutscenes?
We are doing 2D game which will feature Full Motion Video for cutscenes in between the levels. Game is car oriented, although its not a racing game but it will feature some of the driving in it, and we would like to film some real cars for our cutscenes. There will be some "exclusive" cars on our shoot like Porsche, Lambo and Range Rover and we are really concerned about licensing logistics, especially about Porsche and whole EA exclusivity. Bear in mind that no characters will mention cars by its name or model designation and we are ready to remove any badging in post. Still concern is out there.

As far as the driving in game goes we will be using drawn sprites that only resemble physical models to some degree.

# Answer
I will tell you something from my experience and personal understanding off the matter.

First of all, I'd contact the company marketing section. **use your official company email - **no @gmail/@yahoo.com etc.****.** If I were to write to Ford, I'd use their Contact Form and choose the "Other" inquiry type. Say why I would like to use their intelectual property in my product.

Second of all, there is something called the "fair use of copyrighted material". The film industry would be much different if it wasn't legal to use "normal" cars in movies. The corporations pay to have their product included in a AAA movie - Double-o-7 drives Aston Martin, used to drink Martini now switched to Heineken, wears an Omega Watch, loves Coca Cola Zero, and uses sony electronics products. Of course if you are a small studio, you will reach fewer people, most likely you will not be able to get money directly from the brand.

It is a often found in AAA movie/game productions, where the brands like Coca Cola and Pepsi fight each. So I doubt that you will find a Coke next to Pepsi on "one movie dining table". If you watched some movies you might have noticed that the operating systems used by "the FBI " are usually some crazy tech not similar to Windows or Apple OS. They have been doing that to make sure they wont have legal problems with Microsoft/Apple Corporations. This has changed and in fact now the Corporations want their product to be viewed by the biggest ammount of people. This way most of mobile phones carried on stage by Hollywood movie actors, are Iphones, climbing gear is Petzl and so on.

> **Another way Around it:**

I understand that the shoot will be in real world. With real cars. **YOU ARE NOT ALLOWED TO USE THE COMPANY LOGO ON AN INGAME MODEL WITHOUT THE COMPANY PERMISSION**. But when it comes to shooting a clip the law is on your side. You can use the cars in movies as long as you own it or have a written permission from the car owner. You could always rent a Movie Prop Car. The digital form of the game object is the bitter part because you do not own the "idea of the car" where the movie situation is clear that you are in possesion of that car you film. **You can always make a car similar to the car from the movie you shoot, accept with no logos + you should mess a bit with the proportions and they wont be able to say that you stole the car concept from them, as it will be a technically different, yet similar model.**
> 2 votes

---
Tags: licensing, video, car, cutscene
---


# Question
Title: OpenGL - Understanding the relationship between Model, View and World Matrix
I am having a bit of trouble understanding how these matrixes work and how to set them up in relation to one another to get a proper system running.

In my understanding the Model Matrix is the matrix of a object, for example a cube or a sphere, there will be many of these in the application/game.

The World Matrix is the matrix which defines the origin of the 3D world. the starting point.

And the View Matrix is the "camera" everything gets translated with this to make sure you have the illusion of an actual camera when in fact everything is moving instead of this matrix?

I am a bit lost here. So I was hoping someone here could help me understand this properly.

Does every modelMatrix get translated/multiplied with the world matrix and the worldMatrix then with the viewMatrix? Or does every modelMatrix get translated/multiplied with the viewMatrix and then that with the worldMatrix?

How do all these matrixes relate and how do you set up a world with multiple objects and a "camera"?

**EDIT:**

Thanks a lot for the feedback already. I did some googling aswel and I think I do understand it a bit better now, however would it be possible to get some pseudo code advice?

```
projectionMatrix = Matrix;
makePerspective(45, width, height, 0.1, 1000.0, projectionMatrix);

modelMatrix = Matrix;
identity(modelMatrix);
translate(modelMatrix, [0.0, 0.0, -10.0]);  // move back 10 on z axis

viewMatrix = Matrix;
identity(viewMatrix);
// do some translation based on input with viewMatrix;

```

Do I multiply or translate the viewMatrix with the modelMatrix or the other way around? and what then? I currently have a draw method up in such a way that it only needs 2 matrixes for arguments to draw.

Here is my draw method:

```
draw(matrix1 matrix2) {

            bindBuffer(ARRAY_BUFFER, cubeVertexPositionBuffer);
            vertexAttribPointer(shaderProgram.getShaderProgram().vertexPositionAttribute, cubeVertexPositionBuffer.itemSize, FLOAT, false, 0, 0);

            bindBuffer(ARRAY_BUFFER, cubeVertexColorBuffer);
            vertexAttribPointer(shaderProgram.getShaderProgram().vertexColorAttribute, cubeVertexColorBuffer.itemSize, FLOAT, false, 0, 0);

            bindBuffer(ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer);

            setMatrixUniforms(shaderProgram, matrix1, matrix2);

            drawElements(TRIANGLES, cubeVertexIndexBuffer.numItems, UNSIGNED_SHORT, 0);

}

```

What are those matrixes suppose to be? Thanks a lot in advance again guys.

# Answer
> 20 votes
Within a 3D rendered scene, there are typically three main matrices used to transform an object from its own local space (object/model space) to a homogeneous space known as screen space.

**World**

* The World matrix being the first, is unique for every object within your world, and is responsible for transforming the vertices of an object from its own local space, to a common coordinate system called world space.

**View**

* After that, the view matrix provides the concept of a mobile camera, when it reality the camera is actually the only constant point of reference within the world. The view matrix is a transformation that is applied to every object in the scene (but is not unique to each object), and provides the illusion of a camera. The view matrix is basically the inverse of what could be considered a world matrix for the camera. Yet instead of moving the camera itself, it provides the opposite movements to the rest of the scene (the illusion ;) ).

**Projection**

* Finally the projection matrix is responsible for converting a 3D world into the homogeneous screen space that you see on your screen. This is the matrix used to represent your view frustum, and is usually represented as an orthographic or perspective projection.

At the simplest level, every one of your objects needs to contain its own world matrix, your "scene" or whichever context you use must contain a view matrix to represent a camera, and a projection matrix to convert world coordinates to screen coordinates. All of these then need to be passed to the vertex shader (with the world matrix changing for each object, but not necessarily the view or projection) to be transformed.

# Answer
> 3 votes
Good answer is here https://stackoverflow.com/questions/6461740/xna-worldmatrix-and-viewmatrix

First of all, there is no real difference between a **"World Matrix"** and a **"View Matrix"**, they are both transformation matrices and the distinction is somewhat arbitrary. Some systems even combine the two (OpenGL simply has a **"ModelView"** matrix).

Traditionally the **"world matrix"** is used to move individual models from "model space" to "world space". Then the **"view matrix"** is used to move all the models from world space into their relative positions in front of the camera (which, in effect, "moves the camera"). And finally the **"Projection Matrix"** converts the 3D positions into their 2D positions on the screen (generally with a perspective projection). Because they are matrices, they can be multiplied together into a single matrix that can transform points in a single step.

---
Tags: opengl, architecture, matrix
---


# Question
Title: cocos2d-x - object creation and management in game design
How do others keep track of everything going on in their games? I am working on a new game and I am quickly realizing everything that I need to keep track of.

Example:

Maybe a layerManager that keeps track of all the layers and what is happening for a particular scene.

Maybe a sceneManager for sharing objects among scenes

But then getting to game play itself, what if you have 100 objects on the screen each with its own state and happenings, there needs tobe a way to keep track of all of that.

Drawing everything out is really helping me.

Can anyone share with me how they go about object tracking/management? I am seeing a few different managers and then maybe even a parent object that manages the managers..is my thinking way off?

Any design patterns that may be useful for me to read about?

Update: doing some reading and maybe a Factory pattern might apply.

# Answer
> 2 votes
I'll share my design as of current implementation I did for my game.

## ObjectPool & Managers

For objects whether it's enemy objects, collectable items, powers-up, effect (more like particle), etc, I managed them through my own implementation of ObjectPool as you will know roughly number of instances you would need in the game for certain time, so it will help create those ahead of time and put into good use immediately in the game whenever you need it. The benefit is that there's no lagging due to object creation during gameplay.

As well, I have another layer to manage those ObjectPools according to their own category. Anyway for my case, I manage them all inside ObjectSpawner class in which it has responsibility to spawn enemy, effect, etc whenever you need.

In each ObjectPool, there's information I can access later which is array of objects it currently has at the moment (active objects). Thus I can access those information via ObjectSpawner class in which it will get me by accessing specific ObjectPool in another hop. Of course, you can set "tag" for each sprite thus this will add another flexibility in accessing and managing those object (or sprites) and it can suit your need.

## Scene management

Cocos2d-x or Cocos2d-based framework already did a great job in scene management, but as you already knew it's not enough just yet. The same as yours, I have to implement on top to handle the current **scene** and **layer** state. For my current implementation, I have a utility class to manage switching from specific layer to another. I use logical-OR operation to maintain both scene and layer state. I safely, and carefully defined both scene and layer constants separately in the single header file, please take a look as follows.

```
// significant scene constants
#define GAMEPLAY_SCENE_SIGNIFICANT 128
// **don't use the following 3 values directly, they're used inside enum
#define LAYER_1_SIGNIFICANT 512
#define LAYER_2_SIGNIFICANT 1024
#define LAYER_3_SIGNIFICANT 2048

// [0, 511]
struct SceneState {
    // [0,127]
    struct Misc
    {
        enum ID
        {
            SPLASHSCREEN,
            MAINMENU,
            CREDITS,
            INTRO_CUTSCENE_PROLOGUE,
            OUTTRO_CUTSCENE_PROLOGUE,
        };
    };
    // [128, 511]
    struct Gameplay
    {
        enum ID
        {
            PROLOGUE = GAMEPLAY_SCENE_SIGNIFICANT,
            PROLOGUE_BOSSFIGHT
        };
    };
};

// virtual set by hands
// note: MAIN layer always be 0, others use LAYER_<number>_SIGNIFICANT
struct LayerState
{
    struct Gameplay {
        enum ID {
            MAIN = 0,
            PAUSE = LAYER_1_SIGNIFICANT,
            RESULT = LAYER_2_SIGNIFICANT
        };
    };
};

```

Then when I need to switch from one to another layer, I extract the first half of scene information, and another half of layer information to correctly check and switch to target layer properly.

This means I modified CCScene class to maintain one integer, and other utility functions to flexibly switch layer as of your need.

One last thing is that I have a policy for ease in management. In scene in which most of the time in cocos2d-x world, we will create a main layer under the name of -postfix-Scene. Says you need to create a Splash scene. I usually create with this name, "SplashScreenScene". That file is actually CCLayer (not CCScene), but inside that file we have CCScene created to hold it via scene() function. My point is to make clear that in certain scene, it may have layer members as follows.

* Main layer (in which it is itself as I described above)
* Touch / Control layer (this is a layer to interact with players via touch, or gesture)
* Optional layer
* Optional layer
* ... (go on)

Designing like this will help managing scene more easier as we will know exactly which layer we should focus in pause/resume the game as it acts as a controller of all its layer members, which layer we should disable/enable touch, and which layer is just an eye candy (but this will serve you well when you need to hide/show/fade a specific layer of overall scene.

Anyway this is one of many possible ideas you may do with your own implementation. I hope you get some ideas and make one that right to you.

---
Tags: c++, game-design, cocos2d-iphone, cocos2d-x, objects
---


# Question
Title: Making body (box2d) a sprite (andengine) in Android
I can't make body (box2d) a sprite (andengine) and at the same time apply MoveModifier to sprite which is body. If i can make just body, it works namely the sprites can collide. If I apply just MoveModifier to sprites, the sprites can move where i want. But I want to make body (they can collide) and apply MoveModifier (they can move where I want) at the same time. How can i do it? This my code just run MoveModifier not as body at the same time.

```
    circles[i] = new Sprite(startX, startY, textRegCircle[i]);
    body[i] = PhysicsFactory.createCircleBody(physicsWorld, circles[i], BodyType.DynamicBody, FIXTURE_DEF);
    physicsWorld.registerPhysicsConnector(new PhysicsConnector(circles[i], body[i], true, true));
    circles[i].registerEntityModifier(
            (IEntityModifier) new SequenceEntityModifier (
                        new MoveModifier(10.0f, circles[i].getX(),  circles[i].getX(),
                                circles[i].getY(),CAMERA_HEIGHT+64.0f)));
    scene.getLastChild().attachChild(circles[i]);
    scene.registerUpdateHandler(physicsWorld);

```

# Answer
It is exactly as Khawar Raza says. When you connect a body with your physics engine and apply Modifier, the modifier will be active but at the same time the physics will override the change in update loop.

It depends on what kind of movement do you need to do, but your options are:

* `Body.setLinearVelocity`
* `Body.applyLinearImpulse` or `Body.applyForce` \- this is a better way to set the Velocity
* using `MouseJoint.setTarget`. This will make the body go to a "target" point.

I recommend checking all of them, but I bet `MouseJoint` is the one you want. Check out this tutorial: http://www.andengine.org/forums/tutorials/tut-box2d-mousejoint-drag-and-drop-t1156.html
> 1 votes

# Answer
I think you cannot apply move modifiers on physics bodies. If you want to move bodies, you have to use other methods like force, impulse or setting velocity.
> 0 votes

---
Tags: android, box2d, andengine
---


title: UV mapping: Untextured faces?

text:
# Question
Title: UV mapping: Untextured faces?
Im currently trying to texture a (transparent) cylinder. I want the texture image to wrap sideways around the cylinder but not the top and bottom faces, they are supposed to just stay untextured (so transparent, in this case).

So what I did (in Blender) is UV unwrap only the side faces and leaving the top and bottom faces as they are.

However, this method doesn't seem to work very well, because when I import the .obj in Unity the top and bottom faces are mapped to a "random" place in the texture and therefore have color.

My current workaround is to map the top/bottom faces to areas in my texture that are transparent, however, this only works when textures have a transparent place, which isn't always the case.

# Answer
Whether or not you take manual control of a given face's texture coordinates, it will have texture coordinates. Anyway "untextured" isn't transparent, it's the color of the material applied (perhaps a default grey or white.) So this is why as you've noticed it doesn't make faces transparent when you don't directly assign their texture coordinates.

The workaround you describe is, well, pretty much how texturing is done. Thus the word "workaround" is misleading here. Now the fact that this approach doesn't fulfill your needs isn't a problem with that approach, it's just that your needs are more specific.

First off, do you need the cylinder to have a top and bottom face? If they're just going to be transparent anyway, why even have them? Perhaps you need to have a closed surface for physics calculations or something, but you didn't specify.

Now assuming that you can't simply delete the top and bottom faces and actually need those polygons, then you could exclude them from the texture on the sides of the cylinder by assigning them to a separate texture. I'm not sure multitexturing is supported by .obj, but it's certainly supported by Unity.

Another approach would be using vertex colors. I'm not sure Unity supports alpha in vertex color, but I know it supports RGB vertex color so maybe. This approach has the advantage over multitexturing that it doesn't require a new material. I mean, just one additional material in the scene is probably no biggie, but if you don't need a new material then that's better.
> 1 votes

---
Tags: unity, textures, models, blender, uv-mapping
---


title: Normals not rotated correctly

text:
# Question
Title: Normals not rotated correctly
While rendering a cube to the gbuffer (diffuse, normal, depth) I noticed something odd when applying rotations. I build a world matrix for the cube as follows:

```
Yaw = Yaw % MathUtil.PI2;
Pitch = Pitch % MathUtil.PI2;
Roll = Roll % MathUtil.PI2;

Matrix4 s = Matrix4.Scale(Scale);
Matrix4 t = Matrix4.CreateTranslation(Position);

Matrix4 rotY = Matrix4.CreateRotationY(Yaw);
Matrix4 rotX = Matrix4.CreateRotationX(Pitch);
Matrix4 rotZ = Matrix4.CreateRotationZ(Roll);

return s * rotY * rotX * rotZ * t;

```

If I render the cube with scale 1, position 0,0,0 and no rotations my normals are rendered properly. Applying scale/position does not change this fact.

However, when I apply rotations the normals screw up in some cases.

Nothing wrong in these settings:

* Yaw = Pi/2
* Yaw = Pi
* Pitch = Pi/2
* Pitch = Pi
* Yaw = Pi && Pitch = Pi

But when I apply these rotations:

* Yaw = Pi/2 && Pitch = Pi/2

This happens:

For some reason the normals aren't rotated correctly. I rotate them like this in the vertex shader using the world matrix described above:

```
mat3 WorldMatrix3x3 = mat3(WorldMatrix);
normalWS = vertexNormal_modelspace * WorldMatrix3x3;

```

And store them in the fragment shader:

```
rtt_normal.xyz = normalWS * 0.5 + 0.5;

```

I display the normal buffer on the screen like this:

```
color = vec4(abs(texture(gbufferTexture, UV).rgb * 2.0 - 1.0), 1);

```

What am I missing here?

# Answer
> 1 votes
`PI/2` is the magic number that causes gimbal lock. A Euler rotation of that value will disrupt subsequent rotations about another axis, because they have overlain each other. You need to replace

```
Matrix4 rotY = Matrix4.CreateRotationY(Yaw);
Matrix4 rotX = Matrix4.CreateRotationX(Pitch);
Matrix4 rotZ = Matrix4.CreateRotationZ(Roll);
return s * rotY * rotX * rotZ * t;

```

With something that doesn't suffer from the same problem.

```
Matrix4 rot = Matrix4.CreateFromAxisAngle(axis, angle)
return s * rot * t;

```

---
Tags: rotation, normals, opentk
---


# Question
Title: How to properly handle equipment enchants
In my game, the player starts with a set of equipment and unlike many other hack-and-slash RPG's, this base set of stuff never changes - the player never acquires a new weapon or armor.

The only way how to keep up with ever stronger monsters is to enchant the equipment with spells. Each piece can hold a couple of different enchants and as the player slays monsters he gets access to stronger spells for enchanting.

The problem is some encounters favor different enchant strategies than others. While for one type of monster it would be better to go for resistance against magic, another monster is not using magic at all so physical resistance is more important. I want the players be able to replace their enchantments obviously, but i don't want the player to feel like he must redo all his gear before every encounter to be prepared - that would be too annoying.

How would i go about limiting the availability of removing enchants from gear so it does not become a tedious thing to do, but instead is an exciting event in gameplay? (like: "Cool i can now upgrade those old enchants on my staff which will make slaying those ogres easier!") Also the possibility of removing enchants shouldn't be too rare, since it's the core gear-progression mechanic.

The only thing i could think off was using special scrolls to remove the enchants. These scrolls would drop from monsters and the drop chance will be based on how "weak" the enchants the player uses are compared to his level. The weaker the enchants, the higher a chance to get a disenchant scroll and vice versa. However there is a problem that the player can simply farm for the scrolls and save them for later thus allowing him to redo his gear before every encounter in end-game, where the monsters are the hardest. I would like to avoid that.

# Answer
> 1 votes
Here's a random idea. Enchantment parts come in 3 or 4 different colors, and in order to equip one, they must all be combined into one (using one of each color). This means people aren't swapping out minor parts of an enchantment based on the tiny upgrade part they got - and there's some buildup to the point at which you can use a new one ("Argh! I only need a good green enchantment to finish my Magi-slaying set!")

I'd also consider it a good idea to starkly divide sections of the game in which you fight particular enemies, with particular weaknesses. Make those weaknesses pretty easy to discover (ie, via a popup window by "inspecting" the enemy) and have a heavy impact on the damage dealt (or the effectiveness of status effects, etc), and ensure that the game is specifically alerting the player to changes of enemies in the scenery. ("Ohh...you're going to look for her in the Anke Mountains? Be careful up there! The 'Rakne' birds have been attacking anyone daring to venture in there! And their *wind gusts* are nothing to laugh at!")

# Answer
> 1 votes
You say you want to do a lot of things but dont't want a lot of natural consequences to happen. You will eventually have to compromise.
I think you could borrow a lot from the design of diablo 3 gems mechanic.

**Equipment will be enchantable.**
I recommend your equipment to have a quantity of "enchantment slots", you can create your equipment with a number of slots and raise that number later as a progression. If you choose to have the player change gear later slot quantity will be one more design option to balance the gear.

**Enchantmens will be removable**
You want the enchantments to be removable but the process not to be too trivial. As you already pointed, having the component for the disenchant being random loot favors farming. You can solve that by having an NPC do the deed in exchange of a price in currency, which gives you more flexibility to balance the cost.
In diablo 3 you can recover the gems, in torchlight you have to choose between destroying the gear to get the gem or destroying the gem to clear the slot.

**How about a craft system?**
While just destroying the current enchantments to open space for more powerful ones is a solid option, you can also opt to have your enchantments back, or maybe, its raw material, which could be used thru recipes, or a combination system to create new enchantments. The materia fusion system of FF Crisis Core would be something to look into.

# Answer
> 0 votes
Each enchantment could have two properties: a level and a durability. The level would be the strength of the effect, while the durability would determine how long the spell lasts. To be more specific, the level will determine what percentage of damage is absorbed by the enchantment, and the durability tells how many total damage points can be absorbed.

Whenever the player wants to apply a spell, the enchantment is added to his armor. There is a charge-up time, which means that the enchantment does not take effect immediately. Also, the enchantment is not removed from his collection of spells. It has infinite uses, but must be reapplied every once and a while to replenish the durability in order for the effects to remain.

In order to prevent the cycle of reapplying spells to feel repetitive, the enchantments should have a high durability, so that the player will find an upgraded enchantment within only a few reapply cycles.

---
Tags: game-mechanics, rpg, difficulty
---


title: Is Microsoft killing OpenGL?

text:
# Question
Title: Is Microsoft killing OpenGL?
In an article I've read that Microsoft signed GDI/GDI+ as deprecated. I was a bit frightened, I won't be able to use OpenGL in future versions of Windows. Since you need GDI ( more likely the Device Context you get through GDI's GetDC( HWND ) ) to initialize OpenGL.

I got frightened because, when MS marks something as deprecated, it's likely to be removed from the Platform SDK and later from the kernel. This means OpenGL can't be used through GDI.

The only other ways to get the Device Context would be trough WPF or DXGI. But both have their problems:

```
WPF -> slowly

DXGI -> Device Context shows sometimes creepy graphic bugs

```

So my question is: Is Microsoft killing OpenGL ? I'm asking because MS seems to make the use of OGL pretty difficult.

Thank's for reading.

# Answer
Two things:

1. GDI and GDI+ are not going anywhere. *Deprecated* and *Obsolete* have two very different meanings, and GDI/GDI+ are just *Deprecated*. This means that there are better ways to do the same things you used to do with GDI/GDI+, namely DirectX, DirectComposition and WIC, but I don't foresee Microsoft actually removing GDI/GDI+ from the kernel anywhere in the future, as there is way too much software written with these libraries, and Microsoft prides itself on its backwards compatibility (unlike a certain fruit-named company, which seems to enjoy breaking software with each update).

To give you some perspective, `OpenFile` has been deprecated for almost 20 years, but you can still call it, and it still works, and it will still work for a long time. It is of course deprecated, and there are few reasons (if any) to use it instead of the newer `CreateFile`.

So feel free to use GDI/GDI+ if that's what's best for your application. However, you are strongly encouraged to use the newer APIs, and hopefully in the future, there will be no reasons to use GDI/GDI+, just like today there's no reason for anybody to use `OpenFile`.
2. Regarding OpenGL, I haven't done WGL recently, but you only require an hDC to create an OpenGL content, but that's all there is to it. OpenGL is not built on top of GDI, and OpenGL's relationship with GDI is so inconsequential, that even in the extremely bizarre case that GDI is actually removed from the kernel, there will be other ways to create your GL context, probably with the hWnd directly, like in DirectX.

Microsoft certainly has lots of reasons for deprecating GDI/GDI+, but I can assure you that deprecating it with the single interest of cutting OpenGL is not one of them. If they just wanted to kill OpenGL, they would have done it long ago. And honestly, OpenGL doesn't need any help to kill themselves. They did it a long time ago.
> 5 votes

---
Tags: opengl, winapi, microsoft
---


# Question
Title: does cocos2d cache texture automatically
I know if we want the textures cached we can use the sharedtexture manager to cache them, but since this is on mobile platform , why don't cocos2d-x just do this for all texture loads ?

when creating sprites with images, are these textures cached as well ?

# Answer
It automatically caches for us. You can check it via Profiler to monitor for the current usage of memory, it goes up until we purgeCache manually or when memory warning kicks in then it will automatically does the job for us.
> 1 votes

---
Tags: textures, cocos2d-x
---


title: OpenGL Calculate Matrices

text:
# Question
Title: OpenGL Calculate Matrices
Im trying to switch from the glTranslate etc to my own Matrices, but for some reason it does not work. Here are my 2 functions to create the view- and projection matrix:

```
public Matrix4f getViewMatrix() {
    Matrix4f viewMatrix = new Matrix4f();
    viewMatrix.setIdentity();
    viewMatrix.translate(game.player.position);
    viewMatrix.rotate(game.player.rotation.x, new Vector3f(1.0f, 0.0f, 0.0f));
    viewMatrix.rotate(game.player.rotation.y, new Vector3f(0.0f, 1.0f, 0.0f));
    viewMatrix.rotate(game.player.rotation.z, new Vector3f(0.0f, 0.0f, 1.0f));
    //System.out.println(viewMatrix);
    return viewMatrix;
}

public Matrix4f getProjectionMatrix() {
    FloatBuffer projectionBuffer = BufferUtils.createFloatBuffer(16);
    GL11.glGetFloat(GL_MODELVIEW_MATRIX, projectionBuffer);
    Matrix4f projectionMatrix = new Matrix4f();
    projectionMatrix.load(projectionBuffer);
    return projectionMatrix;
}

```

I send those 2 matrices to the Vertex shader with a uniform, and use:

```
gl_Position = view_matrix * proj_matrix * vec4(in_position, 1.0);

```

Where in\_position is the coordinate of the vertex.

I do see some things on the screen, but it's very, very buggy, and nothing is right about it. If I use the build-in gl\_ModelViewProjectionMatrix in the shader and use glTranslate and glRotate in OpenGL, it works perfectly fine.

What am I doing wrong here?

Here is the output of me view projection together with the camera position:

```
0.5095141 0.0 -0.8604623 1.1625774
0.7321221 0.52541286 0.43351877 16.980185
0.45209795 -0.8508474 0.26770526 0.8665553
0.0 0.0 0.0 1.0

Vector3f[1.1625774, 16.980185, 0.8665553]

```

# Answer
> 0 votes
Okay it seemed that my projection matrix was completely wrong. Here is my new version which works great:

```
public Matrix4f getProjectionMatrix() {
    // Setup projection matrix
    Matrix4f projectionMatrix = new Matrix4f();
    float fieldOfView = 40.0f;
    float aspectRatio = (float)Display.getWidth() / (float)Display.getHeight();
    float near_plane = 0.1f;
    float far_plane = 1000f;

    float y_scale = coTangent((float) Math.toRadians(fieldOfView / 2f));
    float x_scale = y_scale / aspectRatio;
    float frustum_length = far_plane - near_plane;

    projectionMatrix.m00 = x_scale;
    projectionMatrix.m11 = y_scale;
    projectionMatrix.m22 = -((far_plane + near_plane) / frustum_length);
    projectionMatrix.m23 = -1;
    projectionMatrix.m32 = -((2 * near_plane * far_plane) / frustum_length);
    projectionMatrix.m33 = 0;
    return projectionMatrix;
}

```

---
Tags: opengl, shaders, glsl, matrix, lwjgl
---


title: Quick 3D sight calculation algorithm

text:
# Question
Title: Quick 3D sight calculation algorithm
I have a tile based board game where units move in 3D space on a 2D isometric view. When calculating attack tiles for a unit, how do I verify that they aren't shooting through a wall or a level too high for them see. I need quickly verify a lot of these attack tiles are within a unit's range of sight (about 20). What's the fastest way I can verify line of sight with the x, y, and z axis?

Somebody posted a similar question here, but it covers 2D sight calculation instead of 3D (making the answer very different).

# Answer
Use 3D DDA. It is the 3D version of 2D cell-based raycasting which you refer to.
> 3 votes

---
Tags: 3d, tiles, path-finding, raycasting, line-of-sight
---


# Question
Title: How to smoothly rotate a vector in a direction?
I'm looking for an easy way to achieve the following:

```
Object A, B
{
    Vector2D position;
    Vector2D orientation;
}

update(elapsed)
{
    //rotate A's orientation in B's direction by x * elapsed degrees
    //until A's orientation equals the direction from A to B
}

```

I am trying to align object A with an object B. Object A should rotate in B's direction by certain degrees/sec, e.g. max 45/sec.

I calculate the direction from A to B with normalize(B.position - A.position), but I don't know how to rotate A's orientation vector stepwise in B's direction.

# Answer
You could always deploy a type of Linear Interpolation. This allows you to slowly move to the target rotation over time and make it look decent.

If I'm misunderstanding and you simply want the angle between the two vectors, you might want to first normalize them (as you have done) and then simply take the dot product and angle. You can find a StackOverflow post on the topic over here, it's written in PHP but very easily read for any language.
> 5 votes

# Answer
thank you for your answers.

Linear interpolation sounds interesting, but I wasn't able to solve my problem with it. What I didn't mention in my question is that object B can change its position while A is aligning to it, so the adjustment of the interpolation scalar seemed quite difficult to me. (e.g. if the angle between both objects increases, the interpolated vector "moves" faster)

I extended my vector class by the following function which should be equivalent to multiplying the vector by a 2x2 rotation matrix:

```
public Vector2D rotate(double radians)
{
    double x = this.x * Math.cos(radians) - this.y * Math.sin(radians);
    double y = this.x * Math.sin(radians) + this.y * Math.cos(radians);
    this.x = x;
    this.y = y;
    return this;
}

```

If I call rotate(desiredRadians * elapsed) on A's orientation vector, the rotation works fine.

I still don't know how to stop the rotation when the desired direction (or angle) is reached. Also A would ideally rotate in the "shorter" and not necessarily in clockwise direction (e.g. prefer a rotation by -90 to +270 degrees).

Thank you.
> 2 votes

# Answer
Finally I solved my issue as follows:

```
update(double elapsed)
{
double targetAngle = Math.atan2(B.position.y - position.y, B.position.x - position.x);
double currentAngle = orientation.toRadians();

//Calculate angular deviation
double deviation = targetAngle - currentAngle;
double absDeviation = (deviation < 0 ? -deviation : deviation);

double maxRotation = maxRad * elapsed;

//If the absolute deviation is less than max rotation, rotate by.
//Else rotate the allowed radians in B's direction.
if(absDeviation <= maxRotation)
    orientation.rotate(deviation);
else
    orientation.rotate(Math.signum(deviation) * maxRotation);
}

```

Thank you for your time.
> 1 votes

# Answer
1. Convert the desired degrees/second to radians/frame;
2. Calculate the rotation matrix M (if 3D, about the cross-product A x B, else about the Z-axis) for the value calculated in (1) above;
3. Each frame, generate a new A from the previous frame's A * M.

Are you familiar with (1) use of homogeneous matrices and (2) converting a rotation matrix about the origin to a rotation matrix about some other point in the plane?
> 0 votes

---
Tags: 2d, rotation, vector, direction
---


# Question
Title: How can I implement infinite scrolling by scrolling the background's texture, not the quad?
I'm writing a 2D platformer game on `Java` with `LWJGL`. I'm doing this just for the sake of learning and not the result itself, so when I decided to implement scrolling I did it two ways I could invent myself:

* Three "sky" rectangle entities that located in a row and when my camera is moved to the right (fully on third), I move my first rectangle (from the far left) to the far right, etc. Pretty sure it can be made that way only with two entities, but I didn't have enough motivation to do it right now.
* Not infinite, but you can just stack these Sky entities in a row for the whole level width. Very lame approach.

But I realised that to optimize it, I can move not the "canvas", but the "painting" on the "canvas" itself. So, is it possible to move it this way? I'm not entirely sure that's possible at all, but I think it should be. How I see it: I change not `position.x` or `position.y`, but the texture coordinates, they should repeat, aren't they?

---

My code, if that will be helpful anyway. Render function in Main class:

```
private void render() {
    setupGL();
    GL11.glPushMatrix();
        GL11.glTranslatef(-Camera.x, -Camera.y, 0.0f);
        GL11.glScissor(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        sky.draw();
    GL11.glPopMatrix();
}

```

Draw function of the Sky entity, and yes, I know that immediate mode is bad, but I still haven't got my hands on arrays and other drawing methods.

```
public void draw() {
    GL11.glBindTexture(GL11.GL_TEXTURE_2D, TextureWrapper.get(EntityTypes.SKY).getTextureID());
    GL11.glColor3f(1.0f, 1.0f, 1.0f);
    GL11.glBegin(GL11.GL_QUADS);
        GL11.glTexCoord2f(0.0f, 1);
        GL11.glVertex2f(this.x, this.y + this.height);

        GL11.glTexCoord2f(1, 1);
        GL11.glVertex2f(this.x + this.width, this.y + this.height);

        GL11.glTexCoord2f(1, 0);
        GL11.glVertex2f(this.x + this.width, this.y);

        GL11.glTexCoord2f(0.0f, 0);
        GL11.glVertex2f(this.x, this.y);
    GL11.glEnd();
    GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
}

```

# Answer
It's even easier to do if your sky is bigger than what's shown on screen and it's continuous/repetitive:

* Always draw your quad with coordinates filling the whole screen.
* Adjust texture coordinates based on the camera's actual position.
* Set the texture clamping to repeat the texture.

As an alternative (especially if you're not using your whole texture), you can move the quad on screen as you did already with some minor modifications:

* Draw the background twice in every dimension the camera might be moving (2 copies for horizontal movement; 4 for diagonal/horizontal+vertical movement).
* Use a modulo operation to clamp the offset/repetition to screen space (e.g. when the left background quad leaves the left screen on the left, it replaces the former right quad; which itself is moved back to the right).
> 2 votes

---
Tags: opengl, java, 2d, lwjgl, platformer
---


# Question
Title: How powerful is modern hardware for complex, intensive 2D graphics?
I am embarking on a massive (image quality, file size, high frame count) project. I am still working on the basic engine, but have a big question that I would like answered before I begin testing. (It requires a lot of work to test, and possibly fail and have to recreate all sprite sheets, so an answer can help me save weeks of work if I'm wrong.)

The game is entirely in 2D, with 2.5D view. I want to eventually have 40 animations, which all have to be animated in 8 directions. I want each direction/animation to have its own sprite sheet. This equates to hundreds of spritesheets and thousands of files.

Before the obvious solution "Degrade quality for file size!" I would like to take every step possible to prevent degradation of quality, animation frame count, and image size.

Before my solution, one character was 350MB in ram (LOL!) but that was fixed quickly down to 10-20MB per whole character. That is...if I were to load ALL (40) animations in ALL directions (8). So if I were to load 320 sprite sheets into memory, it was going to be a ridiculously large amount per character in ram.

MY QUESTION IS THIS:

How much (of total sprite sheets) should I have loaded into memory at any given point?

Can I get away with loading ONLY the CURRENT spritesheet (Direction + Animation) into memory? Is modern hardware fast enough to constantly swap textures on the fly?

Players could, at any moment, change direction. This would change the entire spritesheet. Same for animation. So within a split second, the game would have to load a specific new spritesheet, unload the old one (or unload it eventually), and render all within a split second. This would have to be done once for every character, anytime they animate or change directions in a real time game.

Fortunately, the amount of characters on screen at once will be limited by the fact the game is 2D, but I'd prefer to be able to cram in the maximum amount without performance issues on a mediocre computer.

Is texture swapping, file loading, instant rendering from HDD and memory-- all so fast with modern hardware that I wont even need to worry about ANY of this?

I just dont want to work on all of these spritesheets (from thousands of images I already have) only to find out my performance will be horrible and have to redo all spritesheets. Even to test, since I have a layering equipment system, is a time consuming task for spritesheet creation. That is, until I find a solution to process those faster (automation, i do it manually currently, using a program)

# Answer
> 5 votes
Swapping textures will kill your performance. Modern hardware has only gotten more susceptible to this problem, not less, as the speed and power of the shader units and video RAM are growing much faster than the speed increases of the bus between system RAM and the GPU.

The only sane approach is to cut down your texture sizes, or generate procedural sprites (using vector art). As another reply stated, there is absolutely zero reason to have huge textures for sprites that will only be a few dozen pixels tall on the output. It sounds like you're looking for a solution to a problem that you're imposing on yourself for no reason.

Also, you will usually have better looking art if you design for the target pixel size than if you downscale a high-res texture.

# Answer
> 2 votes
You need to prototype this, with placeholder data.

Create a simple program that outputs a sprite sheet where each frame consists of text describing what it should be (e.g. "Sprite 7 frame 5"). Use that to create the final number of sprite sheets you're going to end up with, and see how well that runs a test scene with everything loaded into memory.

If it runs ok on your target hardware then go ahead and create your sprites, otherwise you'll need to adjust your plans or optimize the code to make it work.

# Answer
> 0 votes
Consider making the graphics quality configurable in the game. For example you could set a target for the "high end" of hardware you want your game to work on, and design your graphics and animations around that target. Then provide graphics quality settings that let you, say, use 50% scaled versions of the sprites, or use every other frame of animation.

# Answer
> 0 votes
If you're only targetting Windows/Mac/Linux, I wouldn't worry about HDD space.

Some of the most popular AAA titles are 20GB+ or larger.

If it's an online game, a singleplayer RPG, or a MMORPG, you could easily introduce a small client with less content (6-8GB max) and then introduce "expansion packs".

What people don't realize is that some games have a large client of 6+GB, and the expansions grow it to over 20GB.

The key though is to allow accessibility without having to download all 20GB of content. Example, WoW's streaming client vs Vanguard: Saga of Heroes. WoW is actually larger than the 20GB beast of Vanguard, but the former can be played in an hour of downloading on Cable, while the latter can take days for people to download.

Your problem is definitely going to be memory, as HDD space isn't a real requirement, nor are the draw calls for 2D graphics. Your memory problem will occur long, long, long before any HDD space (a virtually non-existent problem in modern streaming tech) or Rendering problems.

Keep the number of characters loaded small. Refrain from excessively large spritesheets. It is better to have a Dragon composed of 4+ sprites (chopped up dragon pieces) or stream single images (no sprite sheet at all for Dragons) than to load massive sheets.

Trying to animate a 4000x4000 sprite sheet dragon will make your game slow. Animating 10, 400x400 sprites will not. As long as your memory usage doesn't explode, your game should have no problem. As a 2D game, I can't imagine that many characters being on screen at any given moment unless the camera is zoomed out. If the camera is zoomed out, perhaps having smaller sprite images for that viewpoint would be better. It would create a ton more HDD space, but would help with memory dramatically.

Also, see about loading RGBA4444 instead of RGBA8888 to keep memory even lower. The former can still result in beautiful sprites.

---
Tags: 2d, sprites, spritesheet, memory-efficiency, 2.5d
---


# Question
Title: Panda3d handling collisions on walls created in blender
**Edit 2** : Updated code, so runnable zip isn't the same as the copied section bellow (though all that has changed is that part in run\_me.py)

**Edit:** Runnable zip with source files, sorry: https://dl.dropboxusercontent.com/u/12781104/Collisions.zip

Right now I am trying to create a small room for my character to walk around in, it works decently but will walk through walls, I am having difficulty setting up the collision logic to stop the character from walking through walls. The problem is properly creating the collision plane to line up with the walls (is there a way to do this in blender?)...

Code so far that has to do with wall collisions

```
 [Removed imports]

    ....

    self.cTrav = CollisionTraverser()
    robotCHandler = CollisionHandlerQueue()
    robotWallCHandler = CollisionHandlerPusher()

    WALL_MASK=BitMask32.bit(2)

    ralphStartPos = (0, 0, 0)
    self.ralph = loader.loadModel("robot.x")
    self.ralph.reparentTo(render)
    self.ralph.setScale(1)
    self.ralph.setPos(ralphStartPos)
    self.ralph.setCollideMask(BitMask32.allOff())
    # setup tube to suround robot
    #(robot is 3 height, by 1.5, 1.5)
    cTube = CollisionSphere(0, 0, 0, 3)

    robotCollisionNode = self.ralph.attachNewNode(CollisionNode('robotcnode'))
    robotCollisionNode.node().addSolid(cTube)
    robotCollisionNode.node().setFromCollideMask(WALL_MASK)
    robotCollisionNode.node().setIntoCollideMask(BitMask32.allOff())

    self.environ = loader.loadModel("room2.x")
    self.environ.reparentTo(render)

    root = self.environ.find("**/Root")
    walls = root.findAllMatches("**/Plane*")

    for w in walls:
        # set it to the same bitmask so the collider collides
        w.node().setIntoCollideMask(WALL_MASK)

    robotWallCHandler.addCollider(robotCollisionNode, self.ralph)

    self.cTrav.addCollider(robotCollisionNode, robotWallCHandler)

```

The bottom line is what I am most confused about, how do I get the collision plane properly setup, do I just have to hard code the points or is there something easier (maybe the geom nodes?)?

# Answer
You should be able to export the collision data from Blender without any setup necessary in Panda3D (no setIntoCollideMask). Go to the Logic panel, then add a String property called "Collide" set to "Polyset keep descend". Do this for all your wall objects that you want to be collideable, and it will work out of the box.

If you would like to keep your collision geometry separate from the visible geometry, you can do that too, you'll just need to set the property to "Polyset descend" to tell Panda that that mesh is only to be used as collision geometry and not as visible geometry.
> 3 votes

---
Tags: collision-detection, panda3d
---


title: A very simple game server using c#

text:
# Question
Title: A very simple game server using c#
I just want to see a very simple sample of a c# game server that listens for connections from game client. Hope somebody can help me. I'm on the learning process of making a simple game server

# Answer
> 2 votes
You can use a simple `TcpClient` like in the following example: http://www.codeproject.com/Articles/1415/Introduction-to-TCP-client-server-in-C Or, if you prefer to use `Socket` directly, there are some synchronous and asynchronous examples on MSDN: http://msdn.microsoft.com/en-us/library/w89fhyex.aspx

Those are generic examples, but they apply for games as well.

If you want to use a 3rd party lib, you could use Lidgren: http://code.google.com/p/lidgren-network-gen3/

PS: You didn't specify in what C# environment/version you want to create the game server. Because it might seem the same thing but it isn't. Windows, Windows Phone and Windows 8, for example, each one has it's own way of using networking (some may be shared but it's not a rule).

---
Tags: c#
---


title: Sharing the effect

text:
# Question
Title: Sharing the effect
my problem is :

If I load 2 models ( the same model zombie ) and give them the same effect I got the following error :

```
        for(int i =0 ; i<2 ; i++)
        {
            dwarfModel[i].model = Content.Load<Model>("Models//dwarf//dwarfmodel");
            dwarfModel[i].effect = Content.Load<Effect>("Models//dwarf//skinFX");
            dwarfModel[i].setEffect(camera , game);
            dwarfModel[i].setModelAnimationStatus(game);
            dwarfModel[i].intializeChrachterController(new Vector3(0, 0, 0), 20, 10, 2000, 2000, 80, 40);

            space.Add(dwarfModel[i].chrachterController);

            dwarfModels.Add(dwarfModel);
        }
enter code here

```

# Answer
> 0 votes
When you try to call the Effect property of your ModelMeshPart you get an Effect instance and Effect is the base class for all effect. So you can't cast an Effect instance to a BasicEffect because BasicEffect inherits from Effect.

Furthermore you don't need to cast it to a BasicEffect.

Your line:

```
BasicEffect oldEffect = (BasicEffect)part.Effect;

```

Should be:

```
Effect oldEffect = part.Effect;

```

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


# Question
Title: Library for generating primitive shapes?
I'm looking for a library to generate the data for primitive shapes for opengl. I have lights, and I simply wants to draw a sphere to represent the lights transform in the world

I do not want a library that *draws* it though, I want to control all openGL-related API calls myself (so, freeGLUT is Not what Im looking for), I simply want to generate the vertices, normals, etc for a mesh shape at runtime (a cube, sphere, etc).

Is there any nice, minimal library that can do this task? If not, what is the alghoritm for generating vertices for a sphere-shape?

Thanks

EDIT: I am not looking to load from 3d model formats either

# Answer
For generating simple geometry, a whole (even simple) library would be overkill. You only need a handful of static constructors. You could find any example code that draws shapes, and copy-paste those lines. You may find what you need simply by examining freeGLUT's source code.

It would make more sense to use a model format parser. Generating geometry data is their job. You can create those shapes in any simple 3D editor, then file IO them into your running code. You could create a sphere or cube with a few mouse clicks. Or for something more exotic, you could use any of these: list of common 3d test models
> 2 votes

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


title: Keyboard Enter doing two things at once

text:
# Question
Title: Keyboard Enter doing two things at once
In my `CheckKeyboard(Keys.Enter)` it does both of the things when I only want it to do one and the other on the next to enter click, I can't think of how to fix it. Here is the related code;

```
enum CurrentState
{
    Menu,
    NewGame,
    LevelSelect
}
private CurrentState _currentState = CurrentState.Menu;
public void Update(GameTime gameTime, Game1 game)
{
    keyboard = Keyboard.GetState();
        switch (_currentState)
            {
                //Error-  The name 'Menu' does not exist in the current context.
                case Menu:
                {
                }
            }
    prevKeyboard = keyboard;
}
public bool CheckKeyboard(Keys key)
{
    return (keyboard.IsKeyUp(key) && prevKeyboard.IsKeyDown(key));
}

```

# Answer
In this case a 'state machine' system would be an alternative. (This way you can enhance it later more easily than using different flags).

First, define an enum with the possible states:

```
enum CurrentState {
     ShowOptions,
     SelectLevel
}

```

Then, define a field inside the current class, and initialise it with `ShowOptions`:

```
private CurrentState _currentState = CurrentState.ShowOptions;

```

In the `Update` method you'll have something like this:

```
switch(_currentState) {
    case CurrentState.ShowOptions:
    {
        if (CheckKeyboard(Keys.Enter))
        {
            if (selected == buttonList.Count - 2)
            {
                _currentState = CurrentState.SelectLevel;
            }
        }
        break;
    }
    case CurrentState.SelectLevel:
    {
        if (CheckKeyboard(Keys.Enter))
        {
            if (sChapter == chapterList.Count - 1) sChapter1 = "C3";
            if (sChapter == chapterList.Count - 2) sChapter1 = "C2";
            if (sChapter == chapterList.Count - 3) sChapter1 = "C1";

            // todo: advance to another state (maybe start the actual game?)
        }
        break;
    }
}

```

It can be seen clearly how the states flow and go one after another. This allows you to have complex scenarios where you would need to go back to a state. For every new state, you just add an enum member and handle it inside the switch.
> 1 votes

# Answer
This is one possible solution for the code given. Definitely not the best and I see a couple of other routes, but it should provide enough hints to make better.

Start by giving the class that contains this Update() Method a member variable.

```
private bool _isLevelSelect;

```

remove these from your current CheckKeyboard(Keys.Enter) implementation

```
if (selected == buttonList.Count - 2) Selected = "LevelSelect";

if (sChapter == chapterList.Count - 1) sChapter1 = "C3";
if (sChapter == chapterList.Count - 2) sChapter1 = "C2";
if (sChapter == chapterList.Count - 3) sChapter1 = "C1";

```

add

```
if (CheckKeyboard(Keys.Enter) && selected == buttonList.Count - 2)
{
    Selected = "LevelSelect";
    _isLevelSelect = true;
}

if (CheckKeyboard(Keys.Enter) && _isLevelSelect)
{
    if (sChapter == chapterList.Count - 1) sChapter1 = "C3";
    if (sChapter == chapterList.Count - 2) sChapter1 = "C2";
    if (sChapter == chapterList.Count - 3) sChapter1 = "C1";
}

```

provide a way for user to cancel that selection

```
if (CheckKeyboard(Keys.Escape) && _isLevelSelect)
{
   _isLevelSelect = false;
}

```
> 1 votes

---
Tags: xna, c#, keyboard
---


title: 3D Position won't translate to 2D

text:
# Question
Title: 3D Position won't translate to 2D
My 3D Hero-Model is positioned at a certain point in 3D-Coordinates. Whenever he's colliding with a coin, I want to place an animated sprite sheet there. But my following implementation won't give me useful result.

```
Viewport vP = GraphicDevice.Viewport;
Vector3 unitPos = modelPos.LocalPosition;

Vector3 screenSpace = vP.Project(unitPos, _cam.Projection, _cam.View, Matrix.Identity);
MySprite sprite = new MySprite(unitPos.X, unitPos.Y);

//... Won't draw sprite where the model is

```

The sprites are almost at the exact position, but there's approx. a 100px difference. I am using a perspective camera with these settings:

```
Matrix Projection = Matrix.CreatePerspectiveFieldOfView((float)Math.PI / 3.0f, 800f / 480f, 1, 3000);

```

And when I place my camera to Z= 0 Y = 37 and Z = 220, I have to multiply the result of Vector3 by 3.

The position of my camera is a Vector3 though.

**A** is the pure calculated value for SpriteY and **B** is the calculated value \*3 (coincidentally is the right position)

So, it isn't correct. **Why???**

# Answer
You need to replace this code:

```
Vector3 screenSpace = vP.Project(unitPos, _cam.Projection, _cam.View, Matrix.Identity);
MySprite sprite = new MySprite(unitPos.X, unitPos.Y);

```

3D coordinates, even after projection, will still have their origin at the lower-right corner.

Texture coordinates, which your 2D system surely uses, start from the upper left, like so:

That means that you have to do some calculation other than your current code. For instance:

```
MySprite sprite = new MySprite(unitPos.X, GraphicsDevice.Viewport.Height - unitpos.Y);

```

However, this code is only for example. It will not be correct. You will also need to account for the position of your camera. If your camera ever points in a direction not parallel to the Z axis, the sprite position will be wrong.

To summarize, you will have to think quantitatively about what you are trying to accomplish, and write code that implements that math. Stop throwing code at the wall to see what sticks.
> 2 votes

---
Tags: c#, logic
---


# Question
Title: How to add difficulty levels to a Guess The Number game using rand()?
User guesses a random number (between 1 and 100 or 5000 and 25,000 depending on difficulty) that the computer picks.

User selects difficulty from list, difficulty (1, 2, 3, 4) is assigned to `int level`. Using `do while` loops to check for difficulty.

Here is the current `do while` loop for level 1:

```
do
{

srand(time(0)); // seed the random number generator

int theNumber = rand() % 100 + 1; // random number between 1 and 100
int tries = 0, guess;

    do
    {

        cout << "Enter a guess: ";

        string str;
        cin >> str;
        istringstream iss(str);
        iss >> guess ;
        if (iss.eof() == false)
            cout << "\n\nPlease enter only numbers.\n\n";
        else
        {

            ++tries;

            if (guess > theNumber)
            cout << "Too high!\n\n";

            if (guess < theNumber)
            cout << "Too low!\n\n";
        }

    } while (guess != theNumber);

cout << "\nThat's it! You got it in " << tries << " guesses!\n";

cout << "Play again? (y/n)\n";
cin >> playAgain;

} while (playAgain == 'y' && level == 1);

```

What I need help with is the `int theNumber = rand() % 100 + 1;` section. What do I need to change to allow the random number to be between 100 and 1000, 1000 and 5000, 5000 and 25000?

It would also be extremely valuable information to me if you could explain how `rand() % x + y;` works.

**EDIT**

I know that `rand() = 32767` (for me). I'm just not sure as to how `rand() % x + y` works. I'm actually not sure what the `modulo (%)` operator does. If someone could explain that with an example, it would be extremely helpful.

# Answer
`rand() % 900 + 100` would be between 100 and (900+100) `rand() % 20000 + 5000` would be between 5000 and (20000+5000), etc.

`rand()` gives you a random number from 0 up to a built-in limit (generally 32,767).

`rand() % 10` gives you a number from 0 to 9. What happens is `%` takes that big number and divides it by 10 and gives you what remains.

`rand() % 10 + 1` gets rid of that 0 and gives you a number from 1 to the number after your `%` (10, in this case).

That's about it, good luck !
> 2 votes

---
Tags: c++, game-mechanics, game-loop
---