# Question
Title: Collision Resolution: Objects "swap" places
I am working on making my own simple collision resolution class so I can learn a bit about how it works, while also improving my entity-component model framework. For those of you unfamiliar with a entity-component model, read this, it's a super fascinating way to build games very quickly and focus on code reuseability. I have a algorithm which I got from this tutorial that worked pretty well in my stand-alone tests but, when I implemented them into my framework, it can do some wonky things.

The resolution will work 9/10 but, there are cases where it does bugs, like when the objects "swap" places. You can see the bug in my video here -\> http://www.youtube.com/watch?v=7tGDylY52Wc

Here is the \`CollisionHandler class which deals with the pairing and resolution. This is a service, which is a non-entity way of managing entities, components, or anything you need in a state.

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EntityEngineV4.Collision.Shapes;
using EntityEngineV4.Engine;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace EntityEngineV4.Collision
{
    public class CollisionHandler : Service
    {
        private List<Collision> _collideables;
        private HashSet<Pair> _pairs;
        private HashSet<Manifold> _manifolds;

        public CollisionHandler(EntityState stateref) : base(stateref)
        {
            _collideables = new List<Collision>();
            _pairs = new HashSet<Pair>();
            _manifolds = new HashSet<Manifold>();
        }

        public override void Update(GameTime gt)
        {
            BroadPhase();
            foreach (var manifold in _manifolds)
            {
                manifold.A.OnCollision(manifold.B);
                manifold.B.OnCollision(manifold.A);

                //Attempt to resolve collisions
                if (CanObjectsResolve(manifold.A, manifold.B) || CanObjectsResolve(manifold.B, manifold.A))
                {
                    ResolveCollision(manifold);
                    PositionalCorrection(manifold);
                }

            }
        }

        public override void Draw(SpriteBatch sb)
        {
            _manifolds.Clear();
        }

        public void AddCollision(Collision c)
        {
            //Check if the Collision is already in the list.
            if (Enumerable.Contains(_collideables, c)) return;
            _collideables.Add(c);

            //Generate our pairs
            GeneratePairs();
        }

        public void GeneratePairs()
        {
            if (_collideables.Count() <= 1) return;

            _pairs.Clear();

            foreach (var a in _collideables)
            {
                foreach (var b in _collideables)
                {
                    if (a.Equals(b)) continue;
                    if (CanObjectsPair(a, b))
                    {
                        var p = new Pair(a,b);
                        _pairs.Add(p);
                    }
                }
            }
        }

        public void BroadPhase()
        {
            //Do a basic SAT test
            foreach (var pair in _pairs)
            {
                Vector2 normal = pair.A.Position - pair.B.Position;

                //Calculate half widths
                float aExtent = pair.A.BoundingRect.Width / 2f;
                float bExtent = pair.B.BoundingRect.Width / 2f;

                //Calculate the overlap.
                float xExtent = aExtent + bExtent - Math.Abs(normal.X);

                //If the overlap is greater than 0
                if (xExtent > 0)
                {
                    //Calculate half widths
                    aExtent = pair.A.BoundingRect.Height / 2f;
                    bExtent = pair.B.BoundingRect.Height / 2f;

                    //Calculate overlap
                    float yExtent = aExtent + bExtent - Math.Abs(normal.Y);

                    if (yExtent > 0)
                    {
                        //Do our real test now.
                        Manifold m = CheckCollision(pair.A.Shape, pair.B.Shape);
                        if (m.AreColliding)
                            _manifolds.Add(m);
                    }
                }
            }
        }

        //Static methods

        /// <summary>
        /// Compares the masks and checks to see if they should be allowed to form a pair.
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns>Whether or not the the two objects should be paired</returns>
        public static bool CanObjectsPair(Collision a, Collision b)
        {
            return a.GroupMask.HasMatchingBit(b.GroupMask) || //Compare the group masks.
                   a.GroupMask.HasMatchingBit(b.PairMask) || //Compare the pair masks to the group masks.
                    a.PairMask.HasMatchingBit(b.GroupMask);
        }

        public static bool CanObjectsResolve(Collision resolver, Collision other)
        {
            return resolver.ResolutionGroupMask.HasMatchingBit(other.ResolutionGroupMask) || //Compare the group masks.
                    resolver.ResolutionPairMask.HasMatchingBit(other.ResolutionGroupMask);
        }

        public static void ResolveCollision(Manifold m)
        {
            Vector2 relVelocity = m.B.Velocity - m.A.Velocity;
            //Finds out if the objects are moving towards each other.
            //We only need to resolve collisions that are moving towards, not away.
            float velAlongNormal = PhysicsMath.DotProduct(relVelocity, m.Normal);
            if (velAlongNormal > 0)
                return;
            float e = Math.Min(m.A.Restitution, m.B.Restitution);

            float j = -(1 + e) * velAlongNormal;
            j /= m.A.InvertedMass + m.B.InvertedMass;

            Vector2 impulse = j * m.Normal;
            if (CanObjectsResolve(m.A, m.B))
                m.A.Velocity -= m.A.InvertedMass * impulse;
            if(CanObjectsResolve(m.B, m.A))
                m.B.Velocity += m.B.InvertedMass * impulse;
        }

        public static void PositionalCorrection(Manifold m)
        {
            const float percent = 0.2f;
            const float slop = 0.01f;
            Vector2 correction = Math.Max(m.PenetrationDepth - slop, 0.0f) / (m.A.InvertedMass + m.B.InvertedMass) * percent * m.Normal;
            m.A.Position -= m.A.InvertedMass * correction;
            m.B.Position += m.B.InvertedMass * correction;
        }

        /// <summary>
        /// Compares bounding boxes using Seperating Axis Thereom.
        /// </summary>
        public static Manifold AABBvsAABB(AABB a, AABB b)
        {
            //Start packing the manifold
            Manifold m = new Manifold(a.Collision, b.Collision);
            m.Normal = a.Position - b.Position;

            //Calculate half widths
            float aExtent = a.Width / 2f;
            float bExtent = b.Width / 2f;

            //Calculate the overlap.
            float xExtent = aExtent + bExtent - Math.Abs(m.Normal.X);

            //If the overlap is greater than 0
            if (xExtent > 0)
            {
                //Calculate half widths
                aExtent = a.Height / 2f;
                bExtent = b.Height / 2f;

                //Calculate overlap
                float yExtent = aExtent + bExtent - Math.Abs(m.Normal.Y);

                if (yExtent > 0)
                {
                                        //Find which axis has the biggest penetration ;D
                    Vector2 fixnormal;
                    if (xExtent > yExtent){
                        if(m.Normal.X < 0)
                            fixnormal = -Vector2.UnitX;
                        else
                            fixnormal = Vector2.UnitX;

                        m.Normal = PhysicsMath.GetNormal(a.Position, b.Position) * fixnormal.X;
                        m.PenetrationDepth = xExtent;
                    }
                    else {
                        if(m.Normal.Y < 0)
                             fixnormal = -Vector2.UnitY;
                        else
                            fixnormal= Vector2.UnitY;
                        m.Normal = PhysicsMath.GetNormal(a.Position, b.Position) * fixnormal.Y;
                        m.PenetrationDepth = yExtent;
                    }
                    m.AreColliding = true;
                    return m;
                }
            }
            m.AreColliding = false;
            return m;
        }

        //Collision resolver methods

        public static Manifold CheckCollision(Shape a, Shape b)
        {
            return collide((dynamic) a, (dynamic) b);
        }

        private static Manifold collide(AABB a, AABB b)
        {
            return AABBvsAABB(a, b);
        }

    }
}

```

Next is the `Collision` component. This holds some bitmasks which tell it what groups it is a part of(`GroupMask`), what groups it is allowed to pair with with out being a part of that group (`PairMask`), and who it should resolve collisions with, (`ResolutionGroupMask`) and finally, who it should resolve collisions with one-way (`ResolutionPairMask`). It also holds values related to detection and resolution, such as `Shape`, mass, and restitution.

Just as a quick side note, under the comment "Dependencies" there is a field for a `Body` and a `Physics`, both of these objects are components which are supplied to track the location of the collideable.

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EntityEngineV4.Collision.Shapes;
using EntityEngineV4.Components;
using EntityEngineV4.Engine;
using Microsoft.Xna.Framework;

namespace EntityEngineV4.Collision
{
    public class Collision : Component
    {
        //Delegates and events
        public delegate void EventHandler(Collision c);
        public event EventHandler CollideEvent;

        /// <summary>
        /// The group mask is the bit mask used to determine which groups the component is a part of.
        /// The CollisionHandler will pair all components with the same mask.
        /// </summary>
        /// <value>
        /// The group mask.
        /// </value>
        public Bitmask GroupMask { get; protected set; }

        /// <summary>
        /// The pair mask is the bit mask used to determine which groups the component will pair with.
        /// The CollisionHandler will only pair components whose group mask matches the pair mask.
        /// </summary>
        /// <value>
        /// The pair mask.
        /// </value>
        public Bitmask PairMask { get; protected set; }

        /// <summary>
        /// The resolution mask is the bit mask which will determine which groups will physically collide with each other
        /// </summary>
        public Bitmask ResolutionGroupMask { get; protected set; }

        /// <summary>
        /// The resolution mask is the bit mask which will determine which pairs will physically collide with each other
        /// </summary>
        public Bitmask ResolutionPairMask { get; protected set; }

        //Collision Related Values

        //// <summary>
        /// Backing field for Mass.
        /// </summary>
        private float _mass = 1f;
        /// <summary>
        /// The mass of the object.
        /// </summary>
        /// <value>
        /// The mass.
        /// </value>
        public float Mass
        {
            get { return _mass; }
            set
            {
                if (value < 0) throw new Exception("Mass cannot be less than zero!");
                _mass = value;

                if (Math.Abs(value - 0) < .00001f)
                    InvertedMass = 0;
                else
                    InvertedMass = 1 / _mass;
            }
        }

        /// <summary>
        /// Gets one divided by mass (1/mass).
        /// </summary>
        /// <value>
        /// The inverted mass.
        /// </value>
        public float InvertedMass { get; private set; }

        /// <summary>
        /// Bounciness of this object
        /// </summary>
        public float Restitution = 0f;

        public Shape Shape;

        //Dependencies
        private CollisionHandler _collisionHandler;
        private Body _collisionBody;
        private Physics _collisionPhysics;

        //Properties

