# Question
Title: What's the quickest way to make sprite sheets
We are only a team of three people and between us we don't really have that much spare time, we only do game development as a hobby.

What would be the most efficient way to make sprite sheets for use with programs such as game maker. Just basic movement and actions.

# Answer
> 3 votes
The most efficient way to make sprite sheets is to use pre-existing sprite sheets. You'll find an extensive list of pre-made sprite sheets here (always consult a lawyer and ask the copyright holders for permission when using content found on the internet)

Here are some other ways to efficiently make sprite sheets:

* Limit your sprites to simple shapes only (squares, circles, etc.)
* Constrain your sprites to 1 - 8 pixels
* Hire an artist to make sprites
* Make friends with an artist and get them to make sprites for free
* Modify the sprite sheets found in the above link to fit your purposes

---
Tags: spritesheet
---


# Question
Title: How to adjust the shooting angle of an object
I've been trying to add an angle adjustment feature to a power bar that I got from unity3dStudents. But I can't seem to get the code right. I'm using addforce to rigidbody, it works but the power is too great. I also found that rotating the object it's shooting from changes the angle. But I don't know how to proceed from that.

Can somebody show me the problem with the script below, as in how to add height to the addforce without it going to far up or to the side? Or how to change the angle of the object?

```
var theAngle : int;

var maxAngle : int = 130;
var minAngle : int = 0;

var angleIncreasing : boolean = false;
var angleDecreasing : boolean = false;

var rotationSpeed  : float = 10;
var ball        : Rigidbody;

var spawnPos : Transform;
var shotForce : float = 25;

function Update () {

    if(Input.GetKeyDown("k")){
        angleIncreasing = true;
        angleDecreasing = false;
    }
    if(Input.GetKeyUp("k")){
        angleIncreasing = false;
    }
    if(Input.GetKeyDown("l")){
        angleIncreasing = false;
        angleDecreasing = true;
    }
    if(Input.GetKeyUp("l")){
        angleDecreasing = false;
    }

-------
    if(angleIncreasing){
        theAngle += Time.deltaTime * rotationSpeed;
        if(theAngle > maxAngle){
            theAngle = maxAngle;
        }
    }
    if(angleDecreasing){
        theAngle -= Time.deltaTime * rotationSpeed;
        if(theAngle < minAngle){
            theAngle = minAngle;
        }
    }

}

function Shoot(power : float, angle : int){
----
    var forward     : Vector3 = spawnPos.forward;
    var upward  : Vector3 = spawnPos.up;

    pFab.AddForce(forward * power * shotForce);
    pFab.AddForce(upward * angle * 10);
----
}

```

# Answer
> 1 votes
This is suspect:

```
pFab.AddForce(forward * power * shotForce);
pFab.AddForce(upward * angle * 10);

```

This code is equivalent to:

```
pFab.AddForce(forward * power * shotForce + upward * angle * 10);

```

Lots of variables going into that force, which is probably the cause of "the power is too great". You're also not linearly increasing or decreasing the actual angle but its sine, this means (if I'm not mistaking) that the way you're using "`angle`" in your code contributes superlinearly to the actual angle.

Try this:

```
var angleRad : float = angle / 180.0 * Mathf.PI; // Convert angle to radians.
pFab.AddForce( (Mathf.Sin(angleRad) * upward + Mathf.Cos(angleRad) * forward) * power * shotForce );

```

Now `angle` represents the actual direction of the force w.r.t. the up and forward vectors, and the size of the force will be equivalent to `power * shotForce` (as long as `upward` and `forward` are unit vectors).

*P.S.* If you're not doing anything else with `angleIncreasing/Decreasing`, I would suggest you rewrite your `Update` to this:

```
if ( Input.GetKeyDown("k") ) {
    theAngle += Time.deltaTime * rotationSpeed;
    if ( theAngle > maxAngle ) {
        theAngle = maxAngle;
    }
}
if ( Input.GetKeyDown("l") ) {
    theAngle -= Time.deltaTime * rotationSpeed;
    if ( theAngle < minAngle ) {
        theAngle = minAngle;
    }
}

```

---
Tags: unity
---


# Question
Title: Rotation based on x coordinate and x velocity?
```
-(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{

float deceleration = 0.3f, sensitivity = 8.0f, maxVelocity = 150;

// adjust velocity based on current accelerometer acceleration
playerVelocity.x = playerVelocity.x * deceleration + acceleration.x * sensitivity;

// we must limit the maximum velocity of the player sprite, in both directions (positive & negative values)
playerVelocity.x = fmaxf(fminf(playerVelocity.x, maxVelocity), -maxVelocity);

}

```

Hi, I want to rotate my sprite based on the velocity and accelerometer input. My sprite can move along the X axis like so:

\<--------- sprite -----------\>

But it always faces forwards, if it is moving left I want it to point slightly to the left, the degree of how far it is pointing to be judged from the velocity. This should also work for the right.

I tried using atan but as the y velocity and position is always the same the function returns 0, which doesn't rotate it at all.

Any ideas?

Regards,

Lewis.

# Answer
> 0 votes
Small hack, but have you just tried making the rotation directly proportional to the object velocity.

```
float Proportion = 0.25f; // adjust value to your needs
float maxDiff = 1; // adjust to limit the maximum change of the orientation.
float playerRotation += fmaxf(fminf(playerVelocity.x * Proportion, maxDiff), -maxDiff);

```

It won't be accurate but it should be fairly convincing.

---
Tags: iphone, cocos2d-iphone, cocos2d, rotation
---


# Question
Title: “Play Now” via website vs. download & install
I've spent some time looking over the various threads here on GDSE and also on the regular Stackoverflow site, and while I saw a lot of posts and threads regarding various engines that could be used in game development, I haven't seen very much discussion regarding the various platforms that they can be used on.

In particular, I'm talking about browser games vs. desktop games.

I want to develop a simple 3D networked multiplayer game - roughly on the graphics level of Paper Mario and gameplay with roughly the same level of interaction as a hack & slash action/adventure game - and I'm having a hard time deciding what platform I want to target with it. I have some experience with using C++/Ogre3D and Python/Panda3D (and also some synchronized/networked programming), but I'm wondering if it's worth it to spend the extra time to learn another language and another engine/toolkit just so that the game can be played in a browser window (I'm looking at jMonkeyEngine right now).

Is it worth it to go with engines that are less-mature, have less documentation, have fewer features, and smaller communities\* just so that a (possibly?) larger audience can be reached? Does it make sense to even go with a web-environment for the kind of game that I want to make? Does anyone have any experiences with decisions like this?

(\* With the exception of Flash-based engines it seems like most of the other approaches have downsides when compared to what is available for desktop-based environments. I'd go with Flash, but I'm worried that Flash's 3D capabilities aren't mature enough right now to do what I want easily. There's also Unity3D, but I'm not sure how I feel about that at all. It seems highly polished, but requires a plugin to be downloaded for the game to be played -- at that rate I might as well have players download my game.)

**For simple & short games the Newgrounds approach (go to the site, click "play now", instant gratification) seems to work well. What about for more complex games? Is there a point where the complexity of a game is enough for people to say "OK, I'm going to download and play that"?**

# Answer
> 8 votes
> Is there a point where the complexity of a game is enough for people to say "ok, I'm going to download and play that"?

No. The logic of what you are suggesting is that people see simple games which are uninteresting, and then as they see progressively more complex games, they eventually think, "aha! This is complex enough for my interests - I shall download it".

I don't think that is really what you mean, but that is what your logic suggests.

What really happens is this: a player sees a website with a game on it, and makes an assessment of how interesting the game is to them. The degree of interest they have dictates the amount of effort they are willing to go to in order to play the game.

Therefore, there is almost no situation where a person would be more willing to download and install an executable rather than play a web-based game. And if you have a downloadable executable, you will get better traction with a smaller download than a larger one. You will get more players if you remove the need to explicitly create an account - you'll have even more if there is no login process whatsoever. And so on.

From your side, it's never as simple as that, because even a web-based game may involve installing a plugin, or upgrading a browser, etc. But on the whole, the complexity of your game makes no direct difference - it's a pure comparison of how interesting the game looks vs. how much effort the player will need to put in to try it.

> Is it worth it to go with engines that are less-mature, have less documentation, have fewer features, and smaller communities\* just so that a (possibly?) larger audience can be reached?

You're asking whether 9% of 100 is bigger than 90% of 10. Only you can decide whether you need to reach a wider audience at a cost of whatever sacrifices you need to make to offer it on the web. What's your monetisation strategy? What sacrifices would you have to make? You have to pick what is best for you. If there was One Right Answer then the world couldn't support both Modern Warfare 3 and Farmville, so we know that isn't the case.

