# Question
Title: How can I draw my shapes based on their Z order value?
I'm using C# and I'm drawing shapes to a PictureBox.

I'm not drawing anything in 3D. Instead, I draw 2D shapes and have a "depth" value. (which changes the size of the shape and its opacity)

**My problem is**:

The shapes in the "back" (that are "deep", or basically have high Z value) overlap the shapes in the "front" (the ones with a low Z value).

How can I draw my shapes so that objects with a high Z value overlap the objects with a lower Z value, if they meet.

I want the green ball to render on top of the red ball.

**What I tried for this problem**:

Ordering the shapes by their Z value, (descending and ascending) and then drawing them.

Attached here is some code:

My Game.cs: (basically just has a List of Particles)

```
class Game
{
    public List<Particle> Particles;

    public Game()
    {
        Particles = new List<Particle>();
    }
}

```

My Particle.cs:

```
class Particle
{
    //NOTES--------------------------------------------------
    //Z should always be between 0 and 10.
    //When setting the location locally, make sure to use Location
    //because it changes the other properties with it.
    //-------------------------------------------------------
    #region Properties
    public Pen spawnPen;
    //currentPen for when the color is changing
    //and we need to keep the initial color in spawnPen
    public Pen currentPen;

    public Pen borderPen;

    public Brush spawnBrush;
    //currentBrush for when the color is changing
    //and we need to keep the initial color in spawnBrush.
    public Brush currentBrush;

    public bool ColorChanging = false;
    //The center point of the GraphicsPath
    //that we generated in Window.cs, the main file
    //possibly used for calculating the distance
    //to know by how much to change the color??????
    public PointF ColorChangingRegionCenter;

    //2D movement so we don't need a Z axis for speed.
    private PointF speed;
    public PointF Speed
    { get { return speed; } set { speed = value; } }

    private Vector3D location;
    public Vector3D Location
    {
        get { return location; }
        set
        {
            location = value;
            //50 is the width and height of the shapes at depth 0
            //(the maximum width and height, basically).
            rect = new RectangleF(location.X, location.Y, 50.0f - (location.Z * 4), 50.0f - (location.Z * 4));
            if (spawnPen == null)
                spawnPen = new Pen(Color.FromArgb(180 - (int)location.Z * 15, 76, 247, 219));
            if (spawnBrush == null)
                spawnBrush = new SolidBrush(Color.FromArgb(180 - (int)location.Z * 15, 76, 247, 219));
            if (borderPen == null)
                borderPen = new Pen(Color.FromArgb(235, 76, 247, 219), 1);
        }
    }

    private RectangleF rect;
    public RectangleF Rectangle
    { get { return rect; } set { rect = value; } }
    #endregion
    #region Constructors
    //Must explicity set the location
    //otherwise it's random.
    public Particle()
    {
        Random rng = new Random();
        float X, Z;

        //Lock the Random object
        //so it doesn't generate the same value!
        lock (rng)
        {
            X = (float)rng.NextDouble();
        }
        lock (rng)
        {
            Z = (float)rng.NextDouble();
        }
        Location = new Vector3D(X * 1100, 0, Z * 10);
        //We must generate the speed for 2 reason:
        //1.It is not set by default.
        //2.It depends on the Z value of the particle.
        speed = new PointF(2 - (location.Z * 2 / 10), 2 - (location.Z * 2 / 10));
    }
    public Particle(Pen spawnPen) : this()
    { this.spawnPen = spawnPen; }
    public Particle(Brush spawnBrush) : this()
    { this.spawnBrush = spawnBrush; }

    public Particle(float X, float Y, float Z)
    { Location = new Vector3D(X, Y, Z); }
    public Particle(float X, float Y, float Z, Pen spawnPen)
            : this(X, Y, Z)
    { this.spawnPen = spawnPen; }
    public Particle(float X, float Y, float Z, Brush spawnBrush)
            : this(X, Y, Z)
    { this.spawnBrush = spawnBrush; }
    #endregion
    #region Methods
    public void PerformFrame()
    {
        /*//If it is in the ColorChangingRegion
        if (ColorChanging)
        {
            double dLocationColorChangingCenter = Math.Sqrt(Math.Pow((location.X - ColorChangingRegionCenter.X), 2) + Math.Pow(location.Y - ColorChangingRegionCenter.Y, 2));
            if (currentBrush == null)
                currentBrush = spawnBrush;
            Pen brushColor = new Pen(currentBrush);
            //currentBrush = new SolidBrush(brushColor.Color.A + (255 - brushColor.Color.A) * );
            //Remember to dispose of unused objects.
        }*/
        //If traveling UP
        if (speed.Y < 0)
        {
            //If goes offscreen TOP
            if (location.Y < 0 - rect.Height)
            {
                //Send it to offscreen BOTTOM.
                //Location.Y = 500 + rect.Height;
                Location = new Vector3D(location.X, 500 + rect.Height, location.Z);
            }
        }
        //If traveling DOWN
        else if (speed.Y > 0)
        {
            //If goes offscreen BOTTOM
            if (location.Y > 500 + rect.Height)
            {
                //Send it to offscreen TOP.
                //Location.Y = -rect.Height;
                Location = new Vector3D(location.X, -rect.Height, location.Z);
            }
        }
        //If traveling LEFT
        if (speed.X < 0)
        {
            //If goes offscreen LEFT
            if (location.X < 0 - rect.Width)
            {
                //Send it to offscreen RIGHT.
                //Location.X = 1100 + rect.Width;
                Location = new Vector3D(1100 + rect.Width, location.Y, location.Z);
            }
        }
        //If traveling RIGHT
        else if (speed.X > 0)
        {
            //If goes offscreen RIGHT
            if (location.X > 1100 + rect.Width)
            {
                //Send it to offscreen LEFT.
                //Location.X = -rect.Width;
                Location = new Vector3D(-rect.Width, location.Y, location.Z);
            }
        }
        //Change the particle's location.
        //Location.X += speed.X;
        //Location.Y += speed.Y;
        Location = new Vector3D(location.X + speed.X, location.Y + speed.Y, location.Z);
    }
    public void RenderEmptyRectangle(Graphics g)
    {
        g.DrawRectangle(spawnPen, rect.X - rect.Width, rect.Y - rect.Height, rect.Width, rect.Height);
    }
    public void RenderFilledRectangle(Graphics g)
    {
        g.FillRectangle(spawnBrush, rect.X - rect.Width, rect.Y - rect.Height, rect.Width, rect.Height);
    }
    public void RenderEmptyCircle(Graphics g)
    {
        g.DrawEllipse(spawnPen, rect.X - rect.Width, rect.Y - rect.Height, rect.Width, rect.Height);
    }
    public void RenderFilledCircle(Graphics g)
    {
        g.FillEllipse(spawnBrush, rect.X - rect.Width, rect.Y - rect.Height, rect.Width, rect.Height);
    }
    public void RenderCircleBorder(Graphics g)
    {
        g.DrawEllipse(borderPen, rect.X - rect.Width - 1, rect.Y - rect.Height - 1, rect.Width + 1, rect.Height + 1);
    }
    #endregion
}

```

