title: Problem rotating cubes in opengl

text:
# Question
Title: Problem rotating cubes in opengl
I'm trying to make a simple 3d tetris game, but I'm having trouble rotating my blocks. The blocks are made up of 4 cubes (drawn with glutSolidCube()). I can't figure out how I can rotate them and still have the axes point in the right direction for the cubes' movement.

This is the simplest form of what I've tried that clearly illustrates the problem when I run it

```
for(int i=0; i<4; i++){
    glPushMatrix();
    glRotatef(90.0, 1,0,0);
    glTranslatef(cubes[i]->xPos, cubes[i]->yPos, cubes[i]->zPos);
    cubes[i]->draw();
    glPopMatrix();
}

```

And this not only rotates the block, but rotates the whole system in the sense that now, the blocks are rotated in the right direction, but move in from the side rather than the top as if the axes have been rotated as well. I've tried first translating to the point where they start falling, rotating and translating back, but they still just go sideways. (not included in the sample because the start location isn't the main problem here)

I sort of understand why this happens, but I don't know how to fix it.

# Answer
> 1 votes
What you aren't showing is how the cubes' falling translation is applied. From your description of the effects, it is occurring *after* the rotation; so you are either translating in `->draw()` or updating the `yPos` etc. coordinates. The "graphics" fix to your problem is to apply the falling motion *before* your `glRotate`.

**However**, this would be setting yourself up for bigger problems. You are eventually going to want to collide your cubes against the rest of the objects in the playfield so as to know when to stop them and remove rows etc. Just rotating in the rendering isn't sufficient to handle that.

Therefore, you are going to want to compute the rotation yourself, not delegate it to OpenGL. My recommendation would be to *actually change the configuration of the cubes* — that is, change `xPos`, `yPos`, and `zPos` according to the rotation. Since you are only doing 90° rotations, this is especially simple. This means your collision tests do not have to think about rotations.

(If this does not seem to be an appropriate answer, then please update your question with details of how you are animating the falling.)

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


# Question
Title: Trying to understand 2D vector -> projection space conversion
I'm trying to understand how I can transform 2D vectors (x, y) to projection space. Something hasn't quite clicked for me yet. As per my previous question, here's the effect I'm trying to achieve:

My object model is entirely in 2D world space, but I want to render it as per above. That is, position the camera above at about 45 degrees looking down on my scene. Objects further away will appear smaller and move towards the center of the screen.

In an effort to visualize this, I put together a WPF/XNA application that renders a bunch of dots in world, view, and projection spaces. The parameters for the view and projection matrices can be altered in real-time and the resulting projections update accordingly.

However, things aren't being rendered as I expected/hoped. Here's what I see:

I was expecting to see the projection space render a road off into the distance similar to the earlier screenshot.

Can someone take a look at the code and see what it is I'm doing wrong? Apologies for the wall of code, but I didn't want to leave anything out as I may have done something stupid anywhere.

**Vector2Collection**:

```
namespace PerspectiveTest
{
    using System.Collections.ObjectModel;
    using Microsoft.Xna.Framework;

    public sealed class Vector2Collection : ObservableCollection<Vector2>
    {
    }
}

```

**VectorSurface**:

```
using System.Linq;
using System.Windows;
using System.Windows.Media;
using XNA = Microsoft.Xna.Framework;

namespace PerspectiveTest
{
    public sealed class VectorSurface : FrameworkElement
    {
        public static readonly DependencyProperty BrushProperty = DependencyProperty.Register(
            "Brush",
            typeof(Brush),
            typeof(VectorSurface),
            new FrameworkPropertyMetadata(OnPropChanged));

        public static readonly DependencyProperty MatrixProperty = DependencyProperty.Register(
            "Matrix",
            typeof(XNA.Matrix),
            typeof(VectorSurface),
            new FrameworkPropertyMetadata(XNA.Matrix.Identity, OnPropChanged));

        public static readonly DependencyProperty VectorsProperty = DependencyProperty.Register(
            "Vectors",
            typeof(Vector2Collection),
            typeof(VectorSurface),
            new FrameworkPropertyMetadata(OnPropChanged));

        public Brush Brush
        {
            get { return (Brush)this.GetValue(BrushProperty); }
            set { this.SetValue(BrushProperty, value); }
        }

        public XNA.Matrix Matrix
        {
            get { return (XNA.Matrix)this.GetValue(MatrixProperty); }
            set { this.SetValue(MatrixProperty, value); }
        }

        public Vector2Collection Vectors
        {
            get { return (Vector2Collection)this.GetValue(VectorsProperty); }
            set { this.SetValue(VectorsProperty, value); }
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);

            if (this.Vectors == null)
            {
                return;
            }

            var matrix = this.Matrix;
            var transformed = new XNA.Vector3[this.Vectors.Count];
            var vectors3 = this.Vectors.Select(x => new XNA.Vector3(x.X, x.Y, 0)).ToArray();
            XNA.Vector3.Transform(vectors3, ref matrix, transformed);

            foreach (var vector in transformed)
            {
                drawingContext.DrawEllipse(this.Brush, null, vector.ToWpfPoint(), 1, 1);
            }
        }

        private static void OnPropChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            ((VectorSurface)dependencyObject).InvalidateVisual();
        }
    }

    public static class PointExtensions
    {
        public static Point ToWpfPoint(this XNA.Vector2 vector)
        {
            return new Point(vector.X, vector.Y);
        }

        public static Point ToWpfPoint(this XNA.Vector3 vector)
        {
            return new Point(vector.X, vector.Y);
        }
    }
}

```

**MainWindow.xaml.cs**:

```
using System.ComponentModel;
using System.Windows;
using XNA = Microsoft.Xna.Framework;

namespace PerspectiveTest
{
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private readonly Vector2Collection vectors;
        private XNA.Vector3 cameraPosition;
        private XNA.Vector3 cameraTarget;
        private XNA.Vector3 cameraUp;
        private float fieldOfView;
        private float aspectRatio;
        private float nearPlaneDistance;
        private float farPlaneDistance;

        public event PropertyChangedEventHandler PropertyChanged;

        public Vector2Collection Vectors
        {
            get { return this.vectors; }
        }

        public XNA.Vector3 CameraPosition
        {
            get { return this.cameraPosition; }
            set
            {
                if (this.cameraPosition != value)
                {
                    this.cameraPosition = value;
                    this.OnPropertyChanged("CameraPosition");
                    this.CreateViewMatrix();
                }
            }
        }

        public XNA.Vector3 CameraTarget
        {
            get { return this.cameraTarget; }
            set
            {
                if (this.cameraTarget != value)
                {
                    this.cameraTarget = value;
                    this.OnPropertyChanged("CameraTarget");
                    this.CreateViewMatrix();
                }
            }
        }

        public XNA.Vector3 CameraUp
        {
            get { return this.cameraUp; }
            set
            {
                if (this.cameraUp != value)
                {
                    this.cameraUp = value;
                    this.OnPropertyChanged("CameraUp");
                    this.CreateViewMatrix();
                }
            }
        }

        public float FieldOfView
        {
            get { return this.fieldOfView; }
            set
            {
                if (this.fieldOfView != value)
                {
                    this.fieldOfView = value;
                    this.OnPropertyChanged("FieldOfView");
                    this.CreateProjectionMatrix();
                }
            }
        }

        public float AspectRatio
        {
            get { return this.aspectRatio; }
            set
            {
                if (this.aspectRatio != value)
                {
                    this.aspectRatio = value;
                    this.OnPropertyChanged("AspectRatio");
                    this.CreateProjectionMatrix();
                }
            }
        }

        public float NearPlaneDistance
        {
            get { return this.nearPlaneDistance; }
            set
            {
                if (this.nearPlaneDistance != value)
                {
                    this.nearPlaneDistance = value;
                    this.OnPropertyChanged("NearPlaneDistance");
                    this.CreateProjectionMatrix();
                }
            }
        }

        public float FarPlaneDistance
        {
            get { return this.farPlaneDistance; }
            set
            {
                if (this.farPlaneDistance != value)
                {
                    this.farPlaneDistance = value;
                    this.OnPropertyChanged("FarPlaneDistance");
                    this.CreateProjectionMatrix();
                }
            }
        }

        public MainWindow()
        {
            InitializeComponent();
            this.vectors = new Vector2Collection();
            this.PopulateVectors();

            this.cameraPosition = new XNA.Vector3(75, 200, 150);
            this.cameraTarget = new XNA.Vector3(75, 0, 0);
            this.cameraUp = new XNA.Vector3(0, 1, 0);
            this.fieldOfView = XNA.MathHelper.Pi / 4;
            this.aspectRatio = 1f;
            this.nearPlaneDistance = 1f;
            this.farPlaneDistance = 200f;

            this.CreateViewMatrix();
            this.CreateProjectionMatrix();
            this.DataContext = this;
        }

        private void PopulateVectors()
        {
            for (var i = 0; i < 150; i += 3)
            {
                this.Vectors.Add(new XNA.Vector2(60, i));
                this.Vectors.Add(new XNA.Vector2(90, i));
            }
        }

        private void CreateViewMatrix()
        {
            this.viewSpace.Matrix = XNA.Matrix.CreateLookAt(this.cameraPosition, this.cameraTarget, this.cameraUp);
            this.CreateProjectionMatrix();
        }

        private void CreateProjectionMatrix()
        {
            var viewMatrix = this.viewSpace.Matrix;
            var perspectiveMatrix = XNA.Matrix.CreatePerspectiveFieldOfView(this.fieldOfView, this.aspectRatio, this.nearPlaneDistance, this.farPlaneDistance);
            XNA.Matrix combinedMatrix;
            XNA.Matrix.Multiply(ref viewMatrix, ref perspectiveMatrix, out combinedMatrix);
            this.projectionSpace.Matrix = combinedMatrix;
        }

        private void OnPropertyChanged(string propertyName)
        {
            var handler = this.PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

```

**MainWindow.xaml**:

```
<Window x:Class="PerspectiveTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:PerspectiveTest"
        Title="MainWindow"
        SizeToContent="WidthAndHeight">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>

        <Label FontWeight="Bold" HorizontalAlignment="Center">World Space</Label>
        <Label Grid.Column="1" HorizontalAlignment="Center" FontWeight="Bold">View Space</Label>
        <Label Grid.Column="2" HorizontalAlignment="Center" FontWeight="Bold">Projection Space</Label>

        <Border Grid.Row="1" BorderThickness="1" BorderBrush="Gray" Margin="50, 10, 50, 50">
            <local:VectorSurface x:Name="worldSpace" Vectors="{Binding Vectors}" Brush="Black" Width="150" Height="150"/>
        </Border>
        <Border Grid.Row="1" Grid.Column="1" BorderThickness="1" BorderBrush="Gray" Margin="50, 10, 50, 50">
            <local:VectorSurface x:Name="viewSpace" Vectors="{Binding Vectors}" Brush="Red" Width="150" Height="150"/>
        </Border>
        <Border Grid.Row="1" Grid.Column="2" BorderThickness="1" BorderBrush="Gray" Margin="50, 10, 50, 50">
            <local:VectorSurface x:Name="projectionSpace" Vectors="{Binding Vectors}" Brush="Green" Width="150" Height="150"/>
        </Border>

        <Label Grid.Row="2">Camera Position:</Label>
        <TextBox Grid.Row="2" Grid.Column="1" Text="{Binding CameraPosition}"/>

        <Label Grid.Row="3">Camera Target:</Label>
        <TextBox Grid.Row="3" Grid.Column="1" Text="{Binding CameraTarget}"/>

        <Label Grid.Row="4">Camera Up:</Label>
        <TextBox Grid.Row="4" Grid.Column="1" Text="{Binding CameraUp}"/>

        <Label Grid.Row="5">Field of View:</Label>
        <TextBox Grid.Row="5" Grid.Column="1" Text="{Binding FieldOfView}"/>

        <Label Grid.Row="6">Aspect Ratio:</Label>
        <TextBox Grid.Row="6" Grid.Column="1" Text="{Binding AspectRatio}"/>

        <Label Grid.Row="7">Near Plane Distance:</Label>
        <TextBox Grid.Row="7" Grid.Column="1" Text="{Binding NearPlaneDistance}"/>

        <Label Grid.Row="8">Far Plane Distance:</Label>
        <TextBox Grid.Row="8" Grid.Column="1" Text="{Binding FarPlaneDistance}"/>
    </Grid>
</Window>

```

# Answer
> 2 votes
You seem to be under the misconception that you can apply a projection matrix the same way as you apply a world or view matrix, i.e. just by multiplying a position in world or view space by it. That's *not* how it works!

To put it simply, when applying the projection matrix, the `w` component is relevant, so you need to pass it a *4D vector* `(x,y,z,1)` and call `Vector4.Transform` instead. Afterwards you also need to *homogenize* the result (i.e. convert from 4D back to 3D) by *dividing* every component by `w`.

**Example**

```
// Position and combined matrix
Vector3 position = new Vector3(x,y,z);
Matrix matrix = world * view * projection;

// Apply matrix
Vector4 result = Vector4.Transform(new Vector4(position, 1), matrix);

// Homogenize result
result /= result.w;

// Show result
DrawEllipseAt(result.X, result.Y);

```

But you should also realize that the resulting coordinates are in *normalized clip space* with x/y coordinates ranging from -1 to 1 and the z coordinate ranging from 0 to 1.

Your coordinates might also have received a non-uniform scale by the projection in order to match the aspect ratio you chose when creating the projection matrix, so make sure you use sensible values, i.e. it should match the area in which you'd like to draw.

Finally you still need to convert the points from clip space to *screen space*. This is a simple mapping from the -1 to 1 range into your viewport.

**Example**

```
float halfWidth = viewport.Width / 2f;
float halfHeight = viewport.Height / 2f;
Vector2 screenResult;
screenResult.X = result.X * halfWidth + halfWidth + viewport.X;
screenResult.Y = -result.Y * halfHeight + halfHeight + viewport.Y;

```

*Note: If your Z values are all zero you won't see anything moving "into the distance". You need different Z values for any perspective to take place!*

# Answer
> 1 votes
Based on your camera's position and orientation, the object appearing smaller and farther away has to have a Z component value in the pre-transformed state that is less than the Z value of the closer object. Since both objects are the same height above the road, their Y component values in the pre-transformed state should be equal.

Where you convert your vectors from Vector2s to Vector3s, Your Vector2.Y should probably go to Vector3.Z. All Vector3.Ys should be 0 (or at least equal)...

The road in the screenshot goes off into the distance in the -Z direction (in 3dWorldSpace ref) (based on your camera position/target). So the farther away points should have a decreasing Z value in 3dworld space. Your pre-transformed points should be in 3dWorldSpace but it almost seems like you are trying to set your point values (PopulateVectors) in 2d space. That looks odd to me.

---
Tags: 2d, mathematics, matrix, perspective
---


title: Where can I get people to test my game?

text:
# Question
Title: Where can I get people to test my game?
I've just finished making the core aspects of my HTML5 game. I have a server and all that, but is there a site where I can find people that would test my game? I figured that getting my friends to do it wouldn't be a good option because they are probably biased, so I need people that I never met before, complete strangers. Also, would the people at gamedev forums be willing to do that? Would it be considered as advertising?

# Answer
Best advice I could give is to put what you have up, making it clear that it is still a beta and that you want people to play test it and link to it everywhere. This includes every game site you can think of include gamedev.net, moddb, here, facebook, twitter.

There is nothing wrong with advertising mate. How else are you going to get people to play your game? Just be clear and concise, and you'd be shocked at how friendly the game community is.
> 9 votes

---
Tags: html5, browser-based-games, testing, playtesting
---


# Question
Title: What basic windows form games should I build as a newbie in game development?
I am a complete newbie in game development. I want to know about some basic games that I can start building with simple algorithms and basic knowledge. I have already made few basic games like minesweeper, TicTacToe, basic card games, and a snake game. I just want to have an idea to start a new fun project.

# Answer
Some random ideas:

* A basic Tetris clone. Good practice in working with arrays and event handling, but not too heavy on the graphics side. Getting the blocks to behave exactly as in modern Tetrises (e.g. Tetris DS) is quite a challenge though!
* A point'n'click shooting gallery. You can have fun doing the graphics and sound effects, but the basic algorithms should be quite simple.
* A Geometry Wars type game. Some more geometry is involved, and this would generally be great practice if that is the direction you want to move towards.
> 0 votes

# Answer
To add to Thomas's answer; any 2D based game would be a good idea. Look at a lot of retro games and try and emulate one you really like the look of. Games like Asteroids, Space Invaders and Mario are all challenging enough to, but not too drastically difficult to implement.
> 1 votes

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


# Question
Title: Is there a specific library to handle the collision system of a big game world like WoW, or any physics library will work?
Nothing else to add. Is there a specific library to handle the collision system of a big game world like WoW, or any physics library like ODE will work?

# Answer
> 5 votes
An alternative is not to use any physics library at all:

* Collisions with the **environment** can be handled directly by the underlying **navigation mesh**.
* Collisions with **dynamic objects** could be as simple as **bounding sphere** collision checks using some sort of **space partitioning** to limit the amount of checks necessary.

# Answer
> 2 votes
Any physics library like ODE will work. Most, if not all, physics libraries will offer a way to divide objects into different 'subspaces', where only objects in the same subspace will collide. How exactly you handle things will mostly depend on how you do all the other 'large world handling'.

Let's put this differently: unless you want to do some extreme world-spanning physics effects, physics are going to be the least of your troubles in doing a big game world.

---
Tags: collision-detection
---


title: 3D Procedural Planet Generation

text:
# Question
Title: 3D Procedural Planet Generation
I was looking for some inspration for my Voxel based game I am writting and came across this: http://www.youtube.com/watch?v=rL8zDgTlXso. I would like to know how to go about (or preferably source examples) of how I would do that, in real time, and infinitley. In addition to that I was wondering how I would do this with a voxel based terrain?

A procedural planet generator in 3D which constructs voxel data, my voxels are of the same size of thoose in minecraft.

Any ideas?

**Edit:**

I ported the simplex noise function i\_grok suggested written in C++/Python to C#, I sure hope it works :)

http://pastebin.com/TZSQwnye

**Edit 2:**

```
float noise(float x, float y, float z, float persistance, float amplitude, float frequency, float octaves)  {
    float total = 0;

    for (int i = 0; i < octaves; i++)  {
        frequency = frequency ^ i;            // or frequency *= 2; ?
        amplitude = amplitude ^ i;

        total = total + SimplexNoise.raw_noise_3d(x * frequency, y * frequency, z * frequency) * amplitude;
    }

    return total;
}

```

# Answer
There are already a lot of resources. You can start with this post on gamedev: How are voxel terrain engines made?

These answers may be closer to your question: Voxel heightmap terrain editor

Most of the noise functions discussed here are fine for real-time - some can generate a million values a second. I'm not aware of a C# implementation, but what you're looking for is Simplex Noise (sometimes called Improved Perlin Noise). Simplex Noise can scale to any number of dimensions, but most people seem to implement 2D, 3D and 4D. I have implemented Simplex Noise in C and Python if you wish to port from there. There is also a Java implementation of Simplex Noise.
> 6 votes

# Answer
I was interested in this a while back. There is a (now old, but still relevant) book called Texturing and modelling: a procedural approach. One of the authors is Ken Musgrave aka Dr. Mojo who created mojoworld. There is a chapter in that book about procedural planet generation that you may find helpful.
> 2 votes

# Answer
If you are using Voxel/Boxels to represent your planet, you've got a problem ahead, planets are big balls of stuff, and cubes don't map onto the surface of balls very well.

You could use non-cubic blocks, but distortion will increase as you travel to the poles (and a stack of blocks will have to be wedge shaped)

You could volume fill a planet with blocks but there will be problems when you start approaching the horizon (as the down vector will change)

if you're really clever you will be able to generate the blocks on the fly to match volumetric data, but it won't be a 1:1 mapping like minecraft.
> 0 votes

---
Tags: xna, c#, procedural-generation, voxels, procedural
---