# Answer
> 4 votes
In with Unity before anyone else! (or I'll delete my answer).

Unity really is the standout in this space, and it can in fact be used to distribute standalone games.

If you want to make a game, use something very polished like Unity. If you want to mess with technology, use one of the systems you mentioned.

# Answer
> 1 votes
I don't think you should go with a browser game because it might entail producing 2 version of code: one for browser and one for desktop. In addition, browser technology might not be powerful enough to handle your game (depending on your exact situation).

Unity might be one of the better choices for both desktop and browser deployment, but you have to consider the download of the Unity Player. While its filesize is actually quite lightweight and likely to be much smaller than your game itself, people are rather put off by the need to download.

See http://forum.unity3d.com/threads/27081-losing-users-when-they-have-to-download-Unity-webplayer

# Answer
> 0 votes
I recommend looking into the Three.js. It's a neat abstraction (not sure if it classifies as an engine) on top of WebGL (this is the engine, technically speaking?) and it has loads of great examples. But the best thing about it? No plugins! It's all HTML5 and WebGL, which are standard features of almost all bigger browsers now! I messed around with it a little, and it is great.

---
Tags: java, flash, browser-based-games, platform, psychology
---


title: Where can I find tutorials for LWJGL?

text:
# Question
Title: Where can I find tutorials for LWJGL?
I don't know if this is against the FAQ so if you close this, it'll be no surprise. I have done research but all the tutorials I have seen have been to hard to follow; I reckon there are better ones out there. If you could tell me, that would be great but if you close it, I understand. Thank you

# Answer
I would suggest you to read *Learning Modern 3D Graphics Programming* and check out my LWJGL port, but if you don't understand glBegin and GL\_QUADS maybe you'll find it a bit too difficult for now. Give it a look.

Also, in the official LWJGL wiki are listed some resources that can help you to start.
> 4 votes

# Answer
Look at "Java Game Development" LWJGL tutorials from The Coding Universe. They are really good and can help you to understand LWJGL better.
> 1 votes

# Answer
In addition to the Coding Universe tutorials that Denys P. mentioned I would recommend taking a look at thenewboston's YouTube videos parts 1-12

He hasn't added the additional videos to a playlist, so I created one here parts 13-21

They are strictly 2D and focused and using Slick2D library but can help you get started.

Good luck! -Mitchell
> 0 votes

---
Tags: java, lwjgl
---


title: Override close button

text:
# Question
Title: Override close button
How can I override the close button near minimize/maximize in such a way that the application doesn't automatically close. I want it to show an exit screen or something like this, so I would like to be able to delay the close and display something on the screen when I press the red close button. At first I thought that I should override the OnExiting() method, but I couldn't get it working. This is my first attempt at creating a fully functional game, so I have no previous experience in game development nor with XNA.

# Answer
As described on the XNA Community Forum, you can get the host `Form` and listen to the `FormClosing` event, which allows you to cancel the event. The example code from the community form reads:

```
protected override void LoadContent()
{
    Form f = Form.FromHandle(Window.Handle) as Form;
    if (f != null)
    {
        f.FormClosing += f_FormClosing;
    }
    base.LoadContent();
}

void f_FormClosing(object sender, FormClosingEventArgs e)
{
    if (MessageBox.Show("Are you sure?", "Are you sure?", MessageBoxButtons.YesNo) == DialogResult.No)
        e.Cancel = true;
}

```

Using that as a template, you should be able to come up with a method for bringing up an in-game dialog. You'll likely need to introduce a variable that indicates whether the user really wants to quit or not. For example:

```
bool userReallyWantsToQuit = false;

void f_FormClosing(object sender, FormClosingEventArgs e)
{
    if (!userReallyWantsToQuit)
    {
        displayExitMessage();    // Show the user something useful
        e.Cancel = true;
    }
}

void Update()
{
    if(keyboard.keyDown[Esc])    // Complete pseudocode. This will be your true exit condition
    {
         userReallyWantsToQuit = true;
         Exit();
    }
}

```
> 7 votes

---
Tags: xna, windows
---


# Question
Title: BEPUphysics collision with generated terrain?
I've got randomly generated terrain which is stored in a indices and vertex buffer. How do I go about using this for collision in BEPU? It seems I can do it with a Mesh but it would be a waste to convert it to a Mesh :/.

# Answer
> 1 votes
If it is a traditional terrain (i.e. generated from a heightmap), all you need to do is pass the constructor for BepuPhysics.Collidable.Terrain an array of heights, then provide a world matrix. If your "terrain" allows for concaves, then you will need to use a Mesh.

---
Tags: xna, physics
---


title: Issues implementing arcball viewer

text:
# Question
Title: Issues implementing arcball viewer
My scene has a simple cube, and a camera built with the lookAt function (I'm using OpenGL). The scene renders fine, and I'm sure I have my model/view/projection matrices set up correctly.

Now I'm trying to implement arcball rotation for my camera, but I'm having some trouble. I've got it down to calculating the angle/axis rotation for a virtual sphere in normalized screen coordinates. That means when I move my mouse left to right, I get an angle around the Y axis... and moving my mouse up/down will get me an angle about X.

I'm not sure where to go from here -- what do I need to do with my axis so I can apply the angle to simulate camera rotation about its viewpoint?

If I try directly applying the axis/angle rotation the camera/view transform I get what you'd expect. The view is rotated about the world axes which the mouse moving over the virtual sphere on the screen corresponds to. So if I move the mouse up/down the view rotates about the world's X axis (what I get reminds me of a first-person view)... but this isn't what I want.

I think I need the axis I get to be transformed so it passes through the camera viewpoint and is oriented correct in reference to the camera... but I don't know if that's right or how to do that.

# Answer
> 1 votes
I presume that this is the camera that you want.

This type of camera is composed of two components: a rotation and an offset. The rotation is over yaw (left and right) and pitch (up and down).

The first thing you have to realize is that matrix math is not commutative, which is a fancy mathematical term for "A * B != B * A".

If you were to rotate a matrix and then translate it, you'd get a different matrix than if you were to first translate it and then rotate it.

What you want in your case (an arcball camera) is to first translate the camera matrix by its offset and then rotate it around its angles. In code:

```
// http://glm.g-truc.net - OpenGL Mathematics library

glm::vec3 camera_offset = GetCameraOffset();
glm::vec2 camera_rotation = GetCameraYawAndPitch();

// construct an arcball camera matrix

glm::mat4 camera_transform;
camera_transform = glm::translate(camera_transform, camera_offset);
camera_transform = glm::rotate(camera_transform, camera_rotation.x, glm::vec3(0.f, 1.f, 0.f)); // add yaw
camera_transform = glm::rotate(camera_transform, camera_rotation.y, glm::vec3(0.f, 0.f, 1.f)); // add pitch

```

Now you should have an arcball centered around the world's root (0.0, 0.0, 0.0). However, what if you want to move your camera to some other position? Simply add these lines:

```
glm::vec3 camera_position = GetCameraPosition();
camera_transform = glm::translate(camera_transform, camera_position);

```

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


# Question
Title: how to transform child elements position into a world position
I'm making a 2d space game in Javascript with canvas. In this game there's a bunch of spaceships, positioned in world space, with turrets, positioned relative to their parent ships. These objects also have an orientation.

How do I efficiently calculate the position of a turret in world coordinates? (i.e. when it fires and I need to know where to place a bullet in the world)? Calculating the turrets orientation is trivial - I just add the turrets relative angle to its parents. For position though, I guess I could do a bunch of trigonometry but this MUST be a common problem with a good/fast general solution?

Should I be relearning how to do matrix math again? :)

**Update:**

Following the answers below I went away and read up on matrix math - to that end I can highly recommend "3D Math Primer for Graphics and Game Development" by Fletcher Dunn and Ian Parberry. The neat thing about matrices is you dont need to understand the maths involved in each transform, just how to use them.

As my project is in javascript I also needed a matrix library and went with gl-matrix.js as it is fast and has a clean (to my tastes) API. Sylvester.js is also very feature rich and worth a look, although not as fast as gl-matrix

# Answer
Transform matrices is a common solution to this problem, yes, since you can concatenate rotation, translation and scaling into one matrix and then multiply the childs transform with its parent to get world coordinates.

You don't necessarily have to use actual matrices for this though, you could simply move the turrets center using its local coordinate compared to its parent, then rotate this point with the parents rotation to then finally add the parents coordinates.

This is what the matrix math would have done as well, in simple cases this would work just as well, but if you want to make a ship that can change shape (folding out wings, or such) you would wind up adding another step to this. Then perhaps having multiple cannon barrels and you would have to do another translation. After too many good ideas your positioning code will be unmaintainable, doing it with matrices would allow you greater flexibility without running into this particular problem.
> 1 votes

# Answer
I'm making a 2D top-down shooter too, so I faced the same problems you have. ;)

The first thing I did was separate the two positions an object can have: a *world position* and a *render position*. For example, the player ship determines the position of the camera. So its render position stays roughly the same, but the world position is relative to the root.

After each `GameObject` has determined its final position (after collisions and such), a matrix is created from the object's rotation and position:

```
m_TransformRender.SetRotation(m_DirectionMoving.GetAngle());
m_TransformRender.SetTranslation(m_Position);

```

This matrix is then passed to subsystems that require it, for instance the sprite drawing module and the particles module. The particles module is the interesting one, because it creates world positions for the particles. If it used relative coordinates, the effects would look really weird, because the particles would rotate with the ship. So the `ParticleEmitter` has a position that is relative to its root, which is in this case a ship.

For instance, the `Enemy` class creates the following `ParticleEmitter`'s:

```
m_Particles->CreateEmitter("Exhaust", tb::Vec2(-16.f, -16.f), 512);
m_Particles->CreateEmitter("Exhaust", tb::Vec2( 16.f, -16.f), 512);

```

So it has two emitters, each at the back of the object.

Here's how a `ParticleEmitter` spawns a particle:

```
m_PropertyPosition[index] = m_Transform.Transform(m_Position);

```

And now you have a particle in world coordinates.

You can use this principle for your turrets: give your turret a relative offset to the ship and use a matrix to transform them to world coordinates. Note: your turret could have its own transformation matrix:

```
tb::Mat3x3 local_to_world = m_ParentShip->GetTransform() * m_TransformLocal;

```
> 0 votes

---
Tags: mathematics, javascript, html-canvas, coordinates, transformation
---


# Question
Title: Assigning a colour to imorted obj. files that are being used as default material
I am having a problem with assigning a colour to the different meshes that I have on one object. The technique that I have used is the first approach on this site. Is it possible to export a simulation (animation) from Blender to Unity?

So what I would like to do is the following. I have about 107 meshes that are different frames from my shape key animation of my blender model. What I would like to have is that the first mesh will be bright green and up to the 40th mesh the colour turns to be white /greyish...

the best would be if I could assign every mesh by hand a colour, however they are all default materials. And if I assign the object a colour, the whole "animation" is going to be in that colour

# Answer
> 1 votes
There are different approaches to this problem. It depends a lot on the look you're trying to achieve.

### Texture/Color each Mesh separately

If you want full control over the the resulting animation, this is the way to go. But this is also really cumbersome if you have to set up several animations.

**How to do it?** Instead of using an array of `Mesh` objects as your "frames", you could use an array of `GameObject`. The `GameObject` can have an individual material, colliders etc. Then instead of swapping the mesh, you would swap (toggle visibility) of the different game-objects.

### Animate the color of the material

You could add a start- and end-color variable to your script and interpolate between these colors by altering the `renderer.material.color` property over time. Depending on the type of material/shader you used, this might work out of the box or will need some tweaks on your material-setup. This is presumably more efficient (and certainly less cumbersome to set up) than swapping `GameObjects`, but I haven't tested the performance.

Here's the `MeshAnimation` script from my other answer, but this time with start- and end-color built in as an example: http://pastie.org/4131049

---
Tags: unity
---


title: Thread safe double buffering

text:
# Question
Title: Thread safe double buffering
I am trying to implement a draw map method that will draw the tiled image across the surface of the component. I'm having issue with this code. The double buffering does not seem to be working, because the sprite flickers like crazy;

my source code:

```
package myPackage;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;

    public class GameView extends JFrame implements Runnable {

    public BufferedImage backbuffer;
    public Graphics2D g2d;
    public Image img;
    Thread gameloop;
    Scene scene;

    public GameView() {
        super("Game View");
        setSize(600, 600);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        backbuffer = new BufferedImage(getWidth(), getHeight(),
                BufferedImage.TYPE_INT_RGB);
        g2d = backbuffer.createGraphics();

        Toolkit tk = Toolkit.getDefaultToolkit();
        img = tk.getImage(this.getClass().getResource("cage.png"));
        scene = new Scene(g2d, this);

        gameloop = new Thread(this);
        gameloop.start();

    }

    public static void main(String args[]) {

        new GameView();
    }

    public void paint(Graphics g) {

        g.drawImage(backbuffer, 0, 0, this);
            repaint();

    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        Thread t = Thread.currentThread();
        while (t == gameloop) {

            scene.getScene("dirtmap");
            g2d.drawImage(img, 80, 80, this);
        }
    }

    private void drawScene(String string) {
        // TODO Auto-generated method stub

        // g2d.setColor(Color.white);
        // g2d.fillRect(0, 0, getWidth(), getHeight());

        scene.getScene(string);

    }

}

package myPackage;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;

public class Scene {
    Graphics g2d;
    Component c;
    boolean loaded = false;

    public Scene(Graphics2D gr, Component co) {
        g2d = gr;
        c = co;
    }

    public void getScene(String mapName) {

        Toolkit tk = Toolkit.getDefaultToolkit();
        Image tile = tk.getImage(this.getClass().getResource("dirt.png"));

        // g2d.setColor(Color.red);
        for (int y = 0; y <= 18; y++) {
            for (int x = 0; x <= 18; x += 1) {
                g2d.drawImage(tile, x * 32, y * 32, c);
            }
        }

        loaded = true;
    }
}

```

# Answer
You are interacting with a Swing UI (the component you pass to your scene's constructor) outside the EDT thread - this might be the reason you are having issues. You could try to run the code in the EDT:

```
@Override
public void run() {
    Thread t = Thread.currentThread();
    while (t == gameloop) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                scene.getScene("dirtmap");
                g2d.drawImage(img, 80, 80,this);
            }
        });
    }
}

```
> 1 votes

---
Tags: java, multithreading, double-buffering
---


# Question
Title: How to convert .max files to .egg on linux
I am very new to 3d graphics and game engines and panda3d and python. I followed few panda3d tutorials and now I want to test them with few new models. High majority of 3d models in the internet are in .max format.

Is there a way to convert these models to a format that can be used with panda3d. (.egg or .bam, I think). I am using linux. Thank you

# Answer
The only program that can reliably open .max files is 3DS Max itself. From Max you can export to something more open and portable like fbx.

There's a free trial version of Max available from http://usa.autodesk.com/3ds-max/trial/?nd=1 which should do the job, although it won't run on Linux...
> 3 votes

# Answer
http://www.panda3d.org/manual/index.php/Converting\_from\_3D\_Studio\_Max shows how to use the exporter.
> 1 votes

# Answer
There's way more to .max files than the simple 3d model. Lots of information that makes the animation work properly. Also, blender does not support animation. The only format blender supports that will recognize the module is .3ds, but you'll lose a lot of important information that is stored in the .max file. Blender is okay, but just a simple 3d animation program. If you want a good 3d moduling software for linux, you should try Maya.
> -2 votes

---
Tags: 3d, models, python, file-format, 3dsmax
---


# Question
Title: Trouble with SAT style vector projection in C#/XNA
Simply put I'm having a hard time working out how to work with XNA's Vector2 types while maintaining spatial considerations. I'm working with separating axis theorem and trying to project vectors onto an arbitrary axis to check if those projections overlap, but the severe lack of XNA-specific help online combined with pseudo code everywhere that omits key parts of the algorithm, googling has left me little help.

I'm aware of HOW to project a vector, but the way that I know of doing it involves the two vectors starting from the same point. Particularly here:

http://www.metanetsoftware.com/technique/tutorialA.html

So let's say I have a simple rectangle, and I store each of its corners in a list of Vector2s. How would I go about projecting that onto an arbitrary axis? The crux of my problem is that taking the dot product of say, a vector2 of (1, 0) and a vector2 of (50, 50) won't get me the dot product I'm looking for.. or will it? Because that (50, 50) won't be the vector of the polygon's vertex but from whatever XNA calculates. It's getting the calculation from the right starting point that's throwing me off.

I'm sorry if this is unclear, but my brain is fried from trying to think about this. I need a better understanding of how XNA calculates Vector2s as actual vectors and not just as random points.

# Answer
## Here is the theory you need:

A `Vector2` is nothing but an X coordinate and a Y coordinate. It can represent either a position - OR - a direction and a magnitude (aka: a "length"). If the magnitude is 1, then you have a "normal" (a "normalized vector" or "unit vector" - which represents only a direction).

I think what is making you unstuck here is you might be trying to use only a single vector to represents concepts/data that require two vectors to express: A "**line**" is two positions. A "**ray**" is a starting position and a direction.

Finally, I'm pretty sure that the vector that you are projecting onto must be normalized (of unit length) for the algorithm to work.

## So, using this information:

Take one of the edges of your polygon. It is made up of two position vectors in the form of a line. Call the vectors **A** and **B**.

If you take **A** as a starting point, then do `Q = Vector2.Normalize(B - A)`, then **A** and **Q** together form a ray. If you take **Q** on its own, it represents the **tangent** of the polygon on that edge (a direction).

The algorithm requires you to take an axis that is **perpendicular** to that edge. So rotate your tangent 90 degrees (the vector `(X, Y)` rotated 90 degrees is `(-Y, X)` or `(Y, -X)`, note that the magnitude does not change). The normalized direction vector that faces outwards from an edge is known as the "normal" of that edge.

(Note: the winding order of your polygon will determine which direction you need to rotate 90 degrees in (ie: left or right) in order to have a vector that faces outwards.)

Note that, even though the tangent and normal are associated with a given edge, they contain no positional data - they are only directions!

Just like `(1, 0)` represents the X axis, and `(0, 1)` represents the Y axis, the normal that you have now can be used to represent an axis (starting at the origin). You can project positions onto this axis by taking the dot product of any position with your normal.

From here, the tutorial explains how to project polygon vertices (positions) onto that axis to determine whether a polygon is separated from another polygon on that axis. It goes on to explain how to repeat this technique on multiple axes to determine if polygons are intersecting.

---

What I *strongly* recommend is finding some line-drawing library for XNA, and then using that to make interactive diagrams - similar to those in the tutorials. This will allow you to *see* what your algorithm is doing, so you can more easily see where anything might be going wrong.
> 3 votes

---
Tags: xna, c#, vector, projection, separating-axis-theorem
---


# Question
Title: XNA Spritebatch sorting by texture vs depth
I am refining my 2D game engine, and I want to look in to sorting sprite batches by texture (because I'm quite often using the same textures repeatedly).

However, I also want to retain a few 'layers' of depth (i.e. ground \< buildings \< units \< GUI etc).

My question is, which of the following is the best approach (in terms of performance)?

1. Create multiple SpriteBatches and Begin() and End() them in order; or...
2. Create a single SpriteBatch and call Begin() and End() multiple times, once for each layer (in order)?

# Answer
> 3 votes
There is no reason to have multiple `SpriteBatch` objects unless you are using them as a "sprite buffer" (a list of sprites to be drawn when `End` is called) and filling multiple buffers up at the same time.

If you are going in and out of begin/end blocks, you can reuse the `SpriteBatch` object (there is no saved state between blocks).

There's no major effect on performance. But multiple `SpriteBatch` objects will use more memory.

As you probably already know, `SpriteBatch` (in XNA 4.0) only batches sprites together (improving performance) if two or more sprites share the same texture and are drawn sequentially and within the same begin/end block (and if `Immediate` mode is not set). It sounds like both of your methods will produce the same batches - and thus no performance difference.

# Answer
> 0 votes
You only need multiple `SpriteBatch`es if you like to have other settings for the new layer. So using the same `SpriteBatch` twice or more is just fine.

You could also consider using only a single batch if everything is the same. Just sort your sprites into buckets and draw them at the right time within the batch.

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


title: Different methods of ammo resupply

text:
# Question
Title: Different methods of ammo resupply
I'm writing a small game at the moment. Presently, I have one or two design elements that aren't locked down yet, and I wanted to ask for input on one of these.

For dramatic effect, the player's character in my game is immobilised, alone and has a supposedly limited amount of ammo for their weapons. However, I would like to periodically resupply the player with ammo (for the purpose of balancing the level of difficulty and to allow the player to continue if they're doing well).

I'm trying to think of a method of resupply that's different to the more familiar strategies of making ammo magically appear or having the antagonists drop some when they die. I'd like to emphasise the notion of the player's isolation as much as possible, and finding a way of 'sneaking' ammo to the player without removing too much of that emphasis is basically what I'm trying to think of (it's definitely a valid argument that resupplying the player removes it anyway)

I have considered a sort of simple in-game 'store', where kills get you points that you can spend on ammo for your favourite weapon. This might work well, and may also be good for supporting a simple micro-transaction business model within the game. However, you'd have to pause the game often to make purchases, which would interrupt the action, and it works against the notion of isolation.

Any thoughts?

# Answer
It's an interesting problem, to say the least.

Suppose we consider the game's designer (you) God, with the player (she) being isolated. Because the world was designed, the player is never really alone. There had always been someone watching out for her, in his own sadistic way.

If you really want to emphasize the loneliness of the player, then she will probably have to fashion her own ammunition. But the penalty for creating ammunition is that the enemies creep ever closer.

I would suggest:

* Kills give the player base materials for ammunition (bullets, gun powder, casings)
* The player has to stop the action to resupply her ammunition
* Enemies continue to advance while the player is building

Obviously, some handwaving is still involved: how do the base materials reach the player, how is she able to create ammunition so fast, etcetera.

I would consider cross-posting to /r/gamedev, which is much more suited for an open-ended discussion like this.
> 5 votes

# Answer
It you want them to buy it, then have them buy it but make it have a delay. As if it was being supplied by an ammo drop. Also, depending on the platform you could use a directional button that would work as a purchase ammo for a specific weapon. Since the character is incapable of moving those buttons should be free to used.
> 0 votes

---
Tags: game-design, game-mechanics, balance
---


# Question
Title: How to deal with animated doors in isometric tiles
I've got a tricky issue I'm not sure how to tackle best: I have an animated tile of a door. When it's closed it should be sorted one way, but when it's openend it will need to be sorted a different way, as it belonging to a different(neighbouring tile).

Here's the door closed:

and the door opened:

I imagine it would be possible to override the sorting system for such tiles and adjust the sorting based on the frame, but it feels a bit hacky.

Has anyone encountered a similar scenario ? Any elegant solutions ?

# Answer
Maybe you could make a door out of *two* objects, on different tiles, and only show one of them at a time. This way, opened door might conceivably block movement too, which seems kinda realistic.
> 3 votes

# Answer
There are 2 tricks I use for sorting in 2D:

* Add ground position to sprites, this is a point where sprite touches the ground (f.e. mens feet, trees trunk, doors frame) and sort by it instead of sprites pixels. This way sprite will not be affected by animation
* Add non-sortable childs to objects (f.e. men can have several childs which do not affect sorting - cloak, bow, sword, etc, door frame has child door). This way animation of child sprites does not affects sorting either.
> 3 votes

# Answer
Create three sprites...

1. Door closed (like your first sprite) - blocks movement
2. Just the frame (post in your case) of the door, but no door - doesn't block movement
3. Just the door in open position - blocks movement

When the door is closed, draw sprite 1, and treat it as a "blocker" so players can't walk through it.

When the door is opened, replace that sprite with #2 (just the door post). Then place sprite #3 (just the door) in the adjacent cell that the door would be in.

Closing is just removing the door, and replacing the post with post+door in closed position.

With this setup, you don't have to worry about rendering the opened door in any special order. Just render it in the order as any other object in the square it is in.

The downside is that you can't have the player or any other object in the square where the opened door will go.
> 3 votes

# Answer
The best way to solve the sorting of objects is by not sorting at all. If you use a depth buffer, you can render everything in one pass. Objects that have a higher z-value will be further away than objects with a lower z-value.

Even if your game is 2D, you should still consider using 3D coordinates with a depth buffer, otherwise you will forever tango with the painter's algorithm.
> 1 votes

---
Tags: animation, tiles, isometric
---


title: OpenGL: Drawing to a texture

text:
# Question
Title: OpenGL: Drawing to a texture
Well im just a bit stuck wondering how to draw an item to a texture.

Edit: Well unfortunately my graphics card doesn't support FrameBuffer Objects :/. So i've been trying to get the copy contents from backbuffer method working.

Edit: So i've been trying now for the best part of a couple of hours to get this thing working. Unfortunately all i still get is a white square.

Here's my little testing code that i have set-up. What it should do is draw a red square at 100, 100. But even this isn't working for me :/.

```
glViewport(0 , 0, 512, 512);

glPushAttrib(GL_CURRENT_BIT);
glColor4ub(255, 0, 0, 255);
glBindTexture(GL_TEXTURE_2D, Texture);

glBegin(GL_QUADS);

// Top-left vertex (corner)
glTexCoord2i(0, 0);
glVertex2i(100, 100);

// Bottom-left vertex (corner)
glTexCoord2i(1, 0);
glVertex2i( 100 + 200, 100);

// Bottom-right vertex (corner)
glTexCoord2i(1, 1);
glVertex2i( 100 + 200, 100 + 200);

// Top-right vertex (corner)
glTexCoord2i(0, 1);
glVertex2i(100, 100 + 200);

glEnd();
glPopAttrib();
glLoadIdentity();

//Copy Our ViewPort To The Texture
glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, 0, 0, 512, 512, 0);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
//Reset Viewport
glViewport(0, 0, 768, 480);

glBindTexture (GL_TEXTURE_2D, Texture);
glEnable(GL_TEXTURE_2D);

glBegin(GL_QUADS);

// Top-left vertex (corner)
glTexCoord2i(0, 0);
glVertex2i(0, 0);

// Bottom-left vertex (corner)
glTexCoord2i(1, 0);
glVertex2i( 0 + 512, 0);

// Bottom-right vertex (corner)
glTexCoord2i(1, 1);
glVertex2i( 0 + 512, 0 + 512);

// Top-right vertex (corner)
glTexCoord2i(0, 1);
glVertex2i(0, 0 + 512);

glEnd();
glDisable(GL_TEXTURE_2D);

```

Screenshot of the current output:

Any help is greatly appreciated!

# Answer
> 0 votes
This is most likely not how you want to call this function! The first index is an offset relative to vertex data sources. Most likely, you want:

```
glDrawArrays(GL_LINE_STRIP, 0, indices.size());

```

As for your actual question, use a framebuffer object: http://www.opengl.org/wiki/Framebuffer\_Object \- alternatively, you can also simply draw to the back-buffer and copy that to a texture via glCopyTextureX

# Answer
> 1 votes
I understand that you want to actually "render to a texture", other words, render something and rather than showing it on screen store it as a texture.

If this is the case, you should read about Frame Buffer Objects (FBOs) and the "renter to texture" techniques, which basically consists in attaching a texture to an FBO.

I would recommend that you read **this**, which explains pretty much everything you need and contains a fantastic demo, in which they render a teapot and use it to texture a cube. **Here** you have another tutorial.

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


# Question
Title: Is it better to hard code data or find an algorithm?
I've been working on a boardgame that has a hex grid as this board:

Since the board will never change and the spaces on the board will always be linked to the same other spaces around it, should I just hard code every space with the values that I need? Or should I use various algorithms to calculate links and traversals?

To be more specific, my board game is a 4 player game where each player has a 5x5x5x5x5x5 hex grid (again, the image above). The object is to get from the bottom of the grid to the top, with various obstacles in the way, and each players being able to attack each other from the edge of their grid onto other players based on a range multiplier.

Since the players grid will never change and the distance of any arbitrary space from the edge of the grid will always be the same, should I just hard code this number into each of the spaces, or should I still use a breadth first search algorithm when players are attacking?

The only con I can think of for hard coding everything is that I'm going to code 9+ 2(5+6+7+8) = 61 individual cells. Is there anything else that I'm missing that I should consider using more complex algorithms?

# Answer
> 12 votes
I guess I'll take the counterpoint here and argue against using static values. In this case, all of the hex regions you're talking about are (a) easy to compute - you don't need to use BFS or anything so complicated; you should be able to iterate over all of the hexes in any of them with straightforward doubly-nested loops; and (b) not something you'll need to compute 'on-the-fly' very often. At worst you should only need to compute them once per turn, and if multiple systems *do* want the cells touched by an effect then you can easily cache the values off into a 'reachableCells' array or something similar; regardless, the computation is so easy that it should be effectively free to do in terms of per-frame costs.

So what do you get for that? Flexibility. It's easy to say right now that these values will never change, but games have a knack for surprising you; even if it's more likely than not that these regions *won't* change, you give up essentially nothing by building that flexibility in, and there's a good chance that future-you will thank you down the road. What's more, even if those are the final regions you use, well-written loops for iterating over the regions will be substantially easier to understand and debug than any sort of fixed-tiles array will. I just really don't see any meaningful gain for going with hard-coded data compared to the benefits of going the other way.

# Answer
> 11 votes
If the values will never change, they may as well be static. Why waste CPU time recalculating something that will be the same as last time?

However, they don't necessarily need to be 'hard-coded':

* You can put the values in a data file, and load that in at the start.
* You can perform the search during play and cache the values once you find them.

The first way makes sense if you think you might change the map shape or size in future. The second way makes sense if calculating the static values is a bit tricky.

I have no idea what a six-dimensional hex map looks like, or why there are 9+2(5+6+7+8) cells involved, but the best result for your situation - and indeed most situations in game programming - is to code in whatever gets you the correct result most quickly. You can generalise it to an algorithm later if you need to. "Code for today", as some say.

# Answer
> 0 votes
Q: is this the only hex game you'll ever write? No?

A: Then obviously you should try to be flexible wherever it doesn't cost you a lot of extra effort. Regardless how you define the board, represent it at runtime with explicit links. It's very convenient to code movement and relationship logic in terms of traversing links, which is independent of the size or topology of the board.

---
Tags: algorithm, procedural-generation, hexagonal-grid
---


# Question
Title: Textures on top of other textures when using VBOs
I'm currently making a cube style game. With chunks being drawn with VBOs. I'd like to know if there is a way to create an overlay texture on top of the existing texture without the need to rebuild the VBO. This is required to show activity in a cube (think of Minecraft when destroying a block and the little cracks start spreading).

I believe these are called "decals" but I've not found how to use them with VBOs. So how do I draw decals on OpenGL VBO drawn cubes?

# Answer
> 3 votes
Try to render your VBO with two textures: one as the diffuse map (the block texture) and one showing the crack.

You can combine them in a shader:

```
// GLSL fragment shader

#version 130

uniform sampler2D texDiffuse;
uniform sampler2D texCrack;
uniform float uniCrackAmount; // between 0 and 1

in vec2 vertTexCoord;

out vec4 fragColor;

void main()
{
    vec4 color_diffuse = texture(texDiffuse, vertTexCoord);
    vec4 color_crack = texture(texCrack, vertTexCoord);

    fragColor = color_diffuse + (color_crack * uniCrackAmount);
}

```

# Answer
> 2 votes
For a non-shader solution you could draw in two batches. First of all you flag the cubes in the current scene that need the overlay texture - this can be done during your scene tree traversal or other scene setup. Then draw the regular cubes using your normal draw routine. Finally draw the overlay-textured cubes using multitexturing - you can experiment with a decal or interpolate TexEnv for this.

The VBO setup would just use the same set of texcoords for both texture units; something like this (not intended as copy-and-paste code):

```
glClientActiveTexture (GL_TEXTURE0);
glEnableClientState (GL_TEXTURE_COORD_POINTER);
glTexCoordPointer (2, GL_FLOAT, sizeof (myvertextype), (void *) 12);

glClientActiveTexture (GL_TEXTURE1);
glEnableClientState (GL_TEXTURE_COORD_POINTER);
glTexCoordPointer (2, GL_FLOAT, sizeof (myvertextype), (void *) 12);

// drawing stuff

glClientActiveTexture (GL_TEXTURE1);
glDisableClientState (GL_TEXTURE_COORD_POINTER);

glClientActiveTexture (GL_TEXTURE0);
glDisableClientState (GL_TEXTURE_COORD_POINTER);

```

But otherwise - yeah - the shader-based solution would be preferable. Aside from those ClientActiveTexture calls going away (which is always a good thing) you've got much better control over the type of blend you do between the two textures.

---
Tags: opengl, textures, lwjgl, decal-system
---


title: Texture switching with a entity system

text:
# Question
Title: Texture switching with a entity system
I'm using thinking of using an entity system in my game. So far I've been using Artemis with success. However, I have a question about texture switching. I read that switching textures too often is bad. So I load all the textures when the game loads like so:

```
import org.newdawn.slick.opengl.TextureLoader;
...
public HashMap<String, Texture> Textures;
...

```

Then for each texture I do this:

```
Texture tex = TextureLoader.getTexture("PNG", this.getClass().getResourceAsStream(texturePath));
Textures.put(textureName, tex);

```

Then when drawing entities I do this:

```
drawEntity() {
    glBindTexture(GL_TEXTURE_2D, Textures.get(entityTexture).getTextureID());
    ...
}

```

Say I have 50 entities, using 10 different 3D models, each with their own texture. When the `drawEntity` system runs, it doesn't group by which entities use which texture. So I could be switching textures before drawing each entity! Is there a more efficient way to switch textures between entities? Or is `glBindTexture()` a good option?

# Answer
> 3 votes
glBindTexture is the only option for changing textures in OpenGL, but there are a few things you can do to make things easier on yourself.

First of all you can wrap it with your own version. That just takes a texture number, compares it to the current texture (which you'll declare as a variable), and if it's changed calls glBindTexture and stores the texture number back to the current texture.

The simplest implementation (C, not Java, but you should be able to figure it out) might look something like this:

```
int currenttexture = -1;

void GL_BindTexture (int texnum)
{
    if (texnum != currenttexture)
    {
        glBindTexture (GL_TEXTURE_2D, texnum);
        currenttexture = texnum;
    }
}

```

Things get a little more complex when you get into multitexturing and texture targets other than GL\_TEXTURE\_2D, but that's the basic principle.

Another, more advanced, variation might involve using a texture array, but I don't think you're ready for that yet - let's get the basics right first. ;)

You mention that you're not sorting your entities so that's always a good idea. Any decent sort algorithm is good enough for most cases, and sort them by the texture they use. That will definitely get texture changes down.

Finally, the overhead might not be as high as you think. Yes, too many texture changes is inefficient, but how many is too many? It's certainly a lot higher than your hypothetical 50 - dear old Quake did more than 50 texture changes per frame back in 1996 and didn't suffer too much from it. I think you'll do OK.

So the moral of the story is that any scheme to reduce texture changes is going to add a certain level of extra complexity to your program, and that extra complexity may not be a worthwhile tradeoff. If you're already running fast enough then you're already running fast enough, and the point at which these things become a bottleneck is a lot higher than you think. Profile first, determine if it actually is a problem, then optimize; not the other way around.

---
Tags: textures, lwjgl, entity-system, slick
---


# Question
Title: Slick2D - Cannot instantiate the type Image
I am getting this strange error and I cannot for the life of me figure out why:

```
    Cannot instantiate the type Image

```

### CODE:

```
import java.awt.Image;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;

public class MainMenuState extends BasicGameState {

    int stateID = -1;

    Image background = null;
    Image startGameOption = null;
    Image exitOption = null;

    float startGameScale = 1;
    float exitScale = 1;
    MainMenuState( int stateID )
    {
       this.stateID = stateID;
    }

    public int getID() {
        return stateID;
    }

    public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
        try {

        background = new Image("data/menu.jpg");

        Image menuOptions = new Image("data/menuoptions.png");

        startGameOption = menuOptions.getSubImage(0, 0, 377, 71);

        exitOption = menuOptions.getSubImage(0, 71, 377, 71);

        }catch (SlickException e) {
            System.err.print(e);
        }
    }

    public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {

    }

    public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {

    }

}

```

Why do I get this error? I've googled endlessly and nobody else has it, this worked fine in my other game. Any ideas?

# Answer
You're importing this right at the top of your code:

```
import java.awt.Image;

```

So you're actually trying to instantiate the Java AWT Image class, which is abstract, so no wonder you're getting that error. I'm guessing you used your IDE's suggestion to import a namespace.

Slick2D's Image class is located in the `org.newdawn.slick` namespace, which you never import. The Slick2D Image class simply doesn't exist as far as your code is concerned - but the java.awt Image class does.

`import org.newdawn.slick;` and you'll be fine.
> 0 votes

---
Tags: image, slick
---


title: What is a normalized Vector?

text:
# Question
Title: What is a normalized Vector?
Can someone explain the following code? I need to learn what each part means so I can turn it into enemy movement in a space shoot-em-up

```
Vec2d playerPos;
Vec2d direction; // always normalized
float velocity;

```

I get the above is naming two 2d Vector objects, and creating a variable called velocity. I'm not sure what the normalized comment is about, though.

```
update()
{
   direction = normalize(playerPos - enemyPos);
   playerPos = playerPos + direction * velocity;
}

```

# Answer
You should read this tutorial on vectors for game developers at Wolfire: Linear Algebra for Game Developers Part 1 / Part 2

A vector can be seen as pointing to a specific coordinate. It can also be seen as having a direction and a magnitude (or length).

A normalized vector is one that has a magnitude (or length) of exactly 1. Normalizing a vector produces a vector pointing in exactly the same direction, with a length of exactly 1.
> 5 votes

---
Tags: c#, game-design, movement
---


title: Amazing Jutsu (Technique)

text:
# Question
Title: Amazing Jutsu (Technique)
Hy..I'm newbie here.. Please does anyone knows, how to create such a character(sprites) to have a different Style Technique and different kind of movement, so he/she can alternate many technique to defeat his/her opponent...

I wanna make my 2d character his/her power had a technique like rasengan, I mean for the first the jutsu its just spining around above his/her hand and then going bigger and much bigger so can create a massive giant ball/light/swords or etc blow up when he/she use that technique to defeat his/her opponent? the e.g of game like Disgaea, Final Fantasy, Suikoden, and another RPG, MMORPG game

How the coding is to combine the sprite with his/her different style of technique, and what should I do? Please your guide, thank's a lot... ^\_^

# Answer
> 2 votes
The character and the attack needs to be animated separate. That way you can swap out different attacks as needed.Usually the special attack is a particle effect generated using code, or a separate sprite. You probably could attach the attack to the character using an offset, for e.g. taking the character to be the attack's point of origin and positioning it (x,y) coordinates away.

If it's just a runic effect kind of thing that flares up around the character, you might be able to just use a 2D translucent overlay on top of the character.

You would definitely need to have more character animations though, if your attacks are radically different enough. For example, one set for your Rasengan thrusting, one set for Fireball blasting, and so on. You might probably be able to generalise your attacks as a series of basic classes (ThrustAtk class, MouthBlastAtk) and further inherit from them (LightningThrustAtk, WindThrustAtk, FireMouthBlastAtk, etc.)

---
Tags: c#
---


# Question
Title: multi-dimension array problem in RGSS (RPG Maker XP)
This is my first day code script in RMXP. I read tutorials, ruby references, etc and I found myself stuck on a weird problem, here is the scenario:

1. I made a custom script to display layered images
2. Create the class, create an instance variable to hold the array, create a simple method to add an element into it, done
3. The draw method (skipped the rest of the code to this part):

> ```
>   def draw
>     image = []
>     index = 0
>     for i in 0..@components.size
>       if image.size > 0
>         index = image.size
>       end
>       image[index] = Sprite.new
>       image[index].bitmap = RPG::Cache.picture(@components[i][0] + '.png')
>       image[index].x = @x + @components[i][1]
>       image[index].y = @y + @components[i][2]
>       image[index].z = @z + @components[i][3]
>       @test =+ 1
>     end
>   end
>
> ```

1. Create an event that does these script

> ```
> > $layerz = Layerz.new $layerz.configuration[0] = ['root',0,0,1]
> > $layerz.configuration[1] = ['bark',0,10,2]
> > $layerz.configuration[2] = ['branch',0,30,3]
> > $layerz.configuration[3] = ['leaves',0,60,4] $layerz.draw
>
> ```

1. Run, trigger the event and the result :

ERROR! **Undefined method\`\[\]' for nil:NilClass** pointing at this line on draw method :

> image\[index\].bitmap = RPG::Cache.picture(@components\[i\]\[0\] + '.png')

THEN, I changed the method like these just for testing:

```
def draw
    image = []
    index = 0
    for i in 0..@components.size
      if image.size > 0
        index = image.size
      end
      image[index] = Sprite.new
      image[index].bitmap = RPG::Cache.picture(@components[0][0] + '.png')
      image[index].x = @x + @components[0][1]
      image[index].y = @y + @components[0][2]
      image[index].z = @z + @components[0][3]
      @test =+ 1
    end

```

I changed the **@components\[i\]\[0\]** to **@components\[0\]\[0\]** and **IT WORKS**, but only the root as it not iterates to the next array index

Im stuck here, see :

```
> in single level array, @components[0] and @components[i] has no problem
> in multi-dimension array, @components[0][0] has no problem BUT
> in multi-dimension array, @components[i][0] produce the error as above
> mentioned.

```

any suggestion to fix the error ? Or did I wrote something wrong ?

# Answer
> 1 votes
Ok, after doing some reading, understanding ruby, I found the solution without changing the data type to hash/vector

```
  def draw
    image = []
    index = 0
    @components.each { |arr|
      if image.size > 0
        index = image.size
      end
      image[index] = Sprite.new
      image[index].bitmap = RPG::Cache.picture(arr[0] + '.png')
      image[index].x = @x + arr[1]
      image[index].y = @y + arr[2]
      image[index].z = @z + arr[3]
      @test =+ 1
    }
  end

```

**each** function is really convenient, I just learned that. Thanks the feedback guys.

---
Tags: ruby, rpg-maker-xp
---


# Question
Title: Is there a definitive reference on Pinball playfield design?
I'm looking at designing tables for Future Pinball but I'm not sure where to start as I've little background in game design per se. I've played scores of pinball tables over the years so I've a fairly good idea of what is "fun" in those terms. However, I'd like to know if there is a definitive "bible" of pinball design as far as layout and scoring/mode design goes. I've looked but there doesn't seem to be anything really coherent that I could find. Is it simply a lost art or am I missing some buried gem?

# Answer
> 4 votes
This seems akin to asking if there is a definitive “bible" of first-person-shooter design. Pinball is just a genre/type of arcade game which became popular and was copied in the same why fps games were among video games. The design of pinball games was likely more stable than that of video games due to the complexity and inherently higher cost of developing new mechanical game elements vs. digital game elements. Each player has their preferences as to what would qualify as *definitive* elements of pinball machine design. Some would swear by the early machines with no computerized components, others are going to think the almost seizure-inducing 1992 The Addams Family /// machine was the culmination of pinball design, and I’m sure someone out there at some point swore that adding paddles was heresy and they shouldn’t mess with the design of Bagatelle.

The only other element of design is profit. This is likely a stronger influence to pinball design than anything else. It’s easier and much more cost effective to use the same mechanical elements in many machines just in different configurations and with different themes/graphics. So once they hit on something that worked it was copied many times over. These common elements are what define “pinball”. As for scoring it is mostly just a way to compare relative skill and the particular mechanics of scoring is generally irrelevant as long as a better player scores higher. Scoring systems also has economic implications as well as discussed here: http://cheaptalk.org/2009/11/17/the-economics-of-pinball/

You’ve played lots of machines, you know what you like, and you know what you find fun, I’d suspect you might also have an idea of what you haven’t seen but think might be fun. You know how you define “pinball.” Game design, be it classic arcade or modern computer games, is about what is fun, and is always a matter of taste and opinion. Just use your own experience and try to make something you would find fun.

# Answer
> 1 votes
There was a program called Pinball Builder where you could build your own pinball games based on different layouts. This would be good for planning and designing ideas. The program is old so it may be hard to find.

I'm not sure if there is a definitive set of rules for designing a pinball game. Flippers, bumpers and ramps are the main things that signify the genre, I guess if you have them you have a pinball game?

---
Tags: game-design, level-design
---


title: Elliptical orbit modeling

text:
# Question
Title: Elliptical orbit modeling
I'm playing with orbits in a simple 2-d game where a ship flies around in space and is attracted to massive things. The ship's velocity is stored in a vector and acceleration is applied to it every frame as appropriate given Newton's law of universal gravitation. The point masses don't move (there's only 1 right now) so I would expect an elliptical orbit.

Instead, I see this:

I've tried with nearly circular orbits, and I've tried making the masses vastly different (a factor of a million) but I always get this rotated orbit.

Here's some (D) code, for context:

```
void accelerate(Vector delta)
{
    velocity = velocity + delta; // Velocity is a member of the ship class.
}

// This function is called every frame with the fixed mass. It's a
// method of the ship's.
void fall(Well well)
{
    // f=(m1 * m2)/(r**2)
    // a=f/m
    // Ship mass is 1, so a = f.
    float mass = 1;
    Vector delta = well.position - loc;
    float rSquared = delta.magSquared;
    float force = well.mass/rSquared;
    accelerate(delta * force * mass);
}

```

# Answer
> 7 votes
The bug is in the `fall` function. We have

1. `delta`: a vector from the well to the ship
2. `force`: the magnitude of the gravity between these two bodies.

`|force|` is G * m1 * m2 / r^2

but `|delta|` is already r! so you are actually accelerating too fast. You need to divide by `r` again (basically normalizing the delta vector) before calling accelerate.

```
accelerate(delta * well.mass * mass / rSquared / Math.sqrt(rSquared))

```

# Answer
> 4 votes
Note that even with the math bug(s) fixed, you're using Euler integration (i.e. `velocity += delta` and presumably `position += velocity`), so you're probably going to get some odd effects like rotation of the orbital ellipse over time, and perhaps the ellipse getting larger/smaller since Euler integration isn't guaranteed to conserve energy.

You might want to switch to leapfrog integration, which is energy-conserving and should work better for orbital mechanics. Also, you should include the frame time in your equations so that the speed of your simulation is framerate-independent.

---
Tags: mathematics, physics, orbit
---


title: Essential 2D engine features

text:
# Question
Title: Essential 2D engine features
I have decided to make a simple engine for a new game I'm working on, and now, I'm wondering: **what are the essential features of a 2D game engine?** Or, a game engine in general?

# Answer
> 12 votes
Add whatever your game needs. Not every engine needs every feature and I strongly recommend you to focus on the ones used by your game, if you ever want to finish working on it.

It's as easy to get lost in collecting engine features as it is to be frustrated later when figuring out that the gain of all this work turned out to be void because those engine features were never put to good use.

In general, I'd say that the following 2d engine components are quite common:

* Scene Management
* Resource Management
* Sprites, Tilemaps, Sprite Fields (probably combined with some kind of parallax layering technique or even "3d coordinates")
* Particle systems
* Sound / Music handling
* Input handling
* Collision detection / Physics

# Answer
> 3 votes
There aren't that many essential features for a game engine. It all depends on for what kind of game the engine is.

Well, the few features pretty much any 2D engine needs:

* Loading and displaying sprites (including animations)
* Loading and playing sounds
* Loading and playing music
* Rendering Text
* Resource Management (in a HTML 5/JS engine the browser takes care of this)
* Input handling

Everthing else really depends a lot on the kind of game the engine is made for. Particle effects might be useful for a action game, but maybe not so much for a strategy game. Same for physics. Some games work best with tile maps, while others may work better with some kind of polygon landscape or a landscape made of decals. Story heavy games need a proper way for handling cutscenes. A jump and run engine would need the functionality to handle slopes. etc. etc.

---
Tags: 2d, javascript, html5
---


# Question
Title: Camera rotation - First Person Camera using GLM
I've just switched from deprecated opengl functions to using shaders and GLM math library and i'm having a few problems setting up my camera rotations (first person camera). I'll show what i've got setup so far.

I'm setting up my ViewMatrix using the glm::lookAt function which takes an eye position, target and up vector

```
// arbitrary pos and target values
pos = glm::vec3(0.0f, 0.0f, 10.0f);
target = glm::vec3(0.0f, 0.0f, 0.0f);
up = glm::vec3(0.0f, 1.0f, 0.0f);

m_view = glm::lookAt(pos, target, up);

```

i'm using glm::perspective for my projection and the model matrix is just identity

```
m_projection = glm::perspective(m_fov, m_aspectRatio, m_near, m_far);

model = glm::mat4(1.0);

```

I send the MVP matrix to my shader to multiply the vertex position

```
glm::mat4 MVP = camera->getProjection() * camera->getView() * model;
// in shader
gl_Position = MVP * vec4(vertexPos, 1.0);

```

My camera class has standard rotate and translate functions which call glm::rotate and glm::translate respectively

```
void camera::rotate(float amount, glm::vec3 axis)
{
    m_view = glm::rotate(m_view, amount, axis);
}
void camera::translate(glm::vec3 dir)
{
    m_view = glm::translate(m_view, dir);
}

```

and i usually just use the mouse delta position as the amount for rotation

Now normally in my previous opengl applications i'd just setup the yaw and pitch angles and have a sin and cos to change the direction vector using (gluLookAt) but i'd like to be able to do this using GLM and matrices.

So at the moment i have my camera set 10 units away from the origin facing that direction. I can see my geometry fine, it renders perfectly. When i use my rotation function...

```
camera->rotate(mouseDeltaX, glm::vec3(0, 1, 0));

```

What i want is for me to look to the right and left (like i would with manipulating the lookAt vector with gluLookAt) but what's happening is It just rotates the model i'm looking at around the origin, like im just doing a full circle around it. Because i've translated my view matrix, shouldn't i need to translate it to the centre, do the rotation then translate back away for it to be rotating around the origin? Also, i've tried using the rotate function around the x axis to get pitch working, but as soon as i rotate the model about 90 degrees, it starts to roll instead of pitch (gimbal lock?).

Thanks for your help guys,

and if i've not explained it well, basically i'm trying to get a first person camera working with matrix multiplication and rotating my view matrix is just rotating the model around the origin.

# Answer
Answer:

Thanks for your help guys.

I just kept track and updated the position and heading variable separately from the view matrix.

```
glm::vec3 m_position;
glm::vec3 m_direction;

...

// speed is usually 0.1f or something small like that
void camera::rotate(float amount, glm::vec3& axis)
{
    m_direction = glm::rotate(m_direction, amount * m_speed, axis);
}

void camera::translate(glm::vec3& direction)
{
    m_position += direction;
}

// call this once per loop
// m_up is glm::vec3(0, 1, 0) for a first person camera
void camera::update()
{
    m_view = glm::lookAt(m_position, m_position + m_direction, m_up);
}

```

and just if anyone is curious about strafing of the camera i'll add that code in

```
enum MovementType {FORWARD, BACKWARD, STRAFE_L, STRAFE_R};

void camera::applyMovement(MovementType movement)
{
    switch (movement)
    {
        case FORWARD:
            m_position += m_direction;
        break;
        case BACKWARD:
            m_position -= m_direction;
        break;
        case STRAFE_LEFT:
            m_position += glm::cross(m_direction, m_up);
        break;
        case STRAFE_RIGHT:
            m_position -= glm::cross(m_direction, m_up);
        break;
    }
}

```
> 3 votes

# Answer
This problem doesn't sound like gimbal lock to me.

It seems to be a case of your translation matrix and rotation matrix being combined together and in the wrong order.

The correct way to do this would be to apply the rotation matrix to the object first, then simply ADD the translation vector, rather than multiplying it in. This will then translate the object on the world axes rather than the objects transformed local axes. This means that the final rotation matrix will rotate irrespective of the translation vector applied afterwards, thus pivoting around its local origin, rather than orbiting around the world origin as you have described.
> 1 votes

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


title: Extra fire simulation on iPad device

text:
# Question
Title: Extra fire simulation on iPad device
I have with me an iOS app for iPad which creates a few fire simulations over a png.Well,its working well exactly how we wanted it but when we are testing it on a device,we get an extra fire simulation.Heres the screen:

**iPad Simulator:**

**iPad Device:**

*EDIT:*

Thanks for your responses.I hoped that the response here wouldn't be strong enough so i didn't place the code previously.Apologies.

This is a snippet from my FireplacesAnimation.m which is responsible for generating the emitter

```
-(ParticleEmitter *)generateParticle
{
Texture *particleTexture = [[Texture alloc] initWithName:@"particle.png"];
return [[ParticleEmitter alloc] initParticleEmitterWithTexture:particleTexture
                                                      position:Vector2fMake(0, 0)
                                        sourcePositionVariance:Vector2fMake(100, 10)
                                                         speed:5.25f
                                                 speedVariance:0.2f
                                              particleLifeSpan:0.75f
                                      particleLifespanVariance:0.25f
                                                         angle:90.0f
                                                 angleVariance:0
                                                       gravity:Vector2fMake(0.0f, 0.5f)
                                                    startColor:Color4fMake(1.0f, 0.0f, 0.0f, 1.0f)
                                            startColorVariance:Color4fMake(0.2f, 0.2f, 0.2f, 1.0f)
                                                   finishColor:Color4fMake(1.0f, 1.0f, 0.3f, 0.0f)
                                           finishColorVariance:Color4fMake(0.4f, 0.4f, 0.4f, 0.0f)
                                                  maxParticles:500
                                                  particleSize:20
                                          particleSizeVariance:50
                                                      duration:500.0f
                                                 blendAdditive:YES];}

```

and i am using the following code to create the frame buffer:

```
(BOOL)createFramebuffer {

glGenFramebuffersOES(1, &viewFramebuffer);
glGenRenderbuffersOES(1, &viewRenderbuffer);

glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
[context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(CAEAGLLayer*)self.layer];
glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer);

glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);

if (USE_DEPTH_BUFFER) {
    glGenRenderbuffersOES(1, &depthRenderbuffer);
    glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthRenderbuffer);
    glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight);
    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer);
}