Where drawing is done: (inside a PictureBox's Paint method, the PictureBox is called "DrawingRegion")

```
    //Rendering is done here because
    //the Graphics object is here.
    private void DrawingRegion_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
        e.Graphics.CompositingMode = CompositingMode.SourceCopy;
        e.Graphics.CompositingQuality = CompositingQuality.HighQuality;
        e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        lock (game.Particles)
        {
            //Looping backwards because the collection can be
            //modified and that throws an exception.
            for (int i = game.Particles.Count - 1; i > 0; i--)
            {
                game.Particles[i].RenderFilledCircle(e.Graphics);
                game.Particles[i].RenderCircleBorder(e.Graphics);
            }
        }
    }

```

My game-loop:

```
    //The game process
    //which updates the particles' location
    //and checks whether or not it should start changing colors
    private void GameProc()
    {
        while (true)
        {
            lock (game.Particles)
            {
                //Looping backwards because the collection can be
                //modified and that throws an exception.
                for (int i = game.Particles.Count - 1; i > 0; i--)
                {
                    game.Particles[i].PerformFrame();
                }
            }
            Invoke((MethodInvoker)(() =>
            {
                DrawingRegion.Invalidate();
                DrawingRegion.Update();
            }));
        }
    }

```

If you think any other chunk of code is relevant, ask me to post it and I will.

# Answer
For some reason, ordering the list works NOW.

Solution to this weird problem: ordering the list (on insertion, not in the game loop that would be a waste) by the list members' Z value like this: NameOfList = NameOfList.OrderBy(P =\> P.Location.Z).ToList();

All the comments were right, I was just so sure I tried it and it didn't work! proof that I tried it is that I had already written this method in my class, sorry for the misinformation on my part!
> 0 votes

---
Tags: c#
---


# Question
Title: How do game engines manage to 'detect' the opengl supported in a computer
I am learning OpenGL 3.3 and OpenGL 2.1. I want to make a game engine with both. So far I can do advanced stuff with both of them. I noticed that graphics engines like Irrlicht support OpenGL 1.x to 4.x. When i run an Irrlicht program in my computer that supports OpenGL 3.3, it runs perfectly. And when i run it in a computer with OpenGL 2.1, it still runs perfectly.

How does it *know* that my computer supports OpenGL 3.3, and adapt itself to it. Is it through trial and error? or how are they able to do this. That is a feature i want to incorporate in my game engine.

# Answer
What works for me is simple:

```
// create OpenGL context first, gl** functions dont work without it

fOpenGL_Vendor   := String(glGetString(GL_VENDOR));
fOpenGL_Renderer := String(glGetString(GL_RENDERER));
fOpenGL_Version  := String(glGetString(GL_VERSION)); // <-- this

```

Last line returns OpenGL version reported by GPU driver, in a `x.x.x` format. You can trim last `.x` from it to get common 2-digit version format.

---

For example this is breakdown from my game:

```
Count   Version
2175    4.5
684     3.3
435     4.0
331     4.4
262     4.3
248     3.1
216     4.2
97      3.0
75      4.1
73      2.1

```
> 2 votes

# Answer
The calls to glGetString don't always work without an existing opengl context.

One way to avoid creating a context to get the answers you are looking for is to launch glinfo (or wglinfo.exe) , and read the text stream (or text file) to get your answer.

It may sound as an ugly method, but I remember working with cards that would simply crash for being asked to try a stereo mode. At least, when you launch an executable, you won't crash your application.
> 0 votes

---
Tags: opengl
---


title: Draw a Texture to fit a rectangle

text:
# Question
Title: Draw a Texture to fit a rectangle
I would like to draw a texture in a rectangle that is smaller than the texture, normally the texture will be scaled to fill the rectangle, which results in a squished image. I want to draw it to fit.

For example, if the green stuff is the Texture, I would like to draw only the stuff in the red rectangle.

I already tried to get the color data from the base texture and create a new one, filled with the part from the base.

```
Color[] colorData = new Color[progressRectangle.Width * progressRectangle.Height];
Color[] sourceColorData = new Color[t2dBack.Width * t2dBack.Height];
t2dBack.GetData(sourceColorData);
for (int x = 0; x < progressRectangle.Width; x++)
{
    for (int y = 0; y < progressRectangle.Height; y++)
    {
        colorData[x + progressRectangle.Width * y] = sourceColorData[x + t2dBack.Width * y];
    }
}

t2dBackDraw.SetData(colorData);

```

but that just results in gibberish.

Is there an easy way to accomplish this?
kind regards

# Answer
You can easily draw part of a texture with a simple Spritebatch.Draw command. Consider the following:

```
// width and height of your red rectangle
int width = 100;
int height = 100;

// start x and y position, in texture coordinates
int x = 120;
int y = 0;

// rectangles for our draw call
Rectangle destinationRectangle = new Rectangle(0, 0, width, height);
Rectangle sourceRectangle = new Rectangle(x, y, width, height);

spriteBatch.Draw(mainTexture, destinationRectangle, sourceRectangle, Color.White);

```

This draw call, will draw the sourceRectangle portion of the texture onto the screen at the desired location.

See more here:

https://msdn.microsoft.com/en-us/library/ff433987.aspx
> 1 votes

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


# Question
Title: Best way to find line segment intersection
I need to find the point of intersection between two line segments in 2D space. I receive them in terms of both coordinates of both lines. Because they are line segments I would also need to know if they actually intersect in the first place.

I can find many ways to do this but I would like to know what method would have the best performance in GLSL.

# Answer
This problem can be extremely easy or extremely difficult; it depends on your application. If all you want is the intersection point, the following should work:

---

Let A,B,C,D be 2-space position vectors. Then the directed line segments AB & CD are given by:

```
AB=A+r(B-A), r in [0,1]
CD=C+s(D-C), s in [0,1]

```

If AB & CD intersect, then

```
A+r(B-A)=C+s(D-C), or

Ax+r(Bx-Ax)=Cx+s(Dx-Cx)
Ay+r(By-Ay)=Cy+s(Dy-Cy)  for some r,s in [0,1]

```

Solving the above for r and s yields

```
    (Ay-Cy)(Dx-Cx)-(Ax-Cx)(Dy-Cy)
r = -----------------------------  (eqn 1)
    (Bx-Ax)(Dy-Cy)-(By-Ay)(Dx-Cx)

    (Ay-Cy)(Bx-Ax)-(Ax-Cx)(By-Ay)
s = -----------------------------  (eqn 2)
    (Bx-Ax)(Dy-Cy)-(By-Ay)(Dx-Cx)

```

Let P be the position vector of the intersection point, then

```
P=A+r(B-A) or

Px=Ax+r(Bx-Ax)
Py=Ay+r(By-Ay)

```

By examining the values of r & s, you can also determine some other limiting conditions:

```
If 0<=r<=1 & 0<=s<=1, intersection exists
    r<0 or r>1 or s<0 or s>1 line segments do not intersect

If the denominator in eqn 1 is zero, AB & CD are parallel
If the numerator in eqn 1 is also zero, AB & CD are collinear.

```
* If they are collinear, then the segments may be projected to the x- or y-axis, and overlap of the projected intervals checked.
* If the intersection point of the 2 lines are needed (lines in this context mean infinite lines) regardless whether the two line segments intersect, then
* If r\>1, P is located on extension of AB
* If r\<0, P is located on extension of BA
* If s\>1, P is located on extension of CD
* If s\<0, P is located on extension of DC

Also note that the denominators of eqn 1 & 2 are identical.

---

Source (copy-paste): http://www.gamers.org/dEngine/rsc/usenet/comp.graphics.algorithms.faq
> 3 votes

---
Tags: glsl, geometry, intersection
---


title: How can I render 2D ropes in Unity?

text:
# Question
Title: How can I render 2D ropes in Unity?
I'd like to be able to render flexible lines, or ropes, as below:

I thought about using a Line Renderer but it doesn't have the flexibility to render arbitrary curves.

# Answer
> 6 votes
This effect can be easily accomplished with just hinge joints.

This above gif, was created without any code whatsoever. Each link in the chain is connected to the one above it via a Hinge Joint 2D. You can play around with the mass of the rope vs the object it is holding for better physic response

Point is, you shouldn't be using a line renderer for something like this.

# Answer
> -3 votes
Its by using SetPosition Property. Have a look at this.

http://docs.unity3d.com/ScriptReference/LineRenderer.SetPosition.html

Hope this helps.

---
Tags: unity, 2d, rope-physics
---


title: Fast Ray Sphere collision code

text:
# Question
Title: Fast Ray Sphere collision code
I am looking at here and while it's well organized a lot of links are broken: http://www.realtimerendering.com/intersections.html

I am trying to find fast code that will give me the hit point and the normal of the hit point on the sphere. I saw a lot of functions that only checks if there is collision but nothing else.

I looked at Real Time Collision Detection book but it doesn't seem to have it either.

Any ideas?

# Answer
Real Time Collision Detection does indeed have this information - look at section '5.3.2 Intersecting Ray or Segment Against Sphere', page 178/179 in my copy.

I'm not sure if it is okay to reproduce the code but I found many copies of it online (google books, for example) - here it is verbatim from Real Time Collision Detection:

**UPDATE: The following sample returns the interval T along the ray and the point of intersection Q.**

You can calculate the normal of the contact by subtracting the center point of the sphere from the contact point and normalizing it.

```
// Intersects ray r = p + td, |d| = 1, with sphere s and, if intersecting,
// returns t value of intersection and intersection point q
int IntersectRaySphere(Point p, Vector d, Sphere s, float &t, Point &q)
{
Vector m = p - s.c;
float b = Dot(m, d);
float c = Dot(m, m) - s.r * s.r;

// Exit if r’s origin outside s (c > 0) and r pointing away from s (b > 0)
if (c > 0.0f && b > 0.0f) return 0;
float discr = b*b - c;

// A negative discriminant corresponds to ray missing sphere
if (discr < 0.0f) return 0;

// Ray now found to intersect sphere, compute smallest t value of intersection
t = -b - Sqrt(discr);

// If t is negative, ray started inside sphere so clamp t to zero
if (t < 0.0f) t = 0.0f;
q = p + t * d;

return 1;
}

```
> 7 votes

# Answer
Here's something off the top of my head, trying to minimize expensive operations, without resorting to approximation hacks (ie. with infinite precision real numbers, the algorithm below is exactly correct, although in practice finite precision will introduce numerical errors). Recommendations/edits to improve performance are welcome.

Let **s** be the start point of the ray, and **d** a unit vector in the direction of the ray.

Let **c** be the center point of the sphere, and **r** its radius.

For simplicity, I'll assume that you only want points on the ray where it enters or kisses the sphere, forward from the start point. Intersections behind the start point, or exiting the sphere, are ignored (this means a ray originating inside the sphere detects no collision).

```
// Calculate ray start's offset from the sphere center
float3 p = s - c;

float rSquared = r * r;
float p_d = dot(p, d);

// The sphere is behind or surrounding the start point.
if(p_d > 0 || dot(p, p) < rSquared)
 return NO_COLLISION;

// Flatten p into the plane passing through c perpendicular to the ray.
// This gives the closest approach of the ray to the center.
float3 a = p - p_d * d;

float aSquared = dot(a, a);

// Closest approach is outside the sphere.
if(aSquared > rSquared)
  return NO_COLLISION;

// Calculate distance from plane where ray enters/exits the sphere.
float h = sqrt(rSquared - aSquared);

// Calculate intersection point relative to sphere center.
float3 i = a - h * d;

float3 intersection = c + i;
float3 normal = i/r;
// We've taken a shortcut here to avoid a second square root.
// Note numerical errors can make the normal have length slightly different from 1.
// If you need higher precision, you may need to perform a conventional normalization.

return (intersection, normal);

```
> 2 votes

# Answer
> Given a ray defined as:
>
> ```
> x = x1 + (x2 - x1)*t = x1 + i*t
> y = y1 + (y2 - y1)*t = y1 + j*t
> z = z1 + (z2 - z1)*t = z1 + k*t
>
> ```
>
> $$ \begin{align} x &= x\_1 + t(x\_2 - x\_1) = x\_1 + it \\ y &= y\_1 + t(y\_2 - y\_1) = y\_1 + jt \\ z &= z\_1 + t(z\_2 - z\_1) = z\_1 + kt \end{align} $$
>
> and a sphere defined as:
>
> ```
> (x - l)**2 + (y - m)**2 + (z - n)**2 = r**2
>
> ```
>
> $$ (x - l)^2 + (y - m)^2 + (z - n)^2 = r^2 $$
>
> Substituting in gives the quadratic equation:
>
> ```
> a*t**2 + b*t + c = 0
>
> ```
>
> $$ at^2 + bt + c = 0 $$
>
> where:
>
> ```
> a = i**2 + j**2 + k**2
> b = 2*i*(x1 - l) + 2*j*(y1 - m) + 2*k*(z1 - n)
> c = (x1-l)**2 + (y1-m)**2 + (z1-n)**2 - r**2;
>
> ```
>
> $$ \begin{align} a &= i^2 + j^2 + k^2 \\ b &= 2i(x\_1 - l) + 2j(y\_1 - m) + 2k(z\_1 - n) \\ c &= (x\_1-l)^2 + (y\_1-m)^2 + (z\_1-n)^2 - r^2 \end{align} $$
>
> If the discriminant of this equation is less than 0, the line does not intersect the sphere. If it is zero, the line is tangential to the sphere and if it is greater than zero it intersects at two points. Solving the equation and substituting the values of t into the ray equation will give you the points.

Source (copy-paste from): http://www-labs.iro.umontreal.ca/~sherknie/articles/faq\_Divers/graphics-algorithms-faq.txt
> 0 votes

---
Tags: collision-detection, mathematics, algorithm, raycasting, realtime
---


# Question
Title: Best practice to store level data in a rhythm based game
**Setup:**

I'm planing to do a rhythm based game, where a level is a music score similar to Frets on Fire, but with real music.

I've two options to store that level data, namely a MIDI file and a MusicML file.

It seems that the defacto standard is MIDI files (see Sintesia, for instance).

I don't need to output that data to the audio system, since is only to build the gameplay, since the player will be the one that will produce the sounds with an external device.

**Question:**

I wonder, since MusicML is more structured and easy to interact to, if it would be best to store the level data as a MusicML file.

# Answer
Well, either one of them can be authored with existing tools, which is always a good thing. When I was making a rhythm game, I determined that it would be easier for me to just make my own format with only what I needed and no more. I actually did my transcription with Audacity label tracks, and wrote a Lua script to convert it to a Lua table that I could directly load into my game.

```
    [27] = {
        ["starts_new_line"] = false,
        ["word"] = "the",
        ["pitch_envelope"] = {
            [1] = {
                ["time"] = 13.662976,
                ["pitch"] = "C4",
            },
            [2] = {
                ["time"] = 13.761109,
                ["pitch"] = "C4",
            },
        },
    },
    [28] = {
        ["starts_new_line"] = false,
        ["word"] = "sound",
        ["pitch_envelope"] = {
            [1] = {
                ["time"] = 13.829461,
                ["pitch"] = "B3",
            },
            [2] = {
                ["time"] = 14.24,
                ["pitch"] = "B3",
            },
        },
    },
    [29] = {
        ["starts_new_line"] = false,
        ["word"] = "of",
        ["pitch_envelope"] = {
            [1] = {
                ["time"] = 14.290176,
                ["pitch"] = "A3",
            },
            [2] = {
                ["time"] = 14.636709,
                ["pitch"] = "A3",
            },
        },
    }

```

I know this doesn't really answer your question, I just wanted to demonstrate the possibilities of rolling your own.
> 2 votes

---
Tags: music, xml, storage, midi
---


# Question
Title: Random layout rooms with intersecting walls
I am trying to layout few rectangle rooms on un unlimited map. The main condition is that every next room has to intersect with one of already placed with at least one point of the wall.

The number, width and height are random values generated by something like D&D dice rolling. Every next room can be adjacent to any placed rooms. Result should look like a kind of dungeon (hope the picture makes it more clear)

I am afraid that different packing algorithms too heavy for that problem. I would greatly appreciate any advice!

# Answer
> 2 votes
A very rough algorithm:

1. Create a temporary room
2. Check if the position of the room is allowed
3. Move the room if necessary

The first two are relatively simple, the last one you have to make you own algorithm that suits the layout you prefer.

The following java code produce a level where

1. The room is a Rectangle object
2. If the Rectangle intersects any existing rectangle, it is forbidden, otherwise allowed.
3. The room is moved counter clockwise in a circle, where the circle's diameter is increase with 1 pixel each revolution - this makes the room placement adjacent to existing rooms. (I think there might be some refinement needed, but the general idea seems to work).

(I've just started to learn java, so if you're experience with that you can likely find some better way to achieve the same results)

```
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

import javax.imageio.ImageIO;

public class GenerateLevel {
    private ArrayList<Rectangle> Rooms = new ArrayList<Rectangle>();
    private Random r = new Random();
    private BufferedImage levelImage;

    public static void main(String[] args){
        new GenerateLevel();
    }

    public GenerateLevel(){
        Rooms.add(new Rectangle(500,500,10 + r.nextInt(50), 10 + r.nextInt(50)));
        int numberOfRooms = 30;
        for (int i = 0; i < numberOfRooms; i++){
            addRectangle(50 + r.nextInt(30), 50 + r.nextInt(30));
        }

        levelImage = new BufferedImage(1000, 1000, BufferedImage.TYPE_INT_ARGB);

        drawImage(levelImage);
        //Writes the BufferedImage levelImage to the level.png file.
        try {
            ImageIO.write(levelImage, "png", new File("src/res/level.png"));
        } catch (IOException e) {
            System.out.println("ImageIO.write exception");
            e.printStackTrace();
        }
    }

    //Draws the final level into the BufferedImage levelImage.
    private void drawImage(BufferedImage levelImage) {
        Graphics2D drawGraphics = levelImage.createGraphics();

        for(Rectangle room:Rooms){
            drawGraphics.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
            drawGraphics.fill(room);
            drawGraphics.setColor(Color.BLACK);
            drawGraphics.draw(room);

        }

    }

    //Adds a rectangle to the ArrayList Rooms.
    private void addRectangle(int width, int height){
        int[] position = findAllowedPosition(width, height);
        Rooms.add(new Rectangle(position[0], position[1], width, height));
    }

    //Finds an allowed position by scanning clockwise and increasing the scan diameter.
    private int[] findAllowedPosition(int width, int height){
        boolean positionFound = false;
        boolean intersectionFound = false;
        int radiusCounter = 1;
        int scanCounter = 0;

        Rectangle tempRect = new Rectangle(500, 500, width, height);

        int[] origin = {500, 500};
        int[] lastPosition = {500, 500};
        while(!positionFound){

            //Check if tempRect intersects with any already placed rectangles.
            intersectionFound = false;
            for(Rectangle r : Rooms){
                if (r.intersects(tempRect))
                {
                    intersectionFound = true;
                    break;
                }
            }

            //If tempRect intersects any rectangle, move tempRect.
            if (intersectionFound){

                if(scanCounter == 0){
                    lastPosition[1]--;
                }

                lastPosition = scanClockwise(radiusCounter, origin, lastPosition);
                scanCounter++;
                tempRect.setLocation(lastPosition[0], lastPosition[1]);
            }
            //If tempRect doesn't intersect any rectangle, set PositionFound = true;
            else {
                positionFound = true;
                break;
            }

            //Check if one revolution of the scan radius has been performed, if so, increase scanRadius.
            if(((radiusCounter * 2-1)*4 + 4) < scanCounter){
                radiusCounter++;
                scanCounter = 0;
            }
        }
        int[] foundPosition = {(int)tempRect.getX(), (int)tempRect.getY()};
        return foundPosition;
    }

    private int[] scanClockwise(int scanRadius, int[] origin, int[] lastPosition){
        int[] returnArray = lastPosition;

        // Upper line of the scan rectangle
        if (lastPosition[0] >= origin[0] - scanRadius && lastPosition[0] < origin[0] + scanRadius && lastPosition[1] == origin[1] - scanRadius){
            returnArray[0]++;
        }
        // Right line of the scan rectangle
        else if (lastPosition[1] >= origin[1] - scanRadius && lastPosition[1] < origin[1] + scanRadius && lastPosition[0] == origin[0] + scanRadius){
            returnArray[1]++;
        }
        // Bottom  line of the scan rectangle
        else if (lastPosition[0] <= origin[0] + scanRadius && lastPosition[0] > origin[0] - scanRadius && lastPosition[1] == origin[1] + scanRadius){
            returnArray[0]--;
        }
        // Left line of the scan rectangle
        else {
            returnArray[1]--;
        }
        return returnArray;
    }
}

```

Below is a picture made by this code, but point 3 above is where you'll have to write an algorithm that suits whatever level-layout you have in mind.

---
Tags: tiles, procedural-generation, maps
---


# Question
Title: How do you build a rotation matrix from a normalized vector?
I'm trying to find the correct way to build a rotation matrix from a unit vector. I have two arbitrary points in space (p1 and p2), and I'm trying to create the vertices for a rectangle to span between them.

From the points, I can get a unit vector easily enough. From there I've been trying to create a rotation matrix that I can apply to a set of hard-coded vertices to get them oriented correctly. The rectangle extends along the X axis, so I'm trying to rotate it's X axis to match the unit vector.

So far I've tried GLM::orientation:

```
glm::vec3 direction = glm::normalize( glm::vec3( p2 - p1 ) );
glm::mat4 rotation4 = glm::transpose( glm::orientation( direction, glm::vec3( 0, 1, 0 ) ) );
glm::mat3 rotation = glm::mat3( rotate4 );

```

As well as the manual matrix creation method mentioned in this similar question:

```
glm::vec3 direction = glm::normalize( glm::vec3( p2 - p1 ) );
glm::vec3 rotationX = direction;
glm::vec3 rotationZ = glm::normalize( glm::cross( direction, glm::vec3(0,1,0) ) );
glm::vec3 rotationY = glm::normalize( glm::cross( rotationZ, direction ) );
glm::mat3 rotation( rotationX, rotationY, rotationZ );

```

However, in both cases I end up with rectangle rotations that seem fine for axis-aligned rotations, but which veer off in weird directions in all other cases. In both cases, I'm attempting to specify the positive Y axis as up, to keep the rectangle level, but the rotated rectangle always ends up twisted around despite that.

I'm obviously doing this wrong, but I may just not be understanding the problem well enough. If someone could point me in the right direction, I'd appreciate it.

# Answer
Turns out the manual matrix creation method was on the right track, I just wasn't building it in the correct order. This appears to do what I want (though oriented on the -Z axis rather than the +X axis, but that'll be easy to change on my rectangle vertices).