# Question
Title: Making particle bounce off a line with friction
So I'm making a game and I need a particle to bounce off a line. I've got this so far:

```
public static Vector2f Reflect(this Vector2f vec, Vector2f axis) //vec is velocity
    {
        Vector2f result = vec - 2f * axis * axis.Dot(vec);
        return result;
    }

```

Which works fine, but then I decided I wanted to be able to change the bounciness and friction of the bounce. I got bounciness down...

```
public static Vector2f Reflect(this Vector2f vec, Vector2f axis, float bounciness) //Bounciness goes from 0 to 1, 0 being not bouncy and 1 being perfectly bouncy
    {
        var reflect = (1 + bounciness); //2f

        Vector2f result = vec - reflect * axis * axis.Dot(vec);
        return result;
    }

```

But when I tried to add friction, everything went to hell and back...

```
public static Vector2f Reflect(this Vector2f vec, Vector2f axis, float bounciness, float friction) //Does not work at all!
    {
        var reflect = (1 + bounciness); //2f

        Vector2f subtract = reflect * axis * axis.Dot(vec);
        Vector2f subtract2 = axis * axis.Dot(vec);
        Vector2f result = vec - subtract;
        result -= axis.PerpendicularLeft() * subtract2.Length() * friction;
        return result;
    }

```

Any physics guys willing to help me out with this?

(if you're not sure what I mean with the friction of a bounce see this: http://www.metanetsoftware.com/technique/diagrams/A-1\_particle\_collision.swf)

# Answer
> 4 votes
Here's the physics answer. (I'm not sure exactly what `bounciness` and all refer to, but this should be easy to calculate)

Let's take a particle moving towards the wall with uy, and parallel to it with ux. It's coefficient of restitution is e (akin to 'bounciness', for perfectly bouncy it's 1. For normal items it's less than 1). Also, let the friction coefficient be m (The correct mathematical symbol for this is *mu*, represented as μ. But since that's visually similar to the 'u' value we're already using, we'll instead use 'm' for clarity). A friction coefficient is usually greater than 1.

Now, the resultant velocities will be:

* vy = -euy
* vx = ux \+ m(e-1)uy

---
Tags: c#, physics
---


# Question
Title: How to Simulate Height in a Tiled Top-Down Game
How can I simulate height in a top-down tiled 2D game? One way I thought was to make tiles which are supposed to be higher brighter, but I was wondering if there was a standard or better implementation.

# Answer
First of all and to clarify, do you require it to be *completely* top-down or do you consider something like this as being top-down too. In that example you can tell that the house is much taller than the barrel simply by the amount of tiles that they both span vertically. Also, allowing the character to move *behind* the objects is another good way to let the player realize how tall something is.

If on the other hand you really mean a *pure* top-down view of the world, you could try your own suggestion of giving different brightness values depending on the tile's height. Give it a try since it should be pretty easy to implement, and see if the results are satisfactory enough.

But if you wanted to give a stronger impression, perhaps you could add shadows too. Pick an arbitrary light direction and have your tiles cast a shadow on tiles below their respective heights. This way taller tiles would cast longer shadows than lower tiles, and give the player an additional visual cue of the height of each tile. It should be much harder to implement though.
> 12 votes

---
Tags: 2d, game-mechanics, tilemap, view
---


# Question
Title: As3 Random movieclips from an array to the stage
For a game with orders and clients I was trying to create the following situation:

Every half minute, a client should appear at the counter. In this case I have an array with 4 movieclips (4 clients). After 30 seconds I want the first randomly choosed client to appear at the counter (y = 200). This is my solution (wich obviously isn't the right way, forgive me):

```
    var timer:Timer = new Timer(1000);
    var elapsedTime:Number = 0;

    timer.addEventListener(TimerEvent.TIMER, displaytime);
    timer.start();

    function displaytime(event:TimerEvent):void
        {
            elapsedTime++;
            counterDisplay.text = String(elapsedTime);
        }

    if(elapsedTime == 30){

    for (var i:uint = 0; i < mcArray.length; i++) {

         mcArray[i].x = Math.floor( Math.random()*(stage.stageWidth) );
         mcArray[i].y = 200;
         addChild(mcArray[i]);

    }

    }

```

My question to you is: What am I doing wrong, and how can I accomplish this? Thanks in advance!

# Answer
edit:I'm slightly unclear on the question but I think this is the answer?

I would ditch the timer altogether and just use an enter-frame event listener.

```
var playerArr:Array=[];
var t:int=0;
public function Main(){
addEventListener(Event.ENTER_FRAME, tick)
}

function tick(){

t++;

   //assuming your at 30fps
   if (t%900==1){
   spawnUnits(3)
  }
}

//If you were spawning Characters for the first time
function spawnUnits(numUnits:int){
    for(i=0;i<=numUnits;i++){
    newSpawn:MovieClip=new *CLASSNAME*
    newSpawn.x=Math.Random()*400;
    newSpawn.y=200;
    playerArr.push(newSpawn);
    addChild(newSpawn);
    }
}

//If you were grabbing previously spawned Characters and moving them you would
//Call this function instead of spawnUnits

function characterMover(){
    var moveChar:Object=playerArr[(Math.Random()*playerArr.length)-1];
    moveChar.x=Math.Random()*400;
    moveChar.y=200;
    //then if they weren't already on the display list you could add them here

}

```
> 1 votes

# Answer
Well first off you loop through the entire array, when you only want one customer. If you only want, say, mcArray\[2\] then only manipulate that value, don't loop through the entire array.

More generally however, it looks like you are writing the code outside of any function, which doesn't make any sense in this case and even in situations where it works it is a really bad idea. Whatever you're doing on the timer has to be inside the timer function.
> 3 votes

---
Tags: mathematics, actionscript-3, random, loading, timer
---


# Question
Title: Using Slick2D/LWJGL to brighten an Image
Using the Slick2D Library for Java, I want to know if there is a way to brighten an instance of `org.newdawn.slick.Image`. I'm willing to use other image-manipulation libraries if need be.

# Answer
I can imagine a few different ways to do this, but which one is the best will depend on your particular situation.

First of all, if it is possible to perform this offline using some image editing software then that would probably give the best result and result in better performance for your application. However, I am guessing that this is not possible in your situation.

Now, the easiest and most efficient online solution that I can come up with would be to simply render the image multiple times using additive blend mode. (g.setDrawMode(Graphics.MODE\_ADD)). If you need precise control of the brightness you might be able to render the image with a different alpha value as an intermediate step and then use the result to add to your output image. Here is a small example

```
dark = new Image("media/dark.jpeg");

bright = new Image(dark.getWidth(), dark.getHeight());
Graphics g = bright.getGraphics();
g.drawImage(dark, 0.0f, 0.0f);
g.setDrawMode(Graphics.MODE_ADD);
g.drawImage(dark, 0.0f, 0.0f);
g.drawImage(dark, 0.0f, 0.0f); // The more times you call this the brighter the image will be.
g.flush();

```

If this is not enough for your needs then there is always the possibility of performing the brightness changes manually on a per-pixel basis by rendering 1x1 squares of the desired (brighter) color to the resulting image. There is a Color.brighter(scale) method that could be helpful when doing this. Note however that doing this operation pixel by pixel is likely to be very inefficient.

Please not however that both of the above methods will just uniformly scale the RGB components of the image. This will result in an image that looks brighter, but in order for the image to retain its colors as perceived by the human eye you should instead increase the *perceived brightness* or something along those lines. This can for example be done by first converting the colors from RGB space to HSL space, increase the L component by as much as you want. Finally you can convert back to a new and brighter RGB color. Some additional resources on this can be found here:
> 1 votes

---
Tags: java, image, slick
---


title: Back-face culling in 2d OpenGL game

text:
# Question
Title: Back-face culling in 2d OpenGL game
I have a 2d game I've made using OpenGL ES. The game contains a large quad that fills the entire screen (as a background image) and many smaller quads that make up a number of balls that bounce across the screen.

To illustrate displaying a ball, I may have a single quad with vertices `(0,0),(0,1),(1,1),(1,0)`. I then fill this quad with a texture (a colored ball).

I am wondering if I need to perform back-face culling (for performance reasons). Given these 4 vertices, I assume a polygon is drawn to connect them. Is it actually the case that two polygons are drawn? One facing forward and another one facing the back? I'm struggling to understand.

I have tried getting face culling working and I think I've succeeded, but I've not really noticed any difference in rendering times.

Not sure if relevant, but here is my environment setup code:

```
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glDisable(GL10.GL_DEPTH_TEST);
gl.glViewport(0, 0, width, height);
gl.glLoadIdentity();
gl.glMatrixMode (GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrthof(0, width, height, 0, 0, 1);
gl.glMatrixMode (GL10.GL_MODELVIEW);

```

# Answer
Back face culling is typically used to prevent the drawing of polygons to the screen that are facing away from the camera. For example, if one were to draw a complex three dimensional object to the screen, many of the polygons on the model may not even be visible and culling them will prevent the rendering time of these non-visible polygons. The "face" aka visible side of the polygon is determined by the order in which you specify the vertices. Polygons usually only have one face. In a program you might say

```
glFrontFace( GL_CCW );
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);

```

This would mean you are going to specify the vertices of your polygons in counter clock wise order, culling the polygons facing away from the camera. Based on the description of your program, it does not sound like you need to enable culling. As long as you are consistent with the ordering of your vertices for your polygons, your two dimensional program should not need culling. As for the question of whether two sides are being drawn, the front and back, no they are not.
> 4 votes

# Answer
If you draw one quad, only one quad is being drawn. You don't need back-face culling for your situation.

Back-face culling is used in 3d graphics as an optimization. For example, if you're drawing a cube, your code would draw 6 quads (one for each side of the cube). However, on screen, there will only be 3 sides ever visible at one time. The other 3 sides will be behind the 3 that you see.

You can use back-face culling to tell OpenGL to only draw the 3 sides that are facing towards the camera. That way you can keep your cube-drawing code simple — always draw 6 quads — but let the system only draw the ones that face the camera. To make this work you have to orient the vertices consistently and tell OpenGL which orientation you're using (see user7679's answer).
> 2 votes

---
Tags: opengl, graphics, culling
---


title: XNA: Regarding SpriteBatch.Draw()

text:
# Question
Title: XNA: Regarding SpriteBatch.Draw()
I was trying to develop a very simple ping pong game using XNA.

In my Draw() I am drawing the player paddles first then the ball as follows:

```
spriteBatch.Draw(myPlayer, myPlayer1Pos, null, Color.Aqua);
spriteBatch.Draw(myPlayer, myPlayer2Pos, null, Color.Aqua);
spriteBatch.Draw(myBall, myBallPos, Color.LawnGreen);

```

Now the problem is the ball is no longer displayed in the game window as shown below

If on the other hand I draw the ball before the player paddle

```
spriteBatch.Draw(myBall, myBallPos, Color.LawnGreen);
spriteBatch.Draw(myPlayer, myPlayer1Pos, Color.Aqua);
spriteBatch.Draw(myPlayer, myPlayer2Pos, Color.Aqua);

```

then the right hand side paddle is no longer visible as shown below:

Can anyone explain what is going wrong here?

edit: The complete Draw():

```
protected override void Draw(GameTime gameTime)
{
      GraphicsDevice.Clear(Color.CornflowerBlue);

      // TODO: Add your drawing code here
      spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);

      spriteBatch.Draw(myBall, myBallPos, null, Color.LawnGreen);

      spriteBatch.Draw(myPlayer, myPlayer1Pos, null, Color.Aqua);
      spriteBatch.Draw(myPlayer, myPlayer2Pos, null, Color.Aqua);

      spriteBatch.Draw(myBkgTexture, graphics.GraphicsDevice.Viewport.Bounds, Color.Blue);

      spriteBatch.End();

      base.Draw(gameTime);
}

```

# Answer
The first problem is that you're using `SpriteSortMode.BackToFront` which to put it simply, is not appropriate for this case because you're not even specifying the depth of your sprites. Just use the default mode instead which draws in the same order as your calls (just write `spriteBatch.Begin()` with no parameters). Also, it's strange that you're drawing the background after the other sprites. If it's the background it should come first otherwise it will occlude everything else.

Here's the corrected code, with some redundant parameters removed:

```
spriteBatch.Begin();
spriteBatch.Draw(myBkgTexture, graphics.GraphicsDevice.Viewport.Bounds, Color.Blue);
spriteBatch.Draw(myBall, myBallPos, Color.LawnGreen);
spriteBatch.Draw(myPlayer, myPlayer1Pos, Color.Aqua);
spriteBatch.Draw(myPlayer, myPlayer2Pos, Color.Aqua);
spriteBatch.End();

```
> 5 votes

# Answer
The issue seems to be with spriteBatch.Begin() which the wizard had generated with SpriteSortMode.BackToFront.

Using the default Begin() solves the issue.
> 2 votes

---
Tags: xna, spritebatch
---


title: Car movement in arcade racing game

text:
# Question
Title: Car movement in arcade racing game
I am finishing a very basic 2D racing game with top-down perspective. I can't get the appropriate formulas to make the movement of the cars fun and addictive... Do you have tips on how to achieve that arcade feeling a lot of games have? Do you know of any guide/tutorial on this topic?

Right now, these are the formulas I am using:

```
// (speed changes linearly according to the user input)
direction += turnAmount.Value;
Vector3 pos = Position + new Vector3(speed.Value * (float)Math.Cos(direction), 0, -speed.Value * (float)Math.Sin(direction));

```

I have tested other, more complex options but this is the best I have got so far...

# Answer
> 3 votes
I can you change speed in some non-linear algorithm like :

```
if(userinput == move_faster)
    if(maxSpeed/2 - oldSpeed/2 <= maximum_acceleration)
        newspeed = (oldspeed + maxSpeed) / 2;
    else
        newspeed = oldSpeed + maximum_acceleration;
else
    if (userinput == stop_move)
        newspeed = oldspeed - someValue;
    else
        newspeed = oldspeed * 0.99;

```

in this code `maxSpeed` is the maximum speed that a car can go and `someValue` is how fast a car stops.

I'm not sure but I guess also you can also change rotation algorithm something like this:

```
if (newspeed > somevalue2)
    direction += turnAmount.value / newspeed * somevalue2;
else
    direction += turnAmount.value * newspeed / somevalue2;

```

in this code `somevalue2` represents a speed value in which your car is moving by a reasonable slow speed, let's say if you car can move by max 10m/s setting somevalue2 as 1 seems to be a good choice (although you have to test it runtime).

# Answer
> 2 votes
To get realistic looking movement, you have to apply as realistic physics as you can.

That would involve giving the cars momentum, velocity & mass and interact forces/torques (turning, acceleration, etc.) upon those momentum vectors in the same way an actual automotive engineer might.

Here's a good resource to introduce physics into your game. It's 3d but the principles can easily be applied to 2d as well.

http://gafferongames.com/game-physics/physics-in-3d/

# Answer
> 0 votes
Understanding the separation between realistic physics and fun physics, I suspect real physics are still a really good stepping point as a starting point, and then hacking around the physics to make it fun.

There is a fairly comprehensive guide to racing physics on http://phors.locost7.info/contents.htm. To be fair, I have only read small amounts of it and can not attest to its quality.

I would then start working on special cases - so, for instance adjusting friction when braking to make it more playable, and 'nudging' the car towards driving straight in the correct direction after drifting.

---
Tags: physics, movement, racing
---


# Question
Title: Can I create a remix of a song & incorporate it into my game music?
DJs frequently remix eachothers work and use as they please. Can I as a programmer do similar - remix a song I like and embed it in a game I create without royalty/copyright issues?

Disclaimer: answers will not be considered legal advice, this is just a hypothetical discussion :)