        public Rectangle BoundingRect
        {
            get { return _collisionBody.BoundingRect; }
            set { _collisionBody.BoundingRect = value; }
        }

        public Vector2 Position
        {
            get { return _collisionBody.Position; }
            set { _collisionBody.Position = value; }
        }

        public Vector2 Bounds
        {
            get { return _collisionBody.Bounds; }
            set { _collisionBody.Bounds = value; }
        }

        public Vector2 Velocity
        {
            get { return _collisionPhysics.Velocity; }
            set { _collisionPhysics.Velocity = value; }
        }

        public Collision(Entity parent, string name, Shape shape, Body collisionBody) : base(parent, name)
        {
            _collisionBody = collisionBody;
            _collisionHandler = parent.StateRef.GetService<CollisionHandler>();

            _collisionPhysics = new Physics(Parent, name + ".Physics", _collisionBody);

            Shape = shape;
            Shape.Collision = this;

            GroupMask = new Bitmask();
            PairMask = new Bitmask();
            ResolutionGroupMask = new Bitmask();
            ResolutionPairMask = new Bitmask();
        }

        public Collision(Entity parent, string name, Shape shape, Body collisionBody, Physics collisionPhysics)
            : base(parent, name)
        {
            _collisionBody = collisionBody;
            _collisionHandler = parent.StateRef.GetService<CollisionHandler>();

            _collisionPhysics = collisionPhysics;

            Shape = shape;
            Shape.Collision = this;

            GroupMask = new Bitmask();
            PairMask = new Bitmask();
            ResolutionGroupMask = new Bitmask();
            ResolutionPairMask = new Bitmask();
        }

        public void OnCollision(Collision c)
        {
            if (CollideEvent != null)
                CollideEvent(c);
        }

        public void AddToHandler()
        {
            _collisionHandler.AddCollision(this);
        }
    }
}

```

Lastly, I felt this was pretty self-explanatory but, I feel I should include it in case of an error. This is the `PhysicsMath` class which just holds some simple methods for calculating dot products, normals, and distance.

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

namespace EntityEngineV4.Engine
{
    public static class PhysicsMath
    {
        public static float DotProduct(Vector2 a, Vector2 b)
        {
            return a.X * b.X + a.Y * b.Y;
        }

        public static float Distance(Vector2 a, Vector2 b)
        {
            return (float)Math.Sqrt(((int)(a.X - b.X) ^ 2 + (int)(a.Y - b.Y) ^ 2));
        }

        public static Vector2 GetNormal(Vector2 a, Vector2 b)
        {
            Vector2 ret = b - a;
            ret.Normalize();
            return ret;
        }
    }
}

```

Any help is greatly appreciated.

# Answer
I think the problem is that in one frame the objects move fast enough to pass through each other. Behold my ascii art:

Frame 1:

a is heading towards b

```
+-------+ +-------+
|   A   | |   B   |
+-------+ +-------+

```

Frame 2:

```
    +----+--+----+
    |   B|  |A   |
    +----+--+----+

```

At this point the collision response moves them away from each other but the centre of A is now to the right of B so they will swap places.

I think you need to use a volume sweeping technique to determine the position of the two objects at the time of collision. The time of collision is somewhere between frame 1 and frame 2 e.g. 1.3 frames...

**Edit**

In 2D where you only have to prevent the objects from crossing over you can probably do something like this:

At the beginning of the frame (t0), object A is at Position A0 and object B is at position B0. At the end of the frame (t1), A is at A1 and B is at B1. Assuming there is a collision then at time t (where t0 \< t \< t1) A and B are at the same position i.e. At == Bt.

Given constant velocities for A and B of vA and vB we have:

```
A0 + vA * t = B0 + vB * t
A0 - B0 = vB * t - vA * t
A0 - B0 = t * (vB - vA)

(A0 - B0) / (vB - vA) = t

```

Assuming I haven't had a maths fail, this should give you the time in the frame at which collision occured.

**Edit 2**

Ok, so the maths above is a bit simplistic as it does not include the area of the colliders. I dug out a bit of code from my old 3D collision detection library but I can't remember where I got it from or how it works. The simple explaination is that it forms simultaneous equations for the two objects motion during the frame and attempts to solve for time. There are potentially two collision times, when the objects first moved into collision and when they left collision. You obviously want the lower of the two solutions.

This code is for 3D swept volume involving spheres so you will need to adapt it:

```
protected bool SphereSweepTest(
        Vector3 a0, // A's starting position
        Vector3 a1, // A's finishing position
        Vector3 b0, // B's starting position
        Vector3 b1, // B's finishing position
        float rab, // Sum of the two sphere's radii
        out float t) // Earliest time of collision
    {
        // Form and solve a quadratic equation to determine if the
        // two spheres will cross paths and if so when in normalised time
        // Normalised time means that 0.0 is the start of this frame
        // and 1.0 is the end.  Obviously a collision must occur between
        // 0.0 and 1.0 otherwise the collision is outside this frame, the
        // spheres haven't collided, they are simply on a collision course.

        Vector3 va = a1 - a0;
        Vector3 vb = b1 - b0;

        Vector3 AB = b0 - a0;
        Vector3 vab = vb - va;

        //float ABdot = Vector3.Dot(AB, AB);
        float ABdot = AB.X * AB.X + AB.Y * AB.Y + AB.Z * AB.Z;
        float rabrab = rab * rab;

        //float a = Vector3.Dot(vab, vab);
        float a = vab.X * vab.X + vab.Y * vab.Y + vab.Z * vab.Z;
        float b = 2.0f * (vab.X * AB.X + vab.Y * AB.Y + vab.Z * AB.Z);
        float c = ABdot - rabrab;

        float q = b * b - 4.0f * a * c;
        if (q > 0.0f)
        {
            float sq = (float)Math.Sqrt(q);
            float d = 1.0f / (2.0f * a);
            float u0 = (-b + sq) * d;
            float u1 = (-b - sq) * d;

            // Start and end are outside current time frame
            if ((u0 < 0.0f && u1 < 0.0f) || (u0 > 1.0f && u1 > 1.0f))
            {
                t = -1.0f;
                return false;
            }

            // Make sure start time is less than end time
            if (u0 > u1)
            {
                float ut = u0;
                u0 = u1; u1 = ut;
            }

            // Interpolate time
            t = u0 + u1 - u0;

            // Make sure time is inside current frame - clamp to 1
            // No need to clamp to 0 since the objects cannot begin
            // the frame in collision
            if (t > 1.0f) t = 1.0f;

            return true;
        }

        t = -1.0f;
        return false;
    }

```
> 5 votes

---
Tags: xna, c#, collision-resolution, .net
---


title: How do I make a game tick method?

text:
# Question
Title: How do I make a game tick method?
I've seen in some other simple 2D games that a "tick" method is used to sync game logic and graphics rendering. My main reason for using this is due to my collision detection malfunctioning, since the player entity will completely pass through solid objects unless I tap the controls almost pixel-by-pixel to collide the rectangles.

I figure a tick method will slow the games rapid updating enough to pick up these slight collision detections.

How do I create such a method? I've tried the code you can see below, however, it is causing the entire game to freeze:

The update method:

```
 @Override
    public void update(float deltaTime) {
        List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
            long lastTime = 0;
            long currentTime = 0;

        if (state == GameState.Ready) {
            updateReady(touchEvents);
        }
        while (state == GameState.Running) {
                lastTime = currentTime;
                currentTime = System.currentTimeMillis();
                deltaTime = currentTime - lastTime;

                player.update(touchEvents, deltaTime);
                repaint(deltaTime);
        }
        if (state == GameState.Paused) {
            updatePaused(touchEvents);
        }
        if (state == GameState.GameOver) {
            updateGameOver(touchEvents);
        }
    }

```

The repaint method, which is updated while the regular paint method does nothing. I've tried the while loop with both, doesn't seem to stop freezing:

```
public void repaint(float deltaTime) {
        Graphics g = game.getGraphics();

        if(deltaTime >= 60) {
            g.drawRect(0, 0, 805, 485, color.black);
            map.loadMap(getXScroll(), getYScroll(), g, game);
            map.loadEntities(getXScroll(), getYScroll(), g, game, map);
            g.drawImage(Assets.bitSoldier, 448, 256);
            g.drawImage(Assets.dpad, 0, 280);

            // Secondly, draw the UI above the game elements.
            if (state == GameState.Ready)
                drawReadyUI();
            if (state == GameState.Running)
                drawRunningUI();
            if (state == GameState.Paused)
                drawPausedUI();
            if (state == GameState.GameOver)
                drawGameOverUI();
        }
    }

```

# Answer
In general, there are two ways to make game logic "tick":

* **Fixed time steps** run a fixed number of times per second, for example 100 times or maybe even 1000 times.
* **Dynamic time steps** run the game logic whenever possible, considering the time passed since the last update.

Both approaches got their advantages and disadvantages, depending on what you're trying to achieve.

For movement and such, dynamic timesteps might be better, but for things such as animating pixel graphics, fixed timesteps might be more interesting. You can mix and match both as you like.

In general, as I mentioned in the comments, you should never let your program sleep in the game loop. This slows down the game without any reason and might even create stutter despite the computer being powerful enough to actually run the game without slowdowns.

Your generic game loop should look a bit like this (pseudo code):

```
function mainloop() {
    double time_passed = 0;
    double delta_time = 0;

    while (running) { // keep running

        // update game logic based on time passed
        updateDynamicStep(delta_time);

        // update game logic once for every tick passed
        while (time_passed >= time_per_timestep) {
            updateFixedStep();
            time_passed -= time_per_timestep;
            // You might limit the number of iterations here (like 10)
            // to not get stuck due to processing taking too long (and time adding up)
        }

        // draw screen content
        drawStuff(delta_time);

        // update timing
        delta_time = getTimePassedAndResetTimer();
        time_passed += delta_time;
    }
}

```

Doing it that way - no matter whether you use fixed time steps or not - has the advantage that your game will always run at the same speed, no matter whether you're running at 60 fps, 100 fps, 5000 fps, or only 15 fps.

The only reason to force sleeps could be to save battery (e.g. mobile games), but again I wouldn't sleep for fixed time, just sleep based on the time this iteration took and the time you planned for one frame. For example, if updating your game and drawing takes 10 ms and you plan on running at 60 frames per second, sleep for 5 ms (15ms total; perfect time would be 16.67ms, but you're leaving some space for other stuff like context switches and the like).
> 12 votes