```
glm::vec3 direction = glm::normalize( glm::vec3( p2 - p1 ) );
glm::vec3 rotationZ = direction;
glm::vec3 rotationX = glm::normalize( glm::cross( glm::vec3( 0, 1, 0 ), rotationZ ) );
glm::vec3 rotationY = glm::normalize( glm::cross( rotationZ, rotationX ) );
glm::mat3 rotation( rotationX.x, rotationY.x, rotationZ.x, rotationX.y, rotationY.y, rotationZ.y, rotationX.z, rotationY.z, rotationZ.z );

```
> 2 votes

---
Tags: c++, vector, matrix, glm
---


# Question
Title: How to calculate acceleration and deceleration
I have a car with speed x, and can accelerate at a rate of 0.5 m/s^2, and can decelerate at a rate of -0.1 m/s^2. Maximum speed is 20 m/s.

To accelerate the car speed, at each frame I need to do:

```
car.CurrentSpeed = car.CurrentSpeed + 0.5

```

To decelerate the car speed, at each frame I need to do:

```
car.CurrentSpeed = car.CurrentSpeed - 0.1

```

Is this correct?

I have found this answer which suggest the following speed formula:

> Speed += ((MoveDirection * MaximumSpeed) - Speed) * AccelerationFactor
>
> Where:
>
> * Speed is the current speed the entity is travelling at on the current axis.
> * MoveDirection is the direction the entity is trying to travel in on the current axis, 1 is forward, 0 is still and -1 is backwards. All values in between are allowed.
> * MaximumSpeed is a constant determining the fastest that the entity can travel on the current axis.
> * AccelerationFactor is a constant between 0 and 1 that represents the rate of acceleration and deceleration. 1 is instant, and 0 will never move.

Using the same formula then:

To accelerate:

```
car.CurrentSpeed += ((MoveDirection * 20) - car.CurrentSpeed) * 0.5

```

What would be the *move direction*? Can it be the heading?

# Answer
> 3 votes
*move direction* is the heading. You have to distinguish *speed* from *velocity*; when you multiply speed (a scalar) with the move direction (a unit vector), you get the velocity, which is a vector.

---

Your assumptions show a flaw:

You don't take the *time* into consideration.

If your speed is based on `m/s` and your acceleration is in `m/s^2`, at each frame you should do something like:

```
car.CurrentSpeed = car.CurrentSpeed + (0.5 * delta_time)

```

and to decelerate, you need to reduce the speed:

```
car.CurrentSpeed = car.CurrentSpeed - (0.1 * delta_time)

```

where `delta_time` is the time for each frame.

This will take the frame-rate into consideration.

To cap the speed at it's maximum:

```
car.CurrentSpeed = min( maximum_speed, car.CurrentSpeed + (0.5 * delta_time) )

```

You can then apply this speed to the heading direction, you'll get the velocity vector (if you need it).

Now be aware that if you *brake* your speed will need to be capped to zero:

```
car.CurrentSpeed = max ( zero, car.CurrentSpeed - (0.1 * delta_time) )

```

...as opposed to if you *reverse*, where your reverse speed will need to defined differently. Now it's either going to be a positive speed with a flag that says you're in reverse, or a negative speed; this will depend on the rest of your architecture.

