# Question
Title: How can I use WebGL to create a tile-based multi-layer scrolling platform game?
I've found WebGL (based on OpenGL) to be a fiendish and unforgiving framework for those learning to write HTML5-based games. Despite the presence of many examples on how to get started, I'm really struggling to understand how I could simply load a bunch of images and render them to a canvas quickly using WebGL.

My specific scenario involves trying to render a map using a bespoke but simple multi-layered tile engine, where each value in a three dimensional array points to the image to use for that location in the rendered image. Think "Sonic the Hedgehog" via tilesets, tiles, maps, layers, sprites etc.

Can anyone enlighten me:

1) How can I load an image that I can use as a texture in WebGL?

2) How can I dynamically select an image at run time and draw it at any co-ordinate, that I also select at run time?

--

Edit: Thanks for the responses so far. I'd like to clarify that my original title may not have been the best.

So, rephrasing my original post, here's another stab at the question I really want to ask:

Using WebGL, What is the best way to dynamically load an image at run time and "blit" it to a specific area on a canvas (also at run time)?

# Answer
I think you should use a graphical framework instead of plain WebGL, except if you really need a control on every part of your game engine.

For example, with Three.js your questions could be easily answered :

* You load an image using `Three.ImageUtils.loadTexture` (asynchroneous)
* You display it by creating a mesh based on a `Three.PlaneGeometry` and a `Three.MeshBasicMaterial`, passing your image as the `map` option.
* You now have to set the `myMesh.position` variable to the proper coordinates, and you're done.

If you do this, don't forget to use a `Three.OrthographicCamera` (because you probably don't want any perspective effect).
> 3 votes

# Answer
I wrote a very simple framework for the last Ludum Dare competition: barebones.js

It can create a GL context and you can take apart how it draws the splash to draw any 2D tiles anywhere you want.

Oh, and it has a font drawer too. That's super-useful.

(There's also an animated mesh loader and various 3D camera utils in there too. I have a much extended version of it and would be happy to move new features back into barebones.js if there were actually interested users. Long live hobby coding!)
> 1 votes

# Answer
Check this:

http://learningwebgl.com/blog/?p=507

Long story short (copy-pasted from link, commented by me :P):

```
var neheTexture;
function initTexture() {
    // "gl" refers to the result of canvas.getContext("experimental-webgl");
    neheTexture = gl.createTexture();

    // I believe this is a html5 img element :P
    neheTexture.image = new Image();

    // good practice to set load-callback *before* set image source
    neheTexture.image.onload = function() {
        handleLoadedTexture(neheTexture)
    }

    // set src, this will load the image asynchronously
    neheTexture.image.src = "nehe.gif";
}

```

But I still agree with the previous answers, you should go for a framework ...
> 0 votes

# Answer
I think you should check this out:

https://github.com/libgdx/libgdx

It's a multiplatform framwork, that wraps all the GL stuff. Also includes classes for tiled maps and izometrics. If you just need to load images and draw them at coordinates, you should have it setup in less than 5 minutes.
> 0 votes

---
Tags: html5, webgl
---


title: Connect Micromax A100 with Eclipse

text:
# Question
Title: Connect Micromax A100 with Eclipse
I want to know that I can connect micromax a100 with the eclipse for android development or not. From other community I found that for development purpose micromax device can not be used. Also I doesn't found any usb driver for that. So please help to come out that.

# Answer
> 0 votes
After research about the multiple company devices, I found that windows operating system require device driver. If your device has no driver then you can not use your device for development purpose in windows. While linux has some flexibility in that one. You can connect and use any company device for development purpose that I have tested and used. You have to modify only 51-android.rules file for you device. I answer my own question because this information become useful to many other community members that I think.

# Answer
> 1 votes
I don't know this device but Eclipse doesn't care about this, your bridge between your Android phone and your PC is `adb`, a tool distributed with the Android SDK, and you should be able to develop and test an application with every Android device out there.

The only real problem are the drivers; the suggested platform for Android development is a Gnu/Linux distribution but many people still use Windows or Mac, with Windows you must have the right drivers for your device because otherwise you can't use it and you can't connect it to your PC. On a GNU/linux distribution you don't have this problems and the setup is much more easier.

---
Tags: android
---


# Question
Title: Selection of a mesh with arbitrary region
Considering example:

I have a mesh(es) on the `OpenGL` screen and would like to select a part of it (say for delete purpose). There is a clear way to do the selction via `Ray Tracing`, or via `Selection` provided by `OpenGL` itself.

But, for my users, considering that meshes can get wired surfaces, I need to implement a selection via a *Arbitrary closed region*, so all triangles that appears present *inside* that region has to be selected.

To be more clear, here is screen shot:

I want all triangles inside black polygon to be selected, identified, whatever in some way.

How can I achieve that ?

# Answer
You need to use glUnProject, which allows you to map window coordinates (2D) to object coordinates (3D). You can basically implement a function that allows you to draw a 2D polygon on the screen, then project each its corners to 3D, and select all the vertices of your 3D mesh that lay inside the projected 2D corners.

NeHe has a tutorial about glUnProject, although I don't know how good or useful can be for you.
> 1 votes

---
Tags: c#, opengl, selection
---


title: shader tutorial for unity

text:
# Question
Title: shader tutorial for unity
I would like to start developing my own shaders within unity.

For starters I would like to do a screen spaced blur.

Are there any good tutorials to learn shader development besides the official unity documentation, which i find a bit hard to understand?

# Answer
I think this is what you are looking for: http://en.wikibooks.org/wiki/Cg\_Programming/Unity. The tutorials are organized in an increasing difficulty order and each was written with Unity in mind.
> 6 votes

# Answer
Easy to understand tutorial

And the following wiki book helped me much

Don't forget Jessy's video tutorials

And some Unity3D resources really helped me to build up the basics
> 4 votes

---
Tags: unity, shaders
---


# Question
Title: Understanding Unity3d physics: where is the force applied?
I'm trying to understand which is the right way to apply forces to a `RigidBody`.

I noticed that there are `AddForce` and `AddRelativeForce` methods, one applied in world space coordinate system meanwhile the other in the local space. The thing that I do not understand is the following: usually in physics library (es. Bullet) we can specify the force vector and also the force application point.

How can I do this in Unity? Is it possible to apply a force vector in a specific point relative to the given RigidBody coordinate system? Where does AddForce apply the force?

# Answer
> 5 votes
The documentation isn't terribly clear on it—and I'm not currently in a position to verify it—but I *believe* that the force applied from `RigidBody.AddForce()` (link) is applied at that object's root location (at its `transform.position`). If not at `transform.position`, then at the object's `RigidBody.centerOfMass` (link).

If you want to apply a force vector at a specific point, you probably want to use `RigidBody.AddForceAtPosition()` (link). Similarly, there is `RigidBody.AddRelativeForce()` (link) if you just want it local to the object itself.

And, for even more control if you know the torque you want to apply, there are `RigidBody.AddTorque()` (link) and `RigidBody.AddRelativeTorque()` (link).

\</wallOfLinks\>

---
Tags: physics, unity, rigid-body-dynamics
---


# Question
Title: How do I implement camera axis aligned billboards?
I am trying to make an axis-aligned billboard with Pyglet. I have looked at several tutorials, but they only show me how to get the up, right, and look vectors. So far this is what I have:

```
target = cam.pos
look = norm(target - billboard.pos)

right = norm(Vector3(0,1,0) * look)
up = look * right

gluLookAt(
  look.x, look.y, look.z,
  self.pos.x, self.pos.y, self.pos.z,
  up.x, up.y, up.z
)

```

This does nothing for me visibly. Any idea what I'm doing wrong?

# Answer
> 2 votes
I tried out billboards a while back. I just created a quad that faced the camera. Using the position I want the object at and the up and right vectors (normalized) of the camera, you can set the four corners of the quad like so:

```
a = position - ((right + up) * scale);
b = position + ((right - up) * scale);
c = position + ((right + up) * scale);
d = position - ((right - up) * scale);

```

Where `a`, `b`, `c` and `d` define the corners, use them clockwise or counter-clockwise depending on the winding order of your graphics library.

The right can be derived from the cross product or the look and the up vectors.

---
Tags: opengl, pyglet, billboarding
---


title: Help my graphists sharing their work

text:
# Question
Title: Help my graphists sharing their work
As a developer I'm used to Subversion for source control and I think it's great for sharing source code between developers.

Now thinking about my graphists and game designers, they need to have a slightly different approach I think.

1. They need to share binary files
2. They need to be able to have a thumbnail and preview of their work
3. I don't want to include their binaries into my game repository (would be much too heavy for developer when updating)

I've seen that some graphists uses personally created website to share their work but I was wondering if some "standard" application existed in order to provide my graphists a cool way of working together.

Is there a common way of dealing with this? Is the way I want to do (only final sprites on my game repo) correct? How do you guys do this as game developers?

# Answer
If your artists are more like members of your project and less like casual freelancers that do one time contribution, they should be using version control too, because it's inconvenient to go downloading and uploading stuff from/to websites instead of just keeping everything in sync with simple `svn update`.

Personally I tend to use the the main version control repository also for data needed to play the game and then a separate repo for source art files (e.g. images in a layered format which are flattened for usage in the game), if any.

If source art files are small, I'd just slab everything to the same repo. On the other hand, if I e.g. had lots of level files and other stuff that might not change that often but take up a lot of space, I might put them into a separate data repository, but always using version control software (Git in my case, but subversion works too).

Some comments on your points in your question:

1. SVN can hold binary files without a problem, although you will most likely not get meaningful diffs. Only thing to look for is conflicts as they cannot really be merged easily. It shouldn't be a problem as long as the artists communicate and don't work with the same piece at the same time and commit their work frequently. Note that conflicts would also be a problem with manually uploading stuff to websites etc.
2. They can have thumbnails in the file browser from the svn checkout. If the file cannot be thumbnailed automatically, a separate preview jpg could be added.
3. Depending on what kind of art you are using (you mentioned sprites so 2d pixel art?), you might not have anything else than the files your game needs anyway, and `svn update` is going to be the easiest way for developers to fetch the latest art to use & test.
> 5 votes

# Answer
I maintain two directories:

* **Working assets** \- Has textures/models/GUI graphics in their native format (Blender files, whatever gimp uses, etc.) This is not packaged into my game. Similar to how the source files are used to create the binaries, these files are used to create the resource files
* **Assets** \- Has all the exported textures/models/graphics. These are all in formats that my game reads, they're the "final" format. Blender files are exported in to .x files with meshes and animations, art files are .png. These are packaged with the game.

When switching between my laptop and PC, I just check everything in, including what's in the working directories. Then I have the same tools on both computers, and I can just open the native formats with the appropriate tool and pick up where I left off. No problems.

There are some repositories that have additional functionality, specifically for art. For example, github has Image view modes. Which has features like comparing images side by side, swipe (swipe a seperator across a single image to see "before and after"), onion skin (overlay a transparency of "before and after") and difference which shows just the differences.

Or TortoiseSVN shows images side by side.

The bottom line is, if you're hosting this repository yourself, you're going to need a lot of extra storage for graphics diffs. Because, like you said, it's not like a source code file where you only have to store the differential, you're likely going to end up storing multiple copies with only slight changes.
> 6 votes

---
Tags: graphics, version-control
---


title: j2me Bitmap font

text:
# Question
Title: j2me Bitmap font
I have found a tutorial how to make a bitmap font from an image.

So I have used this code in my game and the problem is that the rest of the graphics which should be seen on the screen like rectangles and etc. is invisible.

Before the newly added code

After

A GameCanvas class play.java

```
  public void start() {

    try {
        map = Image.createImage("/mapas.png");
        human = Image.createImage("/players.png");
        ingame = Image.createImage("/ingame.png");
        items = Image.createImage("/items.png");
        atkPav = Image.createImage("/ingamee.PNG");
    } catch (IOException ioex) {
        System.out.println(ioex);
    }
            // f is the newly added class where is methods drawString() drawChar()                    and etc.
    f = new f();
    f.load("/chatfont.PNG");

         // sprites and etc.
       }
         // method which is called from a Thread (while loop)
 private void createBackground(Graphics g) {
       // some graphics an xp line showing how much xp left to level up and etc.
            g.setColor(0x000000);
    g.fillRect(0, 0, getWidth(), 28);
    g.fillRect(0, getHeight() - 15, getWidth(), 15);

    // xp
    g.setColor(0x9F81F7);

    if (level == 0) {
        g.fillRect(0, 25, getWidth() * xp / 200, 2);
    } else {
        g.fillRect(0, 25, getWidth()
                * (xp - (200 * level + (level * (level - 1)) / 2 * 200))
                / (200 * (level + 1)), 2);
    }
    g.setColor(0xAAAAAA);
    g.fillRect(getWidth() - 24, 0, 24, 24);

    g.setColor(0x000000);
    g.fillRect(getWidth() - 22, 2, 20, 20);

    g.setColor(0xffffff);

            // here`s the statement
    f.drawString(g, "HP: " + humanHp + "/" + maxHumanHp, 5, 0);

     }