---
Tags: java, 2d, collision-detection, timing
---


title: Cocos-2D asteroids style movement (iOS)

text:
# Question
Title: Cocos-2D asteroids style movement (iOS)
So I have a CCSprite subclass, well call this `Spaceship`. Spaceship needs to move on a loop, until I say othersise by calling a method. The method should look something like

```
- (void)moveForeverAtVelocity
{
  // method logic
}

```

The class Spaceship has two relevant iVars, `resetPosition` and `targetPosition`, the target is where we are headed, the reset is where we set to when we've hit our target. If they are both off-screen this creates a permanent looping effect.

So for the logic, I have tried several things, such as

```
CCMoveTo *move = [CCMoveTo actionWithDuration:2 position:ccp(100, 100)];
CCCallBlockN *repeat = [CCCallBlockN
  actionWithBlock: ^(CCNode *node) {
    [self moveForeverAtVelocity];
}];

[self runAction:[CCSequence actions: move, repeat, nil]];
self.position = self.resetPosition;

```

recursively calling the `moveForeverAtVelocity` method.

This is psuedo-code, so its not perfect. I have hard-coded some of the values for the sake of simplicity.

Enough garble: The problem I am having, how can I make a method that loops forever, but can be called and reset at will. I'm running into issues with creating multiple instances of this method. If you can offer any assistance with creating this effect, that would be appreciated.

# Answer
You can build two different types of motion functions that are called if the positions are off the screen or within the screen.

```
//within the SpaceShip Class
void Move(){
   if(InScreen)
       asteroidLikeMotion();
   else if(OffScreen)
       loopMotion();
}

```

I am guessing that you already have the mechanism for asteroid like motion. For looping behavior it is much simpler:

```
x += velocity*cos(direction);
y += velocity*sin(direction);
direction += angularSpeed;

```
> 1 votes

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


# Question
Title: JavaScript "Floats", or ThreeJS wrong positioning?
I want to learn how to use Vectors with 3D.

Here is a strange Error I have encountered today.

Instead of stopping exactly on the other Cube, I get this:

When I change the IF to (cube.position.y \< 0.1) OR change the speed to 0.01, it lands on the other cube. Seems 0.1 is the Magic Number.. But why?
Why does 0.9 and 0.8 seem fine, but then it Jumps into lengthy numbers? This looks more like ThreeJS is moving the Cube inaccurately, rather then JavaScript being unable to move an Object 0.1 sizes.

Such a beginner problem, but this is baffling to me..

Why does this happen? And how can I change it?

Is this where I "normalise" the Vector?

# Answer
As Ivan Kucklr says, floating point values are binary and decimal values such as 0.1 may not be represented exactly. This is true across languages, and is not Javascript specific or Three.js specific. It's fine some of the time, but often bites you worse when repeatedly adding or subtracting like your program does.

In your program, you're waiting for `cube2.position.y` to reach 0. When it's \> 0 you subtract 0.1. But what's happening is that it's reaching some number very close to 0, but not exactly 0. Sometimes it'll overshoot a little; sometimes it'll undershoot. In this case it's undershooting slightly which means you end up running your loop one extra time.

Instead of checking whether it's reached 0, you can check whether it's reached *close* to 0. The easiest thing in this particular case is to test `if (cube2.position.y > 0.00001)`. More generally, if you want to know whether `a == b`, you can instead use `abs(a - b) < epsilon` where epsilon is some small number relative to the expected size of a and b; instead of `a > b` you can use `(a - b) > epsilon`.

Read more on this page, which goes through an example of 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 != 0.1 * 10, just like your program, but then shows some more advanced ways to compare.
> 3 votes

# Answer
You can not "trust" floating point values. First, 0.1 can not be represented in binary system. It is periodical and it should be approximated by finite mantissa.

So, imagine this program on decimal computer:

```
var i = 1;
while( i>0 ) i -= 1/3;
console.log(i);           // prints -0.3333333332

```

1/3 will be approximated as 0.33333333, so values of "i" will be

```
 1.0000000000
 0.6666666667
 0.3333333334
 0.0000000001
-0.3333333332

```
> 0 votes

---
Tags: vector, linear-algebra, floating-point
---


title: Return char + char problems

text:
# Question
Title: Return char + char problems
```
int ReturnString(int , char);
int Finisher(int ChosenSave)
{
       char SaveFolder1[20]="./Data/Saves/Save1/";
       char SaveFolder2[20]="./Data/Saves/Save2/";
       char SaveFolder3[20]="./Data/Saves/Save3/";
       char SaveFolder4[20]="./Data/Saves/Save4/";
       ofstream MyFileOut;

       if(ChosenSave==1) FileOut.open(ReturnChar(1 , SaveFolder1));
  else if(ChosenSave==2) FileOut.open(ReturnChar(1 , SaveFolder2));
  else if(ChosenSave==3) FileOut.open(ReturnChar(1 , SaveFolder3));
  else if(ChosenSave==4) FileOut.open(ReturnChar(1 , SaveFolder4));
}

int ReturnChar(int x, char Folder[50])
{
    if (x==1)
        strcat(Folder , "MapTXT.txt");
    else if (x==2)
        strcat(Folder , "MapPNG.png");
    else if (x==3)
        strcat(Folder , "TreesRare.txt");
    else if (x==4)
        strcat(Folder , "TreesMedium.txt");
    else if (x==5)
        strcat(Folder , "TreesMany.txt");
    return Folder;
}

```

Working at a game which includes worlds and I must save different files to the selected save slot (folder) and I'm not sure how to Return my char back in the .open statement . I need to return the save route + the name of the file and type . As it's very obvious it doesn't work , please help ?

# Answer
I agree with Liosan, however I will expand upon the reasons to use std::string over cstrings for clarity.

## Why not to use c strings

The first, and most important, is that c strings take a large amount of cautious coding and double checking to ensure memory safe operations. Case in point in your code: each call to strcat should be checked before it is run to ensure that the buffer `Folder` is not overrun. `ReturnChar` has no idea what the contents of Folder are to start with, and it is assuming that is has enough space remaining in the buffer to fit whatever arbitrary file name you've selected. A better solution (if you HAD to use c strings) would be to use strncat rather than strcat, however this is not so simple as it sounds. The proper usage of this is something like:

```
char* FileNameLookup(int x){
    switch(x){
        case 1: return "MapTXT.txt";
        case 2: return "MapPNG.png";
        case 3: return "TreesRare.txt";
        case 4: return "TreesMedium.txt";
        case 5: return "TreesMany.txt";
        default: return "";
    }
}

char* SavePathCreation(int x, char saveLocation[SAVE_PATH_MAX_SIZE+1] ){
    char fileName[FILE_NAME_MAX_SIZE+1] = FileNameLookup(x);

    int fileNameLen = strlen( fileName );

    int spaceAvailableForFileName = SAVE_PATH_MAX_SIZE - fileNameLen ;

    if( path == null ){
/* THIS IS AN ERROR THAT WOULD NEED TO BE DEALT WITH  instead of continuing */
    }

    return strncat( saveLocation, fileName , spaceAvailableForFileName );

}

int Finisher(int ChosenSave){
    char SaveFolder1[20]="./Data/Saves/Save1/";
    char SaveFolder2[20]="./Data/Saves/Save2/";
    char SaveFolder3[20]="./Data/Saves/Save3/";
    char SaveFolder4[20]="./Data/Saves/Save4/";
    ofstream MyFileOut;

    if(ChosenSave==1) FileOut.open(SavePathCreation(1 , SaveFolder1));
    else if(ChosenSave==2) FileOut.open(SavePathCreation(1 , SaveFolder2));
    else if(ChosenSave==3) FileOut.open(SavePathCreation(1 , SaveFolder3));
    else if(ChosenSave==4) FileOut.open(SavePathCreation(1 , SaveFolder4));
    //This looks like it should return something? Not sure what your code is doing here
}

```

As you can see, there is actually more overhead than the simple one line call to strcat than you used to safely work with c strings. Not only that, FAR more dangerously this is prone to human error and is very difficult to read it's intentions properly. If you are using c strings instead of std::string for optimization, then I suggest you abandon this reasoning quickly as it is DEFINITELY premature optimization.

Now compare this to using std classes

## An alternative using std::string

```
std::string FileNameLookup(int x){
    switch(x){
        case 1: return std::string( "MapTXT.txt" );
        case 2: return std::string( "MapPNG.png" );
        case 3: return std::string( "TreesRare.txt" );
        case 4: return std::string( "TreesMedium.txt" );
        case 5: return std::string( "TreesMany.txt" );
        default: return std::string( "" );
    }
}

int Finisher(int ChosenSave){
    std::string SaveFolder1 ( "./Data/Saves/Save1/" );
    std::string SaveFolder2 ( "./Data/Saves/Save2/" );
    std::string SaveFolder3 ( "./Data/Saves/Save3/" );
    std::string SaveFolder4 ( "./Data/Saves/Save4/" );
    std::string SaveFolders[] = { SaveFolder1, SaveFolder2, SaveFolder3, SaveFolder4 };
    std::string fileName = FileNameLookup(1);
    ofstream MyFileOut;

    if(ChosenSave>=1 && ChosenSave <= 4){
        /*
         * Note that c_str is only guaranteed to be valid as long as the string
         * is unmodified; This is safe, but it is a good caveat to remember.
         */
        FileOut.open( SaveFolders[ChosenSave].append(fileName)->c_str() );
    }
    else {
        //Handle invalid save location parameter here
    }
    //This looks like it should return something? Not sure what your code is doing here
}

```

## Going EVEN further down the std rabbit hole (using Vectors)

We can even improve this a bit, but using a vector returned from a function to give further memory security AND future extensibility as vector sizes are flexible where as arrays are not. (Even better would be looking up said folder names in a configuration, so folders could be adjusted without recompiling the code).