---
Tags: 2d, physics, mathematics
---


# Question
Title: Textures created with Photoshop show up with a white border
All of a sudden, I started having this problem. I've used libGDX + Photoshop before and never had this problem. One of my textures is showing up with a white border/glow around.

The texture is the black blob on the middle, which is a 256 pixels png with a few black brushstrokes I created with Photoshop, just to test it.

Everything in libGDX is on default. I haven't changed the blending function, I'm just using a SpriteBatch to render the image without any changes.

The weird thing is, some other textures I created with Photoshop, same size, RBG 8 bit color mode (just like my blob image), look fine. These are temporary textures I created by downloading a png from the web, pasting it into Photoshop, applying a solid color overlay effect to it and saving it back as a png.

Any idea what's causing this?

Edit: Here's how I'm loading my textures:

```
private static Texture createTexture(String fileName, boolean maxQuality, Texture.TextureWrap textureWrap) {
    Texture result = new Texture(Gdx.files.internal(fileName), true);
    result.setFilter(maxQuality ? Texture.TextureFilter.MipMapLinearLinear : Texture.TextureFilter.MipMapLinearNearest, Texture.TextureFilter.Linear); // TODO: Are these the best?
    if(textureWrap != null)
        result.setWrap(textureWrap, textureWrap);
    return result;
}

texture = new TextureRegion(createTexture("data/blob.png"));

```

I just found out using this technique that the transparent pixels in my texture are white (1, 1, 1, 0). So I'm pretty sure the cause is a combination of this, the linear resizing and probably the blending function. Not sure what's the right way to fix it though. Don't want to change the resizing to nearest.

# Answer
> 2 votes
So I figured it out and found a couple of ways to solve it.

**Cause:**

Photoshop, for some reason, will produce white transparent pixels. And when libGDX resizes the pictures it seems to average the pixels, so if a pixel is {1, 1, 1, 0} (transparent white) and another is {1, 0, 0, 1} (red), the average would be {1, .5, .5, .5}, which is a semi transparent mix of white and red and looks whitish on a dark background:

**Solution 1:**

One way is to premultiply the image, which turns transparent pixels black, using Texture Packer or some other program. This solves the white border on a dark background problem:

But it'll create another problem when using a bright background. Since the default blending functions are `GL_SRC_ALPHA` and `GL_ONE_MINUS_SRC_ALPHA`, which tells OpenGL to multiply the source image's value times its alpha and add it to the background's value times one minus the source's alpha, blending a mix or red and transparent black caused by image resizing {.5, 0, 0, .5} with a white background {1, 1, 1, 1} will produce {.75, .5, .5, .75}, which is a mix of red, black and white, and looks like a dark border around the texture:

The solution here is to change the blending functions to `GL_ONE` and `GL_ONE_MINUS_SRC_ALPHA` (using `setBlendFunction` is you're using a `SpriteBatch`). This tells OpenGL to multiply the source's value by one, which will produce {1, .5, .5, 1}, an actual mix of red and white, when blending the mix of red and transparent black {.5, 0, 0, .5} with the white background {1, 1, 1, 1}:

**Solution 2:**

What I ended up doing is using Texture Packer to reduce border artifacts. This will replace each transparent pixel with the color of a neighbor non-transparent pixel and will work fine with the default blending function on any background.

The reason I used this solution is simply because I already use the default blending mode on every other place. I guess the way to go is to pick one solution and stick to it.

---
Tags: opengl, libgdx, textures, graphics
---


# Question
Title: Unity3D: 'Physics' does not contain a definition for 'Raycast'
I'm a complete beginner in Unity 3D, and I'm following a video training. In the video the instructor uses the following code to open a door using raycast:

```
using UnityEngine;
using System.Collections;

public class HelloRaycasting : MonoBehaviour {

    bool doorClosed = true;

    // Use this for initialization
    void Start () {

    }

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

        Vector3 backward = new Vector3 ( 0, 0, -1);
        Vector3 origin = this.gameObject.transform.position;

        if (Physics.Raycast( origin, backward, 1f) && doorClosed) {
            doorClosed = false;
            GameObject.Find ("Left_Quad").transform.Translate ( new Vector3(-.8f, 0, 0));
            GameObject.Find ("Right_Quad").transform.Translate ( new Vector3(.8f, 0, 0));
        }
    }
}

```

It works just fine for him. But when I try to run this on my computer I get this error:

> Assets/HelloRaycasting.cs(20,29): error CS0117: 'Physics' does not contain a definition for 'Raycast'

In the end I'm not able to access none of the properties and methods of the Physics class.

I'm using Unity 5.3.2f1 (64-bit). What am I doing wrong?

# Answer
> 4 votes
I'd guess you made your own class or imported some other class named `Physics`. Try fully qualifying it `UnityEngine.Physics.Raycast`.

Alternatively, you can make sure you make a clean build to ensure there's nothing left over that's messing up your build.

---
Tags: c#, unity, scripting
---


title: Rotate object with mouse look script

text:
# Question
Title: Rotate object with mouse look script
I would like to rotate an FPS camera slightly upwards during a shot as an effect of recoil, but the problem is that I have a mouse look script as well and I assume it prevents me from achieving the effect i want. So far I have tried using `transform.Rotate(-10,0,0)` and

```
transform.rotation = Quaternion.Euler(transform.rotation.x - 10, transform.rotation.y, transform.rotation.z);

```

both rotated the camera upwards but then the camera moved back downwards to the initial position. Does anyone know how I can rotate the camera and keep the rotation? Or if there is any better way to achieve this effect.

# Answer
Ok so based on the comment i made earlier here is how i would add offset to the camera. The code is just of the top of my head so it might need a bit of fine tuning:

```
//Inside the mouse tracking class
Vector2 offset = new Vector2();
float startTime = -1f.
    length;

//the code that controls the initial recoil
private void Hit()
{
    transform.rotation = Quaternion.Euler(transform.rotation.x - 10, transform.rotation.y, transform.rotation.z);

    offset.x = 10f;
    startTime = Time.time;
    length = Vector2.Distance(new Vector2, offset);
}

//replace the part were you get the mouse position with this method
Vector2 Recoil()
{
    if (startTime != -1f)
    {
        Vector2 mouse = Input.mouse.position,
            adjustedMouse = mouse + offset;

        //change the 10 to speedup/slow down the transition back to normal
        float dist = (Time.time - startTime) * 10f,
            fracJourney = dist / length;

        if (dist >= 1f)
        {
            startTime = -1f;
            offset.x = 0f;
        }

        return Vector2.Lerp(adjustedMouse, mouse, dist);
    }
    else {
        return Input.mouse.position;
    }
}

```

When you want to trigger the recoil call "Hit" which will setup all the variables for the Lerp. Then instead of checking the input class for the position of the mouse on screen, call the "Recoil" method which should pull the mouse up and then slowly lower it to the actual position of the gun.

You can read up on what I did here but for the sake of completeness: (Vector.Lerp description)

> Linearly interpolates between two vectors.
>
> Interpolates between the vectors a and b by the interpolant t. The parameter t is clamped to the range \[0, 1\]. This is most commonly used to find a point some fraction of the way along a line between two endpoints (e.g. to move an object gradually between those points).

I hope this works for you :)
> 1 votes

---
Tags: unity, camera, rotation, transformation, quaternion
---


# Question
Title: Vector math to calculate the rotation and drift of a tectonic plate?
I've been following the excellent Experilous procedural planet generation post, trying to recreate it in Java using libGDX. My planet is simpler, as it lacks any distortion of the mesh. It's just hexagons and 12 pentagons right now. However, I've been running into trouble at the part:

> The next step was to take the motion of plates and calculate the type and degree of stress at each point along the boundaries between the plates. For each point, I calculated the movement of each plate at that particular position. Subtracting the two gave me the relative movement. I then determined the component of that movement that exactly perpendicular to the plate boundary at that location. This corresponded to the amount of relative movement that was directly pushing the plates into each other or pulling them directly away. This I classified as pressure, and it could be either positive (collision) or negative (separation). I also determined the relative movement that was parallel to the boundary and stored this as shear. (Only the magnitude of this movement was relevant, so shear was strictly non-negative.)

The picture is the example of each tile's motion following this calculation of drift and spin for the tectonic plates. However, the math to actually calculate this completely escapes me. Given that I have the tiles grouped into tectonic plates, a random center (of a tile) for each plate, the center of every tile, and the normal vector of every tile, how could I achieve the same effect depicted here?

Thank you.

# Answer
> 1 votes
Try to reduce the problem down to simple structures.

Representing each plate, mathematically, with a sphere:

1. Centerpoint of each sphere is same distance from center of planet
2. Radius of each sphere is determined by ratio of surface area vs. total (or similar)
3. No intersecting spheres
4. Each sphere can rotate around its' center point
5. Each rotated sphere can also rotate around the planet's center point
6. A sphere's radius determines the plate's "mass", allowing larger spheres to impart more force
7. At run time, pick a sphere and give it a push
8. Continually apply basic elastic collisions between the spheres

Whenever two spheres collide, both spheres impart a portion of their rotational velocity around the planet's center to each other, weighted by their proportional masses. At the same time, each one also imparts a portion of it's own sidereal rotation to the other. This means that larger masses can easily push smaller masses around. Similarly, a massive object spinning clockwise will impart a large counterclockwise force on less-massive objects it collides with.

Each frame, apply each sphere's changes to its' child tiles. The result of tile collisions should be proportionally scaled and then applied back to the parent sphere. Essentially, the spheres will try to rotate all of the tiles and the tiles that collide as a result provide feedback to the sphere.

Red arrows show the rotational velocity around the planet's center while green arrows show the local rotational velocity of each sphere. (Not to scale) Notice that adjacent spheres with complementary rotations generally have complementary "flow directions" while the areas near opposite rotations have generally opposite flows.

Example collision:

Red is movement and green is rotation. The magenta arrows are approximations of the forces calculated at two example collision points. Both masses are of relatively similar size so neither has a clear advantage at the perpendicular intersection site; the two plates are likely to grind along the edge for a long time. The parallel collision site happens so far from the top-left sphere's "center of mass" that the lower-right sphere can easily overpower it. Over time, the two should dance such that the upper sphere "rolls" down the left edge of the lower sphere.

Assuming the other plates allowed it:

# Answer
> 0 votes
What you're referring to as spin is formally called angular momentum. Depending on the level of detail you want, it can get complicated fast; this Q/A on Simulating Torque and Angular Momentum might be a good starting point.

---
Tags: mathematics, vector, procedural-generation
---


# Question
Title: What's the implication of right-handedness when building camera to world matrix?
I found these slides which go through the viewing transform in what I think is a easy way. However, I have hard time understanding two thigs:

1. What would be the implication of using a right-hand coord system when building this matrix?
2. In order to get the final camera-to-world matrix, I thought I should do a matrix composition, i.e. C = T * R. Why on slide 18, it just puts the translation vector in the last column instead of doing such a multiplication?