# Answer
> 4 votes
It always depends on the underlying license, so you need to make sure the tune you want to reuse in yours allows that kinda stuffs. For example, some Creative Common licenses allows other composers to reuse them but you always have to mention the original composer obviously somewhere.

So in a nutshell no general answer for that kind of questions. And most of the time DJs always ask the original composers before doing anything, what you're saying is just an urban legend!

---
Tags: music, copyright
---


title: Are fonts covered by copyright?

text:
# Question
Title: Are fonts covered by copyright?
I want to use the font *Trajan Pro*, but I'm not sure that it would be legal. I've read a bit on fonts and copyright, and the only thing I could get was it depends on the license and where it was copyrighted, and sometimes it isn't copyrighted at all.

So how would I tell if the font *Trajan Pro,* or any other font, is under copyright?

# Answer
> 17 votes
Fonts, like all forms of creative expression, are covered by copyright unless their copyright owner explicitly releases them into the public domain. Distributing a font, or derivative works of the font (bitmap images of text rendered using the font, for example) would be a violation of copyright, unless you have a license to do so.

The particular font you mention, Trajan Pro, was created by Carol Twomby. A license for this font (and several of her other fonts) can be purchased from Adobe.

According to the licensing terms, this font license gives permission to embed the font into an electronic document for the purposes of preview and print, but not for the font to be installable by any end-users of such a document. It does not explicitly grant the right to (for example) be baked into a texture page and used in a game, so it's not obvious whether even purchasing a license would allow you to legally use this font the way that you wish to. As usual for this sort of thing: consult a practising lawyer in your area for an authoritative answer of whether a game constitutes an "electronic document" for the purposes of this font license.

Similar discussions have been held on the official Adobe discussion forums a few years back, but never received an official reply from Adobe.

# Answer
> 1 votes
It looks your font has got a commercial distribution type.

In this case, referring to this article, it looks you can't sell any app using that font without paying additional fees to the author first.

---
Tags: legal, fonts
---


# Question
Title: basic Theory that we need to know before start learning game programming
Came from Java (and fairly C++) and I am very confident in my programming skill Now I'm about to move to something more interesting, game programming The thing is as I am new to this,

I need to know some basic Theory that we need to know before start learning game programming You know there has to be some foundation of theory that we need to know

as in web Programming, basic Http Protocol, ftp and all those theory maybe something like Collision Detection, Vector, and all that you know I don't wanna get too excited about it and then lost at some point and giving up, like most of the newborn

This is purely a hobby so, there's nothing like "I am going to make the next hallo game" a pretty lame game is sufficient thank you

EDIT : You're right its too broad and unclear lol I forgot I'm sorry I mean Its for developing 3D Game on Desktop, And Android And No, No Iphone and not web either And about the game Engine, I can decide myself, but if there are suggestions that'd be okay If its still unclear you can edit it please to prevent this kinda question asked again

# Answer
I'd suggest you to help yourself on www.gamedev.net. They offer a pretty good grasp of articles about :

Nevertheless, nowadays I'm not 100% sure C++ is **THE** best programming language to get a first step into the game development world. I'd rather advise you to start with the XNA .Net framework which provides a well-thought architecture which matches the regular design patterns you could find on the professional engines.

Once you know how XNA works, you can be sure that you won't make everything wrong when restarting your own game engine from scratch with another programming language.
> 5 votes

# Answer
About the only game programming concept that I really think you need to know before you start is to understand the game loop, and that's basically the same concept as the main loop in any program: update the game state, render the game, flip the drawing buffer, repeat forever.

I didn't sit down and read about any game programming concepts until *after* I had already programmed a couple simple games and then hit some snags that I needed help on. For example, I didn't start reading about AI techniques until I started developing more complex AI in later projects. I suggest taking patrick's comment and then hitting up google or coming back here to look up specific questions once you hit a problem you need help with.
> 5 votes

# Answer
I agree with the above answer from user14170 in part as GameDev is an awesome site filled with useful information.

Something you may also be interested in is a course that starts soon (free) from Stanfrod University on Game Theory. They have a couple other courses going on too but seeing as Game Theory is your thing then this fits perfectly.

In regards to start Games Development you can't go wrong with either XNA or Unity 3d. I'd recommend Unity as i use it myself and the free mobile for iOS and Android is available until April 8th.

Unreal Dev Kit may be a little complex to start with and the above two allow you to get your hands dirty and produce games with a little work.
> 2 votes

---
Tags: c++, java, algorithm
---