```
std::string FileNameLookup(int x){
    switch(x){
        case 1: return std::string( "MapTXT.txt" );
        case 2: return std::string( "MapPNG.png" );
        case 3: return std::string( "TreesRare.txt" );
        case 4: return std::string( "TreesMedium.txt" );
        case 5: return std::string( "TreesMany.txt" );
        default: return std::string( "" );
    }
}

std::vector<std::string> GetSaveFolders(){

    std::vector<std::string> sf;

    //push folders onto vector
    sf.push( std::string( "./Data/Saves/Save1/" ) );
    sf.push( std::string( "./Data/Saves/Save2/" ) );
    sf.push( std::string( "./Data/Saves/Save3/" ) );
    sf.push( std::string( "./Data/Saves/Save4/" ) );

    return sf;

}

int Finisher(int ChosenSave){

    std::vector<std::string> saveFolders = GetSaveFolders();

    std::string fileName = FileNameLookup(1); //arbitrary file for this example

    ofstream MyFileOut;

    if(ChosenSave > 0 && ChosenSave <= saveFolders.size ){

        /*
         * append returns a pointer to the string appended to, which is a local
         * variable so no need to free the memory
         */
        std::string* path = SaveFolders.at(ChosenSave-1).append(fileName);

        /*
         * Note: c_str is only guaranteed to be valid as long as the string
         * is unmodified; This is safe, but it is a good caveat to remember.
         */
        FileOut.open( path->c_str() );
    }
    else {
        //Handle invalid save location parameter here
    }
    //This looks like it should return something?
    //Not sure what your code was doing here
}

```
> 1 votes

# Answer
I'm not really sure on what you're trying to achieve here. You can't return a pointer to a string (`char*`) and cast it to an integer (you can but you shouldn't do it).

Instead, you should organize your whole saving in a different way (the following is pseudo code, you might have to replace or implement some of the functions based on your target system etc.):

```
char savepath[256]; // temporary string to store the file name
char oldpath[256]; // temporary string to store current working dir
const char pathtemplate[] = "./Data/Saves/Save%d/"; // save path template

// first create a string with the actual path to save to
snprintf(savepath, 255, pathtemplate, chosenSave);

// save the current working directory
storeWorkingDir(oldpath);

// change the working directory
changeWorkingDir(savepath);

// now open the actual file(s)
ofstream someFile("map.txt");

// restore the working directory
changeWorkingDir(oldpath);

```
> 2 votes

# Answer
I have no idea what you are doing, but I think it would be a lot easier if you used std::string. You can get it's c-string (const char\*) using c\_str().
> 2 votes

# Answer
Your `ReturnChar` function has its return type set to `int` when it seems you want to return `char`. And you probably want to return a `char*` at that.
> 0 votes

---
Tags: c++
---


# Question
Title: Handling collision for sprites with different frame sizes
I am creating a platform game, and the main character has three images for its left and right animation. The problem is that when it is walking and the player run into a block, if at that moment it switches to a stepping image which is bigger than the other imagesit gets stuck inside the block. A temporary fix to this issue was to make all the images the same size and just fill the smaller ones with white-space, however that doesn't work properly either because then the collision box is bigger than the player. Any suggestions? I also tried stretching all the images to the same size but that looked ugly.

# Answer
> 3 votes
You should create size values that are separate from the image size. This is often called a "hitbox". This way, you can add an image of any size with any given amount of whitespace, and collisions will be unaffected.

Fighting games use multiple hitboxes to handle complex collisions.

---
Tags: animation, sprites
---


# Question
Title: Is C++ necessary to learn if I ever want to get a job in the game industry?
Is C++ necessary to learn if I ever want to get a job in the game industry? I am extremely familiar with C# and have a basic mastery of making 2D games in XNA 4.0. Right now I am only 13 years old and love making games, and hope to someday get a game programming job. I have heard a lot of people say that C++ is the 'industry standard' and that it will hurt your career not knowing it. I am also trying to target more platforms than just windows and i am aware of Monogame but for some reason i am having lots of trouble with the visual studio templates, and i find many bugs with monogame. Since i technically can't get a job yet, and probably couldnt get a programming job until i am like 22 or something (unless im self employed). And in that 9+ year time-span the game industry will most likely change a lot. So here is some questions

* Will not learning C++ hurt my chances at getting a programming job?
* By the time i can get a job will C++ still be the 'industry standard' programming language
* If i am an indie developer does it really matter whether i learn C++ or not, and stick with what i know?
* Should i even start learning it now seeing as i have many years before i can even get a job?

I am also having a worry that even though i am familiar with object oriented programming, i may spend lots of time on C++, and get very frustated and confused then just quit learning it, and by this time i've forgotten lots of XNA and i have to learn everything all over. So in short: Should i learn C++ if i ever want a programming job?

**UPDATE**

Thank You All For Your Answers And Suggestions. Recently I Picked Up SFML and C++ and it is going pretty good. I am getting the hang of C++, and starting to open my eyes to not worrying about learning new things because i was able to transfer all my C# knowledge into making C++ easier to learn. Thank You All Once Again.

# Answer
I want to focus on your third question, because it's within my area of knowledge (indie developer):

I haven't written a line of C++ code for many, many years. And, in fact, I have forgotten many of the nitty-gritty details (and in C++ there are a *lot* of those). I do most of my work in C#. And you absolutely don't *have* to learn C++.

*However*, the skills I gained from learning C++ - particularly the low-level stuff, especially how memory and pointers work - have proven invaluable.

Additionally, there have been several occasions where I've had to *read* other people's C++ code. If you know how to program in C# or Java you can probably guess what is going on - but *knowing* is much better.

---

My recommendation to *you*, specifically, is to learn C++ now. At your age you have plenty of time to spend just on learning. That way you won't need to worry about picking up C++ *while* you're trying to develop a game or land a job.

Don't worry about forgetting the details, if you stop using C++ for some reason (or XNA or anything else). The concepts are more important. And you'll be able to pick up the details again easily if you have to.

---

As your other questions hinted at - we don't know what the industry will look like in a decade. Although I'd guess C++ will still be in fairly common use. Speaking for right now - knowing C++ will give you a substantial boost in employability - even at a non-C++ shop.
> 23 votes

# Answer
If you want to be a game programmer you probably can't avoid learning C++. If you want a different job in the game industry, like producer or artist, then you don't need C++.

C++ is hard. Lots of people don't learn it until college. You have lots of time. Work with some other languages to get up to speed on basic programming concepts. Start small and take it one step at a time.
> 7 votes

# Answer
You have a lot of time to learn yet, so I don't think you should be too worried about which language you use, but I will state some things that you might find helpfull:

1. C++ is a language while XNA is a framework. XNA is not going to be updated by Microsoft any more, so I find it incredibly hard to imagine it being used 9 years from now in any serious capacity. C++ on the other and has been around forever, has an active standards committee committed to improving it and provides developers so much control over hardware that it would take a giant leap in hardware power to render this control unneeded and thus allow another language to supplant it as the defacto standard for high performance games.
2. Learning the concepts is the important part, not the language you implement them in. You can "learn" a new language pretty quickly if you already understand its basic principles.
3. C++ would require you to learn about pointers and memory issues at a much deeper level than C# would, so I would recommend you learn it at some point regardless of its use in industry.
4. Your worry about forgetting things is probably unfounded. It is true that you will forget things but the specifics are not really the important part. You won't forget how to design a game by switching languages.

You seem to have reasons not to learn C++, I think you are actually just trying to rationalize your want to not learn something new.

Think of it this way: if you learn C++ and it turns out to not be used in the future, you have many years to learn what is and I will guarantee that having learned C++ will help you do this. If you do happen to forget all your XNA and don't manage to learn C++ it would be better to find this out and move forward than to worry about the possibilities. I don't think either case is very likely.
> 6 votes

# Answer
General advice: don't focus on what you need to learn or what you should be learning. **Just make something.**

To answer your specific question, Microsoft will no longer be updating XNA, so chances are it won't be around for much longer. C++ is a well established industry standard and won't be leaving anytime soon. If you want to work on AAA games, then yes. C++ experience will be necessary.
> 4 votes

# Answer
Since the question has been answered already, let me just fill a few holes here and there...

> I am also having a worry that even though i am familiar with object oriented programming, i may spend lots of time on C++, and get very frustated and confused then just quit learning it, and by this time i've forgotten lots of XNA and i have to learn everything all over. So in short: Should i learn C++ if i ever want a programming job?

Where did you get this idea about C++ being a terrible monster language? It's not! It's actually very fun.

True, you *can* get close to the hardware, which actually has two benefits: you learn a lot more about how the computer actually functions, and second you have a lot more power in your hands than with, say, C#.

But then again, C++ features great abstraction methods and has very useful libraries, so it's not like you'll actually be communicating with the graphics card directly (you definitely can) - it will just be abstracted away.

Knowing just about *any* language is very useful, has a good chance of increasing your probability to be hired, and *definitely* makes you a better programmer.

When you'll have time, check out JavaScript and/or Python. Others would probably suggest Lisp too, but I'm not that knowledgeable when it comes to it, so I wont say anything. But it might be useful to check it out anyway, I think it's pretty neat even with my limited understanding of its concepts. There's Haskell too but bleh.

> And in that 9+ year time-span the game industry will most likely change a lot.

True. But guess what: in 9+ years, we'll still be using assembly, C++ and C. I doubt that game developers will suddenly just decide that they have enough resources and stop pushing the limits of the machines. Of course, this is just a guess, but all of those languages are much older than myself, so I think I'm right.

Besides, by learning C++ you'll make it easier for yourself to transition into a potential new mid-level language.

> Since i technically can't get a job yet, and probably couldnt get a programming job until i am like 22 or something (unless im self employed).

I'm pretty sure you're wrong here. You'll be able to get a job in a few years actually. Few meaning 2 by my country's laws, I think. But not a full-time job.

There are still options to work when the school is out, and if you're good, and you probably are, then there sure will be a dev company that would want to hire you. A gamedev company? Probably not. But there's no reason you'd actually want to work in one as a starter, AFAIK you could get paid better in a regular company, and work on a game in your free time.

Besides, just look at your name, it's almost as if you've already familiarized yourself with the joy of C++ programming!
> 1 votes

# Answer
I'm not in business yet (I'm 17 years old), but I think it is really a must to discover new languages and technologies. While you have time right now, learn C++, OpenGL and Java. Mastering these takes some time (I took me 5 years, so I started at the same age as you are now), but the experience you gain is really amazing.

A good thing to try is to make a Minecraft clone in Java and OpenGL. This will give you insight in a lot of gamedev techniques and will learn you A LOT of optimization techniques. That is whay I did at the age of 16. You can have a look at the result of this at: CraftMania. Why I recommend starting of with Java is because it is easy to program in. There is a garbage collector and neat exception handling. This allows you to learn OpenGL very efficiently, without bothering all the difficulties C++ comes along with for an unexperienced developer.