# Answer
> 1 votes
1) the negative Z would be in front of the camera (and the positive behind it)

2) because of the shape of the matrix (and the many zeros in it). you can do the multiplication by hand, you will end up with the matrix as it is written (with the translation in the last column)

# Answer
> 1 votes
Handedness is referred to as 'chirality'.

Moving the camera "left" is the same as moving the world "right". The ViewMatrix can actually be constructed by inverting the world matrix you'd construct to draw a piece of geometry representing the camera. Applying the ViewMatrix, literally, un-moves, then un-rotates the world to where the camera becomes (0,0,0) and whatever direction the camera is facing becomes "into the scene".

The chirality of the ViewMatrix simply determines whether the direction of "into the scene" refers to (0,0,1) or (0,0,-1). With either chirality, (1,0,0) is "right" and (0,1,0) is "up".

I refer to this diagram whenever I've confused myself:
https://msdn.microsoft.com/en-us/library/windows/desktop/bb204853(v=vs.85).aspx
Notice that while both arms are pointing the same direction, the thumbs, **both** pointing in the Z+ direction, are opposite.

Re #2:
I agree with user75844; that's just how the math works out.

---
Tags: transformation
---


# Question
Title: Ideas for refactoring regarding simple state management in entities and level
I'm actually developing a very simple 3D game, Arkanoid/Breakout style, with very simple mechanics, and it's progressing while I learn the game dev domain own concepts and techniques (My background is C/C++ middleware/low-level systems programmer).

I've advanced to a functional game loop, input, movement, collision checks, all it's working, but I reached to a day where the code was a mess, e.g: my Level class was doing *too much*. So I partitioned, OOP style, the code in several classes.

My intention is to get ideas from more experienced programmers regarding how Game state and substates relate with entities. My general picture is:

* A game object which contains the main loop
* A level object which contains a World instance with a list of all entities.
* A renderer class which does Direct2D and Direct3D rendering.

Prior to the major refactoring, I was doing something like

```
Level::Update(float clockMs)  {
  switch (m_state)
    case (LevelState::Preloading) { ... }
    case (LevelState::Load) { ...}
    case (LevelState::Playing) {
        UpdateBallPosition ( ... )
        CheckCollisions( ...)
    }

}

```

Level contained references to ball, game bricks, etc. Now I create the entities in the Level startup and add them to the World instance. (World is a member of Level).

Now I want to move all state-related code to the entities themselves. Suppose "Ball", it shouldn't do anything until Level is in LevelState::Playing. Where do you store typically state for the current Level (suppose a closed-level game)? It's correct to store entities with a pointer to the World and the World to mantain a pointer to the Level containing it? It's a tightly coupled architecture but I want to discuss how to relate world/level states with entities, and how the entities acknowledge in which higher-level states they are.

Keep in mind that I accept good procedural or data-driven approaches. I'm not an OOP fanatic, I think good designs can be built upon several paradigms. Thanks.

# Answer
In your case, it doesn't make a bit of difference to Ball which world it's in or which Level that World is in.

The only things that matter to the World/Level/GameState/whatever are:

1. Are there any breakable bricks left?
-If not, YOU WIN and/or NEXT LEVEL
-If so and !paused, Ball.Tick()

The only things that matter to Ball are:

1. Level-based velocity
2. Am I off the screen? (GAME OVER)
3. Am I colliding with a brick?
-If so, is it breakable?
-If so, Ball calls Brick-\>Break()
-If not, bounce (wall bricks)

The only things that matter to Paddle are:

1. Should I move left?
2. Should I move right?

The only things that matter to Brick are:

1. Am I breakable?
2. Provides bounding box to Ball upon request
3. "Breaks" upon request from Ball

I've probably left something out but I think this covers most of the game logic.

---

Generally speaking, you need to think of your GameObjects as just data and not as unique individuals. As you advance, you'll create fewer classes that generically apply to more and more objects, the bottom line being the minimization of transfers between the CPU and GPU.

1. Beginner programmers tend to create "objects" for everything and operate the GPU like a standard calculator:

`[number][operator][number][get result][operator][number][get result]`
`1 + 2 = 3 + 1 =4`
2. Buckets and buckets of objects are all Updated() and Rendered(), every frame.
3. Eventually, you realize that you've been spreading your data out, storing it here, and there, and anywhere, even though the GPU prefers super-dense, possibly-massive, streams of data.

* The GPU operates asynchronously and will do what you've told it to **while** you are telling it what to do next
    * The GPU operates like an RPN calculator; you load data, then issue commands
    `[number][number][number][operator][operator]`
    `1 2 1 + (3 appears) + (4 appears)`
    * The instructions between Begin() and End() are batched and sent to the GPU without waiting
    * The \[result\] of the previous GPU operation remains "current" until you specify otherwise. (i.e. Draw() calls only affect the current RenderTarget and no RenderTarget can be Drawn() to without being, first, made current by binding it)
    * That is to say, that you can issue commands that use \[result\] now, even though the GPU hasn't processed the command that produces \[result\]. That's because \[result\] **will** have been calculated by the time the command that uses it actually gets executed.
4. Eventually, you realize the game is nothing but textured quads, which leads to developing generic, reusable, geometry using DrawInstanced(...)
5. Instancing makes every component in the game representable as:

`struct PerInstance
{
 uint TextureIndex;
 uint X;
 uint Y;
 uint Width;
 uint Height;
}`
6. With the abstracted structure, you are now able to store ALL game objects in a single (1) super-dense, possibly-massive, per-instance buffer, that is always ready to be uploaded.
7. Each frame can, now, be rendered with a single (1) DrawInstanced(...) call.
8. Whatever is left of your "objects" are, now, just slightly-specialized wrappers around the same, generic, PerInstance struct\<\>. Your final classes will be extreeeeemly simple and look very similar to my lists, above.

As an example of when it is preferable to move from the abstract-as-possible approach to the specific-kinds-of-objects approach, consider that 99% of your game is Ball.Tick() and Ball.Render(). Some bricks **never** move, some bricks move(break/disappear) occasionally, the paddle moves frequently, and Ball **always** moves. It makes no sense to re-upload the same stationary bricks every time Ball moves. So, we move Ball, and probably Paddle, to their own PerInstance buffer. One tiny buffer for the fast-movers, updated every frame, and one for everything else, updated only when bricks break.

Lastly, it's a truly wonderful feeling to open a project from last year/month/week and LOL at how completely noob you were "back then"; save a copy before you refactor! Also, instead of refactoring, I'd suggest starting over; sort of a... muscle memory.. thing.
> 2 votes

---
Tags: levels, game-state, entities
---


title: Projection Matrix Breaks My Rectangle

text:
# Question
Title: Projection Matrix Breaks My Rectangle
This is my vertex shader, shown below.

```
#version 330 core

in vec3 a_position;
in vec4 a_colour;

// FOV = 70, near plane = 0.1, far plane = 1000
const mat4 u_projection = mat4(
    1.428148, 0.0, 0.0, 0.0,
    0.0, 1.428148, 0.0, 0.0,
    0.0, 0.0, -1.0001999, -0.20002,
    0.0, 0.0, -1.0, 0.0
);

//uniform mat4 u_projection;
//uniform mat4 u_view;
uniform mat4 u_transformation;

out vec4 v_colour;

void main() {

   gl_Position = u_projection * u_transformation * vec4(a_position, 1);
   v_colour = a_colour;
}

```

Whenever I take out `u_projection`, my square appears. When I add it back, the square is malformed.

The vertices of my square are as follows, aka the contents of `a_position`.

```
float[] vertices = {
    0, 0, 0.5f,
    0.5f, 0.5f, 0.5f,
    0, 0.5f, 0.5f,
    0, 0, 0.5f,
    0f, 0.5f, 0.5f,
    0, 0.5f, 0.5f
};

```

The position of the square is `(0, 0, 0)`, the rotation is `(0, 0, 0)` and the scale is `1`. These are computed into `u_transformation` and uploaded. This works perfectly.

If I change the `-1.0001999` and the last `0` to `1` part to 1 then the square is not hidden.

```
void bindAttribute(int index, String name) {
    GL20.glBindAttribLocation(program, index, name);
}
bindAttribute(0, "a_position");
bindAttribute(1, "a_colour");

```

# Answer
First of all, there's something fishy about your vertices. If we write them out properly:

```
float[] vertices = {
    0.0f, 0.0f, 0.5f, // (1)
    0.5f, 0.5f, 0.5f, // (2)
    0.0f, 0.5f, 0.5f, // (3)
    0.0f, 0.0f, 0.5f, // (1)
    0.0f, 0.5f, 0.5f, // (3)
    0.0f, 0.5f, 0.5f  // (3)
};

```

You have only 3 distinct vertices, so if you are seeing a rectangle, then you need to call you GPU manufacturer! (or check your `glVertexAttribPointer` calls)

Your projection matrix doesn't look correct... I believe the reason your triangle (it's not a rectangle) is disappearing is that you are specifying your projection matrix in row-major order. The way you represented your matrix:

```
const mat4 u_projection = mat4(
    1.428148, 0.0, 0.0, 0.0,
    0.0, 1.428148, 0.0, 0.0,
    0.0, 0.0, -1.0001999, -0.20002,
    0.0, 0.0, -1.0, 0.0
);

```

Actually produces the following transformation matrix:

```
[1.428148, 0.0     , 0.0       ,  0.0 ]
[0.0     , 1.428148, 0.0       ,  0.0 ]
[0.0     , 0.0     , -1.0001999, -1.0 ]
[0.0     , 0.0     , -0.20002  ,  0.0 ]

```

This also implies that you are using an aspect ratio of 1.0, whereas you state in the comments that you have a 500x800 aspect ratio, but let's stick to this matrix for now. What you should have is:

```
const mat4 u_projection = mat4(
    1.428148, 0.0, 0.0, 0.0,
    0.0, 1.428148, 0.0, 0.0,
    0.0, 0.0, -1.0001999, -1.0,
    0.0, 0.0, -0.20002, 0.0
);

```

Notice that the `-1.0` and the `-0.20002` are swapped.

Now, let's multiply the transformation matrix by the coordinates of your triangle (again there are only 3), the clip-space coordinates we get are:

vertex (1): \[`0.0, 0.0, -0.70012, -0.5`\]

vertex (2): \[`0.714074, 0.714074, -0.70012, -0.5`\]

vertex (3): \[`0.0, 0.714074, -0.70012, -0.5`\]

Ah! We have a negative w value, and a more negative z value (-0.5 and -0.70012, respectively). This is because you placed your z-values at 0.5, when by OpenGL convention, in view space, the negative z axis points away from the viewer, so you should change those to -0.5, so that the triangle actually lies between your near and far clip planes.

So, let's say we do that, our unique vertices become:

```
float[] vertices = {
    0.0f, 0.0f, -0.5f, // (1)
    0.5f, 0.5f, -0.5f, // (2)
    0.0f, 0.5f, -0.5f, // (3)
};

```

Now, your clip space coordinates become:

vertex (1): \[`0.0, 0.0, -0.3008, 0.5`\]