```

The f.java, a bit modified from the original

```
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

 public class f {

// tarpas tarp raidziu
public int charS = 1;

// image width 99 height 17
// max kirpimo matmenys
public int screenW = 176;
public int screenH = 208;

// flag: set to true to use the Graphics.drawString() method
// this is just used as a fail-safe
public boolean useDefault = false;

// height of characters
public int charH = 5;
// lookup table for character widths
public int charW = 4;

// the bitmap font image
private Image imgFont;

/** Creates a new instance of clsFont */
public f() {
}

public boolean load(String imagePath) {
    useDefault = false;
    try {
        // load the bitmap font
        if (imgFont != null) {
            imgFont = null;
        }
        imgFont = Image.createImage(imagePath);
    } catch (Exception ex) {
        // oohh we got an error then use the fail-safe
        useDefault = true;
    }
    return (!useDefault);

}

public void unload() {
    // make sure the object get's destroyed
    imgFont = null;
}

public void drawChar(Graphics g, int cIndex, int x, int y, int w, int h) {
    // non printable characters don't need to be drawn

    // neither does the delete character

    int cx = 0;

    // getting characters from an Image (cx - coordinate which will be used          for clipRect())
    if (cIndex > 64 && cIndex < 91) {
        cx = (cIndex - 65) * 5;
    } else if (cIndex > 96 && cIndex < 123) {
        cx = (cIndex - 97) * 5;
    } else if (cIndex > 47 && cIndex < 58) {
        cx = (cIndex - 48) * 5 + 135;
    } else if (cIndex == 32) {
        cx = 130;
    } else if (cIndex == 46) {
        cx = 184;
    } else if (cIndex == 58) {
        cx = 189;
    } else if (cIndex == 44) {
        cx = 194;
    } else if (cIndex == 59) {
        cx = 199;
    } else if (cIndex == 63) {
        cx = 204;
    } else if (cIndex == 33) {
        cx = 209;
    } else if (cIndex == 40) {
        cx = 214;
    } else if (cIndex == 41) {
        cx = 219;
    } else if (cIndex == 43) {
        cx = 224;
    } else if (cIndex == 44) {
        cx = 229;
    } else if (cIndex == 42) {
        cx = 234;
    } else if (cIndex == 47) {
        cx = 239;
    } else if (cIndex == 61) {
        cx = 244;
    } else if (cIndex == 96) {
        cx = 249;
    } else if (cIndex == 95) {
        cx = 254;
    } else if (cIndex == 92) {
        cx = 259;
    } else if (cIndex == 35) {
        cx = 264;
    } else if (cIndex == 91) {
        cx = 269;
    } else if (cIndex == 93) {
        cx = 274;
    } else if (cIndex == 38) {
        cx = 279;
    }

    // reset the clipping rectangle
    g.setClip(0, 0, screenW, screenH);

    // resize and reposition the clipping rectangle
    // to where the character must be drawn
    g.clipRect(x, y, w, h);

    // draw the character inside the clipping rectangle
    g.drawImage(imgFont, x - cx, y, Graphics.TOP | Graphics.LEFT);
}

public void drawString(Graphics g, String sTxt, int x, int y) {
    // get the strings length
    int length = sTxt.length();

    // set the starting position
    int cx = x;

    // if nothing to draw return
    if (length == 0) {
        return;
    }

    // our fail-safe
    if (useDefault) {
        g.drawString(sTxt, x, y, Graphics.TOP | Graphics.LEFT);
        return;
    }

    // loop through all the characters in the string
    for (int i = 0; i < length; i++) {

        // get current character
        char c = sTxt.charAt(i);

        // get ordinal value or ASCII equivalent
        int cIndex = (int) c;

        // lookup the width of the character
        int w = charW; // cIndex

        // draw the character
        drawChar(g, cIndex, cx, y, w, charH);

        // go to the next drawing position
        cx += (w + charS);
    }
}

public void drawInt(Graphics g, int num, int x, int y) {
    drawString(g, Integer.toString(num), x, y);
}
   }

```

# Answer
The penultimate line of `f.drawChar` sets the clip to a tiny rectangle. If you reset the clip after rendering the character, you'll probably find that the problem is fixed.

---

In fact, there's room for some optimisation, and it's a good idea to restore the clip afterwards:

```
private int clipX, clipY, clipW, clipH;

private void storeClip(Graphics g) {
    clipX = g.getClipX();
    clipY = g.getClipY();
    clipW = g.getClipWidth();
    clipH = g.getClipHeight();
}

private void restoreClip(Graphics g) {
    g.setClip(clipX, clipY, clipW, clipH);
}

public void drawChar(Graphics g, int cIndex, int x, int y) {
    storeClip(g);
    drawCharInner(g, cIndex, x, y)
    restoreClip(g);
}

// Returns the advance
private int drawCharInner(Graphics g, int cIndex, int x, int y) {
    // lookup the width of the character
    int w = charW;

    int cx = 0;
    // getting characters from an Image (cx - coordinate which will be used for clipRect())
    if (cIndex > 64 && cIndex < 91) {
        cx = (cIndex - 65) * 5;
    } etc // There must be a better way of doing this

    // resize and reposition the clipping rectangle to where the character must be drawn
    // NB Two steps here to work around some buggy implementations
    g.setClip(0, 0, screenW, screenH);
    g.clipRect(x, y, w, h);

    // draw the character inside the clipping rectangle
    g.drawImage(imgFont, x - cx, y, Graphics.TOP | Graphics.LEFT);

    return w + charS;
}

public void drawString(Graphics g, String sTxt, int x, int y) {
    // get the strings length
    int length = sTxt.length();

    // set the starting position
    int cx = x;

    // if nothing to draw return
    if (length == 0) {
        return;
    }

    // our fail-safe
    if (useDefault) {
        g.drawString(sTxt, x, y, Graphics.TOP | Graphics.LEFT);
        return;
    }

    storeClip(g);

    // loop through all the characters in the string
    for (int i = 0; i < length; i++) {

        // get current character
        char c = sTxt.charAt(i);

        // draw the character and go to the next drawing position
        cx += drawCharInner(g, c, cx, y);
    }

    restoreClip(g);
}

```

One final thought, which would require changes outside this class: when you use an image with lots of small sprites, as in this case, it's better to lay them out vertically rather than horizontally. The reason is that memory storage of images tends to be row-major, so keeping the image width to one sprite means that the memory which makes up a sprite is contiguous, which is good for cache performance.
> 1 votes

---
Tags: java, mobile
---


# Question
Title: XNA 4.0 SpriteFont not displaying all Characters
Am looking for a little help and trying to use SpriteFont in my XNA 4.0 game but the problem is am displaying to string
"This is a test" but all that's displayed on the screen is "This is st" so the "a te" are missing from the screen.
The space is there for the characters but the letters are not.

The code am using is:

```
spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
spriteBatch.DrawString(font,"this is a test",new Vector2(692,372),Color.White);
spriteBatch.Draw(texture,new Rectangle(0,0,100,100),Color.White);
spriteBatch.End();

```

Any help with this would be great!

# Answer
It sounds like you need to modify your XML file that defines your spritefont.

You want to ensure that the `DefaultCharacter` and `CharacterRegion` tags are correct. Below are the ones that I use in my `Block.spritefont` file.

```
    <!--
The default character will be substituted if you draw
or measure text that contains characters which were not included in the font.
-->
    <DefaultCharacter>@</DefaultCharacter>

    <!--
CharacterRegions control what letters are available in the font. Every
character from Start to End will be built and made available for drawing. The
default range is from 32, (ASCII space), to 126, ('~'), covering the basic Latin
character set. The characters are ordered according to the Unicode standard.
See the documentation for more information.
-->
    <CharacterRegions>
        <CharacterRegion>
            <Start> </Start>
            <End>~</End>
        </CharacterRegion>
        <CharacterRegion>
            <Start>	</Start> <!-- The tab character -->
            <End>	</End>
        </CharacterRegion>
    </CharacterRegions>