Once you feel like you master Java in combination with OpenGL, have a look at C++ and try to make some easy things (no games yet). Once you think you understand how C++ is being compiled and works on runtime and know how memory is organized in C++, THEN have a look at SDL to make an easy game.

Why do I focus on OpenGL? Because OpenGL runs on every platform except for XBox360. This is: Windows, Linux, OS X, Android, iOS, BlackBerry, Wii, DS, PS3, PSP, etc... When you only master Xna and DirectX, you are bound to Windows and XBox360. I think this is a good reason to learn OpenGL and C++ if you want to get a programming job in game industry.
> 1 votes

# Answer
My answer would be that it really depends on what you want to do in the games industry. At the moment if you want to make AAA console games, C++ is a must. No other language will allow you to take advantage of the limited resources you have on a console.

For a long time C++ was the lingua franca of the games industry, but with the advent of the iPhone and Unity it's now possible to make decent games using languages like C# and Objective-C. Even HTML 5 is capable of making games now. The simple fact is, there are a lot of options out there.

At your age you still have a lot of time to learn and watch how the industry develops. My advice to you would be this: don't focus on the language. Focus on learning how to make games and/or making mods for games that are out there. One idea might be to get Minecraft and figure out how to make mods using Java. Nothing is better than seeing that you can change the way a game behaves, even if you don't actually release any mods.

At your age I was making games using Basic (on the Commodore 64). RPG Maker and later using Java to mod games. I didn't even touch C++ until I was around 18 years old so you still have plenty of time to grow.

To answer your actual questions:

* Will not learning C++ hurt my chances at getting a programming job?

At this stage there is no way to tell. It could be up to 10 years before you start looking for a 'real' job and technology is advancing extremely fast.

* By the time i can get a job will C++ still be the 'industry standard' programming language

See the above answer.

* If i am an indie developer does it really matter whether i learn C++ or not, and stick with what i know?

No. What matters is how many games you finish and release.

* Should i even start learning it now seeing as i have many years before i can even get a job?

It's never too early to start learning, nor is it ever too late.
> 0 votes

---
Tags: xna, c++, game-industry, jobs
---


title: 3D solid object in terrain

text:
# Question
Title: 3D solid object in terrain
Im trying to make a solid object to stay always in the terrain level, but I am facing some problems. The terrain is not flat, I mean, it can have mountains and craters for example. I just have a ASE (ASCII Scene Export) file of the 3D map. The problem is, I know what is the object's X & Z values are, but I don't know how to determine the Y value for that specific location. I suppose I'd need Y value to always stays with the ground level, so I can realistically make the object walk through the cratter or the mountain.

The only info I have of the map (which I think it should help but I'm not that good in physics or in math, so I can't do much with it) is some vertex coordinates, like:

```
*MESH {
    *TIMEVALUE 0
    *MESH_NUMVERTEX 5424
    *MESH_NUMFACES 8357
    *MESH_VERTEX_LIST {
        *MESH_VERTEX         0  32472.1055  52576.4922  1245.4102
        *MESH_VERTEX         1  32660.6992  52576.4922  1245.4102
        *MESH_VERTEX         2  32472.1055  52632.8086  1245.4102
        *MESH_VERTEX         3  32660.6992  52632.8086  1245.4102
        *MESH_VERTEX         4  32467.2617  52576.4922  1550.3711
        *MESH_VERTEX         5  32607.6055  52576.4922  1550.3711
        *MESH_VERTEX         6  32467.2617  52632.8086  1550.3711
        *MESH_VERTEX         7  32607.6055  52632.8086  1550.3711
        *MESH_VERTEX         8  32578.9648  52576.4922  1396.7617
....

*MESH_FACE_LIST {
        *MESH_FACE         0:    A:         7 B:         6 C:         4 AB:    1 BC:    1 CA:    1   *MESH_SMOOTHING 1  *MESH_MTLID 0
        *MESH_FACE         1:    A:         4 B:         5 C:         7 AB:    1 BC:    1 CA:    1   *MESH_SMOOTHING 1  *MESH_MTLID 0
        *MESH_FACE         2:    A:        15 B:         0 C:         1 AB:    1 BC:    1 CA:    1   *MESH_SMOOTHING 1  *MESH_MTLID 0
        *MESH_FACE         3:    A:         1 B:        12 C:        15 AB:    1 BC:    1 CA:    1   *MESH_SMOOTHING 1  *MESH_MTLID 0
        *MESH_FACE         4:    A:        12 B:         1 C:         3 AB:    1 BC:    1 CA:    1   *MESH_SMOOTHING 1  *MESH_MTLID 0
        *MESH_FACE         5:    A:         3 B:        13 C:        12 AB:    1 BC:    1 CA:    1   *MESH_SMOOTHING 1  *MESH_MTLID 0
        *MESH_FACE         6:    A:        13 B:         3 C:         2 AB:    1 BC:    1 CA:    1   *MESH_SMOOTHING 1  *MESH_MTLID 0
        *MESH_FACE         7:    A:         2 B:        14 C:        13 AB:    1 BC:    1 CA:    1   *MESH_SMOOTHING 1  *MESH_MTLID 0
        *MESH_FACE         8:    A:        14 B:         2 C:         0 AB:    1 BC:    1 CA:    1   *MESH_SMOOTHING 1  *MESH_MTLID 0
        *MESH_FACE         9:    A:         0 B:        15 C:        14 AB:    1 BC:    1 CA:    1   *MESH_SMOOTHING 1  *MESH_MTLID 0
....

```

Should I take all the vertices and faces and draw the whole map to simulate the object walking server-side to pass the correct Y values to the client, or can I use somekind of math equation to get them? I don't think it would be wise to "render" the map in the server aswell...

# Answer
So your terrain is made of triangles (Mesh faces). Each mesh face has 3 vertices (A, B, C). I don't exactly know what AB, BC and CA are, but they're always 1, so they're probably some normals or scale factors or whatever.

Your solution is to find out in which triangle your object currently is and by interpolation of those 3 vertices find out correct height on exact location in triangle.

So first you will ignore Y coordinate (height) and just find (with some heuristic) the correct triangle - triangle containing your object position. Then you should use these steps (let's say you have point X in triangle ABC):

You will get line CX and find intersection of this line and AB - let's call this point I. You will interpolate height of A and B points to get height of I.

Then you will interpolate I and C to get height of X. And you are done ;)

Terrain is usually represented by a uniform grid of quads, not triangles. So it's much easier to find quad containing your object. I don't know if your mesh is also uniform grid - it that case, it would be really easy.
> 1 votes

---
Tags: 3d, terrain
---


# Question
Title: Do I need to rewrite my HLSL shaders when porting from XNA to MonoGame?
I'm looking at porting an XNA project I have to monogame, but I have a fair number of HLSL shaders. It seems that Monogame for PC uses OpenGL as the rendering backend, and I'd rather not have to rewrite all of my shaders during the port. Am I wrong about this, and will I need to rewrite my shaders during the port?

# Answer
Not unless you are using features that the target platform does not support.

> If you want to use Effect files from a previous XNA project or an XNA sample, **you'll need to process them with the MonoGame Effect processor to compile them for that specific platform**. Some of these use OpenGL rather than DirectX as their graphics API, so the Effect file from XNA will need to be converted to OpenGL shader language for it to work.
>
> Rather than have developers rewrite their shaders to GLSL, **MonoGame installs some tooling to automatically convert the HLSL in the Effect file to the appropriate shader language for the target platform**. For the DirectX-based platforms, MonoGame uses the DirectX 11 tool chain to compile your Effect into a shader optimized for that platform. For the OpenGL-based platforms, the Effect is processed by a tool called MojoShader, which does a low-level conversion from HLSL to GLSL that allows the Effect to work on that platform.
>
> Of course, **this conversion process can occasionally introduce errors or unsupported features that the target platform does not support**. For example, with OpenGL Shader Model 3.0, you cannot do a texture lookup in a Vertex Shader, so if your Effect uses that feature it probably won't work.

Source: From XNA to MonoGame
> 5 votes

---
Tags: xna, opengl, xna-4.0, hlsl, monogame
---


title: Shadowmapping theory question

text:
# Question
Title: Shadowmapping theory question
I think im on good way to grasp the complete concept of simple hard-edged shadowmapping! The thing i find the hardest to grasp though is about the individual shadow-render for each light...

Since the example shadowmap-textures i have looked at are normal textures with a width and height as any other texture and does not cover the entire area around the light but only the area within a normal view-frustum i cannot help but wonder if it is about rendering a shadowmap for each light AND object with the camera centered on the object in each render?

I think it feels weird since this would create an exponential growth in the number of shadowmaps used in proportion to lights and objects.

I've had a hard time finding information on the subject and simply find it confusing...

So my question basicly is if this is how it works or if im missing something else?

By the way, if this question is confusing it might be because i have mostly learned this from the perspective of deferred shading but i dont think that should make much of a difference, right?

If you would use code-examples to explain something i would appreciate C# syntax by the way...

# Answer
> 3 votes
No, you would not typically render a shadow map for each light AND object. Typically there will be a fixed number of shadow maps per light (sometimes 1, sometimes more), but the number of shadow maps doesn't usually vary with the number of objects to be shadowed.

There are three kinds of lights commonly used in computer graphics: spot, point, and directional.

* A spotlight only shines within a cone with some fixed width, so the shadow map frustum only needs to be big enough to cover that width.
* Point lights (omnidirectional) are commonly just not shadowed at all. But when they are shadowed, it can be done using a cubemap - 6 individual shadow maps forming a cube, each with a 90-degree-wide frustum; collectively they cover the entire sphere of directions around the light.
* A directional light theoretically covers an infinite area. In practice, if the scene is small you can simply fit a shadow map around the boundaries of the scene. If the scene is large, such as outdoor areas in an open-world game, cascaded shadow maps or CSMs are a very good and popular solution. CSMs take the camera's view frustum into account; they focus several shadow maps on different parts of the camera's frustum, with higher resolution closer to the camera and lower resolution farther away.

There are occasional cases where an extra shadow map might be drawn for a specific object. For example, in a cutscene where you are doing close-ups on a character, you might like to put in an extra shadow map focused on the character's head, so you get ultra-high-quality shadows on the character. Or in a racing game, you might put in a shadow map focused on the player's car. But that's the exception rather than the rule, and would only be turned on for specific cases where the extra quality is desired.

---
Tags: c#, shadow-mapping
---