vertex (2): \[`0.714074, 0.714074, -0.3008, 0.5`\]

vertex (3): \[`0.0, 0.714074, -0.3008, 0.5`\]

Now, your triangle should be partially in your window; i.e., because vertices 2 and 3 are actually outside of clip space. Remember that, if you want your triangle to (at least partially) appear, then at least one if its coordinates has to have all x, y and z values between -w and +w. There are several things you can do to fix this, such as increasing your fov angle. It depends on what you want to do.
> 3 votes

---
Tags: opengl, glsl, matrix, projection, projection-matrix
---


# Question
Title: Checking if object passed between two other objects
I have a three objects (strikers), lets say red, green and blue.

When I apply force to the green object I want to check if it has passed between red and blue or not. See the image below for an illustration.

Is there any line collider or something for that?

# Answer
> 4 votes
You can use vectors, they're quite handy in fact. Oddly enough you'll need to use 3D vectors to accomplish this 2D task, but it's all rather straight forward.

First let's look at how to figure out if the test ball is in the "corridor" between the other balls. To do this we'll use the dot products of the vectors between all 3 balls.

The dot product can be thought of telling if two vectors are in the same direction. We'll do one test for each ball we might be moving between. We check to see that our test ball, shown in dark blue labelled C, is in the same direction as the other light blue ball. From B's perspective, we take the vector from B to A (BA) and do it with the vector from B to C (BC). If it's positive, then C is in the same direction as A (the angle between them is less than 90 degrees).

Lastly we'll use a cross product to determine if the dark blue ball C has cross between B and A. This trick uses 3D vectors, but it's still quite simple.

We'll perform one cross product per-frame of your game, and keep the result around to look at in the next frame. Looking in the perspective of B, we'll do BC × BA and inspect the third component, the value in the Z direction. If the sign of (BC × BA).Z changes between frames, we know that the ball has moved to the other side of the BA line. This is due to the way cross products are computed, if the vectors swap sides basically the sign of the cross product will be inverted.

In short, check that the dot products are both positive like I described, and if the sign of the cross product changes between frames, the ball has crossed the line in one direction or the other. If you're interested in a code sample I could provide one if this doesn't make sense as abstract as it is.

# Answer
> 1 votes
Check X any Y boundaries for the respective objects.

So, basically you want your object's X value to be be greater than RED's X value and less than BLUE's X value (so it's horizontally between them), and your object's Y value to be less than the max Y value RED/BLUE (whichever has a greater Y, less than that). When it passes the lower Y value then you note that it passed that and wait for it to pass the greater Y value.

To roll your own here will take a little thinking, particularly if the goal posts (the RED/BLUE objects move) and especially if they move independently. If they are always fixed (game of marbles) when checking this stuff then you can first test to see whether they are vertical or horizontal, relative to each other, and have slightly different sets of checks. Presumably you'd need to calculate distance to objects and figure which pairs of objects you might potentially pass through.

Because these are spheres, you either have to track two X values and two Y values (respective straight line edges) or calculate those two values from the coordinates of the sphere's center and it's radius.

I suppose if you can construct two right triangle by drawing a line connecting the spheres and so, then you need only check if if the ball passes either or both of straight lines that comprise the outside of the triangles(i.e. ball X,Y intersected the line)...

As suggested above, some kind of linear algebra would probably simplify this a bit. I forget exactly how to apply it but you're effectively testing intersection with a line inside a certain domain.

If you know the equation of the line that describes the object's current motion (movement/velocity vector?) and the equation of the line between the two objects then the solution to the system of equations (i.e. those two -- two eqns, two unknowns?) there would be the intersection point. If there is any solution inside the domain then you have a potential collision point. You could get the slope of line with the distance between the two points (RED/BLUE sphere centers).

slope = rise/run = (Y2-Y1)/(X2 - X1)

http://en.wikipedia.org/wiki/System\_of\_linear\_equations
^ You need the line in standard form for this

basic example of how to solve them: http://www.mathsisfun.com/algebra/systems-linear-equations-matrices.html

I think you are only dealing with X,Y here so it is line intersections between two lines. Collision is, I guess, there being a solution to the system and your object being at/close to/past the point of intersection

# Answer
> 0 votes
This method is kind of a hack and will not work at high speeds. Try it out and see if it fits your needs.

This will tell you the position of the Green point relative to the line formed by Red and Blue:

side = (Blue.x-Read.x)*(Green.Y-Red.y) - (Blue.y-Red.y)*(Green.X-Red.x)

* If side = 0: Green is rigth in the middle of Blue and Red.
* If side \< 0: Green is on one side of the line
* If side \> 0: Green is on the other side

You should store this value for Green, and update it. Then, the moment the sign changes, you need to check:

* If (Red-Green)·(Blue-Green) \< 0 : Then Green point passed between both points
* Else : It didn't

# Answer
> 0 votes
> Can you cast a ray from the blue to red? If so, can you determine if the ray is "touched" by the green? – MVCDS

Yes, using a `CircleCollider2D` and `Linecast(...)`;

```
if (Physics.Linecast(redPosition, bluePosition))
{
  //The line intersects a collider
  ...
}

```

http://docs.unity3d.com/ScriptReference/Physics.Linecast.html

I've never used Unity, so I can't say whether this functionality was available at the time of asking.

# Answer
> -1 votes
Use triangle space determinat computation - if you can observe all three points... It should change sign in front of space number after crossing line. Other way is to count angle between points with needle on green when it gets over 180 degree it is behind ;)

---
Tags: c#, unity, unityscript
---


# Question
Title: Finding x and z value in the direction of another object
In my game you can drive a car and it has an arrow point to an object you need to drive towards. The arrow pops up above the car using the same x and z value as the car but adding 2 to the y value. What I am trying to do is push the arrow out a little bit toward the object it is pointing to. This way it looks like it is rotating in a circle around the car instead of rotating about it's own center point.

This is what I am doing right now:

```
if (!(Vector3.Angle(car.transform.forward, obj.transform.position - car.transform.position) < 40f))
{
    arrow.SetActive(true);
    temp = car.transform.position;
    temp.y = car.transform.position.y + 2f;
    arrow.transform.position = temp;
    temp = obj.transform.position;
    temp.y = arrow.transform.position.y;
    arrow.transform.LookAt(temp);
}

```

# Answer
> 1 votes
```
if (...)
{
    carPosition = car.transform.position;
    objectPosition = obj.transform.position;

    //Calculate the car-to-object vector
    carToObjectDirection = objectPosition - carPosition;

    //Make sure it's flat
    carToObjectDirection.y = 0;

    //Make length convenient for multiplication
    carToObjectDirection.Normalize();

    //Move arrowPosition away from (0,0) in carToObjectDirection by offsetLength amount
    arrowPosition = (carToObjectDirection * offsetLength);

    //Move the offset arrow to just above the car
    arrowPosition += carPosition;
    arrowPosition.y += 2;

    arrow.SetActive(true);
    arrow.transform.position = arrowPosition;

    //Uncomment to prevent the arrow from pointing excessively upward or downward
    //LookAt.y is clamped to within 10% of arrowPosition.y
    //objectPosition.y = max(objectPosition.y, arrowPosition.y * 0.9f);
    //objectPosition.y = min(objectPosition.y, arrowPosition.y * 1.1f);

    //Uncomment to keep the arrow parallel to the XZ-plane
    //objectPosition.y = arrowPosition.y;

    //Slightly less parallel (2 lower than lookat) (always points slightly downward)
    //objectPosition.y = carPosition.y;

    arrow.transform.LookAt(objectPosition);
}

```

---
Tags: unity, c#
---


# Question
Title: Normal to an edge of a polygon, from a point inside the polygon
Suppose that I have a closed boundary that is represented by `n` points. Using these `n` points I construct a polygon with `n` sides. I have a point `P(x,y)` that lays inside the polygon.

I want to draw the normal from Point `P` to the edge/edges of polygon. Depending on the shape of the polygon, I can have multiple edges to which I can draw normals from point `P`. How shall I select the subset of edges (from all edges of polygon) that can be chosen to draw normal from point `P`?

# Answer
> I construct a polygon with n sides. I have a point P(x,y) that is inside the polygon. I want to draw normal from Point P to edge/edges of polygon

For each edge:

1) finding a normal for a line-segment is is trivial.

2) but in your case, you also want to identify the point S that lays in that edge and is at the closest distance from P, so you can "put" the normal beginning at S and passing trough P. It means that when you find S, the line segment SP that goes from S to P coincides with the normal you are interested in.

> How shall I select subset of edges (from all edges of polygon) that can be chosen to draw normal from point P

3) for each edge, you have to do the following. When you found the point S in the edge that is the closest from P, you made yourself a new line-segment available, which is SP.

4) so, test whether or not the line-segment SP intersects with any of the other edges (i.e. a simple line-segment vs. line-segment intersection test). If yes, then you know that the edge where S belong to, is **not** one you can chose a normal from that does not crosses other edges before hitting P or passing trough the exterior of the polygon.
> 0 votes

---
Tags: mathematics, geometry
---


title: Stop Unity from smoothening out images

text:
# Question
Title: Stop Unity from smoothening out images
In Unity, low-resolution images are "smoothened out". Is there a way to keep them pixelated?

For your information, the images that I'll be using are in PNG format.

# Answer
This effect is controlled by the Filter mode of the Image. You can change it in the Import settings.

To get a pixelated look, choose the option "Point (no filter)"
> 3 votes

# Answer
It so unusual but you may give a try to *Max Size* property of import settings.

* Select your picture (from Project explorer, not from Hierarchy).
* Set *Max Size* in inspector to lowest as much as you can.
> 1 votes

---
Tags: unity, image
---


title: Best way to structure SDL2/C++ game?

text:
# Question
Title: Best way to structure SDL2/C++ game?
I was reading some SDL2 tutorials and I noticed that you need to pass your window surface handle to any `drawRect` calls. Should I create a global surface handle or pass the handle by reference into draw functions?

Also for dealing with characters sprites, code structure-wise, which method would be more maintainable: each character object encapsulate its own set of sprites, or have a `Sprites` class hold all sprite information, and retrieve from there?

**Edit:** By Jon's advice, I'll probably look at generating one big texture sheet and reading off of that to reduce texturing binding overhead. As for the surface handle, I've created it as a private member variable in my `Game` class, and will pass it to any Draw calls that need it.

# Answer
> 4 votes
In general, the moderators close "best" or "better" questions because answers will be primarily opinions. Please revise your question, sooner than later.

No: Is it better to X or Y?
Everyone is right.

Yes: Given identical inputs, which is faster, X or Y?
One of the two is faster regardless of how anyone feels about it.

---

I have no experience with SDL2, however, this site contains a number of examples that make sense to me. It appears that you are free to maintain global pointers, if desired:

```
//The window we'll be rendering to
SDL_Window* gWindow = NULL;

//The surface contained by the window
SDL_Surface* gScreenSurface = NULL;

//The image we will load and show on the screen
SDL_Surface* gHelloWorld = NULL;

```

---