# Question
Title: How would one generate a texture for cracks in different materials?
I would want to have the ability to simulate different variables like brittleness, or other variables to get varied end results.

I would mainly need to generate impact cracks, so it would need to react to different impact angles and speeds.

I am using ActionScript3, but general theory answers will be helpful as well.

# Answer
You could use a recursive function to generate a root crack, and along that root crack, generate smaller branches of cracks, and so on. You could even animate this to make the effect even cooler.
> 8 votes

# Answer
Recursion sounds like the right idea, but that alone doesn't cover it. If you want to include things like impact angles things an get pretty complicated. the simple way is to just use the angle as a way of calculating approximate force. using the approximate force and the brittleness you can calculate the size of the initial cracks and the depth of recursion.

If you're really looking into breaking an object along the cracks, Binary Space Partitioning might be something to look into. otherwise, generating textures is probably your best bet.

EDIT In response to your request for an example:

You can take a line, straight or jagged, and pick several points along its length from which to draw other, smaller lines. off of those you can draw yet smaller lines. look into fractals if you want detailed examples. Are you looking for code?
> 3 votes

# Answer
For procedural destruction, I've always been a fan of Voronoi diagrams.

If all you're interested in is the shape of the crack itself, then you can use a Voronoi diagram, and discard all but the boundaries between two cells. If you wanted some variability between materials, you could adjust the number and placement of seeds.
> 2 votes

# Answer
You could probably use the same method of generating lightning to simulate cracks. Here is an example. You might need to tweak it to look right for a crack though.
> 0 votes

---
Tags: physics, mathematics, actionscript-3
---


title: How to increase force for every touch?

text:
# Question
Title: How to increase force for every touch?
In my game the character can fall in two directions. The user clicks right or left button to "push" the character to balance them, so they don't fall. I'm not sure how to increase the forces applied to the character for each press.

```
function left:touch(e)
    if(e.phase == "began") then
        boy:applyLinearImpulse(-0.5, .5, boy.x, boy.y)
    end
end

function right:touch(e)
    if(e.phase == "began") then
        print("right");
        boy:applyLinearImpulse(2.1, .5, boy.x, boy.y)
   end
end
left:addEventListener("touch", left );
right:addEventListener("touch" , right );

```

# Answer
> 1 votes
It looks like you need another variable to indicate velocity in each direction. It would look something like this:

```
function left:touch(e)
    if(e.phase == "began") then
        boy.velX = boy.velX - 0.5
        boy:applyLinearImpulse(boy.velX, boy.velY, boy.x, boy.y)
    end
end

```

---
Tags: corona-sdk
---


# Question
Title: How should I account for the GC when building games with Unity?
\*As far as I know, Unity3D for iOS is based on the Mono runtime and Mono has only generational mark & sweep GC.

This GC system can't avoid GC time which stops game system. Instance pooling can reduce this but not completely, because we can't control instantiation happens in the CLR's base class library. Those hidden small and frequent instances will raise un-deterministic GC time eventually. Forcing complete GC periodically will degrade performance greatly (can Mono force complete GC, actually?)

So, how can I avoid this GC time when using Unity3D without huge performance degrade?

# Answer
Luckily, as you pointed out, the **COMPACT** Mono builds use a generational GC (in stark contrast to the Microsoft ones, like WinMo/WinPhone/XBox, who just maintain a flat list).

If your game is simple the GC should handle it just fine, but here are some pointers you might want to look into.

# Premature Optimization

First make sure this is actually a problem for you before trying to fix it.

# Pooling Expensive Reference Types

You should pool reference types that you either create often, or which have deep structures. An example of each would be:

* Created often: A `Bullet` object in a bullet-hell game.
* Deep structure: Decision tree for an AI implementation.

You should use a `Stack` as your pool (unlike most implementations which use a `Queue`). The reason for this is because with a `Stack` if you return an object to the pool and something else immediately grabs it; it will have a much higher chance of being in an active page - or even in the CPU cache if you are lucky. It's just that tiny bit faster. Furthermore always size-limit your pools (just disregard 'checkins' if your limit has been exceeded).

# Avoid Creating New Lists to Clear Them

Don't create a new `List` when you actually meant to `Clear()` it. You can re-use the backend array and save a load of array allocations and copies. Similarly to this try and create lists with a meaningful initial capacity (remember, this isn't a limit - just a starting capacity) - it doesn't need to be accurate, just an estimate. This should apply to basically any collection type - except for a `LinkedList`.

# Use Struct Arrays (or Lists) Where Possible