# Question
Title: How to load up many images without using too much memory
When writing games, I am aware that images take up a lot of space. If one has a large graphical game, they don't want problems with memory, or to give players the message "Go buy a better computer to run this game". However, loading up images everytime one needs an image and discarding it is *very* slow. So if a programmer has a large graphical game, how can they draw many images without sacrificing performance/memory?

# Answer
> 3 votes
1.Use scaling; make images smaller, but still having enough to get the character around. Scaling an 80x80 in to a 60x60 saves a lot of space for five hundred images, seeing as each one will be 1/4th smaller, taking up virtually 1/4th of the space.

2.Use better compressed image formats; a BMP will save more time than JPEG, and is smaller.

3.Remove images that are no longer in a visible portion of the screen to save memory. In the 8 and 16-bit world this was mandatory, as having such tight memory and slow CPUs, on top of bank switching, made the process daunting to imagine for a C/Windows programmer these days. To recover the removed image, save where it was to an 8-bit byte container, and re-load it based on these coordinates. You can't lose with this method.

4.**Don't** load up too many images at once; I know this one is tough to comprehend, but tons of images at once isn't absolutely vital. In fact, it's not vital at all for a beginner program (which you seem to be, no offensive if you aren't) and cutting out a few extra images here and there make a stretch, but the saved memory and speed will thank you. Working with 3-D models, lots of large data files, and rendering is memory tougher. When you get there then it's time to work smarter, but as for 2-D games like a platformer, RPG, etc., my last three prior paragraphs should do the justice for you.

---
Tags: performance, memory
---


# Question
Title: Problems when randomizing x and y position of a picturebox
So, I'm making a simple game. It's like snake but the picturebox doesn't grow. In the game, you have to get fruits and other objects. Look at berry's code:

```
public class Berry : PictureBox
{
    public bool ON_SCREEN;
    public Berry()
    {
        this.BackColor = Color.White;
        this.Size = new Size(20, 20);
    }
}

```

And then I randomize it on a form. Like this:

```
public void Generator_Berry()
    {
        Berry b = new Berry();
        Random randomY = new Random();
        int rY = randomY.Next(10, 270);
        Random randomX = new Random();
        int rX = randomX.Next(10, 270);
        this.Controls.Add(b);
        b.BringToFront();
        b.Location = new Point(rX, rY);
        b.ON_SCREEN = true;
    }

```

So the problem is that Berry's X position is the same as Y or vice-versa. I've never got a problem like this.(It look very simple, but I can't get the solution) What is wrong?! Am I that very stupid?!

# Answer
> 7 votes
A pseudo-random number generator like C#'s System.Random generates a deterministic sequence of numbers from a starting state, a seed.

When you construct a System.Random instance without any arguments, it initializes the seed based on the current time. As your two instances are created very close in time, it's likely that they will get the same seed, and thus the same sequence of numbers.

It's common to create one instance, use it and hold on to it for any future generation of additional pseudo-random numbers in the sequence. Reseeding has a tendency to increase correlation, not reduce it.

Please avoid following knee-jerk responses like "never use more than one instance", those show a lack of understanding as to why you're experiencing the problems you do.

MSDN says:

> The default seed value is derived from the system clock and has finite resolution. As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers.

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


title: GLSL Multiple Uniform Structs

text:
# Question
Title: GLSL Multiple Uniform Structs
I'm developing a lighting system for my voxel game, and I have to send multiple (alot, say up to 200) lights to my shader program. Those lights contain the following data:

* Position (vec3)
* Color (vec3)
* Radius (float)
* Strength (float)

What is the most efficient way to send alof of those light structs to my shaders? I would like it to work with lower versions of OpenGL, like 2.1.

# Answer
The most efficient way to do that would be to *not do that.*

If you have a scene where you want 200 lights to affect an object, you can't use forward rendering anymore. Also, as a practical matter, I'm fairly sure that quite a lot of GL 2.x hardware couldn't handle a uniform array of 400 vec4s. And even if you could, your shader would probably choke attempting to do lighting over 200 lights in one pass.

The performance simply isn't there for such a computation. Every *pixel* of overdraw will hurt by 200x. That's going to kill you in the end. So you need to use some form of deferred rendering.

And in deferred rendering, you wouldn't really render by sending 200 lights to a single shader.
> 6 votes

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


# Question
Title: SDL 1.3 on Windows 7. Better hardware,lower FPS
I've just moved from one PC to another.I've been developing a game in SDL with SDL\_image and SDL\_ttf for about one year. On my old pc, I had about 90 FPS on my game, but now I have about 30, witch I find very strange. My Question is: Why do my FPS dropped from 90 when I used an inferior PC (on windows xp) to 30 when I have a way better PC (on windows 7).

# Answer
> 1 votes
Have you tried any other OpenGL based game? This sounds a lot like your drivers don't provide proper hardware acceleration (happens for some of the default drivers bundled with Windows; at least in the past).

Also, might be useful to show your main application loop (minimized, to see how you update, if you wait somewhere, etc.). Maybe something is happening too fast (e.g. the time between frames would always round to 0) which essentially screws up something.

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


title: How does normal mapping really work?

text:
# Question
Title: How does normal mapping really work?
I'm trying to grasp the concept of normal mapping, but I'm confused by a few things. In short, I'm not sure whether a normal map is *viewpoint dependent* or not (i.e. whether you'll get a different normal map of the same object when you rotate around it). Secondly, I don't get why the blueish color is the *predominant color* in normal maps.

How I think about normals, and their relation to RGB colors, is as follows. The unit sphere represents any unit normal possible — in other words, the X, Y and Z components of a unit normal vector range from -1 to 1. The components of an RGB color all range from 0 to 255. Therefore, it makes sense to map -1 (normal component) to 0 (color component), 0 to 127 or 128, and 1 to 255. Any value in between is just linearly interpolated.

Applying this mapping to the normals of an arbitrary 3D object results in a very colorful picture, not at all predominantly blue. For example, when taking a cube, all six faces would have a different, but uniform, color. For instance, the face with the normal (1,0,0) would be (255,128,128), the face with the normal (0,0,-1) would be (128,128,0) and so on.

However, for some reason the normal maps of a cube I found are completely blueish, i.e. (128,128,255). But clearly, the normals are not all in the positive z-direction, i.e. (0,0,1). How does this work?

**\[Edit\]**

Ok, so the approach described above seems to be referred to as the *object space normal map* or the *world space normal map*. The other one is called the *tangent space normal map*. I understand how such a tangent space normal map can be used to modify the normals of a geometry, but I'm still not completely sure how it is actually calculated (see my comment at Nicol Bolas' answer).

**\[Edit 2\]**

I should probably mention that I'm working with piecewise parametric surfaces. These surfaces consist of a set of *surface patches*, where each patch is associated with its own parametric space (u,v) = \[0,1\] x \[0,1\]. At any point on the surface, the normal can be calculated exactly. Apparently, the vectors T (*tangent*) and B (*bi-tangent*) — required to span the tangent space — are not simply the partial derivatives of the surface patch in the direction of u and v...

# Answer
> 14 votes
A texture mapping is the mapping between points on the 3D surface and their corresponding points on a texture image. If you have a 1:1 texture mapping, then every point on the 3D surface maps to a specific and unique point in the texture image (though the reverse would not need to be true. Some locations in the texture would not necessarily map to locations on the surface).

With such a mapping, you could go through the 3D surface and store each distinct normal in the corresponding location in the texture.

OK fine, let's do that. We'll go through a 3D surface and generate object-space normals the mapped locations, and then stick them in the texture. So when we want to render, we simply fetch the object-space normal from the texture and we're done. Right?

Well yes, that would work. But it also means that the texture's normals can only ever be used with that particular object. And it also means that the texture's normals can only be used with that object and with that specific texture *mapping*. So if you wanted to rotate the texture mapping in some way, or alter it with some UV transform, you're out of luck.

So generally, what people use are normal maps where the normals are in "tangent-space". Tangent-space is the space relative to the mapped point on the 3D surface, where the unmodified normal is in the +Z direction, and the X and Y axes point along the U and V axes relative to the surface.

Tangent-space essentially regularizes the normals. In tangent-space, the normal (0, 0, 1) always means "unmodified"; it's the normal you get from interpolating the vertex normal. This leads to a number of useful things you can do, one of the most important of which is to store them in less data.

Since the Z will always be positive, you can therefore compute it in your shader from the X and Y components. Since you only need 2 values, so you could use (in OpenGL image format nomenclature) `GL_RG8`, a 2-byte-per-pixel format rather than `GL_RGBA8`, a 4-byte-per-pixel (`GL_RGB8` will still be 4-bytes-per-pixel, since GPUs will pad each pixel out to 4 bytes). Even better, you can compress those two values, leading to a 1-byte-per-pixel format. So you've reduced your texture's size to 75% of the object-space normal map.

Before you can talk about any kind of normal map, you need to know first *what it stores.* Is it an object-space normal map, a tangent-space normal map, or something else?

# Answer
> 3 votes
Normal maps are mapped using the so-called tangent space, which is essentially a local space based on the model's texture-space. This should answer both of your questions.

It's not viewpoint dependant because this space has nothing to do with the camera. In the normal map, Z is the up direction. If you look at the normals of a model, most of the normal vectors will be pointing directly out from the mesh. The mesh's surface is the texture space I was talking about, so in that local coordinate system, up is the "outward" direction.

# Answer
> 1 votes
Scroll down in this page

Look at the right hand B/W drawing under datasets - this is (or at least used to be) known as a hedgehog drawing, a rendering of a surface with each of it's normals drawn

So, to understand a traditional normal map, think of an upset hedgehog with all their spines sticking out - each of those spines is normal to the surface of the hedgehog underneath it -

With respect to your sphere question, if you were living purely in parametric space, as with ray tracers, then the infinite set of normals to the sphere would simply create a larger sphere - in tessellated space, i.e. the world the computer forces on us if we want real time, then you have a spiky approximation of a sphere.

Now, this example focused on an OBJECT normal map - it's defining normals with respect to the object, and this is invariant under any rotation, translation, or scaling - of either the object or the camera or anything else - as mentioned earlier, this is only one kind of normal map but it's the most common

# Answer
> 0 votes
I think you might have some misconceptions on what normal maps are. Basically, it's a way of simulating the look of something bumpy when in fact the geometry is completely flat.

The colours of a normal map are interpreted by a tech shader and processed based on light intensity and direction, as well as your camera view. This means that you could have a brick floor for example, which is completely flat, with a flat texture, but because it has a normal map with the same brick shape, when you look around it, light will appear to be bouncing off the side of the bricks making it look more 3D than it is.