Both approaches to character sprites are likely to have advantages over the other in certain circumstances. You should always try to avoid iterating over large collections of CPU data, uploading and drawing it one object at a time. That being said, do things the *easiest way* possible. If circumstances require an atlas, you're going to use an atlas; otherwise, just keep it *simple* and iterate. If both ways are about equal, go with the one you know best.

As a beginner, give yourself some leeway and just focus on completely understanding topics and techniques, rather than trying to produce the "best" code possible. Otherwise, you'll get stuck in feature creep and/or continue solving problems you haven't even had yet. 60FPS is acceptable and attainable, even with disorganized and inefficient code.

---
Tags: c++, sdl2, architecture
---


# Question
Title: How should I construct a Facebook Login Flow for a server-less Windows App in Unity?
I am game programmer with limited web experience that was tasked to figure out how to make our game interact with Facebook. We are building a Unity Windows standalone app (maybe MacIntosh later), and our publisher wants us to enable the player to post in-game selfies to their wall in Facebook. That is all we need to do, we do not need to touch their friends list or anything else like that at all.

I have been digging to find out exactly how to do this, and the available advice online or prebuilt Facebook API Asset Store packages rely on the mobile API which we can't use. So, looks like we have to roll our own for the time being. I have been reading the developers.facebook.com section on Login Flow and it says that we should

1. Request a login dialog for the player with our App ID
2. Take the Access Token out of the response
3. Then combine it with our App Secret to make API calls

Facebook also says that for security reasons, we should never embed the App Secret into the source of our client exe, so that hackers can't disassemble the exe and pull our secret out for them to use for their own purposes. That makes sense. Instead, they recommend that the App Secret remain on a server and that our client delegate API calls to that server. Seems like a smart way to do it.

However, we don't have a server, our publisher won't pay us to make a server or maintain the hardware, and even if they did, we don't have time to make one. So, what is the best practice for a client-only native Unity standalone app?

# Answer
I guess this is the closest thing to an answer for the question:

https://stackoverflow.com/questions/1934187/oauth-secrets-in-mobile-apps

TL;DR: OAuth is not designed well for the non-web experience, and they have discussed ways to fix this (and Twitter & Yammer have their PIN method for this problem), but for right now, there is effectively no answer.
> 1 votes

---
Tags: unity, windows, facebook
---


# Question
Title: How can I procedurally render irregularly shaped health bars?
The issue of the traditional rectangular or heart-based health bar is something well-understood and easily solved. But what is the accepted solution for more "creatively-shaped" health bars, like the mockup I've made below?

The obvious way to do this would be to have "in-between" sprites, so the third image would be its own sprite, along with many other transitions for different levels of health. But that seems really inelegant and the number of in-betweens needed to create a smooth transition between health states would be large.

The only other idea I can come up with is to overlay the "full health" sprite on top of the "empty health" sprite and pre-bake sets of pixel coordinates to represent each tick of health and then make them opaque or transparent as health goes up or down.

I intend this question to be language and platform agnostic but feel free to provide a concrete sample in any language/library/framework if it helps the answer.

# Answer
> 49 votes
There is a very simple way achieving this with shaders, you need three\* textures: empty health bar, health bar texture and mask with gradient of health distribution with one extreme(e.g. darkest not black or most transparent alpha value) on one end and the other on other end. It is best shown on image, I am currently unable do draw curved gradient only linear one - but I am sure your artists wont have any trouble:  Now, in shader sample both textures and threshold the mask value, discarding all the pixels which are not brighter than input threshold (based on health % shader input).
You *could* use mathematical formula for masking instead of a texture, but if you did that, you would be still very limited to shapes you are able(=simple ones) to create with said formulas - and finding one is not trivial.
**see comments*

# Answer
> 35 votes
Implemented mathematically, as a pixel shader:

On the CPU, calculate HealthDirection and its' dot product with V2

On the GPU, calculate a normalized direction away from the centerpoint for each pixel. Compare each dot product to HealthDirections' to choose whether to shade "background", or in color.

If you "inverted" this algorithm and worked from the other direction, you could "un-slerp" each pixel's direction back into a percentage and compare them each to HealthPercent, instead. With each pixel's percentage calculated, peforming the fade from red to green on the GPU becomes trivial.

Draw the bar first applying the algorithm to a quad; output colors between rangeMin and rangeMax (could be baked) and clip() or output transparent every where else. Next, draw the (modified) sprite over it, using alpha. I traced your bar in CAD, flood-filled it, then "magic wanded" the solid color shape in Paint to delete it. Mine looks like crap due to mixing AutoCAD and Paint, by hand; assuming you blend the inner edges to transparent, yours will look **perfect**.

The white border is the limits of the quad. It and the red X's are for reference only:

The "sprite with hole" does not need to be rendered at the same time as the health bar. They should get instanced and drawn all at once, after all the health bars are complete. Since the algorithm is self-contained in the shader, you could also add instancing to it and then, also, draw all of the healthbars with one instanced draw call. Drawing every healthbar on the screen should take 2 DrawInstanced(...) calls and be "crazy fast".

---
Tags: 2d, graphics
---


# Question
Title: Rotation around arbitrary vector (using quaternions?)
I currently have a camera which orbits a specific target object, always looking at it.

The user can drag the mouse to move the camera left/right/up/down and the camera will move over the surface of a sphere of fixed radius (note, I clamp the vertical angle to ± 89°).

Currently it looks something like this...

```
// Store position of camera for future reference
private Vector2 rotation = new Vector2(120, 25);

// Was intended to be the vector from planet to target. Only works with `up`
private rotationalPole = Vector3.up;

if (isDragging) {
    rotation += new Vector2(
        Input.GetAxis("Mouse X") * xSpeed * radius * 0.02f,
        -Input.GetAxis("Mouse Y") * ySpeed * 0.02f);

}

//target is the GameObject to center on...

var pos = target.transform.position;

camObj.transform.position = pos + (Vector3.back * actualRadius);
camObj.transform.LookAt(pos, rotationalPole);
camObj.transform.RotateAround(pos, Vector3.right, rotation.y);
camObj.transform.RotateAround(pos, rotationalPole, rotation.x);

```

This works fine when `up` is in the `y` direction.

Now, however, instead of an object on the ground, the target is something in orbit around a planet (currently on an equatorial orbit but hopefully on an arbitrary one in future).

I want the camera to behave the same as before, but with `up` being the vector from the center of the planet through the target. Nominally forward will be the direction of orbit (but since the user can spin through 360 "horizontally", that's less important).

Currently it looks like this...

Basically, I'd like to rotate the image above counter-clockwise by 90° (which I believe I can do by playing with the camera transform's `up` and `right` vectors) but also that my arbitrary rotation honors the new orientation.

Some research shows that I need to use quaternions but while my mental model for basic trig is fine, I can't picture how to use quaternions correctly in this situation.

### Following on from @Jon's answer below...

I've now got the following.

```
var planetToTarget = (target.transform.position - planet.transform.position).normalized;
// "Reset" the camera before I do any transforms
this.transform.position = target.transform.position - tgtMovement * actualRadius;
this.transform.up = Vector3.up;
this.transform.LookAt(target.transform.position);

var camToTarget = (transform.position - target.transform.position).normalized;
Debug.Log(string.Format("targetMotion = {0}, planetToTarget: {1}, camToTarget: {2}", tgtMovement, planetToTarget, camToTarget));

// Line that's not working...
this.transform.Rotate(camToTarget, -90);

// To be added in when the above is working...
//this.transform.Rotate(Vector3.Cross(camToTarget, planetToTarget), rotation.y);
//this.transform.Rotate(planetToTarget, rotation.x);
//this.transform.up = planetToTarget;

```

The uncommented code (excluding the last line) keeps the camera behind the target, looking forward...

Initially, I get :

> targetMotion = (0.0, 0.0, -1.0), planetToTarget: (-1.0, 0.0, 0.0), camToTarget: (0.0, 0.0, 1.0)

Which generates:

However, as the target moves around the planet, it changes to:

> targetMotion = (0.4, 0.0, -0.9), planetToTarget: (-0.9, 0.0, -0.4), camToTarget: (-0.4, 0.0, 0.9)

By which point, the camera is slewing to the side...

So I'm clearly still missing something. I don't appear to be rotating around `camToTarget` correctly?

# Answer
> 2 votes
Once you calculate the new up, you'll want the lerp from old to new to take a few seconds. Additionally, if `CameraToObject` and `PlanetToObject` are coincident, a single plane cannot be defined. If the object is already selected, your vertical constraint will prevent `CameraToObject` and `PlanetToObject` from becoming coincident, however, if the two are **already** coincident when you click the object, or are made coincident **by** clicking the object, the algorithm will not work. So, if you go to calculate and detect that they are coincident, bump one a tiny bit; this will find *an* up vector, which allows the camera to begin lerping, which allows the vertical constraint to work.

The cross-product of the normalized `PlanetToObject` and `CameraToObject` directions is perpendicular to both vectors and is, by definition, the normal of a plane that contains both. The cross product of the plane's normal (perpendicular to the plane) and `CameraToObject` (a vector in the plane) is a second vector in the same plane, perpendicular to the first; the net-result is a rotation of `CameraToObject` 90 degrees around the face normal.

Note: I may or may not have reversed the order of the cross-products, but you only need to worry about it at the very end; the yellow vector should point to the "right of the camera"; invert it if it doesn't.

This was one of the hardest screenshots I've tried to diagram over; I had given up on making it look right but will post it anyway, since I think you'll still get it.

Regarding quats:

Consider the specific wording of your question. "I want to rotate the image counter-clockwise". That's also saying that you want to rotate the camera clock-wise around `CameraToObject`. In that case, `CameraToObject` is the Quaternion's vector component, and "90 degrees" is the scalar component. Quaternions *twist* inputs around their vector component by the angle stored in their scalar component.

You didn't know you've already been using quaternions for matrix math? With unit-axis vector components, the quaternion equation reduces to the appropriate axis-rotation matrices:

---
Tags: unity, camera, rotation, quaternion
---


title: GLSL strange if statement problems

text:
# Question
Title: GLSL strange if statement problems
I'm trying to use `if` statement in my fragment shader.

I want to compare my `in int finalLightType[4];`

Here is my vertex shader code and fragment shader code:

Vertex:

```
#version 400 core

in vec3 position;
in vec2 textureVector;
in vec3 normalVector;

out vec3 color;
out vec3 surfaceNormal;
out vec2 textureCoords;
out float visibility;
out vec3 toLightVector[4];
out int finalLightType[4];

uniform vec3 mainColor;

uniform mat4 transformationMatrix;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;

uniform float tilingX;
uniform float tilingY;

uniform float density = 0.01;
uniform float gradient = 1.5;

uniform int lightType[4];
uniform float lightRange[4];
uniform vec3 lightPosition[4];

void main(void)
{
    finalLightType[0] = 1;
    color = mainColor;

    textureCoords = textureVector;
    textureCoords.x = textureCoords.x * tilingX;
    textureCoords.y = textureCoords.y * tilingY;

    vec4 worldPosition = transformationMatrix * vec4(position,1.0);

    vec4 positionRelativeToCam = viewMatrix * worldPosition;

    float distance1 = length(positionRelativeToCam.xyz);

    visibility = exp(-pow((distance1 * density), gradient));
    visibility = clamp(visibility,0.0,1.0);

    surfaceNormal = (transformationMatrix * vec4(normalVector,0.0)).xyz;

    gl_Position = projectionMatrix * positionRelativeToCam;
}

```