```
> 2 votes

# Answer
Found out if i change the SpriteSortMode to deferred then this sorts my issue with drawing fonts
> 1 votes

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


title: Visual Studio 2012 and Game Development

text:
# Question
Title: Visual Studio 2012 and Game Development
Alright, I think it's a simple question, but I got difficulties to find some answers around.

I already read that XNA wouldn't be in Visual Studio 2012. I recently learned to use XNA, but since I would like to work on games, I'd like to know if there's a way to develop games using C# on Visual Studio 2012, or if I should learn everything again using C++ and Direct3D?

C# is a language I like a lot, so if there's no way to do it in C# but something quite easy to use Java for game development, I'd also be interested.

Thanks a lot!

# Answer
Visual Studio 2012 does not work out of the box with XNA 4.0 but there is a workaround but since this still requires VS2010 to be installed as well I would recommend to just use VS2010 since that still works as expected.
> 11 votes

# Answer
I think many here are in the same boat, so to speak. XNA was great and I had a lot of fun, now I'm moving on as Microsoft is keeping too silent about it, and excluding it in the ways you already noticed.

There's a workaround to develop XNA projects with Visual Studio 2012 and they should still run on Windows 8 desktop, but there's no official support from Microsoft.

Look at other frameworks/wrappers for .NET/C# like SlimDX if you want to continue this route.

Microsoft seems to want to focus on native code now, it almost feels like a revival movement from within the company, with C++ and DirectX being the combo of choice, even on their Windows Phone 8 platform.

Me myself am completely refocusing on

1. using existing game engine for serious game development projects, like UDK and Unity
2. switching to HTML+Javascript for hobby game tinkering, with C# on the backend (currently using SignalR) and I'm having a blast, especially with ReSharper 7.0 and JSLint as a R# plugin ^^

*Some additional rambling: I'm contemplating C++11 now and then as this seems the new old Microsoft way but I never really did like C++ to begin with, especially after being exposed to languages like Java an C#, so I feel a bit spoiled. Also, JavaScript turned out to be much less of an ugly language after reading through The Best Parts and getting seriously into web front-end work in my career again, I feel the powerful ways of expressing myself in JavaScript really makes me smile these days, and there are JavaScript+WebGL demo and intro compos at demoparties these days - doing very cool stuff.*
> 6 votes

# Answer
Head over to the MONOGAME repo on Codeplex i have XNA running in the Win8 Store in both full game mode and embedded within a XAML Application

the discussion forums contain plenty of example on how to achieve this

sometime this month MONOGame 3.0 is being released that officially supports Windows8 (rather than using a development branch)
> 5 votes

# Answer
XNA and C# was a strong combo for neat PC games and XBOX games development. I would doubt that Microsoft could drop it just so. More resonable is the thought that the new upcoming MS console and Xbox 360 successor, is going to rely heavily upon current Direct X 11 interface and techniques, which current gpus implement already. It is very likely that a refurbished XNA is going to cover them in a future release. XBOX indie market has been a great place of innovation and development, why should Microsoft abandon that. Not really...

Regarding the news about the new XBOX devkits, i would argue that DX11 is the big player in future game development, since it is used by the XBOX successor. Thinking bout Direct X9, it is only the current XBOX 360 what keeps it alive after years somehow...
> 2 votes

# Answer
You might want to look up the ANX project. It aims to be source code compatible with XNA - ie beeing able to read and compile projects made with XNA Game Studio - and it can be used with Visual Studio 2012. More than that, it also supports DirectX 10 and 11 using SharpDX and also OpenGL. It is a work in progress but already now it seems quite useable. I've just started playing around with it, and it seems a very promising project.
> 2 votes

---
Tags: xna, c#, 3d, directx, .net
---


# Question
Title: How do I render everything in software using XNA/C#?
I'm trying to find how to render everything with software in XNA, but I can't find what option I need to set.

I'd like to know which method/properties I have to call/set to make my app run in software mode as opposed to hardware accelerated mode.

# Answer
It looks like you can use the reference device in XNA 4.0 using this code:

```
GraphicsAdapter.UseReferenceDevice = true

```

Not sure if this works but that is what the MSDN says.
> 5 votes

# Answer
Except for maybe debugging shaders why would you want to use software rendering?

You can use the Reference Device but it is extremely slow. I don't normally work in XNA but a quick google found me this: How to: Use the Reference Device
> 0 votes

# Answer
There is this Windows Advanced Rasterization Platform on the most recent Windows platforms which i think it's what you are looking for or there are commercial solutions like Pixomatic.
> 0 votes

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


# Question
Title: OpenGL: Move camera regardless of rotation
For a 2D board game I'd like to move and rotate an orthogonal camera in coordinates given in a reference system (window space), but simply can't get it to work.

The idea is that the user can drag the camera over a surface, rotate and scale it. Rotation and scaling should always be around the center of the current viewport.

The camera is set up as:

```
gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrtho(-width/2, width/2, -height/2, height/2, nearPlane, farPlane);

```

where `width` and `height` are equal to the viewport's width and height, so that 1 unit is one pixel when no zoom is applied.

Since these transformations usually mean (scaling and) translating the world, then rotating it, the implementation is:

```
gl.glMatrixMode(GL2.GL_MODELVIEW);
gl.glLoadIdentity();

gl.glRotatef(rotation, 0, 0, 1); // e.g. 45°
gl.glTranslatef(x, y, 0); // e.g. +10 for 10px right, -2 for 2px down
gl.glScalef(zoomFactor, zoomFactor, zoomFactor); // e.g. scale by 1.5

```

That however has the nasty side effect that translations are transformed as well, that is applied in world coordinates. If I rotate around 90° and translate again, X and Y axis are swapped.

If I reorder the transformations so they read

```
gl.glTranslatef(x, y, 0);
gl.glScalef(zoomFactor, zoomFactor, zoomFactor);
gl.glRotatef(rotation, 0, 0, 1);

```

the translation will be applied correctly (in reference space, so translation along x always visually moves the camera sideways) but rotation and scaling are now performed around origin.

It shouldn't be too hard, so what is it I'm missing?

# Answer
> 2 votes
In order to move your camera about in space using camera-relative controls, you must apply the camera transform *to your camera position delta* before adding it to the current camera position. There is no good way to have OpenGL do it for you. Once you have set that up, the proper order of transformations for rendering is: scale and rotate (either order), then translate.

---
Tags: opengl, 2d, camera, transformation
---


# Question
Title: How do client-server cooperation based games like Diablo 3 work?
Diablo 3 cooperates with Blizzard servers even during single player games. In fact, Blizzard has had problems with the games "melting their servers."

I would like to ask: How do the client and the server communicate? What details does the client leave to the server, and vice versa? What details are redundant - both the client and the server know - and how often do they disagree?

The previous paragraph contains the important questions, but I have a few more that I must explain my motivation towards. I am interested in the programming of botting. Ethical botting - I don't plan on actually abusing the automation to run 24/7. I just find it to be a great programming challenge to glean information from a game, and then make decisions from that information. I am stuck in the starting gate. The unofficial questions from this post would be: How can I make a bot (language, tools, libraries)? Can I get information through the communication between client and server, rather than the brute force pixel detection easily used in more static games?

There probably is a trust issue, and to that all I can say is that I promise not to abuse the answers. But please feel free to answer any of the questions you feel comfortable with. Thank you!

# Answer
In case of Diablo 3, client sends to server almost everything: clicking on an NPC, clicking on ground to move, using a key to use ability, setting an ability, changing an item's place in your backpack (even though it has absolutely no effect on anyone and item positions could be safely stored locally - and only a list of items in backpack must be updated on server when you pick/drop an item, use it or give to someone). What isn't sent to server is e.g. moving your mouse cursor, minimizing your game or changing video resolution.

Server sends to client everything it should know - monsters in sight (in some games too soon, and that's why map hacks are possible there), actions of another players (or rather effects of them), and results of your actions: what item did you craft? what loot do a monster drop? did you attack critically or not? did you move or connection failed you and you still stand in the old place?

The failed connection scenario is the only reason a client and a server should 'disagree'. It happens sometimes in Diablo 3 because it's client is cheating the player. When You click somewhere on ground, your character moves instantly, even though you need at least 50 ms for request to go to server and back. When connection gets laggy, it's clearly visible because of gold picking, as client simulates only changing position of a character, and not picking the gold, hence sometimes you run through a gold piece and see it disappear after a few more steps. And in case of packets lose, the client will disagree with server as to your position, but as the server is always right, not the client, you will be teleported to where server says you should be. Such 'disagreement' is called a desynchronisation, and often makes a game crash.

When making a bot, language of the bot-client doesn't matter as long, as it supports the right technology to connect to the server. In case of Diablo it will be sockets, sometimes just a http POST or GET request to server. Just like with hacking, making bots are easiest when you test them on your own servers first. To put it simply, it's hard to play chess if you always play as black, and don't really understand the strategies of the white player (it's also hard to understand the analogy to chess if you didn't play them much).

White Player (W) makes a server, and a client Black Player (B) makes an automated client W encrypts data using some simple technique (xoring every character) B decompiles the original client or guesses encryption method and implements decryption in his automated client W makes the client always send his version to the server, and make it behave differently from version to version, then the server bans the client's IP if it doesn't act as expected for his version B either looks into original client and updates his bot regularly, or never played as W and doesn't understand part of data (verid=1.5.2) and loses the game.

Bots are usually not hard to make, though when an admin looks into logs, they're often obviously visible.
> 1 votes

# Answer
You should inspect the incoming and outgoing network traffic with programs like wireshark to detect wich information is sent or retrieves. But I believe this information could be encrypted...
> 0 votes

---
Tags: ai, client-server, online
---


# Question
Title: XNA frame rate spikes in full screen mode
I'm loading a simple texture and rotating it in XNA, and this works.

But when I run it in full screen 1920x1080 mode I see spikes while my texture is rotating.

If I run it windowed with 1920x1080 resolution, I don't get the spikes.

The size of the texture does not seem to matter, I tried 512 texture size and 2048 texture size, same thing happens. Spikes in full screen, no spikes in windowed, resolution does not seem to matter, Debug or Release does not seem to do anything either.

Anyone got ideas of what could be the problem?

**Edit:**

I think this problem has something to do with the vertical retrace. Set this property: `_graphicsDeviceManager.SynchronizeWithVerticalRetrace = false;`

you'll lose vsync but it will not stutter.

# Answer
> 2 votes
Use maximised border-less windows to 'simulate' fullscreen mode. I actually prefer games that have this option - it works MUCH better with multiple screens and there's no delay when alt-tabbing out. The main issue is that you can't minimise the game easily so it will cover the desktop unless you use the minimise shortcut or show desktop shortcut.

I use this code in my `Game.Initialize()` method to do it:

```
var myScreen = Screen.AllScreens[0]; // Change 0 for other screens

graphics.PreferredBackBufferWidth = myScreen.Bounds.Width;
graphics.PreferredBackBufferHeight = myScreen.Bounds.Height;
graphics.ApplyChanges(); // Not necessary, however this is a method in my code

Form gameForm = (Form)Form.FromHandle(Window.Handle);
gameForm.FormBorderStyle = FormBorderStyle.None;

gameForm.Left = myScreen.WorkingArea.Left;
gameForm.Top = myScreen.WorkingArea.Top;

```

I'm not sure if there's a performance hit, I haven't checked.

**EDIT:**

If you want to come out of this mode you need to do this:

```
Form gameForm = (Form)Form.FromHandle(Window.Handle);
gameForm.FormBorderStyle = FormBorderStyle.Sizable;