You gain little benefit from use structs (or value types in general) if you pass them around between objects. For example, in most 'good' particle systems the individual particles are stored in a massive array: the array and and index are passed around instead of the particle itself. The reason this works so well is because the when the GC needs to collect the array it can skip the contents entirely (it's a primitive array - nothing to do here). So instead of looking at 10 000 objects the GC simply needs to look at 1 array: huge gain! Again, this will **only work with value types**.

After RoyT. provided some viable and constructive feedback I feel I need to expand on this more. You should only use this technique when you are dealing with massive amounts of entities (thousands to tens of thousands). In addition it **must** be a struct which **must not** have any reference type fields and must live in an explicitly-typed array. Contrary to his feedback we are placing it in an array which is very likely a field in a class - meaning that it is going to land up the heap (we are not trying to avoid a heap allocation - merely avoiding GC work). We really care about is the fact that it's a contiguous chunk of memory with a lot of values that the GC can simply look at in a `O(1)` operation instead of a `O(n)` operation.

You should also allocate these arrays as close to your application startup as possible to mitigate the chances of fragmentation occurring, or excessive work as the GC tries to move these chunks around, (and consider using a hybrid linked list instead of the built-in `List` type).

# GC.Collect()

This is definitely **THE BEST** way to shoot yourself in the foot (see: "Performance Considerations") with a generational GC. You should only call it when you have created an ***EXTREME*** amount of garbage - and the one instance where that could be an issue is just after you have loaded the content for a level - and even then you should probably only collect the first generation (`GC.Collect(0);`) to hopefully prevent promoting objects to the third generation.

# IDisposable and Field Nulling

It is worthwhile to null fields when you no longer need an object (more-so on constrained objects). The reason is in the details of how the GC works: it only removes objects that are not rooted (i.e. referenced) even if that object would have been unrooted because of other objects being removed in the current collection (*note:* this depends on the GC flavour in use - some do actually clean up chains). In addition, if an object survives a collection it is immediately promoted to the next generation - this means that any objects left lying around in fields will be promoted during a collection. Each successive generation is exponentially more expensive to collect (and occurs as infrequently).

Take the following example:

```
MyObject (G1) -> MyNestedObject (G1) -> MyFurtherNestedObject (G1)
// G1 Collection
MyNestObject (G2) -> MyFurtherNestedObject (G2)
// G2 Collection
MyFurtherNestedObject (G3)

```

If `MyFurtherNestedObject` contained a multi-megabyte object you can be guaranteed the GC won't look at it for quite a long time - because you have inadvertently promoted it to G3. Contrast that with this example:

```
MyObject (G1) -> MyNestedObject (G1) -> MyFurtherNestedObject (G1)
// Dispose
MyObject (G1)
MyNestedObject (G1)
MyFurtherNestedObject (G1)
// G1 Collection

```

The Disposer pattern helps you set up a predictable way to ask objects to clear their private fields. For example:

```
public class MyClass : IDisposable
{
    private MyNestedType _nested;

    // A finalizer is only needed IF YOU CONTROL UNMANAGED RESOURCES
    // ~MyClass() { }

    public void Dispose()
    {
       _nested = null;
    }
}

```
> 18 votes

# Answer
Very little dynamic instantiation happens automatically inside the base library, unless you call something that requires it. The vast majority of memory allocation and deallocation comes from your own code and you can control that.

As I understand it, you can't avoid this entirely - all you can do is ensure that you recycle and pool objects where possible, Use structs instead of classes, avoid the UnityGUI system, and generally avoid making new objects in dynamic memory during times when performance matters.

You can also force garbage collection at certain times, which may or may not help: see some of the suggestions here: http://unity3d.com/support/documentation/Manual/iphone-Optimizing-Scripts.html
> 7 votes

---
Tags: unity, performance
---


# Question
Title: XNA 2D - How to switch to a new sprite upon collision and delete itself
Let's say I have a 2D spaceship that shoots at moving rocks. If a bullet intersects one of the rocks' bounding boxes, that rock will animate according to a new spritesheet and remove itself.

My question is this: How can I load the new animated rock (breaking apart) onto the screen upon colliding with the bullet?

# Answer
> 3 votes
> *tl;dr: You'll want to use a sprite sheet and create an animated sprite with a delegate to notify the owner when the animation has completed.*

Let's break down the steps and design this out.

### User Story

When a bullet collides with an asteroid, the asteroid should explode and disappear.

### Feature Breakdown

1. Detect collision between `Bullet` and `Asteroid`
2. Play destroy animation on `Asteroid`'s sprite.
3. Remove `Asteroid`

### Class Breakdown

* `AnimatedSprite`: Displays an animated `Sprite` at a given position onscreen at a given rate
* `Hitbox`: Defines an object's collidable area, and can be used to determine if two hitboxes collide
* `Bullet`: Projectiles shot by the player containing a `Sprite` and a `Hitbox`
* `Asteroid`: Obstacles to be shot by the player containing an `AnimatedSprite` and a `Hitbox`

### Walkthrough

I'm assuming you already have solved `1. Detect collision between Bullet and Asteroid`, so let's jump to step 2.

There is a fairly comprehensive article regarding Sprite animation on MSDN that you should read before continuing development, but I'll try to sum it up here.

We're going to be using a sprite sheet for the asteroid's animation. The reasoning here is that a sprite sheet has much less memory overhead than discrete images (due to graphics card implementation and other stuff that you don't really need to worry about for this example).

The basic premise is to create a rectangle and only render that portion of the image. You can think of it as a film reel: There are many individual frames to create the motion, but you only see one at a time. Each update loop, a timer in the `AnimatedSprite` will be increased, and once it reaches the desired frame-rate, we will move the rectangle to the next part of the animation.

We'll want to modify the sample code above, adding a function, `Play()` and a delegate, `AnimationComplete`. Additionally, we'll only want to play the animation once, stop our animation, and call `AnimationComplete`. Then, in Asteroid, we'll want to pass a function, `Destroy()` to the delegate we created in `AnimatedSprite`. This means, once the animation is complete, the `AnimatedSprite` will call `Destroy()` on the asteroid (which is what we're trying to do).

### Summary

Here's the task breakdown:

* Detect collision between `Bullet` and `Asteroid`
* Create an `AnimatedSprite` class to handle our animation
    + Should begin paused on the first frame
    + Should be able to begin playback via a function call
    + Should call a delegate once the animation is complete
* Create a function to allow `Asteroid` to destroy itself

# Answer
> 1 votes
I think that the easiest solution is to load all images you need (and store it for example in an array) - I except you have animation stored as a lot of images. All time (while it's not colliding) you are drawing first image.

When it collides, you just start to use other sprites (you can draw for example one new sprite each frame). When you reach end of array, explosion (animation) is finished and you will stop drawing this rock.

---
Tags: xna-4.0
---


# Question
Title: How to schedule Render and Logic loops in browsers with RequestAnimationFrame?
Question derived from this tweet:

> @Vincent\_Scheib, thoughts on using using two loops for a HTML5 game: one requestAnimationFrame for rendering, and one setInterval for logic?

# Answer
> 3 votes
Experimentation and prototyping are likely the only way to get the right answer for a given game, so I encourage keeping code easy to re-work into different loop paradigms. My thoughts:

1. Logic and Render in different loops will have many of the same issues that placing logic into a Web Worker will have. Listing them here:
2. Logic and Render in different loops will add latency.
    * The updates must occur before the draw calls come, but there is nothing keeping the timing close together. So, there will be 'idle' time between the logic update and render code.
3. Logic and Render in different loops may cause strobing or beat patterns.
    * A simple approach will simply try to update both at 60hz, but as the timers are uncorrelated they may drift and result in some frames with more than 1 logic update, or even no logic updates.
4. Some logic doesn't need to run at 60Hz.
    * For example decorative physics and AI planning updates are often suggested to be run less frequently to reduce CPU load. They can either be rendered as moving less often, or animation can tween them to keep things moving smoothly.
5. Network communication may not need to run at 60Hz, and might be necessary even when Request Animation Frame is not calling your draw function.
    * E.g. if a browser stops calling your draw function from R.A.F. you may still be receiving data via Web Sockets and want to keep a logic update ticking occasionally to deal with that.

---
Tags: html5, browser-based-games
---


# Question
Title: Should have one device per application or per form when doing MDI Forms work with XNA?
I am just making a simple editor for a project I am working on and as part of this I need to add a few different MDI forms within a larger container form.

Now the XNA (4.0) example Windows Forms projects use a shared graphics device for all controls, however I was assuming I would have a graphics device per control (assuming we have an XNA-specific panel/control element).

So is there any reasons that you *should* share the same graphics device? As I can imagine there being problems if you are changing render states in one panel but do not want it to effect the other panels...

It would make sense to share it if the GraphicsDevice object is literally a representation of the underlying graphics card, but thats what the GraphicsAdapter is, so I wasn't sure if there would be any problems with isolating a graphics device per control.

# Answer
> 1 votes
I wouldn't create multiple devices, I'd stick with one that you share across all render windows/controls. A device has some overhead involved in it's existence and you don't gain any advantages to having multiple instances, really.

In fact, it can become much harder to share resources like textures between controls because they must be shared between devices, which I'm not even sure XNA exposes or supports given the version of D3D that backs it. If you can't share resources you have to create multiple copies, which is pointlessly wasteful in terms of memory.

> As I can imagine there being problems if you are changing render states in one panel but do not want it to effect the other panels...

Effectively, you can't do this, so it's not a problem. You can only manipulate a Windows Forms control from the thread it was created on (almost always the UI thread), so you generally could not be attempting to change the render state from one control's thread while you are rendering on another control's thread. Even if you did create controls in isolated worker threads you would need to serialize access to non-thread-safe resources anyway, so you'd just have to include the render states in that serialization anyhow (but again, it's not terribly useful to put controls on the non-UI thread).

Create a local abstraction that encapsulates the render state data for a particular control or render window, and in that render window's drawing method, apply those render state changes.

---
Tags: xna, windows-forms, multiple-graphics-devices
---


# Question
Title: Collision Detection doesnt work because some things move more than 1px at a time
I'm writing a 2d scrolling game in javascript using canvas and since I'm limited to setInterval running at minimum once every ms, I need to have some objects moving at greater than 1 pixel a second. I have this for collision detection between objects:

```
// ** oversee collisions
collisionsInterval = setInterval(function() {

    // outter object
    for(i = 0; i < objectsToCollision.length; i++) {

        // inner object
        for(j = 0; j < objectsToCollision.length; j++) {

            // dont compare an object to itself
            if(i==j) continue;

            // check if they touch on x axis
            if(Math.abs(objectsToCollision[i].centerX - objectsToCollision[j].centerX) <= (objectsToCollision[i].halfWidth + objectsToCollision[j].halfWidth)) {

                // check if they touch on y axis
                if(Math.abs(objectsToCollision[i].centerY - objectsToCollision[j].centerY) <= (objectsToCollision[i].halfHeight + objectsToCollision[j].halfHeight)) {

                    // a collision was detected, do something useful
                    alert();

                }

            }

        }

    }
}, 1);

```

The problem is, since it wont alert() when two things are about to touch because my objects move at more than 1px at a time. The problem is, some objects might move 3px at a time, some might move at 8px at a time, and I also have gravity occurring so in the Y direction especially the velocity of my objects will really vary.

In my code above objectsToCollision is an array which contains all the objects I'm checking for collisions with. I've modelled what I've done so far after this https://gamedev.stackexchange.com/a/587 but it doesn't discuss how to solve the problem I'm experiencing!

# Answer
> 3 votes
This looks like you're comparing the objects at a single point - the center-point of the rectangle is not important - only the bounds:

```
object1 = ship
object2 = bullet

if (object2.y2 > object1.y1) AND (object2.y1 < object1.y2):
    if(object2.x2 > object1.x1) AND (object2.x1 < object1.x2):
        print ('a hit!')

```

# Answer
> 0 votes
This is by no means a complete answer, but instead of describing objects as points describe them as a line or set of lines, each with a start point and time and end point and time. Now you can easily calculate the position of something at any given nanosecond. This is great if you are shooting at them with a laser over short distances. Figuring a collision between two such objects is harder and would require either some fancy mathematics or else a series of successive approximations. If the approximations start to diverge, you missed. If they converge, you'll get to the collision point soon enough.

At any rate, you'll quickly get the objects into a position where you can do the hard work of checking for a collision, answering questions like "would object A pass through the hole object B or smack a projecting fin?" at time t + 0.4398224, despite the fact that they were miles apart at both times t and time t + 1.

---
Tags: 2d, collision-detection, javascript, html-canvas
---


# Question
Title: OpenGL: Rotating cannon about non-centre position?
So I have a "cannon" object (basically a long cylinder) and I want to be able to control its angle. The code I have now is:

```
    glPushMatrix()
    glTranslatef(self.position.x,2.5,self.position.z)
    glRotated(self.tube_angle, 1.0, 0.0, 1.0)
    glScaled(1.0, 0.5, 1.0)
    glCallList(self.tube.gl_list)
    glPopMatrix()

```

This rotates it around the axis, obviously. I want the bottom to stay in the spot it is (moving object) and just change the angle.

# Answer
Since `glRotated()` rotates a specified angle around the desired axies (x and z in your example), you'll need to translate your object first. This is important.

> **Note: The rotation center is always considered (0,0,0).**

### Example: Rotate 20° About Point (0, 5, -10)

```
// Save the current display for other items.
glPushMatrix();

// Translate by the opposite of the desired point of rotation.
glTranslate(0, -5, 10);

// perform the desired rotation.
glRotate(20, 1, 0, 0);

// Put the object back where it was.
glTranslate(0, 5, -10);

// Now, draw the object with proper rotation!
...draw code...

// Finally, reset our transformation matrix to where we left it.
// It's the polite thing to do, after all.
glPopMatrix();

```
> 3 votes

---
Tags: opengl, python, rotation, pygame
---


# Question
Title: Game Loop Problem - Growth and Recharge as Integer Values
I have a question about game loops. I understand that you shouldn't have a static loop, say 100ms and set something's speed to 1px/frame so it moves 10px/sec. You should have a speed and multiple that by the elapsed time so frame rate does not effect game speed. This works fine for values that can be floats, but what if I need integer values? Say shields recharging or something. I have a damage system is my game and I would really love to stay away from float damage values, both for memory and game design reasons.

However if I just have a running total of elapsed time, and I recharge one point once this elapsed time is over 1 second then over the course of time won't I have some consistency errors between recharging over one set of 100 real seconds and another set of 100 real seconds because those two sets may not have the same number of frames in them. This questions also comes up in rate of fire. If I need a turret to fire every .5seconds, won't there be some variance if I do a running total of elapsed time? Sometimes it may fire every .501 seconds and other time .510 seconds?

I guess my question is, how exact are games really? Do most games just do a check every frame and say, "Well your rate of fire is .5 seconds, and its been .504 since you last fired, so fire now." If so would it work out for the next fire cycle to only check for .496 seconds to average out? I know it most games under 10 minutes this would barely be noticeable, but over the long term this may actually mater in some cases.

# Answer
> 10 votes
> I have a damage system is my game and I would really love to stay away from float damage values, both for memory and game design reasons.

My first instinct is to question your assumptions. It's extremely unlikely that using floats rather than ints for something like this is going to affect your memory usage in any noticeable way. On most systems, they take up the same amount of memory anyway, and on any other system you probably won't have enough values in question for it to make a difference. (Unless you have millions upon millions of these values?)

Also, it sounds like you may just be suffering from a bit of inertia. If you need a turret to fire every 0.5 seconds, that's a job for floating point values. Using integers for that in some way is incorrect.

The same might be said for the damage value, though this could be debated. Do you REALLY need your damage value to be an integer? Or is that just how you've been envisioning it in your mind? Most games would model a damage value as a float and simply display it to the player as an integer value. I'm betting that you are massively overthinking this issue, and should start thinking about what would be easier to work with, rather than chasing some idea of what is "correct" (which may not even be right in the first place)

That said, if you still decide that you want to use integers, the best thing in the case you describe (recharging an integral value, for instance) is to link it with a float that describes how often to recharge, and an integer that describes how much to recharge by, and a float that describes how much time has passed since the last recharge:

```
int myValue;
int rechargeValue;
float timePassed;
float rechargeTime;

void Update( float TimeDelta )
{
    timePassed += TimeDelta;
    if( timePassed >= rechargeTime )
    {
        timePassed -= rechargeTime;   //Save the remainder for later
        myValue += rechargeValue;
    }
}

```

Something like this will ensure that your value recharges at the right rate, and saving the remainder ensures that the rate remains steady over time.

If you're concerned about your game becoming less accurate over time, then be sure to store your elapsed time values in accurate data types like unsigned ints, and doubles, and only use floats for your time deltas.

# Answer
> 3 votes
Memory reasons? In day to day C++ a float is 4 bytes, an int is 4 bytes, there is no memory reason. For example, to maintain a float value for shields for **one million** enemies is only 4M RAM, typical low end PCs have at least 2G so this kind of data storage isn't really a problem. Trying to process one million enemies, that's a problem =)