You can see `out int finalLightType[4];` and `finalLightType[0] = 1;`

Fragment:

```
#version 400 core

in vec3 color;
in vec3 surfaceNormal;
in vec2 textureCoords;
in float visibility;
in vec3 toLightVector[4];
in int finalLightType[4];

out vec4 out_Color;

uniform bool textured;

uniform sampler2D sampler;

uniform vec3 bgColor;
uniform vec3 ambientColor;

uniform vec3 lightColor[4];
uniform float lightIntensity[4];
uniform vec3 lightDir[4];
uniform float lightSpotAngle[4];

void main(void)
{
    vec3 unitSurfaceNormal = normalize(surfaceNormal);

    if(finalLightType[0] == 0)
    {
    }

    if(textured == true)
    {
        out_Color = texture2D(sampler,textureCoords);
    }
    else
    {
        out_Color = vec4(color,1.0);
    }

    out_Color = mix(vec4(bgColor,1.0),out_Color,visibility);

    vec3 convAmbientColor = vec3(1.0,1.0,1.0) - ambientColor;

    out_Color = out_Color - vec4(convAmbientColor,1.0);

    out_Color.w = 1.0;
}

```

Everything looks good, but if I start my game I receive really strange effect (Uncolored, untextured, transformed on the front of the camera object):

But.. If I try to compare another int same way, but not `in` variable, but local variable (Or even uniform variable, they works fine too):

```
#version 400 core

in vec3 color;
in vec3 surfaceNormal;
in vec2 textureCoords;
in float visibility;
in vec3 toLightVector[4];
in int finalLightType[4];

out vec4 out_Color;

uniform bool textured;

uniform sampler2D sampler;

uniform vec3 bgColor;
uniform vec3 ambientColor;

uniform vec3 lightColor[4];
uniform float lightIntensity[4];
uniform vec3 lightDir[4];
uniform float lightSpotAngle[4];

void main(void)
{
    vec3 unitSurfaceNormal = normalize(surfaceNormal);

    int lightTyp = 0;

    if(lightTyp == 0)
    {
    }

    if(textured == true)
    {
        out_Color = texture2D(sampler,textureCoords);
    }
    else
    {
        out_Color = vec4(color,1.0);
    }

    out_Color = mix(vec4(bgColor,1.0),out_Color,visibility);

    vec3 convAmbientColor = vec3(1.0,1.0,1.0) - ambientColor;

    out_Color = out_Color - vec4(convAmbientColor,1.0);

    out_Color.w = 1.0;
}

```

It only happens if I compare `in` variables, everything is works fine with uniform variables, local variables, etc.. (Also tried with varying variable).

Edit:

This object after I run my game is always on the front of the camera and never rotates or whatever. I can't also see other object like a cube that should appear something (probably my camera is inside this cube and I can't see it because of culling faces).

# Answer
> 3 votes
As per the GLSL Language Specifications section 4.3.4 "input variables":

> Fragment shader inputs that are signed or unsigned integers, integer vectors, or any double-precision floating-point type must be qualified with the interpolation qualifier "flat".

That is, these types cannot be smoothly interpolated between vertices the way that input variables are by default. Therefore, the GLSL specification states that your shader must explicitly state that it doesn't expect them to be smoothed.

You can do this by replacing your current variable declarations with these lines:

```
flat out int finalLightType[4];

```

and:

```
flat in int finalLightType[4];

```

It surprises me that you don't get compile errors from your current code; my understanding is that most drivers will outright refuse to compile your original GLSL code at all.

---
Tags: c++, glsl
---


title: Should FPS exceed ticks/second?

text:
# Question
Title: Should FPS exceed ticks/second?
I was once told that you should never re-draw a frame if the game logic has not changed since the last draw.

Assuming game logic is updated once every tick, and assuming a game runs at 40 FPS @ 20 ticks/second, does that mean that every two consecutive frames will be exactly the same? If so, is there any visual difference between a game running at 40 FPS @ 20 ticks/second versus a game running at 20 FPS @ 20 ticks/second?

Perhaps I don't understand game loops that well, but it seems to me that ticks/second is a limiting factor of FPS.

# Answer
Your engine and your game must be super flexible to allow the possibility of drawing two times with no state change.
A usual game loop ties very closely all updates in a sequential fashion.
One thread, one loop, one point to flush events, one point to execute processing updates (entity/component processors, or simply manager's updates), and finally one render call which triggers the whole engine 1-frame render.

Whole engine 1 frame render can be made in two fashions, extrospective (intrusive), by accessing (with visitors) the state of the drwable objects of the game, and create the rendering states, passes and commands that go with it.

Or it could be fully **retained**, and the state of the engine was set BY the processors during the logic update, and it holds sufficient information per se to draw a frame in isolation.

This is a classical game loop. It uses a `delta_time` variable that is given to all managers during update.

If you have a physical manager, usually there is another loop within the Update itself, that will use a fixed `dt` and iterate as many time to fill the lagging-time to reach `delta_time`. And store the remainder for the next frame's refresh, to execute as part of the first loop next time.

Now, its possible to have a more advanced game loop by separating event treatments, by using a thread specific system event queue, preparing a pool of timestamped events, and when the main thread is in the event treatment update, it pulls this queue.

Its hardly possible to completely asychronize managers updates and frame rendering. Many engine state updates are not atomic. Even a fully retained engine will have limitations. DirectX11 introduces isolated command lists (deferred devices, in their parlance), which can help to design such an engine. But if you have such basic doubts about your own render loop, I suppose you don't use such things, yet.

Since you are in java, and you talk about ticks, I imagine you must have plugged your refresh function to a periodic timer. Of course this is sub-par as a game loop design, even from the most basic loop design described above. This is not how real time systems are designed, doing this, you rely on a framework, that depends on operating system native kernel tick rate, and java's virtual machine to relay you the wakening events (and scheduling) to fire up your frame routine. This will incur bad sampling rates (aliasing) and randomness from various sources. You will have to suffer from potentially long sleep times that are not controlled, in the thread ready queue, or kernel timer tick rounding issues. This will all misalign with your framerate presentation, and result in stutterings, and if the event queue is not fully depleted at each refresh, you will also have input lag, and potentially, building up with time. Worse, since you are event based, your events I fear, are consumed by event treatment, therefore your processing time will vary according to input, and delay your frame rendering. Potentially totally masking it out. This is like a security flaw, lots of input could overflow the game and make it unresponsive.

Event based systems are not made for real time applications, they are made for **basically idling applications**.

Now, back to your question, it should not be a problem to fraw at 40FPS when your game updates at 20. Also be careful, in a timer based system, 20 FPS = 50ms, it will likely round up to 60ms (4\*15 ; 15=typical kernel), therefore you'll get 16FPS. Use some precise chronometers to display frame update time on screen, and another one to display display rate. (use a counter around the `Present` call. Or framebuffer `Swap` (OpenGL term), or simply install Fraps.)

This will give you some statistics.

The people advocating that high display rates are bad probably refer to useless loss of resource, resulting in machine heating up, or the useless frame taking time to finish, the GPU is not ready to render the next frame when its ready, that is to say, likely right in the middle of the useless redraw. Which is why, no redraw = better responsiveness, leaving the GPU available right away when the next frame is ready.

Also tearing, is an argument often heard. Tearing is caused by swappings (presentations) frequencies that are non multiples of the screen frequency. the `VSynch` is the feature that helps that, by using hardware support, the VGA/DVI/HDMI cable transports a tick signal that says "I flipped!", the graphic cards receives it, signal it to the CPU with an interrupt (most likely), and the driver gets it and communicate it to the currently waiting OpenGL/DirectX presenting threads. This unleash a fast back-to-front copy, which executes in much less that the 60Hz timeframe, and then when the screen next flips, a full image is presented, this avoids perfectly the **tearing**.

The best is to respect this presentation rate, it is a tempo given by hardware, and the whole game/engine thread is put to sleep by the graphics API itself inside of the `Swap`/`Present` call, which allows to rest the CPU, allowing it to cool down, and allows perfect frame/game synchronization if using a linear loop like mentioned above.

Provided your game can update faster than 60Hz. Otherwise, it will fallback immediately to 30Fps naturally, then 20, then 15, by plateaus. This is a natural response.
> 2 votes

# Answer
It depends on your design.

If you have **interpolation/extrapolation** in your render layer, then any extra frames will add to the smoothness on animation. For example particle effects don't affect games logic and can use much higher framerates. Your GUI might work at higher framerates to respond to player interaction faster.

If there's indeed no change between frames (**no interpolation/extrapolation/GUI**), then skipping the extra frames is beneficial, since that extra frame might overlap with next ticks frame, delaying it.
> 2 votes

# Answer
Consider Minecraft as an example of when this is a good idea. Minecraft runs at a fixed 20 ticks per second, but can run at hundreds of frames per second if allowed. The frames between ticks are not identical - actually Minecraft interpolates movements and animations to smooth them out, so with a higher framerate you will see smoother movement. This is a good way to offset the high resource requirements of ticking with the low resource requirements of drawing. It also allows very smooth movement when looking around - the camera movement need not be constrained by the tick rate.
> 1 votes

---
Tags: java, game-loop
---


# Question
Title: How can I check if the player clicks (or doesn't) on a target within a time limit?
In GameMaker, I'm trying to set up something like this:

The player will need to click on some object within three seconds. If they click on it within the timeframe, I'll do one thing (call `room_restart()`). Otherwise the game is over.

How can I set this up?

# Answer
> 1 votes
Basically you will need two variables and set alarm\[0\] for 3 seconds (or however many you want) in the create event of whatever is being clicked or handling the clicking. One can be called click the other timeup. Set both to zero. click will be used to check if the player clicked within the amount of time given. timeup will only be used to see if the time is up. Add the event for alarm\[0\] and make sure you set timeup to 1. Then make a click event and have it first check if timeup still equals 0.... if so set click to 1. then you can use this click variable for whatever you want. If it's 1 the player managed to click it in time. If it's zero the player failed. In my example I added another object that simply changes color depending on if the first object was clicked.

You can download my two example below if you want. One is all in code the other is all in drag and drop.

There is a black button that you have 5 seconds to click starting as soon as the game starts. There is also a white box that will change color after 5 seconds depending on if you clicked it or not. It will turn green if the black button was clicked and red if it was not.

http://www.mediafire.com/download/yiauc1u7own2ii4/Click\_Timer\_Example.zip

If this isn't quite what you were going for tell me because I was slightly confused by your description. I just went with what it sounded like you needed rather than just detecting when the player is not clicking because while possible that wouldn't be a very good way to solve this problem.

---
Tags: timer
---