if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) {
    NSLog(@"failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES));
    return NO;
}

return YES;

```

}

aand.. drawview:

```
(void)drawView {
if(fireStopcount > 75){
self.alpha = 1.0;
static BOOL viewInitialized = NO;
static CFTimeInterval lastTime;

CFTimeInterval time;
time = CFAbsoluteTimeGetCurrent();

float delta = (time - lastTime);
lastTime = time;
// Replace the implementation of this method to do your own custom drawing

[explosion1 update:delta];
[explosion2 update:delta];
[explosion3 update:delta];

[EAGLContext setCurrentContext:context];
//NSLog(@"Draw Animation Fire Places View");
glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);

if(!viewInitialized)
{
    //viewInitialized = YES;
    glViewport(0, 0, backingWidth, backingHeight);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    glOrthof(0.0f, 320.0f, 0.0f, 480.0f, -100.0f, 100.0f);
    glMatrixMode(GL_MODELVIEW);

    glDisable(GL_DEPTH_TEST);
    glEnable(GL_TEXTURE_2D);
    glEnable(GL_BLEND);

}

glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);

if(explosion1.active != YES)
{
    explosion1.angle = 90.0f;
    explosion1.particleSize = 20.0f;
    explosion1.sourcePosition = [self firstFirePlacePoint];
    explosion1.active = YES;
    explosion1.duration = rand() % 2 + 1;
    explosion1.sourcePositionVariance = Vector2fMake(20,20);
}

if(explosion2.active != YES)
{
    explosion2.angle = 90.0f;
    explosion2.sourcePosition = [self secondFirePlacePoint];
    explosion2.active = YES;
    explosion2.duration = rand() % 2 + 1;
    explosion2.sourcePositionVariance = Vector2fMake(20,20);
}

if(explosion3.active != YES)
{
    explosion3.angle = 90.0f;
    explosion3.sourcePosition = [self thirdFirePlacePoint];
    explosion3.active = YES;
    explosion3.duration = rand() % 2 + 1;
    explosion3.sourcePositionVariance = Vector2fMake(20,20);
}

[explosion1 renderParticles];
[explosion2 renderParticles];
[explosion3 renderParticles];

glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
[context presentRenderbuffer:GL_RENDERBUFFER_OES];
}
else
{
fireStopcount++;
}}