As for game design please keep in mind that what you show the player is only a representation of the underlying simulation, if you simulate +1 shield/second then your simulation works in fractional seconds but you only show the integer representation.

Most games do carry over left-over time in systems, particle emitters work this way to avoid stuttering for example or the +1 shield regeneration above. I think the deciding factor should not be "how small a number doesn't matter" but "what am I modeling?"

# Answer
> 2 votes
Within Stendhal RPG have something similar, we simulate real time by having turns with a short duration. The server works turn wise, each turn is 300 ms for us. Now if we have for example food that regenerates a player over time, we do not calculate how many ms till the next healing should happen. We count the number of turns, that need to pass till the next time the player gets healed.

To handle this there is a TurnNotifier, which checks each turn, what to do. What to do is defined in implementations of an interface TurnListener:

```
public class TurnNotifier {

     private final Map<Integer, Set<TurnListener>> register = new HashMap<Integer, Set<TurnListener>>();

    public void onTurn(Integer turn) {
        Set<TurnListener> nowToHandle = register.remove(turn);
        for(TurnListener tl : nowToHandle) {
            tl.onTurnReached(turn);
        }
    }
}

```

The TurnListener looks sth like this:

```
public interface TurnListener {

    void onTurnReached(Integer turn);

}

```

With this concept you are able to abstract from actual time passed and whenever the TurnListener is called, you know, that enough time has passed to do what is necessary.

I don't think it is important to be as precise as possible.

# Answer
> 1 votes
If you want your shield percentage (for instance) to actually *be* an integer from zero to one hundred, then there's little you can do; as you note, you'll be prone to error on things like recharge simply because your 'resolution' isn't fine-grained enough for what you need.

But I think you're confusing an integer *value* with an integer *view* \- simply because you present shields to the player as a whole number between 0 and 100 doesn't mean that you need to represent it that way! Indeed, reasons like your recharge example are exactly why even values that look like integers to the player are often represented as floats (or, at least, 'higher-resolution' fixed point numbers - for instance, imagine that shields scale from 0 to 1,000,000) and rounded (or truncated) for purposes of showing to the player.

You say you 'would like to stay away from float damage values for memory reasons' - how many enemies are you expecting to keep track of? Unless you're processing far more enemies than most games can dream of (literally tens of thousands at once if not more), then it's hard to believe that using four bytes instead of one for a handful of values will have any substantial impact at all on your memory footprint. This is really a drop in the bucket, and I can almost guarantee that you'll have far more important things to worry about memory-wise.

# Answer
> 0 votes
> I understand that you shouldn't have a static loop, say 100ms and set something's speed to 1px/frame so it moves 10px/sec. You should have a speed and multiple that by the elapsed time so frame rate does not effect game speed.

I disagree, or that is, I disagree to the extent that variable step is a performance optimization at the cost of making a lot of things slightly harder to handle. For most small scale developers that is not a good tradeoff.

The easy fixed step solution is to run the game mechanics at 120 Hz (good number for 60 Hz screens). But you must keep the rendering flexible, an easy way of doing this is to set up a loop that first advance the game mechanics one step, then render a frame if the mechanics are ahead of schedule, and then if necessary wait until the mechanics are back on schedule.

**Integers**
As others have mentioned there is no need to use integers for the sake of performance, but for the sake of gameplay they are often the best choice, in some cases even as implicit fixed point values.

Specifically for shield recharging and similar slowly changing values it may be a good idea to use a fraction accumulator. Instead of adding some value to the shield every step, add a value to an integer accumulator every step, and whenever the accumulator reaches a given threshold, subtract that threshold from the accumulator and add 1 to the shield. If your mechanics run at 120 Hz, and you decide that the threshold should be 1200 then you can make the shield recharging be any multiple of 0.1 per second, and you can change it simply by changing how much you add to the accumulator each step.

---
Tags: game-loop, frame-rate, timer
---


# Question
Title: Multiple Kickstarter campaigns. Good? Bad? Ugly?
I've been toying with the idea of doing a Kickstarter for my game to help fund some good artists to replace the placeholder graphics I currently have. Just a small goal of $2k or so. Regardless of whether the campaign is successful this time, would it be considered a faux pas to do another, larger kickstarter once the game is looking better?

Would the rewards need to be the same, or could I offer better rewards at lower donation levels for the first one as an "early adopter" bonus?

# Answer
> 4 votes
I did some searching around and found that people occasionally launch a second Kickstarter campaign for the same project, often with success. However I wasn't able to find this situation with a game. The projects I found were for Kickstarting a project to some significant milestone of completion, or to complete to project. Then the second Kickstarter project was to expand the first or add additional elements to an opensource or free project.

People may feel like they're not contributing to much if they're not even donating to help finish a project. If the first Kickstarter were to be solely for art, it may not be successful. Perhaps create it for reaching beta level, perhaps where you can start charging for access and fund yourself to reach your goal of completion. I've found that people like helping other people get to the point of self sufficiency.

# Answer
> 11 votes
From Kickstarter's Defining Your Project page:

"What are you raising funds to do? Having a focused and well-defined project with a clear beginning and end is vital. For example: recording a new album is a finite project — the project finishes when the band releases the album — but launching a music career is not. There is no end, just an ongoing effort. Kickstarter is open only to finite projects."

To me, finite projects (in spirit if not in letter) means that the Kickstarter project's completion means the completion of primary work. Which is to say, all work would be complete save for bugfixes and other patches, but you should have a reasonably shippable product at the end of one funding drive.

There's also the question of what you would deliver to people who participated in the first round should the second fall prey to unforeseen circumstances. If you say "Donors of $15 will get a copy of my game, signed by me" in your first round, but find before the second round is completed that you won't be able to finish the game, what do you tell those people whose money is already spent?

In summary, whether or not it goes against the guidelines of Kickstarter (which I believe it does), it seems like an attempt to game the system. If you want to use Kickstarter as a resource, do the work, nail down a budget to total completion/polish/master, and start a project for that much, even if it's $10k instead of $2k.

---
Tags: fund-raising
---


# Question
Title: Using the same font with different sizes in libgdx
I am using BitmapFonts, LabelStyles and Labels for my texts.

I want to resize some labels, so i use this.

```
fontType.scale(-.6f);

LabelStyle style = new LabelStyle(fontType, Color.WHITE);

titleLabel = new Label("Points", style);
titleLabel.setColor(Color.RED);
titleLabel.x = 260;
titleLabel.y = 310;

```

but when i want to resize another label, all the labels containing that font resize (I create a new LabelStyle). So i resize the label instead of the font, but that doesnt solve the problem, because it doesnt resize the label, any idea?

# Answer
I would preffer adding this as a comment, but i have no commetn priviledge yet.

Have you tried creating a new bitmapfont instead of a new label?
> 2 votes

---
Tags: libgdx, fonts
---


# Question
Title: Deferred shading - how to combine multiple lights?
I'm starting out with GLSL and I've implemented simple deferred shading that outputs G-buffer with positions, normals and albedo.

I've also written a simple point light shader.

Now I draw a sphere for the point light and output goes into a lighting buffer.

The problem is, how do I combine the results of lighting buffer when drawing multiple lights?

E.g. when I'm drawing the second light to the lightbuffer using the point light shader, how do I add first light to the second light in the lighting buffer. I mean, you can't read from and write to the same output buffer?

# Answer
> 12 votes
Additive blending, i.e. glBlendFunc(GL\_ONE, GL\_ONE) and glEnable(GL\_BLEND).

# Answer
> 2 votes
For my deferred renderer, I aggregate all the lights into one light render target using the information from the g-buffer and then sample that render target for light intensity while creating my final backbuffer image.

So basically, I run all my game geometry through my geometry pass to build the g-buffers. From there I feed the g-buffers to my light pass shader. Each light is ran through the pass using a full screen quad. This way my pixel shader can calculate the light intensity for all the visible surfaces from the g-buffer and then add them to the light render target. You simply just add the light intensity for each light to the light buffer but make sure you clamp the intensity from 0 to 1.

All you would need to do to handle different types of lights (point, spotlight, parallel) is to make the light pass more robust by possibly using a constant buffer to designate which lighting procedures to execute.

# Answer
> 0 votes
There is likely a better answer than this, but I know, if in your shader you repeat the code needed to do a second light, you can then process two lights on a single object instead of one. It does require droubling up a lot of code for the second light and seams a little redundant, but I know it does work. However, I do believe, as someone will hopefully point out for you, there might be a more elegant solution.

---
Tags: opengl, shaders, glsl, deferred-rendering
---


title: XNA Platformer Screen Collision

text:
# Question
Title: XNA Platformer Screen Collision
I am making a game, and it has platforming and animation. I am trying to make it so that when the player goes to the end of the screen, he stops and cannot go further. I put this code in:

```
            if (player.playerRect.X <= 0)
        {
            player.playerRect.X = 0;
        }

        if (player.playerRect.X + player.playerTexture.Width >= 1800)
        {
            player.playerRect.X = 1800 - player.playerTexture.Width;
        }

```

It didn't do anything. I am confused why it doesn't work.

If you need it, here is my Game1.cs and my Player.cs

Game1.cs:

```
 using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Cubiez
{
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        Player player;
        Texture2D grass;
        Rectangle grassRect;

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

        protected override void Initialize()
        {
            player = new Player(Content.Load<Texture2D>("cubewalk"), new Vector2(100, 100), 47, 44);

            base.Initialize();
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            grassRect = new Rectangle(0, 0, 1200,480);
            grass = Content.Load<Texture2D>("grass");
        }

        protected override void UnloadContent()
        {

        }

        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            if (player.playerRect.X <= 0)
            {
                player.playerRect.X = 0;
            }

            if (player.playerRect.X + player.playerTexture.Width >= 1800)
            {
                player.playerRect.X = GraphicsDevice.Viewport.Width - player.playerTexture.Width;
            }

            player.Update(gameTime);
            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();
            spriteBatch.Draw(grass, grassRect, Color.White);
            spriteBatch.End();

            player.Draw(spriteBatch);
            base.Draw(gameTime);
        }
    }
}

```

Players.cs:

```
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace Cubiez
{
    class Player
    {
        public Texture2D playerTexture;
        public Rectangle playerRect;
        public Vector2 position;
        public Vector2 origin;
        public Vector2 velocity;

        public int currentFrame;
        public int frameHeight;
        public int frameWidth;

        float timer;
        float interval = 150;

        bool hasJumped;

        public Player(Texture2D newPlayerTexture, Vector2 NewPosition, int newFrameHeight, int newFrameWidth)
        {
            position = NewPosition;
            playerTexture = newPlayerTexture;
            frameHeight = newFrameHeight;
            frameWidth = newFrameWidth;
            hasJumped = true;
        }

        public void Update(GameTime gameTime)
        {
            position += velocity;

            playerRect = new Rectangle(currentFrame * frameWidth, 0, frameWidth, frameHeight);
            origin = new Vector2(playerRect.Width / 2, playerRect.Height / 2);
            position = position + velocity;

            if (Keyboard.GetState().IsKeyDown(Keys.Right))
            {
                velocity.X = 2f;
                AnimateRight(gameTime);
            }
            else if (Keyboard.GetState().IsKeyDown(Keys.Left))
            {
                velocity.X = -2f;
                AnimateLeft(gameTime);
            }
            else
            {
                velocity.X = 0f;
            }

            if (Keyboard.GetState().IsKeyDown(Keys.Space) && hasJumped == false)
            {
                position.Y -= 3f;
                velocity.Y = -4.5f;
                hasJumped = true;
            }

            if (hasJumped == true)
            {
                float i = 1;
                velocity.Y += 0.15f * i;
            }

            if (position.Y + playerRect.Height >= 450)
            {
                hasJumped = false;
            }

            if (hasJumped == false)
            {
                velocity.Y = 0f;
            }

        }

        public void AnimateRight(GameTime gameTime)
        {
            timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 2;
            if (timer > interval)
            {
                currentFrame++;
                timer = 0;
                if (currentFrame > 3)
                {
                    currentFrame = 0;
                }
            }
        }

        public void AnimateLeft(GameTime gameTime)
        {
            timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 2;
            if (timer > interval)
            {
                currentFrame++;
                timer = 0;
                if (currentFrame > 7 || currentFrame < 4)
                {
                    currentFrame = 4;
                }
            }
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Begin();
            spriteBatch.Draw(playerTexture, position, playerRect, Color.White, 0f, origin, 1.0f, SpriteEffects.None, 0);
            spriteBatch.End();
        }

    }
}

```

# Answer
> 5 votes
You want to modify the player's position, not its source rectangle.

As I understand it, you use `playerRect` to represent the rectangle *inside* the image to draw, in order to animate it properly. That is the **source rectangle** and it does not affect where the player is drawn.

What you want is to modify the player's `position` field in order to really clamp its position within the screen boundaries.

Here is how you would do:

```
if (player.position.X <= 0)
{
  player.position.X = 0;
}

if (player.position.X + player.playerTexture.Width >= 1800)
{
  player.position.X = 1800 - player.playerTexture.Width;
}

```

Even better, use the existing `MathHelper.Clamp` function:

```
player.position.X = MathHelper.Clamp(player.position.X, 0, 1800 - player.playerTexture.Width);

```

As a side note, you want to block the player's movement **after** updating its position. Right now you are doing it inside your `Update` method before updating the player. This will make it that when you'll reach the border you'll have your position set back to the limit, but your position will still be updated directly afterwards, making you move a little off the screen.

---
Tags: xna, platformer
---


title: Shadows in deferred rendering

text:
# Question
Title: Shadows in deferred rendering
I've read some material about deferred rendering, and I think I get the gist of it. But what I don't understand is how it accomplishes shadows. The G-buffer, as far as I'm aware, does not involve creating a shadowmap for each light, so I'm confused as to how the lighting pass is aware of whether or not each pixel is occluded. After all, a given pixel which is visible from the camera's perspective may not actually be visible from the perspective of any given light- and that occluding geometry may not be visible from the camera's perspective and therefore have nothing written about it into the G-buffer.

If you start rendering shadowmaps, then it seems pretty much the same as forward rendering- you render all the geometry in the scene for every light to render the shadowmaps.

So how does deferred rendering accomplish shadows equivalent to forward rendering?

# Answer
Deferred shading doesn't do anything special for shadows. You still need to render the shadow maps normally and then render each light with the appropriate shadow map bound as a texture.

It's still better than forward rendering because you don't need to redraw the scene in the main view to apply the lighting. Drawing the shadow map is often much cheaper than drawing more passes in the main view because you don't need to do any pixel shading, and shadow maps often contain less of the scene (you can cull out a lot more stuff).

People do sometimes do "deferred shadows" for one light, typically the main directional light. The primary reason to do this is to use cascaded shadow maps or another approach that uses multiple shadow maps for the same light. You can reserve one channel in the G-buffer for a shadow mask (white where lit, dark where shadowed) and apply all cascaded shadow maps into this G-buffer channel; then the shader for the light just reads the shadow mask and multiplies it into the light color. This is nice since it decouples shadows from shading, but you're still drawing all the same shadow maps.
> 16 votes

# Answer
Well, what is a shadow map? A shadow map is a texture who's texels answer a simple question: at what distance from the light, along the direction represented by the texel, is the light occluded? Texture coordinates are generated using various projective texturing means, depending on the particular shadow mapping algorithm.

Projective texturing is simply a way of transforming an object into the space of the texture (and yes, I know that sounds backwards. But that's how it works). Shadow mapping algorithms use several different kinds of transforms. But ultimately, these are just transformations from one space into another.

When rendering the shadow map, you take the vertices of your geometry and transform them though a standard rendering pipeline. But the camera and projection matrices are designed for your light position and direction, not for the view position and orientation.

When doing forward rendering with a shadow map, you render the object as normal, transforming the vertices into the view camera space and through the viewing projection matrix. However, you also transform the vertices through your light camera and projection matrices, passing them as per-vertex data to the fragment shader. It uses them via projective texturing to access the shadow texture.

Here's the important point. The projective texture access is designed such that the location it accesses on the texture represents the direction between that point on the surface (the point that you're rendering in the fragment shader) and the light. Therefore, it fetches the texel that represents the depth at which occlusion happens for the fragment being rendered.

But there's nothing *special* about this pipeline. You don't have to transform the vertex positions into the shadow texture and pass those to the fragment shader. You could pass the world-space vertex positions to the fragment shader, and then have the fragment shader transform them into the projective space of the shadow texture. Granted, you'd be throwing away lots of performance, since you'll come up with the exact same texture coordinates. But it is mathematically viable.

Indeed, you could pass the view camera-space vertex positions to the fragment shader. It could then transform them to world, then into light camera-space, then into the projective shadow texture space. You could put all of that transformation into one matrix (depending on your shadow projection algorithm). Again, this gives you exactly what you had before, so when forward rendering, there's no reason to do it.

But in *deferred* rendering, you *already have* the view camera-space vertex positions. You have to, otherwise you can't do lighting. You either wasted a lot of memory and bandwidth by writing them to a buffer, or you were smart and recomputed them using the depth buffer and various math (which I won't go into here, but is covered online).

Either way, you have view camera-space positions. And, as stated above, we can apply a matrix to transform them from view camera-space into shadow projective texture space. So... do that. Then access your shadow map.

Problem solved.
> 6 votes

---
Tags: 3d, shadow-mapping, deferred-rendering, shading
---


title: improving speed of 2d ball collision

text:
# Question
Title: improving speed of 2d ball collision
I am making a game which has many balls bouncing around the screen (around 200-300 balls in a small area). One thing I am trying to do is improve the performance of the collision detection and resolution.

What I've tried to do so far is to maintain a large number of `ArrayLists`. I split the screen up into a grid and for each cell I keep an `ArrayList` containing each ball that is currently inside that particular grid square. Whenever I update the positions of the balls, I also update which list they belong to.

When checking for collisions, I have a separate ArrayList which contains all the balls. I iterate through this list, and for each ball:

* find out what grid square it is in
* check for collisions with all the balls in adjacent grid squares

I've tested this approach and it doesn't seem any different to just iterating over a list of all the bubbles twice.

Does anyone have some suggestions on how I can improve things? For instance, with my current algorithm I am handling collisions twice but I'm unsure how I can work around it.

# Answer
It sounds like you're halfway to a Quadtree, which I think could help speed things up.

The basic idea is this: Instead of having a fixed number of cells in which these balls can reside, you have a node which subdivides itself into exactly four nodes if there are more than two balls residing in it. Repeat this process until each node has two or fewer balls in it, and then you only have to check the pairs in each node for collisions, rather than checking each ball against a larger potential set of colliders.
> 1 votes

---
Tags: java, collision-detection, performance
---