gameForm.Icon = System.Drawing.Icon.ExtractAssociatedIcon(
    Process.GetCurrentProcess().ProcessName + ".exe");
// IMPORTANT - XNA loses it's icon when going from no border back to having a border

graphics.PreferredBackBufferWidth = 800;
graphics.PreferredBackBufferHeight = 600;
graphics.ApplyChanges();

```

# Answer
> 2 votes
A potential explanation found in a Steam forum of all places.

> It's a bug in XNA framework's fixed timestep code. I have the same problem.
>
> Only way developers will fix this issue is that they don't use XNA's fixed timestep loop for PC version of the game. They have to make their own fixed step gameloop, but it's really easy to do.
>
> Even official XNA code samples that use XNA's fixed step, stutter on my computer in fullscreen.

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


# Question
Title: Does XNA 4 support 3D affine transformations for 2D images?
Looooong story short I'm essentially trying to code Mode 7 in XNA. Before I continue bashing my brains out in research and various failed matrix math equations; I just want to make sure that XNA supports this just out-of-the-box (so to speak).

I'd prefer not to have to import other libraries, because I want to learn how it works myself that way I understand the whole thing better. However that's all for naught if it won't work at all. So no opengl, directx, etc if possible (will eventually do it just to optimize everything, but not for now).

tl;dr: Can I has Mode 7 in XNA?

# Answer
You can pass an arbitrary 4x4 matrix to `SpriteBatch.Begin` (MSDN) - it doesn't even have to be affine (but it can be if you leave the extra elements set to the identity matrix). This transformation will be applied to all the sprites that you draw within that batch.

You can build the matrix by hand, or use the helpful `Create*` methods on the `Matrix` type (MSDN). I think for the classic perspective plane effect you need to create the matrix by hand - I'll let you figure out the actual maths involved ;)

(Just remember that XNA's `Matrix` type is row vector, `M41` and `M42` are the X and Y translation elements.)

Remember that `SpriteBatch` draws its sprites, by default and after transformation, in "client space" - (0,0) in the top left, (width,height) in the bottom right. But you can have a completely arbitrary projection by using a custom effect \- this is actually easier if you're trying to draw sprites in 3D space, because you can just use a real perspective projection matrix (instead of the built-in orthographic client one) and you can use the built-in creation methods.
> 2 votes

---
Tags: xna, 3d, matrix
---


# Question
Title: Predictive firing (in a tile-based game)
I have a (turn-based) tile-based game, in which you can shoot at entities.

You can move around with mouse and keyboard, it's all tile-based, except that bullets move "freely".

I've got it all working just fine except that when I move, and the creatures shoot towards the player, they shoot towards the previous tiles.. resulting in ugly looking "miss hits" or lag.

I think I need to implement some kind of predictive firing based on the bullet speed and the distance, but I don't quite know how to implement such a thing...

Here's a simplified snip of my firing code.

```
class Weapon {

public void fire(int x, int y) {
  ...
  ...
  ...
  Creature owner = getOwner();
  Tile targetTile = Zone.getTileAt(x, y);

  float dist = Vector.distance(owner.getCenterPosition(), targetTile.getCenterPosition());

  Bullet b = new Bullet();
  b.setPosition(owner.getCenterPosition());

  // Take dist into account in the duration to get constant speed regardless of distance
  float duration = dist / 600f;

  // Moves the bullet to the centre of the target tile in the given amount of time (in seconds)
  b.moveTo(targetTile.getCenterPosition(), duration);

  // This is what I'm after
  // Vector v = predict the position
  // b.moveTo(v, duration);

  Zone.add(bullet); // Now the bullet gets "ticked" and moveTo will be implemented
  }
}

```

Movement of creatures is as simple as setting the position variable.

If you need more information, just ask.

# Answer
> 6 votes
At its core you are going to have to predict which tile the target will be on.

A simple solution would be to take the current velocity of the target, figure out where the target would be in the amount of time it would take the bullet to traverse to the player (to get a rough estimate you could use the current distance to the target), and then aim at that tile.

# Answer
> 4 votes
Sounds like `ballistics` technology in Age of Empires. You need to find the correct angle of fire.

```
         A
        | \\
        |  \ \
        |   \  \
        | vb \   \
        |     \   \
        |      \    \
        D------ B--->C
                vp

Here A = enemy
B = player current position
C = player future position
vb = speed of bullet
vp = speed of player

```

Hope you understood the graph. If I got the problem correct, then your enemy is shooting at B, but you want it to shoot at C.

```
Let angle(DAB) = o
angle(DAC) = p

```

Clearly,

```
vb*sin(o) + vp = vb*sin(p)
p = inv_sin( sin(o) + vp/vb )

```

Here is the angle you needed to shoot.

**NOTE**

I does not depend on the distance between enemy and player

---
Tags: mathematics
---


title: Alpha blend 3D png texture in XNA

text:
# Question
Title: Alpha blend 3D png texture in XNA
I'm trying to draw a partly transparent texture a plane, but the problem is that it's incorrectly displaying what is behind that texture.

Pseudo code:

```
vertices1
basiceffect1
// The vertices of vertices1 are located BEHIND vertices2

vertices2
basiceffect2
// The vertices of vertices2 are located IN FRONT vertices1

GraphicsDevice.Clear(Blue);
PrimitiveBatch.Begin();

//if I draw like this:
PrimitiveBatch.Draw(vertices1, trianglestrip, basiceffect1)
PrimitiveBatch.Draw(vertices2, trianglestrip, basiceffect2)
//Everything gets draw correctly, I can see the texture of vertices2 trough
//the transparent parts of vertices1

//but if I draw like this:
PrimitiveBatch.Draw(vertices2, trianglestrip, basiceffect2)
PrimitiveBatch.Draw(vertices1, trianglestrip, basiceffect1)
//I cannot see the texture of vertices1 in behind the texture of vertices2
//Instead, the texture vertices2 gets drawn, and the transparent parts are blue
//The clear color