```

**Thanks for your time guys.**

# Answer
> 1 votes
I can't comment on your method of producing fire as you haven't shared any code, so I'm going to suggest a new one for creating fire.

http://particledesigner.71squared.com/

Download that and take a look at the fire animations on there. In the meantime edit your answer with some code and a little bit more about the framework you're using (if you're using one), for example cocos2d.

---
Tags: iphone, ios, opengl-es, ipad
---


title: Mapping a Vertex Buffer in DirectX11

text:
# Question
Title: Mapping a Vertex Buffer in DirectX11
I have a VertexBuffer that I am remapping on a per frame base for a bunch of quads that are constantly updated, sharing the same material\index buffer but have different width/heights. However, currently right now there is a really bad flicker on this geometry.

Although it is flickering, the flicker looks correct. I know it is the vertex buffer mapping because if I recreate the entire VB then it will render fine. However, as an optimization I figured I would just remap it. Does anyone know what the problem is?

The length (width, size) of the vertex buffer is always the same.

One might think it is double buffering, however, it would not be double buffering because it only happens when I map/unmap the buffer, so that leads me to believe that I am setting some parameters wrong on the creation or mapping.

I am using DirectX11, my initialization and remap code are:

### Initialization code

```
  D3D11_BUFFER_DESC bd;
  ZeroMemory( &bd, sizeof(bd) );
  bd.Usage = D3D11_USAGE_DYNAMIC;
  bd.ByteWidth = vertCount * vertexTypeWidth;
  bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
  //bd.CPUAccessFlags = 0;
  bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;

  D3D11_SUBRESOURCE_DATA InitData;
  ZeroMemory( &InitData, sizeof(InitData) );
  InitData.pSysMem = vertices;

  mVertexType = vertexType;

  HRESULT hResult = device->CreateBuffer( &bd, &InitData, &m_pVertexBuffer );

  // This will be S_OK
  if(hResult != S_OK)
     return false;