This is of course just an illusion, but it's much cheaper than having complex geometry. And no, the colours of the normal map don't change. They really just represent values to compare against in the shader. I'm sure someone here will be able to fill you in in much more detail.

---
Tags: vector, normal-mapping
---


# Question
Title: SpriteBatch does not draw on graphicDevice
I'm using a control which is using XNA inside. But when I try to draw something, it doesn't appear. I already did a lot of tests but can't figure out what's wrong. Here is the test I set up:

```
RenderTarget2D rTarget = new RenderTarget2D(GraphicsDevice, 1000, 1000);

GraphicsDevice.SetRenderTarget(rTarget);
GraphicsDevice.Clear(Color.White);
_spriteBatch.Draw(ts.Texture, layer.Location, source, Color.White, layer.Angle * (float)Math.PI /180, origin, SpriteEffects.None, 1f);
int spriteBatchGraphics = _spriteBatch.GraphicsDevice.GetHashCode();
int normalGraphics = GraphicsDevice.GetHashCode();
GraphicsDevice.SetRenderTarget(null);

using (FileStream stream = new FileStream("pic.png", FileMode.Create))
     rTarget.SaveAsPng(stream, 1000, 1000);

using (FileStream stream = new FileStream("pic2.png", FileMode.Create))
     ts.Texture.SaveAsPng(stream, ts.Texture.Width, ts.Texture.Height);

```

`SpriteBatch.Begin`, `End` and `GraphicDevice.Present` is called too.

Because I didn't see anything, I tried to draw the stuff onto a `renderTarget` and save it to the HDD. I also saved the texture itself to be sure it's not just white.

However, spriteBatch should draw a 48x48 block here and I checked the parameters of spriteBatch, they are okay. But on the rendertarget, nothing appears. I reacts on GraphicDevice.Clear, the color I pick there really gets drawn. The hashCodes of both graphicDevices are the same, so they really seem to draw to the same device.

What could cause this?

**EDIT:------------------------------------------------------------------------------**

I searched for some more and I found the following: I'm getting a AccessViolationException when closing the program. First I thought it's unrelated but it seems it's caused by what happened before. I found in the internet that a very bad graphic card can cause this. And the graphic card I tried this on was very bad indeed. So I tried it on an other machine now - I'm getting different results, but it's still not working and I'm still getting the exception.

Here is what it draws now:

In place of the black spot, the tile should be drawn. But it's not happening. The AccessViolationException only happens when the draw glitch happens - in this case as soon it just draws a black block instead the real texture. The lines are planed and part of it (the horizontal are still missing for some reason, but trying to fix that later).

So what is happening? Gets the graphic device too much stressed? I'm also running a game class which runs with the default loop (which manages the winforms and game).

I absolutely need the XNA technology here, because it should "preview" something from the game and using System.Drawing could change the outcome. The program also could get used by clients so a normal powered graphic card should be able to deal with it.

# Answer
I can only speak to the example code you've posted:

`SpriteBatch` in all modes *except* `SpriteSortMode.Immediate` defers all rendering until `End` is called (it *batches*). If you're not calling `End` *before* you save contents of the render target, your sprite hasn't actually been drawn to it yet.

In `Immediate` mode, render states are set on the GPU in `Begin` and actual draw calls are sent to the GPU in `Draw`. Although I wouldn't be happy having `SetRenderTarget` inside a `Begin`/`End` block either way. I'm not even sure how that would behave (as it messes with things like the viewport).

Also note that, by default, `SetRenderTarget` will clear the render target that is being set.

Also, rather than `GetHashCode`, you should be using `ReferenceEquals(_spriteBatch.GraphicsDevice, GraphicsDevice)` for what you seem to be trying to achieve.
> 3 votes

# Answer
I found the solution, that one was a really hard one. The problem was the texture was loaded on a different graphicsDevice.

I said I have a gameLoop running and because it always exists, I was taking the graphicsDevice from there to create the texture. But the Control creates a graphicDevice itself (I guess I should let them use the same one, have to fix that) and caused the glitch with that.
> 0 votes

---
Tags: xna, c#, graphics-programming
---


title: Mesh objects and a draw function

text:
# Question
Title: Mesh objects and a draw function
I'm currently working with a mesh class so I can easily create mesh objects. Now I want a draw function in my mesh class so when ever i want draw it to the screen I can just call it without any fuss. But i have run in to a dilema and i need some insperation/ other persons perspectiv. To draw a mesh object there is alot of thing you need. You need blend states, rasterizer state, depth stencils ect (lets call them "tools" for futher reference).

Now there is a couple of diffrent ways you can go about it and i wanted your input to choose one.

1. You can have the object create their own tools. It requires more space, but you dont have to pass pointer around as much.
2. You create the tools in the GameEngine object and pass pointers to the tools in the draw function parameters. It looks messy and could cost alot of time, but it take up less space.
3. You create the tools in the GameEngine object and then store pointers to them in the mesh object. Now this save both time and space, however i got the feeling that this could get really messy and caus you alot of trouble easily.

I greatly appriceate any feedback or diffrent solutions. Thank in advance.

# Answer
You are using Direct3D 11. So the *only* thing your mesh should be doing is setting up the Input Assembly stage and issuing some form of Draw call. So your mesh should only call `IASetIndexBuffer`, `IASetInputLayout`, `IASetPrimitiveTopology`, and `IASetVertexBuffers`, followed by one or more `Draw*` calls.

Everything else should be handled by whatever code *called* the mesh's draw function. A mesh is just a dumb collection of the vertex state needed to draw. Any higher-level logic (what shaders to use, blend modes, etc) should be handled *outside* of the mesh.
> 1 votes

---
Tags: c++, directx11, objects, mesh
---


# Question
Title: How does a single non-artistic programmer make a game?
I'd like to try my hand at making games. In making some simple ones, I realised *I can't do art*!

I've tried to find others to help: Most existing teams wouldn't want me because of my limited experience (I'm in high school) and I've been unable to find an available local artist with an appropriate skillset.

How do you guys do it? Do I have to wait until college to see if I like working in games? Is there a way to get free art so I can start messing around on my own? Or am I just having bad luck or looking in the wrong places for others interested?

# Answer
> 170 votes
I work full-time doing security software, and in my "free" time I work on my game. I'm not spending any money on making my game, I'm only using free software and making my own art. Don't get me wrong, I'm NOT an artist, just a programmer. It's not stopping me though. I just keep chugging away on my game, and I'll worry about making it look really pretty later. Or just make it good enough that the art doesn't matter. For now it's ordained with what I call "Programmer Art". Depending on the type of game you want to make, the art can be really important. But for a lot of games, it's all about the gameplay. Look at Dwarf Fortress. Not really a lot of "art" involved, but the gameplay is great!

If anything, you can get your game built with Microsoft Paint textures and sprites, then you'd have something to show off to get an artist interested.

You should definitely try your hand at making a game. I love making my game. It's the most fun I've ever had programming. Every aspect is a new interesting thing to learn.

Not everyone can do it all, so we just have to make do with the skills we have. Our skill is programming, so that's what we do. I think it's been proven more often than not, that it's the gameplay (programming) that makes or breaks games, not the art.

# Answer
> 31 votes
An option is to take photos of things and use those. It's fairly simple to create a texture or cubemap from a photo for example.

# Answer
> 27 votes
I want to add a slightly different point of view from what has been previously answered.

First, I disagree that gameplay is the *only* important thing in a game. Visuals sell, and you will most likely have your game played by other people if you show a pretty screenshot that catches their eye. Because of this, I do not recommend you disregard art, or use stock or placeholder art for your game. This also goes for sound and story (if your game has one).

Second, I wouldn't recommend you work on a project alone. Having more people in your project is a great way to stay motivated, and also by sharing ideas with other members you are more likely to get a better game.

So what you have to do is gather people who are interested in making a game, and making a project with them. It sounds hard, but it is actually very easy, if you approach the problem from the right angle. I've done several indie games with other people, and I've had really good experiences doing so.

Let me tell you that you are in a very privileged position, being a programmer. There are lots of people in the world who love games and would want to make one for themselves, but only very few know how to code. Even though it is technically possible to one-man-army a game project being a programmer, it is simply impossible being an artist. You would be surprised to know that for every "how do I make a game if I'm a programmer and not an artist?" question, there are a dozen "how do I make a game if I'm an artist and not a programmer?" questions.

So, people are there. There's a lot of artists and musicians and game designers who want to make games, and would do them for free. Unfortunately, pretty much everyone who is able to competently participate in the development of a game will most likely not be interested in joining *your* game, so that's the problem you want to attack if you want to successfully make indie games.

In few words, it's (good) programmers that are scarce, not artists.

In my opinion, there are two ways to solve this problem. I've done both, and I can assure you both work.

1. If you're interested in making games, but don't have the specific requirement that they have to be *your* games, you can offer people to make their games! If you can prove you're a competent programmer, there are lots of artist forums you can lurk, and if there's an interesting idea, you can contact the artist by telling them you're interested in making their game. If you say it right, it is almost guaranteed they will say "yes".
2. If you can prove you can make *and complete* games (for every finished indie game, there are thousands of projects that will never end), and if you have a good idea, you can hit the forums and propose that idea. Maybe the first time only one person will join you, but if you can deliver a finished product, and make sure you publicize your progress and success in said forum, you will gain credibility and more people will be interested in joining you for your next project.

For my latest game, I was able to convince two graphic artists, one musician, one writer and nine voice actresses (two of them who are actually professional) to help me for free. Of course it is crucial to actually deliver. I did, and because of that I'm confident that I will be able to get their help, and other people's help for the next project.

Keep in mind both of these options are viable **only** if you're serious about making games. If you stop halfway, or if they sense you're not being serious, you will lose reputation, and people won't join you in subsequent projects, so proceed only if you're actually capable, and willing to walk the walk.

# Answer
> 13 votes
Here's a thread that contains a ton of links that you'll find useful; everything from legal, to art to music, etc. http://www.mangatutorials.com/forum/showthread.php?742-The-Ultimate-Indie-Game-Developer-Resource-List

It's mentioned in other answers, but while you're looking for an artist etc, you should be developing your game at the same time. Use programmer art, stand-ins, free sprites anything. Most of the time, before even thinking about final assets, I just want something up and running quickly to see if it's fun. Prototype the crap out of it and find the game. Then, when the gameplay's locked down, you can start putting in the proper art. Doing it the other way around leads to lost money, and work that needs to be redone multiple times, which aside from harming your project, sucks your motivation to finish it (and if you're making a game to get a job, showing that you can finish a project is a good thing).

If you still can't find an artist, then make the graphics yourself. Dwarf Fortress was mentioned, but there's also games like Geometry Wars, where the graphics are created through math. Anything is possible to get around if you put your mind to it.

# Answer
> 12 votes
We're in a similar situation when it comes to art, me and a friend build games in our spare time. We're both developers who love games, we must've started a dozen game projects.

The projects that have stuck, we've approached a number of people on artist community sites whose art styles have matched our ideas.

Having a project up and running, ready to show you're serious and to demonstrate your passion for the project has been enough for us to generate some interest.

Give it a go :)

# Answer
> 5 votes
I don't think the fact you are not an artist is that much of a downer, programmer are essential to make a game, and if you don't have content, it's not really a problem: \- Do the game without content, and try to find artists after the game has more features: you will have more leverage, and you will have much less pressure to add those features. \- Use an user-friendly 3D modeling tool, like sketchup.

# Answer
> 4 votes
You could always go for the "less is more" approach and use as little and as simple artwork as possible.

Retro-style vector graphics are pretty popular these days, so there's plenty of inspiration to get there. Just draw some lines and make 'em glow a bit.

# Answer
> 3 votes
First, you're doing really good by doing all this stuff *before* you get to college.

Now, have you *tried exploring art yourself*?

> I'm a programmer, not an artist

Is a common cop-out people use to avoid judgement on their artwork.

But if you just put the time into it, you can learn to draw, too. (and a couple of bucks for a Wacom tablet!)

---

# But how does a single programmer make a game?

You just keep working on it until it's done.

It is true that *the barrier to entry* to create a game *that captures attention and has a market* has been *raised quite a great deal* just by the quality and amount of money and time invested into *games that are actually selling*.

So, because companies like Blizzard or *Edge Of Reality* are investing so much time+money just to get the next card game/First person shooter out, the game marketplace today is a very competitive place. Compare this with the time when Mario Bros. *was* bleeding edge technology, and John Romero was able to sell games like Crazy Climber that looked like this:

# Answer
> 3 votes
It depends on what kind of game developer career you are seeking. Most titles created in the modern game industry are made by huge teams where a programmer doesn't ever have to draw a single pixel.

Though if you're more into developing your own indie game, you could assume the "one man army" role, in which you'll have to deal with graphics and sound creation.

Programming was the easy part, while generating synthesized sound effects and drawing pixel art consumed most of my time. Thanks God for public domain music which in this case perfectly suited the whole groove of the thing.

If you grew up in the 80's when you could actually see pixels on the screen (and then never being able to ever ignore them later) it could just grow naturally on you, but if that's not the case, I'd recommend reading a bit on pixel art creation. Of course you can always digitalize some paper drawing and just do the finishing later.

Anyway, creating games has always been a multidisciplinary craft. You'll need a good depth of programming skills (but not 'too much', or you'll end being unable to create the simplest game, because you'll be over-worried about abstractions, just like a good grammatician can't write a single book), good understanding of math, geometry, physics and also a good deal of artistic skills, like drawing, sound creation, level design, story telling, etc.