PrimitiveBatch.Draw(vertice
PrimitiveBatch.End();

```

My question is, Why does the order in which I call draw matter?

**Edit: Added screenshots**

It's like there is no Z buffering at all. this is done with: `GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;` I've tried other settings but they don't help

Edit: I think I have to somehow set the BlendState of the graphic card in some way so that the textures behind other textures get rendered.

# Answer
The rendering depends mainly on two things:

* spatial configuration (z-buffer configuration) - closest fragment is written to output pixel usualy
* blending settings (there is a lot of possible blending configurations)

If you render your planes with same Z-depth, you can experience some z-fighting problems. GPU usualy performs some optimalization in rendering pipeline - for example early Z termination. This could sometimes imply unexpected results...

From what you've posted it's not clear, what shader code are you using and what are the depth buffer and blending states.

(For me it seems that one of the effects (shaders) used (basiceffect1, basiceffect2) is discartign fragments while the other does not...)

But in general: the rendering order MATTERS when handling transparency...
> 2 votes

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


title: box2d tween what am I missing

text:
# Question
Title: box2d tween what am I missing
I have a Box2D project and I want to tween an kinematic body from position A, to position B. The tween function, got it from this blog:

```
function easeInOut(t , b, c, d ){
    if ( ( t /= d / 2 ) < 1){
        return c/2 * t * t * t * t + b;
    }
    return -c/2 * ( (t -= 2 ) * t * t * t - 2 ) + b;
}

```

where t is the current value, b the start, c the end and d the total amount of frames (in my case). I am using the method introduced by this lesson of todd's b2d tutorials to move the body by setting its linear Velocity

so here is relevant update code of the sprite:

```
if( moveData.current == moveData.total ){
        this._body.SetLinearVelocity( new b2Vec2() );
        return;
    }

    var t = easeNone( moveData.current, 0, 1, moveData.total );

    var step = moveData.length / moveData.total * t;

    var dir = moveData.direction.Copy();

    //this is the line that I think might be corrected
    dir.Multiply( t * moveData.length * fps /moveData.total ) ;

    var bodyPosition = this._body.GetWorldCenter();

    var idealPosition = bodyPosition.Copy();
        idealPosition.Add( dir );

    idealPosition.Subtract( bodyPosition.Copy() );

    moveData.current++;

    this._body.SetLinearVelocity( idealPosition );

```

`moveData` is an Object that holds the global values of the tween, namely:

* current frame (int),
* total frames (int),
* the length of the total distance to travel (float)
* the direction vector (targetposition - bodyposition) (b2Vec2) and
* the start of the tween (bodyposition) (b2Vec2)

Goal is to tween the body based on a fixed amount of frames: in `moveData.total` frames.

The value of `t` is always between 0 and 1 and the only thing that is not working correctly is the resulting distance the body travels.

I need to calculate the multiplier for the direction vector. What am I missing to make it work??

Greetings philipp

# Answer
I have got it working now! I just missed one vector difference and one multiplication.

here is the code:

```
function moveFocused( center, bbox ){
    var moveData;
    if( ! this._animationData.hasOwnProperty( 'moveFocus' ) ){
        this._body.SetLinearVelocity( new b2Vec2() );
        setBodyType.call( this, b2Body.b2_kinematicBody );
        var m = this._animationData[ 'moveFocus' ] = {};
        m.start = this._body.GetWorldCenter().Copy();
        m.direction = new b2Vec2( center.x - m.start.x, center.y - m.start.y );
        m.current = 1;
        m.total = 10;
    }

    moveData = this._animationData.moveFocus;

    if( moveData.current == moveData.total + 1 ){
        this._body.SetLinearVelocity( new b2Vec2() );
        return;
    }

    var t = easeInOut( moveData.current, 0, 1, moveData.total );

    var sEnd = moveData.direction.Copy();
        sEnd.Multiply( t );
        sEnd.Add( moveData.start.Copy() );

    var sStart = this._body.GetWorldCenter();

        sEnd.Subtract( sStart );
        sEnd.Multiply( fps );

    moveData.current++;

    this._body.SetLinearVelocity( sEnd );
}

```

the fun is the line where `t` get calculated, because there the tween functions come into play and it is possible exchange them against each other, what makes it very easy to test different easing.

Btw: It is working for dynamic bodies too.
> 4 votes

---
Tags: box2d, tweening
---


# Question
Title: Xbox thumbstick used to rotate sprite, basic formula makes it "stick" or feel "sticky" at 90 degree intervals! How do you get smooth rotation?
I am using a very basic formula to calculate what angle my sprite (spaceship for example) should be facing based on the Xbox controller thumbstick i.e. you use the thumbstick to rotate the ship.

In my main update method:

```
shuttleAngle = (float) Math.Atan2(newGamePadState.ThumbSticks.Right.X, newGamePadState.ThumbSticks.Right.Y);

```

In my main draw method:

```
spriteBatch.Draw(shuttle, shuttleCoords, sourceRectangle, Color.White, shuttleAngle, origin, 1.0f, SpriteEffects.None, 1);

```

As you can see it's quite simple, I take the current radians from the thumbstick and store it in a float `shuttleAngle` and then use this as the rotation angle (in radians) argument for drawing the shuttle.

For some reason when I rotate the sprint it feels sticky at 0, 90, 180 and 270 degrees angles. It wants to settle at those angles. It's not giving me a smooth and natural rotation like I would feel in a game that uses a similar mechanic. PS: My Xbox controller is fine!

# Answer
> 20 votes
It might be because of how the GamePad's deadzone works. It defaults to `GamePadDeadZone.IndependentAxes`, which means each axis is checked against the dead zone individually. This tends to cause the input to snap to each axis of the analog thumbstick. Instead, try using `GamePadDeadZone.Circular`:

```
newGamePadState = GamePad.GetState(playerIndex, GamePadDeadZone.Circular);

```

This should give you much smoother control on both axes. Check out the MSDN page and this article by Shawn Hargreaves.

---
Tags: xna, c#, sprites, rotation, gamepad
---


title: Off center projection

text:
# Question
Title: Off center projection
I'm trying to implement the code that was freely given by a very kind developer at the following link:

http://forum.unity3d.com/threads/142383-Code-sample-Off-Center-Projection-Code-for-VR-CAVE-or-just-for-fun

Right now, all I'm trying to do is bring it in on one camera, but I have a few issues. My class, looks as follows:

```
using UnityEngine;
using System.Collections;

public class PerspectiveOffCenter : MonoBehaviour
{

    // Use this for initialization
    void Start () {

    }

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

    }

    public static Matrix4x4 GeneralizedPerspectiveProjection(Vector3 pa, Vector3 pb, Vector3 pc, Vector3 pe, float near, float far)
    {
        Vector3 va, vb, vc;
        Vector3 vr, vu, vn;

        float left, right, bottom, top, eyedistance;

        Matrix4x4 transformMatrix;
        Matrix4x4 projectionM;
        Matrix4x4 eyeTranslateM;
        Matrix4x4 finalProjection;

        ///Calculate the orthonormal for the screen (the screen coordinate system
        vr = pb - pa;
        vr.Normalize();
        vu = pc - pa;
        vu.Normalize();
        vn = Vector3.Cross(vr, vu);
        vn.Normalize();

        //Calculate the vector from eye (pe) to screen corners (pa, pb, pc)
        va = pa-pe;
        vb = pb-pe;
        vc = pc-pe;

        //Get the distance;; from the eye to the screen plane
        eyedistance = -(Vector3.Dot(va, vn));

        //Get the varaibles for the off center projection
        left    = (Vector3.Dot(vr, va)*near)/eyedistance;
        right   = (Vector3.Dot(vr, vb)*near)/eyedistance;
        bottom  = (Vector3.Dot(vu, va)*near)/eyedistance;
        top     = (Vector3.Dot(vu, vc)*near)/eyedistance;

        //Get this projection
        projectionM = PerspectiveOffCenter(left, right, bottom, top, near, far);

        //Fill in the transform matrix
        transformMatrix = new Matrix4x4();

        transformMatrix[0, 0] = vr.x;
        transformMatrix[0, 1] = vr.y;
        transformMatrix[0, 2] = vr.z;
        transformMatrix[0, 3] = 0;

        transformMatrix[1, 0] = vu.x;
        transformMatrix[1, 1] = vu.y;
        transformMatrix[1, 2] = vu.z;
        transformMatrix[1, 3] = 0;

        transformMatrix[2, 0] = vn.x;
        transformMatrix[2, 1] = vn.y;
        transformMatrix[2, 2] = vn.z;
        transformMatrix[2, 3] = 0;

        transformMatrix[3, 0] = 0;
        transformMatrix[3, 1] = 0;
        transformMatrix[3, 2] = 0;
        transformMatrix[3, 3] = 1;

        //Now for the eye transform
        eyeTranslateM = new Matrix4x4();

        eyeTranslateM[0, 0] = 1;
        eyeTranslateM[0, 1] = 0;
        eyeTranslateM[0, 2] = 0;
        eyeTranslateM[0, 3] = -pe.x;

        eyeTranslateM[1, 0] = 0;
        eyeTranslateM[1, 1] = 1;
        eyeTranslateM[1, 2] = 0;
        eyeTranslateM[1, 3] = -pe.y;

        eyeTranslateM[2, 0] = 0;
        eyeTranslateM[2, 1] = 0;
        eyeTranslateM[2, 2] = 1;
        eyeTranslateM[2, 3] = -pe.z;

        eyeTranslateM[3, 0] = 0;
        eyeTranslateM[3, 1] = 0;
        eyeTranslateM[3, 2] = 0;
        eyeTranslateM[3, 3] = 1f;

        //Multiply all together
        finalProjection = new Matrix4x4();
        finalProjection = Matrix4x4.identity * projectionM*transformMatrix*eyeTranslateM;

        //finally return
        return finalProjection;
    }

    // Update is called once per frame

    public void FixedUpdate ()
    {
        Camera cam = camera;

        //calculate projection
        Matrix4x4 genProjection = GeneralizedPerspectiveProjection( new Vector3(0,1,0), new Vector3(1,1,0), new Vector3(0,0,0), new Vector3(0,0,0), cam.nearClipPlane, cam.farClipPlane);
                                                                //(BottomLeftCorner, BottomRightCorner, TopLeftCorner, trackerPosition, cam.nearClipPlane, cam.farClipPlane);
        cam.projectionMatrix = genProjection;

    }
}

```

My error lies in `projectionM = PerspectiveOffCenter(left, right, bottom, top, near, far);`

The debugger states:

> Expression denotes a \`type', where a 'variable', 'value' or 'method group' was expected.

Thus, I changed the line to read: `projectionM = new PerspectiveOffCenter(left, right, bottom, top, near, far);`

But then the error is changed to:

> The type 'PerspectiveOffCenter' does not contain a constructor that takes '6' arguments.

For reasons that are obvious.

So, finally, I changed the line to read: `projectionM = new GeneralizedPerspectiveProjection(left, right, bottom, top, near, far);`

And the error I get is:

> is a 'method' but a 'type' was expected.

With this last error, I'm not sure what it is I should do / missing. Can anyone see what it is that I'm missing to fix this error?

# Answer
You're trying to complete the method `GeneralizedPerspectiveProjection()` I'm pretty sure trying to use `GeneralizedPerspectiveProjection()` within that method is a poor choice. I dodn't see anything to indicate that this was a recursive method.

Here's your problem:

```
public class PerspectiveOffCenter : MonoBehaviour

```

Your class is named `PerspectiveOffCenter`. Then when you're trying to run the code you pasted in you're getting the following error:

> The type 'PerspectiveOffCenter' does not contain a constructor that takes '6' arguments.

From the code you've shown, it clearly doesn't contain a constructor that takes *any* arguments, let alone six. You said "For reasons that are obvious." But, I'm not sure they were obvious to you.

**Your code is incomplete.** You copied an pasted without checking that everything was included. You need to find or create a proper constructor for your class if you want to use that code. A quick Google search yielded this. But I don't know if that's the same code the original author used or not. You'll have to ask them, or figure out what's required based on your current code and write it yourself.
> 0 votes

---
Tags: unity, projection
---


# Question
Title: Issue with distinguishing levels in isometric game
> **Possible Duplicate:**
> How can I change this isometric engine to make it so that you could distinguish between blocks that are on different planes?

I'm working on an isometric game however I am having trouble visually distinguishing between levels in the game.

Take the example below, the first image shows concrete blocks at ground level and the following images show an attempt to build a few blocks a level above. As you can see the level above is visually swallowed the one below.

I've tried shading to make lower levels darker with respect to camera, but this doesn't work that well.. any ideas?

# Answer
> 10 votes
Try highlighting the edges of elevated blocks to illustrate the difference in depth.

Like so:

---
Tags: 2d, graphics, isometric, graphics-design
---


title: Pass large array to pixel shader

text:
# Question
Title: Pass large array to pixel shader
I am trying to write a Pixelshader for a curve effect in Direct2d.

A curve effect maps each color channel value to a different value by using a look up table.

For this effect I would need to pass 3 arrays to the effect. Each array has 256 entries to map the specific color channel.

How can I pass these arrays to a Pixel shader (i.e. Direct2d Effect)?

# Answer
> 3 votes
You can pass arrays as 1D textures (which usually are 2D textures with height set to 1). Or 2D, if you need to store more than 2048/4096/8192 items - depending on graphics card. A 1D texture look-up is done by dividing array index by array size and then aligned to pixel centers with the required offsets. A 2D texture look-up is about the same, the only difference being texture coordinate calculation from array index - it's something like this with 2D textures:

```
float2 texcoord = ( float2( array_index % texture_width, array_index / texture_height ) + texel_offset ) / float2( texture_width, texture_height );

```

---
Tags: hlsl, directx10
---


# Question
Title: UVW Unwrap multiple quads on same texture space automatically
I've been looking around the web for the answer to this question, but to no avail. So here I go.

I'm looking for a way to automatically map several quads on the same texture space (for example (0,0) ~ (0.4,0.4)) using the UVW unwrapper modifier of Max (or something else).

Here is a quick (and dirty) graphical explanation (click for larger):

# Answer
> 2 votes
In the edit UV's we have flatten mapping, make sure you check down all the three boxes and click ok. This will adjust your UV's automatically in the texture space.

But from your image, it seems like you are texturing a track or road something like that. If in that case, i suggest you to follow this tutorial. Explains how to texture road/race track using tilable texture.

http://3dlad.com/how-to-texture-unwrap-a-race-track/

---
Tags: 3d, 3dsmax, uv-mapping
---


# Question
Title: Get blocky look on textures some textures
If I do this:

`GraphicsDevice.SamplerStates[0] = SamplerState.PointWrap;`

All textures I draw are blocky.

`GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;`

All of my textures are blurred a bit.

What do I have to do so that only some of my textures are blocky and some are blurred?

# Answer
> 2 votes
You would need to use two separate sprite batches for each type of drawing. One for the blocky. One for the blurry.

Use this overloaded method when you begin your sprite batch:

```
SpriteBatch.Begin (SpriteSortMode, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)

```

The result should look something like this:

```
SpriteBatch.Begin (SpriteSortMode.Deferred, nil, SamplerState.PointWrap, nil, nil, nil);
//SpriteBatch.Draw(**blocky stuff**);
SpriteBatch.End ();

SpriteBatch.Begin (SpriteSortMode.Deferred, nil, SamplerState.LinearWrap, nil, nil, nil);
//SpriteBatch.Draw(**blurry stuff**);
SpriteBatch.End ();