```

### Remap code

```
  D3D11_MAPPED_SUBRESOURCE resource;
  HRESULT hResult = deviceContext->Map(m_pVertexBuffer, 0,
     D3D11_MAP_WRITE_DISCARD, 0, &resource);

  // This will be S_OK
  if(hResult != S_OK)
     return false;

  resource.pData = vertices;

  deviceContext->Unmap(m_pVertexBuffer, 0);

```

# Answer
> 9 votes
When you invoke Map with D3D11\_MAP\_WRITE\_DISCARD, Direct3D considers the whole buffer contents invalid and will replace it with the data that exists inside the memory that the new data buffer points at when invoking Unmap.

Your problem is that instead of copying your data into the memory that Direct3D provides to you when you map the buffer, you instead change the pointer to point somewhere else.

Direct3D does not expect that, nor will care about where the pointer points. It will just assume that you've filled in the buffer that the pData pointer originally pointed at.

The reason for your flicker is because the buffer may contain bogus uninitialized data, as it expects you to fill it in completely.

# Answer
> 0 votes
I think the map you used is wrong, look the code below, wish to help you.

```
if(FAILED(pCtx->Map(m_pvertexbuffer[0],0,D3D11_MAP::D3D11_MAP_WRITE_DISCARD,0,&Mapped)))
{
    PostQuitMessage(0);
}
VERTEX_STRUCT *ptr=(VERTEX_STRUCT*)Mapped.pData;
for(int i=0;i<LENGTH;i++)
{
    x=r*cos(2*3.142*i/length);
    y=r*sin(2*3.142*i/length);
    ptr[i].pos = XMFLOAT3(x,y,0);  // Bottom left.
    //srand((int)time(0));
    srand((GetTickCount()%65536));
    ptr[i].color.x=(float(rand())/RAND_MAX);
    srand((GetTickCount()%65536)-1000);
    ptr[i].color.y=(float(rand())/RAND_MAX);
    srand((GetTickCount()%65536)-2000);
    ptr[i].color.z=(float(rand())/RAND_MAX);
}
pCtx->Unmap(m_pvertexbuffer[0],0);