Ultimately, you must fall in love with your creation. You need a good deal of motivation and a genuine desire to make your game see the light. You must become the #1 fan of your own game, because if you don't like playing it at all, who else will?

With all that in mind, I really hope you overcome your obstacles and have a great time creating your own game. It's an incredibly fun and rewarding experience once it's up and running. :)

# Answer
> 2 votes
You can always replace your sounds and art later on. In my opinion the important thing is the game itself.

It can be an excellent 3D shooting game even if the walls are all brown and the characters are cubic block people.

It can be a wonderful sandbox world and look like Minecraft.

The sound effects are easy to make. Just record yourself making the sounds with your mouth. I've played some really fun tower defense games where it's quite obvious the shooting sound is a guy going, "Pew! Pew!" into a microphone. :-)

The really important thing is to finish the game. It doesn't have to be perfect. It doesn't have to have every feature you planned out. But once you finish a limited version of the game, no matter how many features it's missing and no matter how crap the art and sound is, then you have a basis for making changes and improvements, and you have something to show clients or potential employers as a code demonstration.

# Answer
> 1 votes
I wouldn't worry about art so much at your current state. The first game I ever managed to get to a satisfactory level of completion, I did completely without an artist and it was before I started college.

In my view, you have four good options depending on your level of game programming:

1. You can find a good game programming book that has a project which includes all of the art and you can get a feel of if you like the work involved in game programming
2. You can find a game engine that lets you write mods on using their artwork
3. Use Unity3d or Torque Game Engine, look those up, both have asset stores with some free art
4. You can take my route which I think is the best :) You can start programming a game and write the main functionality of the engine. Use extremely ugly art for it, like blocks or stick figure sprites. Then once you have a working engine, post it up on GameDev.net's help wanted forums. I got my first two artists this way. They liked the gameplay of my flight sim even though the plane was made up of 4 blocks and the terrain was painted in a terrain editor.

# Answer
> 1 votes
I'm a solo, hobbyist game developer, and although it tools many weeks, I did manage to publicly release a handful of 2D mobile games. Like you, I am a programmer and not an artist.

First off, I agree with the comments by others that Unity3D is a great way to go. The only thing I have against this is you're stuck with the splash-screen unless you go for the Pro version, and the Android/iPhone plug-ins aren't (normally) free (I'm unclear from your question whether you want to target mobile or desktop?).

If it's important to you to actually *complete* a project, as a solo non-artist, and you decide against Unity3D (or some other similar game engine), I suspect you'll find it more manageable if you go - at least initially - for 2D. The volume of assets and the complexity/size/effort of the programming will be much less.

Finally a quick tip - I found it much easier to model objects in 3D and then render them - with appropriate shading - into 2D sprites, rather than try and hand-draw 2D artwork. Blender is a fantastic, free 3D modelling tool. I can't recommend it enough.

Even when I kept things really simple (and 2D), I found it took far longer to complete my first game than I imagined. This was down to the sheer number of aspects that had to be tackled - game design, playability (e.g. input controls), programming, artwork, marketing material, animation, sales pitches, level design, level editors, you name it.

Good luck - you can do it. I think game development is one of the most multi-disciplined projects. I love it!

# Answer
> 0 votes
I think it's a great to see actual pretty things happen on the screen in the development process. Small projects often follow graphical artistic / lore concepts from the beginning as a guideline and a it's very strong motivator.

I might be wrong about this but from the perception i get, most indie projects that actually ever see the light of day are either made by single devs who do the whole thing both art and programming (i hate them) or small teams who have someone on the art, but rarely a programmer who hired someone in the end of development to replace the placeholders - even though this method should work in theory.

Try to find a friend, co worker, a girlfriend, wife, whatever, someone who can DRAW. They don't have to know how to work with any software or use a mouse. Tell them you want to make a game and need someone to do the drawing while you do the programming. If not someone you know from your life find some artist online or in forums. Work on an idea together. I actually had the same dilemma as you until i saw some drawings a friend made on his Facebook page, anyway, I posted this question that may seem relevant.

An alternative could be doing a game with some abstract graphics concept thingy that anyone could draw. Like stickman games, but can easily be more than that. Or some abstract 3D in a level that could be created after 2 days of learning from Lynda. It worked for MineCraft :)

# Answer
> 0 votes
I've had some experience writing my own games, both open source and commercial indie-style. Like you, I encountered problems with assets (images, animations, audio, ...). You have a few options:

1. Do it yourself
2. Find someone to volunteer their time for you
3. Find something that you can legally use for free/for a fee
4. Pay someone \[probably good money\] to give you a decent product

Without much money, all these options can be frustrating. You can find artists to volunteer their time, but in my experience they don't like to sit around and wait for you to develop and fix a new game/rendering engine, so here is my advice (I'm assuming you aren't willing to spend any money):

Create some very simple graphics to test with. In one game I created, I made some very simple stick figure graphics that were merely sufficient to indicate what action / state my character was currently in. Later, when the game/rendering engine is compelling, it will hopefully be inspiring and you will have less trouble finding artists willing to help out.

# Answer
> 0 votes
It wasn't specified if you want to do a game professionally or as a hobby. For a professional game, you need professional graphics. Minecraft is a great counter example, but an exception to the rule. As a programmer making games for a living, I get the graphics from a paid artist and from online websites that sells 3d models, images and sound.

For a hobby, there are free online resources as well as doing your own art. However, if you are anything like me, my art sucks, takes too long to do and I don't like the end result of the game. That means I lose my mojo doing stuff I don't like vs stuff I do like and I am not motivated by my results... which means: I get it from good sources.

Get at least decent looking placeholder for your graphics. Then figure out how to get a better version, if you reach the point when you are ready to release, etc..

**Don't force yourself to do stuff that will demotivate you - whatever it is. Motivation is the only thing that will make you finish your game and finishing the game will be the most important thing for you to accomplish. Do not squander motivation on graphics if it is not your thing, but realize that a nice looking UI will motivate you.**

# Answer
> 0 votes
A lot depends on the type of game and corresponding expectations of the players. I minimize the requirement for graphics in my games by basing the artwork on actual photos of game bits.

# Answer
> 0 votes
All that is required is motivation and time.

Unless you're limited on time so severely that your life will end before completing the project, you will be able to do anything alone, over time.

Motivation is something that each individual has to figure out themselves. Personalities differ, and so does what works. For me, what works best is to force myself to work a set of hours each day, and if I miss to make up for it on the weekend.

Setting tiny, tiny goals works. Then when you have the game built enough, you get better motivation to finish it because you are so close. The hardest part is beginning.

---
Tags: art
---


# Question
Title: Texturing spherical terrain, seemingly arbitrary distortion
I'm using this algorithm to find texture coordinates on a sphere: Wikipedia UV Coordinates

I get the famous seam due to the wrong interpolation, but I also get odd distortions on certain points on the sphere. A picture follows where you can see like five starshaped distortions.

What could cause this?

# Answer
> 0 votes
Took me some time, but I finally found the problem. In the wiki entry is written that the unit vector is needed. I basically forgot to normalize the vector before the calculation!

---
Tags: textures, coordinates, uv-mapping, sphere
---