```

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


# Question
Title: Lua or C# beneficial over C++ for small, single person project?
I plan to do a fairly small game development project as a single programmer. I have read that alternatives to C++ such as C# or integrating Lua scripts is more time and effort efficient in development.

Why is C# easier to work with (if it even is), and what benefits does Lua offer (as well as why)?

# Answer
Choose a language based on what you are personally interested in using. especially since this is a single-person project. You could write the whole thing in C++ and be fine. You could also write the whole thing in C#. You could also use something like Corona or Love2D and write the whole thing in Lua.

A common pattern is to write low-level and speed-critical game code in C++, and wrap this up into a higher level API with a scripting language. Lua is a common choice because it has a lightweight runtime and flexible syntax. The reason that an integrated scripting language is more time/effort-efficient is because you don't have to spend the time recompiling your game engine. In fact, you could feasibly load game scripts while the game is still running, constantly tweaking them as they game runs.

C# with Mono has made headway as a scripting language thanks to Unity. C# will generally have faster execution time overall since it's JIT-compiled, but these things always depend on the use case.

Since C#/.NET/Mono is so fast, it's also common for people to just write their whole game in C# using frameworks and libraries like XNA, MonoGame, or OpenTK. You can also use a language that targets .NET IL code and write a lot of game logic in a non-C# language such as IronPython, IronRuby, F#, or Boo. If you go the route of C#/.NET, it's often viewed that a scripting language integration is not necessary. C# on its own is very expressive, and you could always use a more dynamic language like IronPython to write higher level game logic.

You can also consider Java (as your "native" language, it's not very good for embedding). The same principle of targetting the VM from C# (C# vs IronPython vs F#, etc.) works with Java (except you're looking at Scala and Clojure).

### C# Advantages

* Garbage collection frees you from concern about memory management
* The standard library is very very large. Not Java-large, but that's probably a good thing.
* Linq makes data processing pain-free.
* Lambda expressions standard part of the language
* XNA is a very nice framework

### C++ Advantages

* As fast as you can hope to get.
* Explicit control over memory.
* A large variety of game libraries are implemented in C++.
* The lingua franca of commercial games (good "career language" to get employment as a game programmer)
* Explicit control over your memory cannot be overstated.

### Lua Advantages

* A very flexible language. Although no support for "classes" right out of the box, tables are a rich mechanisms for rolling your own.
* Relatively easy to integrate into an existing game engine (compared to say, Python or C#/Mono)
* A very small core library and runtime.
* Fairly standard, used by a lot of big game companies in addition to UnrealScript and Python.
* LuaJIT is supposed to be really really fast.

### Other scripting languages in the same vein as Lua

These also see common use as scripting languages.

(Anyone with more experiences with other scripting languages or the ones listed here, please edit.)
> 3 votes

# Answer
C# and Java are managed languages. They take care of memory management for you. Though the main selling point is that they offer much more support when it comes to standard libraries compared to C++. If you're alone and you're making a simple project, then these languages will offer you portability and ease of development. Developing in C# and Java is much easier than C++ **unless** you need your code to perform perfectly. The lack of const types, or template metaprogramming makes developing complex code much easier under C++. Benchmarking C++ is **much** easier aswell. It's all up to you. As a one man project i daubt that you need this kind of code quality and the minimal performance gains you'll get by writing custom memory allocation and other such hassle. C# and Java are perfect candidates.

Now the reason you use LUA is the same as using any other scripting langauge. You want to make your program do something without recompiling it. Scripts let you do that. You can tweak objects in game like AI or hotspots without waiting 10 minutes for your code to compile. This is why scripting is said to be speeding up development. However, this is for big projects, if you're making a game by yourself then between pressing "Run" and seeing your game window you'll be waiting maybe 30 seconds. Implementing scripting is an interesting excercise, but probably not necessary in your case.

Other alternatives would be HTML5/CSS3/JavaScript and Flash. For HTML5 all you need is a browser preferably Chrome or Firefox with the Firebug plug-in. It's a scripting langauge like LUA, so you get instant feedback, you can alter your code on the fly, etc. Besides you learn alot about web technologies. The technology is still brand new, so it has its problems. Flash is more mature, still faster and works, but requires an IDE.
> 1 votes

# Answer
The difference is just in how hard it is too learn, C++ is one of the hardest practical languages out there.

Lua is a purely embedded language and the API is customized by every game, it's easy to mod a game which is using Lua, but making your own game using Lua isn't. It only pays of when you have a lot content.
> 0 votes

# Answer
Lua wouldn't be the most efficient language to use. It's got lots of things you will find it hard to get used to (like array indices that start from 1 and the requirement to handle many different argument setups in each exposed function, as well as lack of IDE function-name-guessing support). It might work well if you can memorize things easily.

The reason people say things like "using Lua is more efficient than using only C++" is because Lua is a scripting language so you don't have to wait a lot of time for it to recompile when you change something. Well, the same is true for a C++ project if you don't use too much of STL (limit yourself to string, vector and map and/or unordered\_map) and don't use Boost at all and don't use any engines which have lots of those headers included. You can most probably enable a header dump in compile options to see what is included. This is how you can do it for MSVC.

Now for the C++ vs. C# problem: people often pick C# as if it's going to save their life but unfinished projects and all sorts of other problems happen either way. For this choice, it's all about what you like to do - whether you like to be closer to metal and fight memory allocation correctness (C++) or have all sorts of things handled for you, if you can endure the extra typing, annoying exceptions and compiler errors appearing in place of simple features like using an integer like a boolean (C#).

If it's a project you need to finish quickly, I'd recommend looking at the toolsets available, picking the best (no matter what programming language it works on) and forgetting about the language dilemma.
> 0 votes

---
Tags: c++, software-engineering, scripting
---


# Question
Title: Does every Entity in an XNA game need it's own BasicEffect instance?
From what I see, the position/matrix is stored in the BasicEffect instance, so it makes sense to me that every object has it's own position matrix, but I'm not 100% sure it's correct to let every Entity have it's own BasicEffect instance, so I'm asking here.

# Answer
**Probably not. But you could...**

First of all, you'll note that `BasicEffect` in fact has 3 matrices: World, View, and Project. World is per-object. But view and project are per-camera - so these should not be duplicated in different places around your program (for reasons of maintainability).

Secondly: You should usually treat states that go onto the GPU as write-only. The upshot of this is that you generally store the information to generate those states (such as effect parameters) yourself - in your own classes. Then, for each object you draw, you generate the appropriate state and set it on the GPU and follow it up with a draw call.

So with a single, shared `BasicEffect`, what you'll usually do is set the projection matrix once at the start of your game. Then set the view matrix at the start of each frame. And then set the world matrix right before you draw each object.

But - there *are* scenarios where you might want an `Effect` for each object. For example: you might have completely different settings for different objects. But at the same time - you still don't want to waste GPU resources by having multiple copes of the same effect program in existence.

To solve this, use the `Effect.Clone` method (MSDN), which gives you a copy of the `Effect` object that *shares* the underlying GPU resources.

(Note, of course, that `BasicEffect` is an `Effect`.)
> 3 votes

# Answer
BasicEffect is shader program. So it is resource it must be single( to save memory etc). And parameters are passed same as in function.
> 2 votes

# Answer
You have different WVP matrices for each object. But you can create a single `BasicEffect` instance to render all the objects. You just have to make sure that before rendering, you assign the correct matrices to the `BasicEffect` properties.

```
for every object
{
    basicEffect.World = obj[i].world;
    basicEffect.View = obj[i].view;
    basicEffect.Projection = obj[i].projection;
    GraphicsDevice.SetVertexBuffer(obj[i].vertexBuffer);
    foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
    {
        pass.Apply();
        GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 1);
    }
}

```

Check this
> 1 votes

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


# Question
Title: How to get distance from point to line with distinction between side of line?
I'm making a 2d racing game. I'm taking the nice standard approach of having a set of points defining the center of the track and detecting whether the car is off the track by detecting its distance from the nearest point. The nicest way I've found of doing this is using the formula:

d = |Am + Bn + C| / sqrt(A^2 + B^2)

Unfortunately, to have proper collision resolution, I need to know which side of the line the car is hitting, but I can't do that with this formula because it only returns positive numbers.

So my question is: is there a formula that will give me positive or negative numbers based on which side of the line the point is on? Can I just get rid of the absolute value in the formula or do I need to do something else?

# Answer
you could multiply to the formula the sign of the ***z*** component from the resulting cross product of two vectors ***v, w***.

given segment **s** with points **s1,s2** you compute.

***v*** = vector from **s1** to **car\_pos**.

***w*** = vector from **s1** to **s2**.

if the ***z*** component of the resulting vector ***r = v x w*** is positive then car is on the right, otherwise (z negative) the car is on the left. In practice you just need to compute the following:

```
float rz = v.x * w.y - w.x * v.y;
return (rz > 0);

```

These types of methods are known as predicates in the field of computational geometry. In particular, this one is known as **is\_left(segment s, point p)** or equivalently **is\_right(segment s, point p)**.
> 4 votes

# Answer
```
// l1 - line start, l2 - line end, x - point
// perp() returns vec2(y,-x)  -- a perpendicular vector
// dot() returns v1.x * v2.x + v1.y * v2.y  -- it's the 2D vector dot product
// normalized() returns vec2(x/length,y/length), where length = sqrt(x*x+y*y)
ln = ( l2 - l1 ).perp().normalized();
distance = dot( ln, x ) - dot( ln, l1 );
// positive distance means that point's on the left side, negative - on the right

```

Note: this assumes screen-space axis directions, not the mathematical (Y+ points down, not up).

"ln" is the line normal - a normalized vector that points away from line and is perpendicular to it. The "perp" function returns the vector, turned 90 degrees counter-clockwise.

Both "dot" functions return projections of points on an axis that is defined by the line normal. "distance" is a subtraction of those projections, which makes it a distance from an infinite version of the line defined by the two points "p1" and "p2".

Now it wasn't clearly defined whether you need a finite or an infinite line (and if this, what kind of infinite). I initially assumed infinite so... this code works with all kinds of "infinite" - you really need one point and the line normal to use this method.
> 1 votes

# Answer
Consider the line with two points A `(xa, ya)` and B `(xb, yb)` and the line `y = m*x + c`

```
yb      B    /
|       |   /
y1      |  /|
|       | / |
y2      |/  |
|       /   |
|      /    |
ya    /     A
|    /
|   /
|------xb---xa-----------

```

To check at which side the point lies, you can just compare the y-coordinates of the point with that of line at same x position.

For A,

```
y1 = m*xa + c
y1 > ya

```

For B,

```
y2 = m*xb + c
y2 < yb