```

---
Tags: directx, rendering, directx11, vertex
---


# Question
Title: What kind of performance issues does multiple instances of the exact same object have on a game?
I'm fairly new to programming, and I've pretty much learned all the things I know on the go, while working on projects. The problem is that there some things that I just don't know where to begin searching.

My question is about performance, and how can multiple instances of the same object affect it -- Specifically, I'm talking about XNA's "GraphicsDevice" class. I have it instanced on four different parts of my game, and in three of those, the object has the exact same values for all the attributes. So, in that case, should I be using the same instance of GraphicsDevice, passing it as a parameter, even if I use it in different classes?

I apologize if the question seems redundant, but like I said, I've taught myself most of what I know, so there are quite a few "holes" in my learning process.

# Answer
> 2 votes
Yes, you should have only one `GraphicsDevice` per game, and don't instance it manually ever. Just pass it as a parameter to the functions that need to access it or share it via a global singleton class.

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


# Question
Title: How do I draw a single Triangle with XNA and fill it with a Texture?
I'm trying to wrap my head around:

http://msdn.microsoft.com/en-us/library/bb196409.aspx

I'm trying to create a method in XNA that renders a single Triangle, then later make a method that takes a list of Triangles and renders them also. But it isn't working. I'm not understanding what all the things does and there's not enough information.

## My methods:

```
// Triangle is a struct with A, B, C (didn't include) A, B, C = Vector3

public static void Render(GraphicsDevice device, List<Triangle> triangles, Texture2D texture)
{
    foreach (Triangle triangle in triangles)
    {
        Render(device, triangle, texture);
    }
}

public static void Render(GraphicsDevice device, Triangle triangle, Texture2D texture)
{
    BasicEffect _effect = new BasicEffect(device);
    _effect.Texture = texture;
    _effect.VertexColorEnabled = true;

    VertexPositionColor[] _vertices = new VertexPositionColor[3];

    _vertices[0].Position = triangle.A;
    _vertices[1].Position = triangle.B;
    _vertices[2].Position = triangle.B;

    foreach (var pass in _effect.CurrentTechnique.Passes)
    {
        pass.Apply();

        device.DrawUserIndexedPrimitives<VertexPositionColor>
        (
            PrimitiveType.TriangleList,
            _vertices,
            0,
            _vertices.Length,
            new int[] { 0, 1, 2 }, // example has something similiar, no idea what this is
            0,
            3 // 3 = gives me an error, 1 = works but no results
        );
    }

}

```

---

## Now my method looks like this, according to your recommendations:

```
    public static void Render(GraphicsDevice device, Triangle triangle, Color color)
    {
        BasicEffect _effect = new BasicEffect(device);
        _effect.Texture = ColorToTexture(device, color, 1, 1);
        _effect.TextureEnabled = true;
        //_effect.VertexColorEnabled = true;

        VertexPositionTexture[] _vertices = new VertexPositionTexture[3];

        _vertices[0].Position = triangle.A;
        _vertices[1].Position = triangle.B;
        _vertices[2].Position = triangle.C;

        foreach (var pass in _effect.CurrentTechnique.Passes)
        {
            pass.Apply();

            device.DrawUserIndexedPrimitives<VertexPositionTexture>
            (
                PrimitiveType.TriangleStrip, // same result with TriangleList
                _vertices,
                0,
                _vertices.Length,
                new int[] { 0, 1, 2 },
                0,
                1
            );
        }

    }