```

Then you can know to which side does the point belong.
> 0 votes

---
Tags: collision-detection, geometry, mathematics
---


title: OpenGL Lighting

text:
# Question
Title: OpenGL Lighting
I have a simple day and night cycle by at day disabling OpenGL lighting and at night enabling openGL Lighting. When I enable everything appears darker. My question is How would I make it that at a specific spot there would be a light that will only light up its surrounding area for example:

http://media.giantbomb.com/uploads/0/276/1414275-light\_large.png

Where the light is is where I want to position my light. **My application is in 2D.**

EDIT:

I read up more about 2D Lighting and I thought about it how would I do it so that I have a QUAD that is over all the screen and has a certain opacity and then i draw s circle on a QUAD that is yellow and it overwrites the quad so that the images that are drawn behind it aren't effected, like poking a hole in it..

# Answer
I would use a 2D lightmap and blend it using GL\_DST\_COLOR,GL\_ZERO and playing on opacity.

If you want a more complex thing look for projected texture using a shader :

```
// The vertex shader

varying vec4 pos;

void main(void){
  pos=vec4(gl_Vertex);
  gl_Position=ftransform();
}

// The fragment shader

uniform sampler2D inputImage;
varying vec4 pos;

void main(void){
gl_FragColor=texture2DProj(inputImage,gl_TextureMatrix[0]*pos);
}

```

Another solution is by using 3D lightmapping (if 3D textures are available on your platform), wich is also easy to implement.

I hope it helps :)
> 0 votes

# Answer
Another option is to perform per-pixel lighting in your pixel shaders. If you calculate vector L to light (in screenspace) for each fragment (and supposing fragment normal N is (0,0,1) in screenspace ) then modulate fragment color by some f(N, L). If you prefer some fancy shading model, you're free to implement one.

This solutions is not dependent on some texture resolution and is always smooth, but requires either additional post-process pass, or using this piece of shader to color each object with spot on it...
> 1 votes

---
Tags: opengl, 2d, java, lighting
---


# Question
Title: My grid based collision detection is slow
Something about my implementation of a basic 2x4 grid for collision detection is slow - so slow in fact, that it's actually faster to simply check every bullet from every enemy to see if the BoundingSphere intersects with that of my ship. It becomes noticeably slow when I have approximately 1000 bullets on the screen (36 enemies shooting 3 bullets every .5 seconds). By commenting it out bit by bit, I've determined that the code used to add them to the grid is what's slowest.

Here's how I add them to the grid:

```
for (int i = 0; i < enemy[x].gun.NumBullets; i++)
{
   if (enemy[x].gun.bulletList[i].isActive)
   {
      enemy[x].gun.bulletList[i].Update(timeDelta);

      int bulletPosition = 0;
      if (enemy[x].gun.bulletList[i].position.Y < 0)
      {
         bulletPosition = (int)Math.Floor((enemy[x].gun.bulletList[i].position.X + 900) / 450);
      }
      else
      {
         bulletPosition = (int)Math.Floor((enemy[x].gun.bulletList[i].position.X + 900) / 450) + 4;
      }

      GridItem bulletItem = new GridItem();
      bulletItem.index = i;
      bulletItem.type = 5;
      bulletItem.parentIndex = x;

      if (bulletPosition > -1 && bulletPosition < 8)
      {
         if (!grid[bulletPosition].Contains(bulletItem))
         {
            for (int j = 0; j < grid.Length; j++)
            {
               grid[j].Remove(bulletItem);
            }
            grid[bulletPosition].Add(bulletItem);
         }
      }

    }
}