```

and my method that creates a texture from color (tried this with single spriteBatch.Draw() = works)

```
    public static Texture2D ColorToTexture(GraphicsDevice device, Color color, int width, int height)
    {
        Texture2D texture = new Texture2D(device, 1, 1);
        texture.SetData<Color>(new Microsoft.Xna.Framework.Color[] { color });

        return texture;
    }

```

and in my Draw method in Main Game:

```
Render(GraphicsDevice, new Triangle(new Vector3(50, 50, 0), new Vector3(100, 100, 0), new Vector3(150, 50, 0)), Color.Green);

```

= no triangle on screen.

# Answer
I think you should rather use VertexPositionTexture structure instead of VertexPoisitionColor to define vertex and texture coordinates. Also set: `_effect.TextureEnabled` to true.

And to your DrawUserIndexedPrimitives call:

* fifth parameter is indeces to the array of vertices. So you render triangle defined by vertices \_vertices\[0\], \_vertices\[1\], \_vertices\[2\].
* Last parameter is number of primitives to render - you have only one triangle with 3 vertices. So you should really pass 1.

As r2d2rigo wrote: your two vertices are the same point:

```
_vertices[1].Position = triangle.B;
_vertices[2].Position = triangle.B;

```

**UPDATE:**

Vertex coordinates have to be in range \<-1;1\>. 0,0 is center point of the screen (window).
> 0 votes

# Answer
The code you pasted should be drawing a line because you are assigning `_vertices[1]` and `_vertices[2]` the same triangle vertex. Fix it and change the last paramenter in `DrawUserIndexedPrimitives` to 1, since it's the number of primitives (in your case, triangles) that you are going to draw with that call.
> 0 votes

---
Tags: c#, textures, xna-4.0
---


title: Smoothing rotation

text:
# Question
Title: Smoothing rotation
I've spent the last three days trying to work out how to rotate a sprite smoothly depending on the velocity.x value of the sprite. I'm using this:

```
float Proportion = 9.5;
float maxDiff = 200;
float rotation = fmaxf(fminf(playerVelocity.x * Proportion, maxDiff), -maxDiff);
player.rotation = rotation;

```

The behaviour is what I required but if the velocity changes rapidly then it will look like the sprite will jump to face left or jump to face right.

I'll go into the behaviour in a little more detail:

```
0 velocity = sprite faces forwards

negative velocity = sprite faces left depending on value.

positive velocity = sprite faces right (higher velocity the more it faces right) same as above.

```

I've read about using interpolation rather than an absolute angle to rotate it to but I don't know how to implement that.

I have a physics engine available.

There is one other way to get around this: to use `+=` on the rotation angle. The thing is that I would then have to change the equation to produce positive and negative values then to make sure the sprite faces 0 once it reaches 0 velocity again. If I add that in now, it keeps the previous angle even after the velocity has dropped / is dropping.

Any ideas/code snippets would be greatly appreciated.

# Answer
> 5 votes
There are numerous ways of smoothening a rotation. If there is any physical meaning to it, we'll need to know what that is, but if you are merely doing it to make it appear less jerky, it is pretty arbitrary. Note that unless you know what the velocity is going to do in advance, any attempt to smoothen the corresponding rotation will cause it to lag behind to some degree, which may lead to weird oscillatory behaviour. It also prevents you from smoothly setting the rotation to zero simultaneously with the velocity hitting zero.

A simple way would be to make the rotation respond exponentially, i.e. use an angular velocity proportional to the difference between the sprite's current and target rotation.

```
targetrotation = fmaxf(fminf(playerVelocity.x * Proportion, maxDiff), -maxDiff);
angularvelocity = (targetrotation - player.rotation) * rotationspeed;
player.rotation += angularvelocity * timestep;

```

Let's say your `playerVelocity.x` looked like this:

The plots below indicate an example rotation against time using various values for `rotationspeed` using this exponential smoothening method.

You may want to cap the angular velocity to zero under a specified magnitude. The integration method is very crude and given enough time to settle, the timestep will eventually be too large and the rotation will overshoot its target. The resulting oscillation might even consistently increase in amplitude. An example:

Imagine the rotation being very close to its target. As it comes closer, the angular velocity should gradually decrease until it eventually stops. However, the angular velocity isn't constantly updated; it is updated once every timestep. During these steps, the angular velocity should be decreasing, but instead, the rotations keeps changing at a constant rate. Below is what might happen.

The yellow line indicates the intended behaviour. You can see the blue line (timesteps of 0.1) starts with the right slope, but isn't updated for a while. It's a little high, but doesn't cause any major issues. The red line has more time in between steps (0.2). By the time the slope is updated, the rotation has overshot its target.

There are more elaborate ways of tackling this problem, but you are somewhat handicapped by the fact that the target rotation might be changing too. The simplest way would be to specify a range around the target where the rotation is 'close enough' and should stop moving. How large this range should be depends on your timestep and maximum angular velocity, but I suggest some experimentation.

---
Tags: mathematics, iphone, cocos2d-iphone, cocos2d, rotation
---


title: How to handle animations?

text:
# Question
Title: How to handle animations?
I am coding a simple 2D engine to be used with HTML5. I already have classes such as Picture, Scene, Camera and Renderer, but now I need to work on Animations.

Picture is basocally a wrapper for a normal image object, with it's own draw method, but this is unrelated, I'm interested in how animation in 2D games is usually done.

What I planned to do, is to have the Animation class as well act like a wrapper for a few image objects, and then have methods such as getCurrentImage, next and animate (which would use intervals to quickly change the current image). I meant to feed the animation a couple of PNG's at inicialisation.

Is quickly swapping PNG images acceptable for 2D animation? Are there some standard ways of doing this, or are there flaws in my ways?

# Answer
> 2 votes
The specific answer depends a lot on your specific needs. Your approach will in general work quite fine. It can potentially be made faster using a texture atlas (aka sprite sheet) depending on how you're doing the rendering, and faster still by using batching rather than having the objects draw themselves, but the actual approach to loading and running the animations is generally the same.

More advanced games sometimes need more advanced animation techniques. Multi-part sprites allow for a single character to transform and move in independent ways. A basic example of that is to have the legs and torso of a character separate, so you can animate walking and aiming a weapon independently. Again, though, the core of the animation system there is the exact same a your idea.

More complex systems exist that use techniques usually seen only in 3D. Flash games sometimes make use of these techniques as Flash has som excellent 2D skeletal animation packages. Even some non-Flash games use such approaches, often by importing the Flash assets (so artists can keep using the familiar high quality tools they already have). The math and rendering techniques for these kinds of animations are much more complex, and you almost certainly don't want to use them unless you've got a team dedicated just to graphics and art pipeline code and a mob of artists to produce content for it.

---
Tags: 2d, animation, javascript, html5
---


# Question
Title: Calc direction vector based on destination vector and distance from enemy in AS3
I'm working on a zombie game in AS3 where I want a character to be able to move away from a zombie depending upon how close the zombie is. The character also has a destination that it's trying to get too on the screen.

Ok so I have 2 vectors, one pointing to my destination, and one pointing to the zombie which I then invert to get my "away" vector. I then turn the distance between my character and the zombie into a value between 0 and 1. And then I'm stuck on how to get a resultant vector for my character. How would I use my 0-1 value to calculate how much of the away vector is used and how much of the original destination vector is still left if that makes sense? to end up with 1 direction vector to move my character? So if the zombie is right where my character is, then my direction vector = away vector, and if I'm far away from the zombie than my direction vector = destination vector, but how do I calculate the in-between?

Ideally need the answer in AS3.

# Answer
Simply add the vectors together, after scaling them.

```
 DestinationVector.scale(1-awayFactor)
 AwayVector.scale(awayFactor)

 CharacterDirection = DestinationVector + AwayVector

```

Where `awayFactor` is your 0-1 value.

Sorry, I don't know AS3, so I can't write it in that language.

If it's just `x` and `y` vectors this is the same as:

```
DestVec.x *= (1-awayFactor)
DestVec.y *= (1-awayFactor)

AwayVec.x *= awayFactor
AwayVec.y *= awayFactor

CharVec.x = DestVec.x + AwayVec.x
CharVec.y = DestVec.y + AwayVec.y

```
> 2 votes

# Answer
I would try ordinary linear interpolation. If your destination vector is D (dx, dy, dz) and away vector is A (ax, ay, az), and your 0-1 value is V, then final vector F would be:

```
F = V * A + (1 - V) * D = (V * ax + (1 - V) * dx, ....)

```

If V is 1 (as in your example), you will get `F = 1 * A + (1 - 1) * D = A`, just as in your example.

But you should be careful with 0-1 value (if it isn't in range 0-1, then don't use interpolation) and also with vector normalization (I don't know, if you are using normalized vectors or not).
> 1 votes

---
Tags: actionscript-3, vector
---


# Question
Title: Help with converting an XML into a 2D level (Actionscript 3.0)
I'm making a little platformer and wanted to use Ogmo to create my level. I've gotten everything to work except the level that my code generates is not the same as what I see in Ogmo. I've checked the array and it fits with the level in Ogmo, but when I loop through it with my code I get the wrong thing. I've included my code for creating the level as well as an image of what I get and what I'm supposed to get.

EDIT: I tried to add it, but I couldn't get it to display properly

Also, if any of you know of better level editors please let me know.

```
xmlLoader.addEventListener(Event.COMPLETE, LoadXML);
xmlLoader.load(new URLRequest("Level1.oel"));
        function LoadXML(e:Event):void
        {
            levelXML = new XML(e.target.data);
            xmlFilter = levelXML.*
            for each (var levelTest:XML in levelXML.*)
            {
                crack = levelTest;
            }
            levelArray = crack.split('');
            trace(levelArray);
            count = 0;
            for(i = 0; i <= 23; i++)
            {
                for(j = 0; j <= 35; j++)
                {
                    if(levelArray[i*36+j] == 1)
                    {
                        block = new Platform;
                        s.addChild(block);
                        block.x = j*20;
                        block.y = i*20;
                        count++;
                        trace(i);
                        trace(block.x);
                        trace(j);
                        trace(block.y);
                    }
                }
            }
            trace(count);

```

# Answer
this is just a guess but can you make sure your "levelArray" does't contain "\n" at the end of each line. maybe changing your condition to `if(levelArray[i*37+j] == 1)` solve the problem. note that it might also have an extra "\n\r" at the end of each line. In that case you need to multiply i by 38 in that condition.

actually after checking the image you provided again, I'm now pretty sure the lines are ending with an only extra "\n", meaning each line is 37 character not 36 as you expected.
> 3 votes

---
Tags: flash, actionscript-3, level-design
---