```

And here's how I check if it collides with the ship:

```
if (ship.isActive && !ship.invincible)
{
   BoundingSphere shipSphere = new BoundingSphere(
    ship.Position, ship.Model.Meshes[0].BoundingSphere.Radius * 9.0f);
   for (int i = 0; i < grid.Length; i++)
   {
   if (grid[i].Contains(shipItem))
   {
      for (int j = 0; j < grid[i].Count; j++)
      {
         //Other collision types omitted
         else if (grid[i][j].type == 5)
         {
            if (enemy[grid[i][j].parentIndex].gun.bulletList[grid[i][j].index].isActive)
            {
               BoundingSphere bulletSphere = new BoundingSphere(enemy[grid[i][j].parentIndex].gun.bulletList[grid[i][j].index].position,
               enemy[grid[i][j].parentIndex].gun.bulletModel.Meshes[0].BoundingSphere.Radius);
               if (shipSphere.Intersects(bulletSphere))
               {
                   ship.health -= enemy[grid[i][j].parentIndex].gun.damage;
                   enemy[grid[i][j].parentIndex].gun.bulletList[grid[i][j].index].isActive = false;
                   grid[i].RemoveAt(j);

                   break; //no need to check other bullets

                }
             }
             else
             {
                grid[i].RemoveAt(j);
             }
          }

```

What am I doing wrong here? I thought a grid implementation would be faster than checking each one.

# Answer
> 1 votes
Here you have created a new instance of bulletItem... OK, but see later...

```
  GridItem bulletItem = new GridItem();

```

Check if grid doesn't contains bulletItem... NOT OK, Why? The line above, you have made an new instance of bulletItem, it is 100% guaranteed not to be in any grid and so no need to check if it in any grid. The for next loop will never succeed in Remove() either, so...

```
     if (!grid[bulletPosition].Contains(bulletItem))
     {
        for (int j = 0; j < grid.Length; j++)
        {
           grid[j].Remove(bulletItem);
        }
        grid[bulletPosition].Add(bulletItem);
     }
  }

```

May as well just be...

```
 grid[bulletPosition].Add(bulletItem);

```

Instead of doing

```
 else if (grid[i][j].type == 5)
 {
      if (enemy[grid[i][j].parentIndex].gun.bulletList[grid[i][j].index].isActive)
      ...e.t.c...

```

do

```
 GridItem bulletItem = grid[i][j];
 else if (bulletItem.type == 5)
 {
      if (enemy[bulletItem.parentIndex].gun.bulletList[bulletItem.index].isActive)
      ...e.t.c...

```

Not only is it more readable, depending on how smart the compiler is, it may end up recalculating the pointer to grid\[i\]\[j\] each time you reference it.

Instead of creating a new instance of BoundingSphere within the loop which requires allocating memory each time

```
 BoundingSphere bulletSphere = new BoundingSphere(.....)

```

Can you not create 1 instance at the very top and let all bullets share the same instance? You should be able to call a method to set bound for each bullet you wish to check. Doing it as you are currently doing means each time you create an instance will call the memory manager to allocate memory which takes a bit of processing time, there is no need to create what could be like 100+ instances and fragmenting the memory quickly. Also, not sure how memory management works, it is automatically garbage collected? If not, make sure you are deleting them when you finish with them.

Is

```
  for (int j = 0; j < grid[i].Count; j++)
  {

```

Counting the actual number each time or it is a constant? For example, the following may be quicker.

```
  int c = grid[i].Count;
  for (int j = 0; j < c; j++)
  {

```

Instead of

```
for (int i = 0.....
if (grid[i].Contains(shipItem))
{

```

Do something like

```
int i = shipItem.gridIndex;

```

which is basically a cross reference to which grid the shipItem is currently in, it saves having to loop what could essentially be up to 1,000 times just to find it.

# Answer
> 0 votes
My guess is that the slowness comes from this "adding objects to a grid" thing. This is not the "grid implementation" as everyone knows it because such grid implementations usually include only one native (or smaller, like a few bits) value per grid cell. How you use it is totally up to you. However, there must be no nested arrays or anything as horrible as that.

So in this case, I don't see a good reason why a grid should be used.

---
Tags: xna, collision-detection, optimization
---


# Question
Title: Playing a death anim on an enemy that I want to remove
I've been trying to find a tutorial on how to best make animations in Android. I already have some animations for my enemies and my character that are controlled by rectangles and changing rectangleframe between updates using a picture like this:

When I'm shooting my enemies they lose HP, and when their HP == 0 they get removed. As long as I'm using an `arrayList` (which I do for all enemies and bullets) I'm fine, since I can just use `list.remove(i)`. But when I'm on a boss-level and the Boss's HP == 0, I want to remove him and play an animation of an explosion of stars before the "End-screen". Is there a preferred way to do temporary animations like this?

If you can give me an example or redirect me to a tutorial, I'd be really grateful!

# Answer
You could have a special kind of entity that plays an animation right upon creation, and auto-deletes when done with it. Just spawn it when you boss' health reaches 0.
> 5 votes

# Answer
Can't you associate an explosion sprite to your boss and play it when your `Boss_HP == 0`?
> 3 votes

# Answer
Android provides an Animation API that allows you to manipulate the properties of an object on the screen over a time interval. See http://developer.android.com/reference/android/animation/package-summary.html for a description of the API and http://www.vogella.com/articles/AndroidAnimation/article.html for a good tutorial.
> 0 votes

# Answer
It's probably not the most elegant thing in the world, but I accomplish this in the game by making a simple conditional.

```
if (enemy.isDead() && enemy.getCurrentFrame() == enemy.numberOfFrames())
     //Remove enemy

```

I'm sure there are better ways to do this, but this gets the job done for me with minimal effort.
> 0 votes

---
Tags: android, animation, timer
---


# Question
Title: Marching squares: Finding multiple contours within one source field?
Principally, this is a follow-up-question to a problem from a few weeks ago, even though this is about the algorithm in general without application to my actual problem.

The algorithm basically searches through all lines in the picture, starting from the top left of it, until it finds a pixel that is a border. In pseudo-C++:

```
int start = 0;
for(int i=0; i<amount_of_pixels; ++i)
{
   if(pixels[i] == border)
   {
      start = i;
      break;
   }
}

```

When it finds one, it starts the marching squares algorithm and finds the contour to whatever object the pixel belongs to.

Let's say I have something like this:

Where everything except the color white is a border.

And have found the contour points of the first blob:

For the general algorithm it's over. It found a contour and has done its job. How can I move on to the other two blobs to find their contours as well?

# Answer
Could you simply erase the polygon it's found by drawing it in the background colour and repeat until there's nothing left?
> 7 votes

# Answer
Check this:

http://en.wikipedia.org/wiki/Connected-component\_labeling After detecting blobs just apply marching squares alg to get the margins of each blob.

Bye Lo
> 2 votes

# Answer
why not save the blob information to another array and check if the newly found pixels fall within the bounding box of the earlier blob? Some more manipulation will be required to deal with blobs below the centriod of the earlier blob and which fall within the bounding box.
> 1 votes

---
Tags: 2d
---


# Question
Title: Is it legal to develop a game using D&D rules?
For a while now I've been thinking about trying my hand at creating a game similar in spirit and execution to Baldur's Gate, Icewind Dale and offshoots. I'd rather not face the full bulk of work in implementing my own RPG system - I'd like to use D&D rules.

Now, reading about the subject it seems there is something called "The License" which allows a company to brand a game as D&D. This license seems to be exclusive, and let's just say I don't have the money to buy it :p.

Is it still legal for me to implement and release such a game? Commercially or open-source? I'm not sure exactly which edition would fit the best, but since Baldur's Gate is based of 2nd edition, could I go ahead an implement that?

**in short: what are the issues concerning licensing and publishing when it comes to D&D?**

Also: Didn't see any similar question...

# Answer
You cannot brand your game as D&D, period. You used to be able to brand your game as being D20 System compatible provided you followed a number of stipulations, not the least of which is that you couldn't reproduce or include rules for character advancement (XP, gaining levels, etc.) which basically means a player of your game would need a copy of the D&D Player's Handbook to level up; obviously those requirements are not in any way geared towards computer games, and creating one that is in any way officially a part of the D&D universe is going to require you forking over boatloads of cash to WotC. However, when WotC released 4th Edition D&D, they withdrew the d20 License so you can no longer brand anything as d20. You can just take the 3rd edition rules under the OGL, so long as your rules are also under the OGL. I have no idea how that translates to non-print rules, though, and it may well just be fundamentally incompatible (ask a lawyer; programmer nerds won't be able to answer that for you).

You are basically free to use a ruleset that looks an awful lot like D&D at any time, though. Ever since the first computer RPG, D&D has been "ripped off" repeatedly, down to seeing obviously D&D-original mechanics like THAC0 showing up in a lot of old non-TSR-affiliated computer RPGs. You are legally obligated to avoid WotC trademarks (campaign setting names, iconic creatures like Beholders or Mind Flayers, etc.) and your rules cannot be a direct copy of the D&D source material. If you've got the same races with the same ability modifiers and the same feat tree and the same prestige classes, you're probably going to be in trouble. If you've got your own races and classes and a new "perk" tree and it just so happens that you have Primary Attributes that mathemtically work like D20's Ability Scores and a level advancement scheme that uses XP to gain levels and you get Primary Attribute increases every X levels and a new perk every Y levels and other class abilities each level... well, that's what just about every other combat-based RPG ever made has done and there's nothing WotC can do about it. A system that "feels" like D&D is one thing so long as nobody is going to look at it and think, "holy cow, that's D&D!"

I know it's not an answer to your question, but my advice is to just steer clear, if for the following reason only: different gaming mediums have different strengths and weaknesses, and the design choices and compromises made for one medium rarely make sense when transferred to another. D&D's rules work great in pen-and-paper games but do not work well in a computer game, an ARG or LARP, a card game, or so on. Even awesome classic D&D computer games like Baldur's Gate made a lot of subtle and not-so-subtle tweaks to the rules and even then still came out with worse experience than what could have been accomplished with a set of mechanics better suited to a point-and-click real-time dungeon crawler.

And really, inventing your own game mechanics isn't terribly hard in the grand scheme of things. If you can write a game like Baldur's Gate (something a team of fans working on GemRB has still yet to completely finish off even after years of work, and that's ignoring the development of any custom content!), you can absolutely write an RPG rule set. Doing so is going to take a tiny fraction of the time it'll take you to make the rest of the code and content for your game.
> 23 votes

# Answer
http://www.wizards.com/default.asp?x=d20/oglfaq/20040123i

This from the Wizards of the Coast website regarding OGL and software.

> Q: So I could make a game?
>
> A: Sure. Remember though, you cannot use any Product Identity with the OGL or claim compatibility with anything. So you can't say your game is a d20 System game or uses D&D rules or call it *Elminster's Undermountain Crawl*.

However further down the page they say you can't make an interactive game?! Huh?

> Key components of games are goals, rules, challenge, and **interaction**.

http://en.wikipedia.org/wiki/Game

Further however:

> Copyright does not protect the idea for a game, its name or title, or the method or methods for playing it. Nor does copyright protect any idea, **system**, method, device, or trademark material involved in developing, merchandising, or playing a game. **Once a game has been made public, nothing in the copyright law prevents others from developing another game based on similar principles.** Copyright protects only the particular manner of an author’s expression in literary, artistic, or musical form.
>
> Material prepared in connection with a game may be subject to copyright if it contains a sufficient amount of literary or pictorial expression. For example, the text matter describing the rules of the game or the pictorial matter appearing on the gameboard or container may be registrable.

From: Link

It appears that WoTC are fudging the legality a bit. You **can** make a game called Dungeons and Dragons (title) but it can't look like the dungeons and dragons title which is trademarked, or contain any other distinct likenesses of trademarked WotC elements, ie certain monsters, settings, characters.

WOTC might have patented the Dungeons and Dragons game system, but it appears that they have only patented the magic the gathering system, and all collectible trading card game systems somehow, not really sure how that works... http://search.usa.gov/search?utf8=%E2%9C%93&affiliate=web-sdmg-uspto.gov&query=wizards+of+the+coast&go=Go

It would also appear that they can't patent DnD rules, if they haven't already, as it appears you can't patent something after a year has passed since you released it publicly. http://boardgamegeek.com/thread/493249/mythbusting-game-design-and-copyright-trademarks-a

Most info I read though, says the guy with most lawyers wins. I'm gonna patent that system so every time someone with more lawyers wins, they need to pay me royalties.

As for WotC being overly litigious, the only examples I read were when some guy released early pics of their new MTG cards, one guy made a porno version of DnD using the d20 and WotC said we don't want that associated with d20 so he removed the d20 logo and released it under OGL, which differs from d20. http://en.wikipedia.org/wiki/D20\_System

Summary, you can make a dnd-like game using OGL even if it doesn't specifically allow games(if you ban an interactive game you effectively ban all games as interactivity is a key component of a game) but you would need to change the names of most identifiably DnD stuff. But the WotC website seems to confuse OGL with d20 trademarked system, so I also did initially. This may be intentional to dissuade people from making a computer game based on OGL.

You can make a game of any type based on OGL, but not on d20. Everything in these system reference documents(SRD) is OGL: http://www.wizards.com/default.asp?x=d20/article/srd35

More info: http://www.wizards.com/default.asp?x=d20/oglfaq/20040123d

Down the bottom they even say they can't copyright a game, and half-way down they say you can make any type of content using OGL. Main rule is you must identify clearly somewhere in your game distribution what content is OGL and you can't use the d20 content but the SRDs from the link above cover nearly every rule you need anyway.

BTW I'm making a game from the SRD in Unity. First step is a character generator which is mostly done.
> 8 votes

# Answer
You probably couldn't implement 2nd edition. But WotC was kind enough to release 3rd and 3.5 edition under what they called the "Open Gaming License", which is what basically allows RPGs like Pathfinder to exist. Basically, you can probably use the 3.5 edition *rules*, but without any of the setting details. So no Beholders, etc, nothing that is part of D&D setting-wise.

Now that doesn't guarantee legal cover, but Pathfinder is still around. If they're basically able to implement 3.5 (with modifications), you probably can too. Though the OGL *may* not cover videogames.

In any case, if you're worried about it, it really doesn't take much to just make the system sufficiently different. Start with it as a base, lose some ability scores, make a couple of new ones, change some feats, invent a few tables. It's not that hard. Plus, you'll likely make a better game if you're not hidebound to some edition of table-top D&D.
> 6 votes

# Answer
You can't implement a direct copy of the D&D rule set, there are however, open rule sets that have been created with the express purpose of being copied and modified for your own use. You can build a game system based on one of these free rule sets, or you can make your own.

You can check out Draft, it's a free RPG rule set.
> 1 votes

---
Tags: rpg, licensing
---


# Question
Title: How do I make an entity move in a direction?
I have an `Entity` instance which is updated every game tick. Let's just assume that entity moves forward constantly. I'd like to be able to give the entity's angle to a function that makes it move in that direction:

`moveForward(90);` should make them move to the right. If I declared my rotation as a global `int`, then doing

```
moveForward(rotation);
rotation++;

```

would make it trace a small circle with its movement.

How can I do this? I assume this involves vector math; I don't know any, so a brief explanation would be nice.

# Answer
Well in the simplest sense you have something like this.

```
   y  |\
      | \
   m  |  \         s
   o  |   \        p
   v  |(a) \       e
(y)e  |angle\      e
   m  |      \     d
   e  |       \
   n  |        \
   t  |         \
      |__________\
      x movement
        (x)

```

The speed is however fast the enemy is, and you can determine how much they should move in the x direction and how much they move in the y direction by taking the sin or cos of the angle and multiplying by speed. Because...

```
 sin(a) = x / speed

```

So:

```
 x = speed * sin(a)

```

And:

```
cos(a) = y / speed

```

So:

```
y = speed * cos(a)

```

In your example `moveForward(90)` would yield `speed * sin(90)` or `speed * 1` in the x direction and `speed * cos(90)` or `0` in the y direction (It should move to the right as you specified). That should get you started in the basic sense.

Making it general:

```
moveForward(float angle)
{
    x += speed * sin(angle);
    y += speed * cos(angle);
}

```
> 20 votes

# Answer
The other answer is wrong as of now, to correctly move along a plane based on a rotation you do the following:

```
posX += Math.cos(rotation) *  forwardSpeed + Math.sin(rotation) * strafeSpeed;
posY -= -Math.cos(rotation) * strafeSpeed + Math.sin(rotation) * forwardSpeed;

```

However I'd recommend making a variable for cos/sin that you update only when the rotation changes so you aren't calculating it 4 times a tick.

The strafeSpeed would be moving from side to side, the forwardSpeed for moving forward along your rotation.

edit: tesselode does the same thing except he doesnt have side to side movement.
> 3 votes

# Answer
You said update ticks, so I'm assuming you don't have a variable frame rate. If so:

x += speed * math.cos(angle)

y += speed * math.sin(angle)

If you're using variable frame rate, you need to multiply by delta time as well.
> 2 votes

---
Tags: java, movement, rotation, trigonometry
---


# Question
Title: Pix for visual studio express 2012 (Desktop)
(Originally asked on stackoverflow)

Using visual c++ express 2010 for direct3d you have to download the directX sdk and there is a tool called pix for debugging shaders, looking at 3d resources etc.

With visual studio 2012 express the directx sdk is included in the windows sdk that comes with it but this does not seem to include the winpix.exe tool. Is this very useful tool still available? I guess I can still use the one from the previous sdk but it seems wrong to install the entire sdk just for that tool.

Is there a version for VS2012 express that I'm missing?

# Answer
It does not seem to be present in the Desktop Express I installed in a virtual machine. The whole Debug-\>Graphics menu is missing and none of the terms involved can be found using the quick search.

It's either an oversight or one of the things that the paid editions adds value with.
> 3 votes

# Answer
It used to be PIXWin.exe, not winpix.exe. At least that was the case for the last DirectX SDK (June 2010). It seems that things have changed now:

> Starting with Windows 8, the DirectX SDK is included as part of the **Windows SDK**.
>
> (...)
>
> A replacement for the PIX for Windows tool is now a feature in Microsoft Visual Studio, called **Visual Studio Graphics Debugger**. This new feature has greatly improved usability, support for Windows 8, and Direct3D 11.1, and integration with traditional Visual Studio features such as call stacks and debugging windows for HLSL debugging. For more info about this new feature, see Debugging DirectX Graphics.
> 1 votes

---
Tags: directx, pix
---