# Question
Title: Distance travelled by gameObject and behavior depend on device's performance?
The distance travelled by my gameObject and behavior depend on my device's performance. If the device is slow for example, it takes longer to accomplish a specific task, thus travels at a smaller speed, smaller distance etc. and doesn't end up where it's supposed to. How can I fix this?

Here's the code:

```
variable1 -= variable2 * Time.deltaTime;
transform.position += new Vector3 (13, variable1 * Time.deltaTime, 0);

```

# Answer
I don't know if you're fully understanding why delta time is used. So here's a quick recap.

---

Say you have an object that you want to move at a constant speed, such as 100 units. To update its position, lets say you call a method *UpdatePosition()*;

Assuming that *UpdatePosition()* is called within a physics engine loop, a separate thread, or a part of just some loop in general, that function is automatically at the mercy of the speed of that loop, or rather its rate is limited to how fast the things before it finish. That's fine and dandy.

This means that the speed of the object that you want to move will vary depending on how busy and how fast the CPU is.

One method of dealing with this, is instead of declaring an amount of space an object should move, you should instead figure out how much you want it to move per unit of time. So if we wanted to move the object 100 units every second, then a timer object should be used to **record the time that it takes from the end of the last time you updated the object to the start of the following time you want to update the object.** So if for some reason it took 3 seconds to get around to being able to update the object, and you have a rate of 100 units per second, then the value that the object will update by will be:

> 100 units * 3 seconds = 300 units

So some pseudocode would look like this:

```
void UpdatePosition()
{
    float timeOld = getOldTime();
    float timeCurrent = getSystemTime();
    float difference = timeCurrent - timeOld;

    float rate = 100.0f; // 100 units every second, on X Axis
    float desiredAmount = rate * difference;

    Vector3 desiredVector(desiredAmount, 0, 0);
    setOldTime(timeCurrent);
}

```

---

Now looking at the snippet of code you provided us:

```
variable1 -= variable2 * Time.deltaTime;
transform.position += new Vector3 (13, variable1 * Time.deltaTime, 0);

```

We can see that you have something similar, you have some sort of a rate defined as variable 2 multiplied by a change in time. You then proceed to take it away from some other var, variable1. That makes sense if you are treating variable 1 as like the momentum of the object or something, and are degrading it over time. However for some reason you are only doing this to the second value of the vector, or rather only its **Y-Axis**. Further, you're then multiplying it again by the rate. But none of this is done to that constant 13 you have for the **X value**
> 2 votes

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


# Question
Title: XNA - Efficient way to get pixel color from rendertarget2D
I'm stuck with a framerate perf down with getData from a rendertarget, what's your idea, what are the other options I can use ?

I explain my problem : I'm making a board game, the objects or monsters are overflow the board rooms, I use kryton framework to manage light sources, krypton is an efficient 2D pixel shader raycasting engine, I've made Hulls (#blocking light blocks) all around the rooms of my board, but the objects and monsters Texture2D were cutted by the hull shadows of the board sides... So I can't use Krypton to light my monsters

krypton give me a rendertarget of the screen which is a screen light color map If I pick color from center board square, It give me the perfect color to draw my monsters, but with getData it's reaaaallllyy slow.

I'm using this code :

> public Color GetLightColorOnPoint(Vector2 position) {
> Vector2 v = WorldToScreen(position); return lightManager.GetLightColorAtPoint((int)v.X, (int)v.Y); }
>
> public Color LightManagerClass.GetLightColorAtPoint(int x, int y) { Color\[\] lightPixel = new Color\[ 1 \]; Rectangle sourceRectangle = new Rectangle(x, y, 1, 1); //rendertarget2D
> this.krypton\_SolShadow.mMap.GetData(0, sourceRectangle, lightPixel, 0, 1); return lightPixel\[0\]; }

(I don't understand well pixel shaders and I don't think you can pick a board square center color and apply it to an entire monster texture2D with the correct offset/zoom of a camera 2D of course and variable texture2D size (a giant vs a rat texture2D size))

with 40 GetData (40 monsters on screen) per draw, the FrameRate slow down to 7 FPS :(, please help

# Answer
So you have a lightmap in a texture, and later in the drawcall you want to use that information as a base to draw sprites. Create a shader for this. The shader should have the lightmap as a register, and a parameter should be the position you want sampled. This one is updated for each sprite. Start a spritebatch with the effect, and draw all sprites with it. It should then tint everything on GPU power only. Note the code below is all from my head as I have no XNA near me right now, so *it is untested*. But it should show the basic principle.

```
//set the lightmap in the GPU's register.
GraphicsDevice.Textures[1] = this.lightManager.krypton_SolShadow.mMap;

//begin the spritebatch with the "tint" effect.
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied, null, null, null, tinteffect);

foreach(GameEntity entity in entities)
{
    //note, the shader expects coordinates to be between 0.0 and 1.0.
    tinteffect.Parameters["lightmappos"].SetValue(new Vector2(entity.Position.X/lightmapwidth,entity.Position.Y/lightmapheiht));

    spriteBatch.Draw(entity.texture,entity.position,Color.White); // your draw call here;
}

spriteBatch.End();

```

The shader should have a sampler set up for the lightmap like this:

```
sampler LightMapTexture: register(s1); //note s1 corresponds to GraphicsDevice.Textures register 1.

```

And you can read the value like this:

```
float4 entitycolor = tex2D(s0, coords);
float4 tintcolor = tex2D(LightMapTexture, lightmappos.xy);

```

Entitycolor should now have the color value of the pixel in the sprite that is being drawn. Tintcolor holds the sampled color in the lightmap at the provided coordinates. You can then return the color of the pixel using these 2 values (for example mutiply them?):

```
return entitycolor*tintcolor;

```

I did a quick Google for you, this tutorial seems a nice starting guide for shaders: https://gmjosack.github.io/posts/my-first-2d-pixel-shaders-part-1/
> 0 votes

# Answer
One Big GetData of all the fullscreen renderTarget per draw seems to be more efficient than doing multiple GetData of one pixel per object to draw

```
        public override void Initialize()
        {
                    ....
            //initializing the Color Table
            this.lightManager.LightMap = new Color[this.graphics.PreferredBackBufferWidth * this.graphics.PreferredBackBufferHeight];
        }

       public override void Draw(GameTime gameTime)
       {
            ...
            //getting the lightMap from krypton
            this.lightManager.krypton_SolShadow.mMap.GraphicsDevice.SetRenderTarget(null);
            this.lightManager.krypton_SolShadow.mMap.GetData<Color>(this.lightManager.LightMap);

            //for each object get the color (do not affect the FPS)
            //Object position (x,y)
            Color objectColor = this.lightManager.LightMap[this.krypton_SolShadow.mMap.Width * y + x];
       }

```

if I found a better solution, I share...
> 0 votes

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


# Question
Title: Unity>How to make a Box Collider( or any other collider) fits the gameObject perfectly?
I have downloaded and imported the Robot Kyle model in Unity 3D...and the problem with me is I want to add a Box or Capsule Collider to it...but I can't fit it perfectly...

So what shall I do?

# Answer
You could use a mesh collider and enable convex check box :)
> -2 votes

---
Tags: unity
---


# Question
Title: Unity UI Button not working on PC build but working on Android mobile build
I am using Unity to build a game that is going to be used on PC and Android mobile devices. The problem I have is that when I use a UI Button, it works perfectly on mobile, but on PC and in the editor, is not working.

Why could this be happening?

# Answer
I found out why this is happening. I use player preferences to store some user settings, and after I tested the app a few times on my Android device, I decided to modify the script. The previous settings remain saved after the update, so it worked on mobile devices, but on the PC it was never used so there was no previous settings to work from.
> 1 votes

---
Tags: unity, android, gui, pc
---


title: Tetris: 2D Rotation Matrix?

text:
# Question
Title: Tetris: 2D Rotation Matrix?
I'm creating a Tetris clone right now. I've got the tiles of `tetromino` stored as an `std::array<tile, 4>`. Each `tile` holds its (x,y) coordinates relative to the piece. For example, the `t-block` is:

```
(-1, 0)
( 0, 0)
( 1, 0)
( 0,-1)

```

I want to create a function: `rotate(const bool clockwise)` that applies a 2D rotation matrix to the tiles to rotate the block either 90 degrees clockwise, or 90 degrees counter-clockwise.

After doing some reading on rotation matrixes, I've found that a 2D rotation matrix looks like this:

```
 cos(angle), sin(angle)
-sin(angle), cos(angle)

```

Since I'm doing 90 degrees only, I figure it should look like this:

```
//clockwise
 0, 1
-1, 0

//counter-clockwise
 0,-1
 1, 0

```

After doing some more reading on how to multiply matrixes, multiplying the tile position by the matrix gives me this:

```
//(-1, 0) should end up as (0, 1) if rotated clockwise

-1                     0, 1                1,-1
 0  /*multiplied by*/ -1, 0  /*gives me*/  0, 0

```

**My question is** how do I get an (x,y) position out of that result? Am I missunderstanding how matrixes work? Is there a more trivial way to rotate coordinates around the axis by 90 degrees?

# Answer
At 90 degrees, you can work out rotations in both directions just by swapping and reversing positions. Begin with the following shape:

Ahead, we rotate it manually clockwise, and look at the resulting positions (grey dots are rotated positions):

Analyzing point *B*'s position: Before transforming, it was (1, 2). After transforming, it was (-2,1). If you look at the other points, they all follow the same pattern: *Protated=(Py,-Px)*

Applying the same principle you can find a similar property for counterclockwise 90-degree rotation: *Protated=(-Py, Px)*

And we never touched any matrices! **However**, note that this method rotates around the center (0,0)! So you should operate on the relative positions of the tiles, and not their world position (you would have to do that too with matrices, but it's always good to note).

---

# Reiterating:

* Clockwise: *Protated=(Py,-Px)*
* Counter-clockwise: *Protated=(-Py, Px)*

Addendum: All paragraphs in this answer start with the letter A. Don't ask me why...

P.S.: Here is a interactive demo (requires Java): http://tube.geogebra.org/m/Qg9fcEwE
> 3 votes

---
Tags: c++, 2d, rotation, matrix
---


# Question
Title: Duplicating and adding sprites at runtime in Unity
I am trying to create a 2D game in Unity in which objects keep falling from top and the player has to dodge them. Suppose I have created a sprite which serves as a single enemy that the player has to dodge.Now I have to create multiple such sprites at runtime so that they can keep on spawning from random positions.Despite searching on the net for quite some time i could not find a clear answer.

I am just a newbie and I am just starting to learn game development in Unity so answers in detail will be very helpful.

Thanks in Advance.

# Answer
You do it in Unity by creating prefabs in editor (see video) and then instanciating them in script (read manual) or in editor.
> 1 votes

---
Tags: unity, sprites
---


title: XNA Get model height in location

text:
# Question
Title: XNA Get model height in location
I am trying to make simple RTS game, and here is the problem I encountered. I need to get model height in any position. Model will not be rotated or scaled. For example, I have a terrain model like this:

and I want to get terrain height in unit\`s position to place it correctly.

Thanks in advance!

# Answer
> 1 votes
You would have to extract all triangles from your terrain model and do a collision check on them. Preferably line against the triangle plane. XNA has methods for this but let's start by extracting the mesh data.

A XNA model contains Meshes which contains MeshParts which contains the Vertex buffer and Index buffer. You have to construct the triangles from these if you want to check collisions on them. You should not do this per frame of course but at initialization and store a Triangle list for later usage.

Start by creating a simple class that holds your triangles and a list for storing them.

```
class CollisionTriangle{
     public Vector3 [] v;
     public CollisionTriangle()
     {
         v = new Vector3[3];
     }
}

List<CollisionTriangle> triangles = new List<CollisionTriangle>();

```

You then iterate through your model and and fill up the list.

```
foreach(ModelMesh mesh in MyModel.Meshes){

    Matrix transform = CreateTransform(mesh.ParentBone);
    foreach (ModelMeshPart meshPart in mesh.MeshParts)
    {
           ExtractMeshPart(meshPart, transform);
    }
}

```

Meshes has it's on Transformation space, there isn't ONE model space all vertices are located in. You create the current mesh space by going through the bone structure and build a matrix. This is used later when transforming the vertex positions to world space.

```
Matrix CreateTransform(ModelBone bone)
{
    if (bone == null)
        return Matrix.Identity;

    return bone.Transform * CreateTransform(bone.Parent);
}

```

This is where the vertex data is extracted and stored in your list:

```
public void ExtractMeshPart(ModelMeshPart meshPart, Matrix transform)
{

            VertexDeclaration declaration = meshPart.VertexBuffer.VertexDeclaration;
            VertexElement[] vertexElements = declaration.GetVertexElements();
            VertexElement vertexPosition = new VertexElement();

            foreach (VertexElement element in vertexElements)
            {
                 if (vert.VertexElementUsage == VertexElementUsage.Position && vert.VertexElementFormat == VertexElementFormat.Vector3)
                       vertexPosition = vert;
            }

```

The VertexDeclaration tells us how the Vertex buffer is structured. We are only interested in retrieving the position part but this could be used for normals, UV, etc. as well.

```
Vector3 [] allVertex = new Vector3[meshPart.NumVertices];
meshPart.VertexBuffer.GetData<Vector3>(
                meshPart.VertexOffset * declaration.VertexStride + vertexPosition.Offset,
                allVertex,
                0,
                meshPart.NumVertices,
                declaration.VertexStride);

```

This is pretty straight forward, we allocate a array to store all vertex positions, send the offset and vertex stride to GetData() and it fills our array. Yay! But we still don't have any triangles so we need to get the indices as well.

```
short [] indices = new short[meshPart.PrimitiveCount * 3];
meshPart.IndexBuffer.GetData<short>(meshPart.StartIndex * 2, indices,  0,  meshPart.PrimitiveCount * 3);

```

Here is almost the same thing, indices are stored as short in XNA models so we create an array with the correct size. Please note that I assume the mesh is triangulated!

Before filling up your triangles and storing them away we need to transform the vertices from model space to world space. We use the transform we created earlier.

```
for (int i = 0; i != allVertex.Length; ++i)
{
    Vector3.Transform(ref allVertex[i], ref transform, out allVertex[i]);
}

```

And now we are ready to create triangles and fill up our list.

```
for (int i = 0; i < indices.length; i+= 3)
{
     CollisionTriangle triangle = new CollisionTriangle();
     triangle.v[0] = allVertex[indices[i]];
     triangle.v[1] = allVertex[indices[i + 1]];
     triangle.v[2] = allVertex[indices[i + 2]];

     triangles.add(triangle);

}

```

Now we have a triangle list to check collisions on each frame! (or rather after X frames for optimizations) For each unit that's moving, go trough all triangles check if it's position is within the three vertices. If so create a plane from the triangle and do a ray vs plane collision check, the unit should be placed at the intersection point.

```
foreach(RTSUnit unit in Unitlist)
{
    foreach(CollisionTriangle tri in triangles)
    {
       if(InsideTriangle(unit.Position, tri))
       {
            Vector3 rayStartPos = unit.Position + Vector.Unity * 100;
            Ray ray = new Ray(rayStartPos , -Vector3.UnitY);
            Plane plane = new Plane(tri.v[0], tri.v[1], tri.v[2]);

            float? intersectDist = ray.Intersection(plane);

            if(intersectDist != null)
                unit.Position = ray.Position + ray.Direction * intersectDist;

       }
    }
}

```

We start the ray from a bit up in the air to make sure we hit the ground even if moving up a slope. If there's an intersection intersectDist will tell us how far away from the rayStartPos the point is. That's where the ground is!

The way we check if the point is inside or not is by measuring the angles to the vertices from the point. If the combined angles are roughly 360 degrees then it's inside, otherwise it's not.

```
bool InsideTriangle(Vector pos, CollisionTriangle tri)
{
            Vector3 vec1 = Vector3.Subtract(tri.v[0], pos);
            Vector3 vec2 = Vector3.Subtract(tri.v[1], pos);

            vec1.Normalize();
            vec2.Normalize();

            double dotV = Vector2.Dot(vec1, vec2);
            double angle = (float)Math.Acos(dotV);

            vec1 = Vector3.Subtract(tri.v[1], pos);
            vec2 = Vector3.Subtract(tri.v[2], pos);

            vec1.Normalize();
            vec2.Normalize();

            double dotV = Vector2.Dot(vec1, vec2);
            double angle = (float)Math.Acos(dotV);

            vec1 = Vector3.Subtract(tri.v[2], pos);
            vec2 = Vector3.Subtract(tri.v[0], pos);

            vec1.Normalize();
            vec2.Normalize();

            double dotV = Vector3.Dot(vec1, vec2);
            double angle = (float)Math.Acos(dotV);

            float tolerance = 0.001f;

            if(angle > (Math.PI * 2) - tolerance)
                return true;

            return false;
}

```

We need to add a tolerance to the check because of float precision, angle is never going to be exactly 360.

That should be it! But please note that depending on terrain mesh detail, size and number of units this could be really slow. So if you are going with this solution I recommend having a collision mesh. Meaning a simpler mesh than what's being rendered. It should be as low poly as possible. Also you might want to split up the terrain mesh in smaller pieces so each unit doesn't have to check a huge triangle list each time.

Disclaimer, I wrote this here, the code has never been compiled so I suspect a few typos but you should be able to figure it out I think.

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


# Question
Title: Extrapolating performance on cheaper devices
I am in the final stages of developing a game with XNA and MonoGame and am planning to release it on Windows Phone and Android. I personally have a Blu Win HD LTE and my father and sister have a Nexus 5 and Moto e, respectively.

I am testing on all of these devices. What I am unsure of is how to extrapolate what the performance will be on cheaper devices, like a Lumia 630. I already can use profiling on my phone to make sure I'm under the 185MB memory limit, but I'm not sure what the framerate/performance will be.

I am looking for a way to roughly estimate how much slower the performance will be based on some variable (processor speed, GPU model, number of cores, etc.), such that I can tune performance on my current device and be assured of performance on cheaper devices. Has anyone tried this?

# Answer
The only reliable option is to test on the actual devices you care about, or at least devices with the same GPU / CPU. This can get expensive though.

The easiest option is to let your users tell you what the performance is like on slower devices. You could give away a few beta copies to people with different hardware and ask them for feedback. You could also expose some configuration settings for them, so they can trade off performance and rendering quality.

Having said that, there are some things you can do to improve your guesses as to how it will perform.

To start with you need to do some detailed profiling to work out if you're CPU or GPU limited on performance. The limiting factor can guide your guesses about other devices.

For example how many CPU threads are doing work when your game is running? If you only use one or two threads it doesn't matter how many CPU cores are available.

Once you understand your performance, you can find some GPU and CPU benchmarks that have been run on both the devices you know about, and the ones you're interested in. Based on those benchmark results, and what you know about how your game uses the CPU and GPU you can estimate how fast it will run on the other hardware.
> 1 votes

---
Tags: xna, performance, monogame, windows-phone-8
---


# Question
Title: Collision happens even though the objects are not colliding according to what we see
I'm trying to build a pool game as my first phaser project.

The biggest challenge today was to make the cue rotate around the white ball. After hours of searching and not finding anything useful (there is an example about rotating points but no sprites) I was able to create something, not very clean but it works.

Here is the white ball

```
    balls = game.add.group();
    balls.enableBody = true;
    balls.physicsBodyType = Phaser.Physics.P2JS;
    wball = balls.create(350, 240 , 'ballW');
    wball.body.setCircle(15);
    wball.body.setCollisionGroup(wballCollisionGroup);
    wball.body.collides([wballCollisionGroup, ballsCollisionGroup , sidesCollisionGroup , holesCollisionGroup , playerCollisionGroup]);
    game.physics.p2.setImpactEvents(true);

```

Here is the cue which i call it player

```
player = game.add.sprite( 0   , 0   , 'player');
game.physics.p2.enable(player);
player.enableBody = true;
player.body.setCollisionGroup(playerCollisionGroup);
player.body.setZeroVelocity();
player.body.createBodyCallback(wball, ballHit , this);
player.anchor.setTo(-0.5, 0.5);
player.pivot.x = wball.x +150;
player.pivot.y = 0;

player.body.x = wball.x  ;

setTimeout(function(){
     player.body.y = 150 ;
} , 1000 );

setTimeout(function(){
     player.body.y = 200 ;
} , 2000 );

setTimeout(function(){
     player.body.y = 240 ;
} , 3000 );

```

As you can see I have set the `y` position for player in 3 steps to demonstrate the problem .

It starts at the top of the page and comes down as soon as i set `y=240`, which is the wball y a collision happens even though we can see clearly they are not colliding.

Pleaes note both codes are in the create function. Here is the live code: http://199.26.84.223/

# Answer
The physics body is offset from the sprite body, causing collisions to happen to the right of the displayed sprite for the pool cue. To see what I mean, enable debugging on the P2 body by changing: `game.physics.p2.enable(player);` to `game.physics.p2.enable(player, true);`

The second parameter, as specified in the documentation here (http://phaser.io/docs/2.4.3/Phaser.Physics.html#enable) enables optional debugging on the physics object.

As you can see in the following image, this is the physics body:

This can be "fixed" by removing the lines

```
player.anchor.setTo(-0.5, 0.5);
player.pivot.x = wball.x +150;
player.pivot.y = 0;

```

But I have a feeling that you intended to have the cue rotate about the end of the stick. I'm unsure of how to accomplish that.
> 3 votes

---
Tags: 2d, physics, html5, phaser
---


# Question
Title: Java 2D Game Hitbox Detection & Rounded Corners
I am working on a simple 2D game with Java, Swing and no framework. I have a rectangular player that the user can move around. On the map are few obstacles which the player should not be able to go through. I did this by making a new Rectangle Object for the player and each obstacle with their bounds. But I’m not really sure if this is the right way to do it. It works but the movements of the player are not really user friendly. If the player wants to pass two obstacles they must be on the perfect coordinates to pass.

Is it even a good idea to check for intersections between the player and the obstacle with a Rectangle object or should I do it another way?

Now for my 2nd question:
I’d like to replace the rectangular hitboxes with the same hitbox but with rounded corners so the player could pass more easily.

This is what the game looks like with hitboxes enabled.

The code that checks if the player and the obstacles have yet intersected:

```
for (Player p : this.getPlayerArray()) {
    Rectangle recPlayer = p.playerBounds();
        for (Obstacle kiste : obstacleArray) {
            Rectangle recKiste = kiste.obstBounds();

            if (recPlayer.intersects(recKiste)) {
                p.setX(100); //Not actual code here
            }
        }
}

```

The function that returns the hitbox of the player / obstacle:

```
public Rectangle obstBounds() {
    return new Rectangle(this.getX(),
    this.getY(), image.getImage().getWidth(null),
    image.getImage().getHeight(null));
}

```

# Answer
> 1 votes
Here's why you probably don't want to use a rounded rectangle to try to fix your problem:

Now, getting stuck on the edge like that is probably just as frustrating, if not more, than not being able to move right at all.

I think you probably want to employ some error correction when you move. What I mean is, when your character moves, let's say, right, if there's a collision don't move back right away! Instead, move the rectangle up and down about 5 pixels (1 pixel at a time) to see if it can avoid a wall. Same for the other arrows. When moving up, if there's a collision, check if you can avoid it by moving left and right.

I've posted an answer similar to this before which you might find helpful:

How can I detect a perfect passageway for collision detection? // see method 1

The second thing you can do here which is common in a lot of tile games like yours is to move the character exactly 1 tile every time you move. So if you tap the right arrow and then release it after the character only moves a few pixels, the character will keep moving until it is in the center of the next tile.

Hope this helps! :)

# Answer
> 0 votes
As it is said, you should make one post per question.

You can use a circle collider instead of a rectangle collider. Set the circle radius by experimentation.

You can also implement a combination of both, if you care about extreme precision, but a circle should be enough for your purposes.

# Answer
> 0 votes
Set your player bounds or object bounds to a couple pixels less than the actual object is. I usually do about 5 each way. That way you have a little leeway going in between objects.

---
Tags: java, collision-detection, intersection, swing
---


# Question
Title: Change 3ds max mesh local origin pivot point
I'm developing a 3D videogame in C# with XNA, my problem comes when I load my model done in 3ds max, and I try to rotate a mesh of it, because the pivot point isn't exported so it takes the local origin of the mesh, the point you get when pressing "Reset Pivot" in 3ds max.

What I want to do is to change its point default value, so that my animation gets the correct pivot point, how can I achieve this?

Thanks in advance! :)

# Answer
> 0 votes
Well, as we talked in comments, the way to fix it was to reset transform matrix with the Xforms modifier.

# Answer
> 4 votes
find here a good description of why this problem exists and a script to solve it: xna3ds script

# Answer
> 0 votes
Another way to fix this, make your shape an editable mesh & move every vertex so that the current center is where you want it to be. Don't forget to move each vertex with respect to the screen space or world space, not local space.

---
Tags: 3d, 3dsmax
---


# Question
Title: How can I set 3d sound to my game in unity5?
I have been working on a racing game in unity5. Now I want to set 3d sound so that if the game objects are far away from and coming towards the camera then it sounds like began to attenuate and then louder when closer to the game camera.

But I don't know how to do that.......if anyone knows then please help me out. Thanks...!

# Answer
> 2 votes
Usualy you have an audio listener atached to your main camera. And an audio source attached to every of your noisy objects. The 3d sound effect is managed by unity. You can "play" with some audio parameters as shown in picture (like doppler level). Enjoy

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


title: Texturing in blender

text:
# Question
Title: Texturing in blender
I am texturing a tree in bender using the sappling add-on, when i put the tree bark texture (which is saved as .jpg) the texture looks stretched and wierd, ive used "Use UV for mapping" on the curve modifier and it still looks stretched. I have blender 2.75.

Thanks in advance. :)

# Answer
> 0 votes
I have seen this heaps of times myself, I found that one weird way of fixing it was to convert the curve to a mesh, then select all \> U for unwrap \> cube projection. I will look like a huge mess in the UV Image editor but actually looks really good in the 3d Viewport in terms of unwrapping! Another option is to use the space tree addon, which is very good:

http://www.blenderartists.org/forum/showthread.php?282550-A-new-tree-add-on

And the newly released addon called The Grove, expensive but spectacular:

https://www.thegrove3d.com/

---
Tags: unity, game-design, textures, blender, tree
---


# Question
Title: What mistake did I make? Source engine reskin issues
Here is a reskin of the Half Life 2 Wallace Breen model that I made for a mod I am developing, but the checkerboard on the suit is very odd. All my other skins have no issue, but this skin has checkerboards under certain lighting situations. When mat\_fullbright 1 is on, chekerboards do not show. When dynamic shadows and shading in on, or when mat\_fullbright 0 is in use, the suit checkerboards.

# Answer
> 2 votes
Looks like you're missing one of your textures.

The source engine, when it can't find a specific texture, instead shows a checkerboard of purple and black squares, the different settings probably mean that a specific texture isn't loaded.

From looking around a bit the only references I can find to the settings and cvars you've mentioned are about lighting, I think you are missing a light map in your material.

# Answer
> 1 votes
Your model most likely has incorrect normals (pointing inward) in some places. If you made this in Blender, I know there's like a recalculate normals button that should have them all going the correct direction.

---
Tags: modding, shading, source-engine, rendertexture
---


# Question
Title: 'Ball.rigidbody' hides inherited member 'Component.Rigidbody'
I have some understanding of c# and I am new to unity. I am currently making a 3D project which use the Rigidbody component on the ball object. When I use following code:

```
public class Ball : MonoBehaviour
{
    public float launchSpeed;

    private Rigidbody rigidbody;

    // Use this for initialization
    void Start()
    {
        rigidbody = GetComponent<Rigidbody>();
        rigidbody.velocity = new Vector3(0, 1, launchSpeed);
    }

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

    }
}

```

I get the compiler warning:

> 'Ball.rigidbody' hides inherited member 'Component.Rigidbody'. Use a new keyword if hiding was intended

I understand the idea behind using new and override in c#, but I just don't understand why is the rigidbody hidden?

I am using Unity 5.2.0f3, and MS Visual Studio Community 2015.

# Answer
> 2 votes
It was an old version of Unity API where you used to be able to access `GameObject.rigidbody` through the property by default. Now this possibility is considered obsolete, but it is partially preserved for backward compatibility (it called legacy API). Therefore, the compiler says about ambiguity. To resolve the problem, call your variable different from 'rigidbody'.

More info here:

> Removed in version 5.2.0p1 Property rigidbody has been deprecated. Use GetComponent() instead. (UnityUpgradable)

**Please note**: despite the fact that the official documentation says that you should use GetComponent(), you should use a caching to store a reference to the component instead of calling GetComponent everywhere, because it affects bad on a performance:

```
private Rigidbody rBody;

private void Awake()
{
    rBody = GetComponent<Rigidbody>();
}

public void Test(Vector3 force)
{
    rBody.AddForce(force);
}

```

---
Tags: unity, c#, polymorphism, rigidbody
---


# Question
Title: OpenGL 3.3+ bounding volume only partly drawn
I am currently trying to set up a little debug view as I am planning to implement occlusion queries later. For those, I have written code to determine the "extreme coordinates" of the VAO I want to run the occlusion query for. The coordinates I then want to use to build a cube (bounding volume) that contains the shape to be tested. At the moment, I am using a simple triangle as test shape.

As far as I have tested, the extreme coordinates seem correct. Based on those coordinates, I went on to build the points needed for a cube. Of course I do not feel like fiddling around with 36 values, so instead, I'd like to draw the cube using indices with only 8 points.

So far so good, but I have ran into an issue: Only about 1/3 of the cube is being drawn.

Here my code to setup vertices:

```
//The coordinates for the triangle shape
verticesVector.push_back(-0.4f);
verticesVector.push_back(0.1f);
verticesVector.push_back(0.0f);
verticesVector.push_back(0.4f);
verticesVector.push_back(0.1f);
verticesVector.push_back(0.0f);
verticesVector.push_back(0.0f);
verticesVector.push_back(0.7f);
verticesVector.push_back(0.3f);

//The colors for the triangle shape
colorsVector.push_back(1.0f);
colorsVector.push_back(0.0f);
colorsVector.push_back(0.0f);
colorsVector.push_back(0.0f);
colorsVector.push_back(1.0f);
colorsVector.push_back(0.0f);
colorsVector.push_back(0.0f);
colorsVector.push_back(0.0f);
colorsVector.push_back(1.0f);

glGenVertexArrays(1, &vertexArrayObject);
glGenBuffers(1, &vertexBuffer);
glGenBuffers(1, &colorBuffer);
glBindVertexArray(vertexArrayObject);

glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, 9 * sizeof(float), &verticesVector.front(), GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
glBufferData(GL_ARRAY_BUFFER, 9 * sizeof(float), &colorsVector.front(), GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0);

//Finding the extremes of the shape
float minx = std::numeric_limits<float>::max();
float miny = std::numeric_limits<float>::max();
float minz = std::numeric_limits<float>::max();
float maxx = std::numeric_limits<float>::lowest();
float maxy = std::numeric_limits<float>::lowest();
float maxz = std::numeric_limits<float>::lowest();
for (size_t i = 0; i < verticesVector.size(); i += 3)
{
    if (verticesVector[i] < minx) minx = verticesVector[i];
    if (verticesVector[i+1] < miny) miny = verticesVector[i+1];
    if (verticesVector[i+2] < minz) minz = verticesVector[i+2];

    if (verticesVector[i] > maxx) maxx = verticesVector[i];
    if (verticesVector[i+1] > maxy) maxy = verticesVector[i+1];
    if (verticesVector[i+2] > maxz) maxz = verticesVector[i+2];
}

//The indices (or elements) for the debug bounding volume
//front
cubeElements[0] = 0;
cubeElements[1] = 1;
cubeElements[2] = 2;
cubeElements[3] = 2;
cubeElements[4] = 3;
cubeElements[5] = 0;
//top
cubeElements[6] = 3;
cubeElements[7] = 2;
cubeElements[8] = 6;
cubeElements[9] = 6;
cubeElements[10] = 7;
cubeElements[11] = 3;
//back
cubeElements[12] = 7;
cubeElements[13] = 6;
cubeElements[14] = 5;
cubeElements[15] = 5;
cubeElements[16] = 4;
cubeElements[17] = 7;
//bottom
cubeElements[18] = 4;
cubeElements[18] = 5;
cubeElements[20] = 1;
cubeElements[21] = 1;
cubeElements[22] = 0;
cubeElements[23] = 4;
//left
cubeElements[24] = 4;
cubeElements[25] = 0;
cubeElements[26] = 3;
cubeElements[27] = 3;
cubeElements[28] = 7;
cubeElements[29] = 4;
//right
cubeElements[30] = 1;
cubeElements[31] = 5;
cubeElements[32] = 6;
cubeElements[33] = 6;
cubeElements[34] = 2;
cubeElements[35] = 1;

//The actual vertices made from extreme coordinates
//lower left here
boundingVertices.push_back(minx);
boundingVertices.push_back(miny);
boundingVertices.push_back(minz);

//lower right here
boundingVertices.push_back(maxx);
boundingVertices.push_back(miny);
boundingVertices.push_back(minz);

//upper right here
boundingVertices.push_back(maxx);
boundingVertices.push_back(maxy);
boundingVertices.push_back(minz);

//upper left here
boundingVertices.push_back(minx);
boundingVertices.push_back(maxy);
boundingVertices.push_back(minz);

//lower left there
boundingVertices.push_back(minx);
boundingVertices.push_back(miny);
boundingVertices.push_back(maxz);

//lower right there
boundingVertices.push_back(maxx);
boundingVertices.push_back(miny);
boundingVertices.push_back(maxz);

//upper right there
boundingVertices.push_back(maxx);
boundingVertices.push_back(maxy);
boundingVertices.push_back(maxz);

//upper left there
boundingVertices.push_back(minx);
boundingVertices.push_back(maxy);
boundingVertices.push_back(maxz);

//Generate VAO for debug view of bounding volume
glGenVertexArrays(1, &boundingAO);
glGenBuffers(1, &boundingVB);
glGenBuffers(1, &boundingCB);
glBindVertexArray(boundingAO);
glBindBuffer(GL_ARRAY_BUFFER, boundingVB);
glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(float), &boundingVertices.front(), GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

glGenBuffers(1, &elementsBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementsBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 36 * sizeof(float), cubeElements, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

```

Here is how I am drawing the shapes:

```
glBindVertexArray(boundingAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementsBuffer);
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, 0);

glBindVertexArray(vertexArrayObject);
glDrawArrays(GL_TRIANGLES, 0, 3);
glBindVertexArray(0);

```

I understand, of course, that this is an awful lot of code still, but that is mostly because of the vertices.

Here is an image of how the whole thing currently looks:

My question finally is:

**What am I doing wrong here, how come only half is drawn?**

To clarify: The coloured triangle is the shape that is supposed to be enclosed in the (white) cube.

# Answer
> 1 votes
I am answering my own question because I have found the mistake (and a smaller one).

When I am sending the vertex data for the cube to OpenGL, I am doing the following:

```
glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(float), &boundingVertices.front(), GL_STATIC_DRAW);

```

This means I am sending 8 floats to OpenGL, which is very wrong as that number is not even divisible by 3 (x, y and z coordinates).

The correct number of bytes I want to send to OpenGL is thus `8 * 3 * sizeof(float)`(8 vertices composed of 3 coordinates equals 24 floats).

Very simple mistake with huge impact.

The second discrepancy was that I was sending a wrong byte count of indices to OpenGL. I was sending 36 floats, but of course I actually meant to send 36 unsigned shorts.

---
Tags: opengl, c++, bounding-boxes
---


# Question
Title: Game architecture / design question - building an efficient engine while avoiding global instances (C++ game)
I had a question about game architecture: What is the best way to have different components communicate with each other?

I do really apologize if this question has already been asked a million times, but I can't find anything with exactly the kind of information I'm looking for.

I've been trying to build a game up from scratch (C++ if it matters) and have observed some open source game software for inspiration (Super Maryo Chronicles, OpenTTD and other). I notice that a lot of these game designs use global instances and/or singletons all over the place (for things like render queues, entity managers, video managers, and so forth). I'm trying avoid global instances and singletons and build an engine that is as loosely coupled as possible, but I'm hitting some obstacles that owe to my inexperience in effective design. (Part of the motivation for this project is to address this :) )

I've built a design where I have one main `GameCore` object that has members that are analogous to the global instances I see in other projects (ie, it has an input manager, a video manager, a `GameStage` object that controls all the entities and game play for whatever stage is currently loaded, etc). The problem is that since everything is centralized in the `GameCore` object, I don't have an easy way for different components to communicate with each other.

Looking at Super Maryo Chronicles, for example, whenever a component of the game needs to communicate with another component (ie, an enemy object wants to add itself to the render queue to be be drawn in the render stage), it just talks to the global instance.

For me, I have to have my game objects pass relevant information back to the `GameCore` object, so that the `GameCore` object can pass that information to the other component(s) of the system that needs it (ie: for the situation above, each enemy object would pass their render information back to the `GameStage` object, which would collect it all and pass it back to `GameCore`, which would in-turn pass it to the video manager for rendering). This feels like a really horrible design as is, and I was trying to think of a resolution to this. My thoughts on possible designs:

1. Global instances (design of Super Maryo Chronicles, OpenTTD, etc)
2. Having the `GameCore` object act as a middleman through which all objects communicate (current design described above)
3. Give components pointers to all other components they will need to talk with (ie, in the Maryo example above, the enemy class would have a pointer to the video object it needs to talk to)
4. Break the game into subsystems - For example, have manager objects in the `GameCore` object that handle communication between objects in their subsystem
5. (Other options? ....)

I imagine option 4 above to be the best solution, but I'm having some trouble designing it... perhaps because I've been thinking in terms of the designs I have seen that use globals. It feels like I'm taking the same problem that exists in my current design and replicating it in each subsystem, just at a smaller scale. For example, the `GameStage` object described above is somewhat of an attempt at this, but the `GameCore` object is still involved in the process.

Can anyone offer any design advice here?

Thanks!

# Answer
> 19 votes
Something we use in our games to organize our global data is the **ServiceLocator** design pattern. The advantage of this pattern compared to the **Singleton** pattern is that your global data's implementation can change during the runtime of the application. Also, your global objects can be changed during the runtime too. Another advantage is that it's easier to manage the order of initialization of your global objects, which is very important especially in C++.

e.g (C# code that can be easily translated to C++ or Java)

Lets say that you have a rendering backend interface which has some common operations for rendering stuff.

```
public interface IRenderBackend
{
    void Draw();
}

```

And that you have the default render backend implementation

```
public class DefaultRenderBackend : IRenderBackend
{
    public void Draw()
    {
        //do default rendering stuff.
    }
}

```

In some designs it seems legit to be able to access the render backend globally. In the **Singleton** pattern that means that each **IRenderBackend** implementation should be implemented as unique global instance. But using the **ServiceLocator** pattern doesn't require this.

Here's how:

```
public class ServiceLocator<T>
{
    private static T currGlobalInstance;

    public static T Service
    {
        get { return currGlobalInstance; }
        set { currGlobalInstance = value; }
    }
}

```

In order to be able to access your global object you need to intialize it first.

```
//somewhere during program initialization
ServiceLocator<IRenderBackend>.Service = new DefaultRenderBackend();

//somewhere else in the code
IRenderBackend currentRenderBackend = ServiceLocator<IRenderBackend>.Service;

```

Just to demonstrate how implementations can vary during the runtime, let's say that your game has a minigame where rendering is isometric and you implement an **IsometricRenderBackend**.

```
public class IsometricRenderBackend : IRenderBackend
{
    void draw()
    {
        //do rendering using an isometric view
    }
}

```

When you transition from the current state to the minigame state you just need to change the global render backend provided by the service locator.

```
ServiceLocator<IRenderBackend>.Service = new IsometricRenderBackend();

```

Another advantage is that you can use null services too. For example, if we had an **ISoundManager** service and the user wanted to turn the sound off, we could just implement a NullSoundManager that does nothing when its methods are called, so by setting the **ServiceLocator**'s service object to a **NullSoundManager** object we could achieve this result with hardly any amount of work.

To summarize, sometimes it may be impossible to eliminate global data but that doesn't mean that you can't organize them properly and in an object oriented way.

# Answer
> 4 votes
There are many ways to design a game engine and it really all boils down to preference.

To get the basics out of the way, some developers prefer to design it like much like a pyramid where there is some top core class often referred to as a kernel, core or framework class that creates, owns, and initializes a series of subsystems such as audio, graphics, network, physics, AI, and task, entity, and resource management. Generally, these subsystems are exposed to you by this framework class and usually you would pass this framework class to your own classes as a constructor argument where appropriate.

I believe you're on the right track with your thinking of option #4.

Keep in mind when it comes to communication itself, that doesn't always have to imply a direct function call itself. There are many indirect ways communication can occur, whether it be through some indirect method using `Signal and Slots` or using `Messages`.

Sometimes in games, it's important to allow actions to occur asynchronously to keep our game loop moving as fast as possible so that frame rates are fluid to the naked eye. Players don't like slow and choppy scenes and so we have to find ways to keep things flowing for them but keep logic flowing but in check and ordered too. While asynchronous operations have their place, they're not the answer for every operation either.

Just know that you'll have a mix-in of both synchronous & asynchronous communications. Pick what is appropriate, but know you'll need to support both styles among your subsystems. Designing support for both will serve you well into the future.

# Answer
> 1 votes
You just have to make sure that there are no reverse or cyclical dependencies. For example, if you have a class `Core`, and this `Core` has a `Level`, and the `Level` has a list of `Entity`, then the dependency tree should look like:

```
Core --> Level --> Entity

```

So, given this initial dependency tree, you should never have `Entity` depend on `Level` or `Core`, and `Level` should never depend on `Core`. If either `Level` or `Entity` need to have access to data that's higher up in the dependency tree, it should be passed as a parameter by reference.

Consider the following code (C++):

```
class Core;
class Entity;
class Level;

class Level
{
    public:
        Level(Core& coreIn) : core(coreIn) {}

        Core& core;
}

class Entity
{
    public:
        Entity(Level& levelIn) : level(levelIn) {}

        Level& level;
}

```

Using this technique, you can see that each `Entity` has access to the `Level`, and the `Level` has access to the `Core`. Notice that each `Entity` stores a reference to the same `Level`, wasting memory. Upon noticing this, you should question whether or not each `Entity` really needs access to the `Level`.

In my experience, there is either **A)** A really obvious solution to avoid reverse dependencies, or **B)** There is no possible way to avoid global instances and singletons.

# Answer
> 0 votes
So, basically, you want to avoid global mutable state? You can make it either local, immutable, or not a state at all. Latter is most efficient and flexible, imo. It is known as iplementation hiding.

```
class ISomeComponent // abstract base class
{
    //...
};

extern ISomeComponent & g_SomeComponent; // will be defined somewhere else;

```

# Answer
> 0 votes
The question is actually seems to be about how to reduce coupling without sacrificing performance. All global objects (services) usually form a sort of context which is mutable during the run-time of the game. In this sense, the service locator pattern disperses different parts of the context into different parts of the application, which may or may not be what you want. Another real world approach would be to declare a structure like this:

```
struct sEnvironment
{
    owning<iAudio*> m_Audio;
    owning<iRenderer*> m_Renderer;
    owning<iGameLevel*> m_GameLevel;
    ...
}

```

And pass it around as a non-owning raw pointer `sEnvironment*`. Here pointers point to interfaces so coupling is reduced in a similar way compared to service locator. However, all services are in one place (which might or might not be good). This is just another approach.

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


# Question
Title: Help me understand this vbo/rotation, and how its done opengl c++
Im pretty new to opengl, and I just cant figure out how to rotate this vbo/vao in 2d space. This is how I bind my coordinates:

```
float points[] =
{
    0.0f,  0.10f,  0.0f,
    -0.10f, -0.10f,  0.0f,
    0.10f, -0.10f,  0.0f
};

glGenBuffers(1, &points_vbo);
glBindBuffer(GL_ARRAY_BUFFER, points_vbo);
glBufferData(GL_ARRAY_BUFFER, 9 * sizeof(float), points, GL_STATIC_DRAW);

```

I place the vbo at vao\[0\]

```
glBindBuffer(GL_ARRAY_BUFFER, points_vbo);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);

```

And I enable the array

```
glEnableVertexAttribArray(0);

```

and call to draw in the cpu, with

```
glDrawArrays(GL_TRIANGLES, 0, 3);

```

In my shader, I load the array by:

```
//glsl shader
layout ( location = 0 ) in vec3 vertex_position ;
void main()
{
 gl_Position = vec4(vertex_position, 1.0);
}

```

Ive edited out the coloring/fragment to save space, but this is my problem: I can make a uniform to move my triangle around, but idk how to apply a transformation matrix to a vec4.

It seems the shader reads my vertex\_position VAO one vec/element at a time, and trying to apply any matrix just gives an error.

How do you make or apply a rotation matrix on vao, am I inputting it wrong? All the uniforms I apply seem to only stretch, zoom, or move the overall triangle.

Sorry if the question is bad, or partially confused, shading is new to me overall, so thanks in advance.'

my shader:

```
#version 410 core
layout ( location = 0 ) in vec3 vertex_position ;
layout ( location = 1 ) in vec3 vertex_colour ;

out vec3 colour;
uniform vec3 fade=vec3(0.0,0.0,0.0); //fade
uniform float zoom=1.0;
uniform mat4 transform = mat4(vec4(1.0,0.0,0.0,0.0),
vec4(0.0,1.0,0.0,0.0), vec4(0.0,0.0,1.0,0.0), vec4(0.0,0.0,0.0,1.0));

void main()
{
colour=vertex_colour+fade;
gl_Position=transform*vec4(vertex_position,1.0);
}

```

this example https://open.gl/transformations and the answer made it doable.

# Answer
> 2 votes
Alright, so transformations in **general** are best done with matrices. Translation, Rotation, and Scaling can all be done using a \**single matrix\*. \*Since you will be working with vector 3's and 4's, what you end up using is a *4x4 matrix*.

There are several libraries out there such as GLM for handling the mathematics generally used in opengl, but whatever library you're using may already have the appropriate vector and matrix related operations.

Secondly, the technique you may use really depends on what you are trying to do. For instance, in 3D software, the position, rotation, and scale of an object is held within a *single* "**Model Matrix**", ***instead of modifying the entire object's vertices***. However, when the model gets rendered it's underlying vertices then get transformed by that matrix every frame. It is much better to do it like this as GPU's are incredibly fast and are optimized for doing it like this, rather than doing this CPU side.

---

**To rotate a vector**

* the order of operations is:

vector4 newVector4 = TransformationMatrix * oldVector4;

**To prepare the matrix**

* most libraries have functions for their matrices such as the "***lookAt()***" function for rotating the matrix to look at a particular point in space. This can sometimes be problematic as Euler rotations can lead to gimbal locking, but are a much easier starting point.
* Additionally, Quaternions may be supported in the library used for rotating a matrix. Even if no class exists, one can still write in the functionality themselves, however the math can be very off-putting to some.

In your shader, you want to provide it with a uniform mat4. You will need to bind the correct data to it in your application, but the implementation may vary if you have a library which aids you with shader logic. The implementation will look something like this:

```
layout ( location = 0 ) in vec3 vertex_position ;
uniform mat4 ModelMatrix;

void main()
{
   gl_Position = ModelMatrix * vec4(vertex_position, 1.0);
}

```

---
Tags: opengl, c++, glsl, rotation, vao
---


# Question
Title: Random white lines appearing while translating rendering slick 2d images
Hmm I'm getting this weird problem that i think may be a bug with slick but when ever i translate an image in slick 2d for some reason a weird white line appears on the left side of every image like this

This is the method for rendering each of the tiles, btw they are 32x32 textures

```
public void render(GameContainer gc, StateBasedGame game, Graphics g) throws SlickException {
    g.translate(-playerX, -playerY);
    //render the blocks here
    for(int x = 0; x <= ((Size.WIDTH/Size.Tile)+1); x++) {
        for(int y = 0; y <= ((Size.HEIGHT/Size.Tile)+1); y++) {
            g.drawImage(Sprites.dirt, x*Size.Tile, y*Size.Tile);
        }
    }
    g.translate(playerX, playerY);
    //render the player here, dont touch
    //no texture it was based off an old sheet
    g.drawImage(Sprites.grass, (Size.WIDTH-Size.Tile)/2, (Size.HEIGHT-Size.Tile)/2);

```

Sprite Getter :

```
public class Sprites {
    public static Image SpriteSheet;
    public static Image grass;
    public static Image dirt;
    public static void Init() throws SlickException {

        SpriteSheet = new Image("assets/images/SpriteSheets/Sprites.png");
        grass = SpriteSheet.getSubImage(0, 0, Size.Tile, Size.Tile);
        dirt = SpriteSheet.getSubImage(0, 1*32, Size.Tile, Size.Tile);
    }
}

```

if you want to see the rest of the code it is at MC2D.zip

# Answer
There are several possible reasons for this issue.

I have not yet worked with Slick2d - but one of the following things might help:

1. Make sure that the coordinates you are rendering to are all on full pixels - not on e.g. 100.2
2. If possible set the texture interpolation mode to nearest neighbour, not linear. This might lead to colors being dragged in.
3. Try to surround the tiles with a 1 px line that repeats the tiles's outline. This might fix artifacts from rounding errors in OpenGL.

In your case I would assume that 2+3 fixes the issues - it seems that you are dragging in white color from the left side of the tiles (which in wrap mode means that you are dragging in the right border of the texture).
> 1 votes

# Answer
In this part of the code

```
public class Sprites {
    public static Image SpriteSheet;
    public static Image grass;
    public static Image dirt;
    public static void Init() throws SlickException {

        SpriteSheet = new Image("assets/images/SpriteSheets/Sprites.png");
        grass = SpriteSheet.getSubImage(0, 0, Size.Tile, Size.Tile);
        dirt = SpriteSheet.getSubImage(0, 1*32, Size.Tile, Size.Tile);
    }
}

```

You do the following

```
dirt = SpriteSheet.getSubImage(0, 1*32, Size.Tile, Size.Tile);

```

As you mentioned you are using 32\*32 images. Maybe if you switch form 1\*32 to 1\*31 the while one pixel line will disappear. For me it seems like you are taking one pixel outside of the texture.

Corrected code:

```
 dirt = SpriteSheet.getSubImage(0, 1*31, Size.Tile, Size.Tile);

```
> 0 votes

---
Tags: java, lwjgl, slick
---


title: Algorithm for triangle picking?

text:
# Question
Title: Algorithm for triangle picking?
I need a triangle picking algorithm, that is, I need to see if my mouse is over a triangle. I've heard what color picking is, but it would pretty much just drop the performance twice (which is not what I want).

I use LWJGL java, and OpenGL 3.3.

If anyone can point me to a triangle picking algorithm then that would be awesome!

My best attempt was to do some transformations on the vertices and then check if it is within the center, it is limited and not what I exactly want.

# Answer
> 5 votes
What I do is a test known as **Ray-Picking**. It is a test to see if a "ray" intersects a triangle. In order to use it, you need to learn how to convert your mouse coordinate into world coordinates (where your triangles are). Then, you need to create a matrix which is the inverse of how you render your triangles, so it should equal the **inverse view matrix \** multiplied by the \**inverse projection matrix**.

```
QVector3D screenToSpace(int x, int y, int z)
{
    makeCurrent();
    GLint viewport[4];
    GLfloat winX, winY;

    glGetIntegerv(GL_VIEWPORT, viewport);
    winX = ((float)x/viewport[2]*2)-1;
    winY = ((float)(viewport[3]-y)/viewport[3]*2)-1;

    QMatrix4x4 mat =  ViewMatrix().inverted() * Projection().inverted();
    QVector4D wSC = (mat) * QVector4D(winX,winY,z,1);
    wSC /= wSC[3];     // Divide xyz by w (the fourth component in a 4D vector)
    return wSC.toVector3D();
}

```

The above method is called to generate a ray at a given z distance. If you are just clicking on the screen, the first point of the ray should use a **z** of -1, and a far ray point should be +1.

With the ray points, you can now use the following alogorithm to check if your mouse coordinates (now converted into a line in 3D space, and in the code = NearPoint && FarPoint) intersects with a triangle:

```
bool intersect(QVector3D nearP, QVector3D farP)
{
    for (int aA = 0; aA < triangles.size(); aA+=3)
    {
        QVector3D    u, v, n;              // triangle vectors
        QVector3D    dir, w0, w;           // ray vectors
        float     r, a, b;                 // params to calc ray-plane intersect

        // get triangle edge vectors and plane normal
        u = Point1 - Point0;
        v = Point2 - Point0;
        n = QVector3D::crossProduct(u,v);    // cross product
        if (n == (QVector3D(0,0,0)))         // triangle is degenerate
            return false;                    // do not deal with this case

        dir = farP - nearP;                  // ray direction vector
        w0 = nearP - temp0;
        a = -dot(n,w0);
        b = dot(n,dir);
        if (fabs(b) < 0.00000001) {     // ray is  parallel to triangle plane
            if (a == 0)                 // ray lies in triangle plane
                continue;
            else continue;              // ray disjoint from plane
        }

        // get intersect point of ray with triangle plane
        r = a / b;
        if (r < 0.0)                    // ray goes away from triangle
            continue;                   // => no intersect
        // for a segment, also test if (r > 1.0) => no intersect

        QVector3D I;
        I = (nearP + r * dir);          // intersect point of ray and plane

        // is I inside T?
        float    uu, uv, vv, wu, wv, D;
        uu = dot(u,u);
        uv = dot(u,v);
        vv = dot(v,v);
        w = I - temp0;
        wu = dot(w,u);
        wv = dot(w,v);
        D = uv * uv - uu * vv;

        // get and test parametric coords
        float s, t;
        s = (uv * wv - vv * wu) / D;
        if (s < 0.0 || s > 1.0)         // I is outside T
            continue;
        t = (uv * wu - uu * wv) / D;
        if (t < 0.0 || (s + t) > 1.0)  // I is outside T
            continue;

        return true;                   // I is in T
    }
    return false;
}

```

---

In practice, the above 2 functions can be used like this:

```
bool createRay(int MouseX, int MouseY)
{
    QVector3D nearP = screenToSpace(MouseX,MouseY,-1);
    QVector3D farP = screenToSpace(MouseX,MouseY,1);
    bool rayIntersect = intersect(nearP, farP);
    return rayIntersect;
}

```

Where "createRay() returns true if the mouse intersects a triangle, and false if not.

# Answer
> 1 votes
You only need to render the triangle IDs when you need to pick *and* if the rendered scene changed (object moved, camera rotated,...) since the last time you needed to pick.

You can also improve picking by only rendering what *can* be picked. No need to render the background into the color pick buffer if it can't be interacted with. You can **simplify the geometry** of the pickable objects as well.

Often you can use a **smaller target texture** than the 4kp screen as you only need a small area around the mouse. Applying a scaling offset matrix at the bottom (after projection) of the transform stack will let you render only the needed area.

If you absolutely refuse to do color picking then can use a raycast instead. This will cast a ray and return the first object it hit. This works fastest with a spatial partitioning so you don't need to iterate over all objects to find the one that hits.

---
Tags: java, lwjgl, vertex
---


# Question
Title: Problem designing my pseudo-3D game with SFML
I am designing the game so the objects I create (Character, Enemy, Enemycast...) can inherit all from

* Collider
* SpineDrawable // Sprite // AnimatedSprite
* D2D // D3D

Both D2D and D3D inherit from `virtual sf::Drawable`. D3D also is supossed to apport the functionality of an additional axis. When the object is drawed in screen, the object is scaled and repositioned in (X, Y) with some calculations.

Collider inherits from D3D, because all my colliders are going to have 3 axis, and it creates its own AABB box from D3D interface -to be implemented by the graph type Sprite//SpineDr...-.

I am trying to have two vectors to hold all my graphics, `std::vector<D2D*>` and `std::vector<D3D*>`, because the D3D ones will need to be sorted depending on their `float z`.

The problem arise because D2D///D3D classes inherit `virtual sf::Drawable`, and I am using my class `Sprite` inheriting from `sf::Sprite`, which inherit `sf::Drawable` as non-virtual function from in Sprite.hpp of SFML.

So I got two questions

* Must I rewrite my sprite function in lower level, so it can inherit sf::Drawable as virtual?
* I think my design is poor. Which alternatives are there instead of creating two separated lists of sf::Drawable/s to order the ones which have 3 axis?

# Answer
You might want to look into *entity systems*. Instead of using inheritance (with all its problems), each entity is composed of pluggable *components*. See this article for an introduction of the whys and hows.
> 2 votes

# Answer
I think your idea of separating the types of objects in two lists is actually good. Clearly there's a difference between 2D and 3D things, so don't mix them. It would be nicer though, if you stored them by value in those arrays (instead of pointers), that would gain better CPU cache usage thanks to *data locality*.

If you put inheritance aside and use composition instead, much like @Thomas suggested, you can store the objects by value. That would also resolve eventual *diamond of death* issues you might come across.

Without looking at your code, I'd start with something like this (pseudocode):

```
class Obj3D {
    sf::Drawable myDrawable;
    Vec3 myPostion;

    // methods ...
}

class Obj2D {
    sf::Sprite mySprite;
    Vec2 myPostion;

    // methods ...
}

class Game {
    std::vector<Obj3D> objects3d;
    std::vector<Obj2D> objects2d;
}

```

If you ever find the need to put everything under a generic `Object` interface, that englobes both 2D and 3D, then scale-up to that, but try to keep it simple until you really need it.

Lastly, a recommended read, related to this: Component pattern.
> 1 votes

---
Tags: c++, sfml, inheritance
---


# Question
Title: In Box2D, how can I SetTransform of a body without getting an IsLocked assertion error?
I've created a bullet body and stored a reference to it in `herobody`:

```
bDef.type = b2_dynamicBody;
bDef.position.Set(herobody->GetPosition().x, herobody->GetPosition().y);
b = world->CreateBody(&bDef);
b2FixtureDef fixturebDef;
b2CircleShape circlebShape;
circlebShape.m_radius = 0.05;
fixturebDef.shape = &circlebShape;
b->CreateFixture(&fixturebDef);

```

I'm trying to change the current position of the bullet. I tried to use `SetTransform` but I get an error `Assertion failed: (IsLocked() == false)` during `world->step` in my `update` method.

```
// This doesn't work. Causes the above assertion.
/*
b->SetTransform(
  b2Vec2(
    herobody->GetPosition().x,
    herobody->GetPosition().y
  ),
  0
);
*/

// This works, but doesn't set position directly.
b->ApplyLinearImpulse(b2Vec2(5, 0), b->GetWorldCenter(),true);

```

How do I do this correctly?

# Answer
Call `SetTransform` *before* or *after* your `World::step` call. Make sure it's not inside a Box2D callback, as those happen *inside* the `step`, during which the `World` is locked.

---

Further details:

The `isLocked() == false` assert implies you're attempting to directly change something in the Box2D `World` *during a simulation step*. This could break the simulation, so Box2D guards against it. `SetTransform` directly changes the body's position, so it is disallowed when locked.

`ApplyLinearImpulse` works even when locked, because all it does is register a new impulse that should act on the body, which does not directly change anything. The impulse is only applied on the next world step.

---

If you want the `SetTransform` to in response to some event (not every step), you'll need to introduce some additional state. For example, a `bool shouldResetBallPosition` that the appropriate callback sets to `true`. You can then then check for that inside your update method, with something like—

```
if (shouldResetBallPosition) {
    b->setTransform( ... );
    ...
    shouldResetBallPosition = false;
}

```
> 1 votes

---
Tags: box2d
---


# Question
Title: How do I set an object's speed to arrive in X seconds?
I want to move an object to a point in the game world, I have the distance value which is far the player should move. I want to complete the movement in X seconds.

I have tried many equations and formulas to no success.

```
Speed = Distance/Time

```

This one doesn't seem to give me the right result. Thing is the game is updated 60 times a second and the movement is affected by delta time.

I'm pretty sure I am not taking the framerate in consideration.

What am I doing wrong?

---

Edit:

This is how I calculate the speed:

```
int dst = 500;
int time = 2; // in seconds
float speed = dst / time;

```

Doing it this way is making the movement instant and the game object is not traveling the distance in 2 seconds.

Every frame each game objects gets updated this way:

```
p.x += dir.x * speed * deltaTime;
p.y += dir.y * speed * deltaTime;

```

The dir vector holds the direction of movement which is calculated on mouse click:

```
Vector2 dir = new Vector2(mouseX, mouseY).subtract(objectX, objectY).normalize();

```

Delta time calculation:

```
long time = System.nanoTime();
float deltaTime = (time - lastTime) / 1000000000.0f;
lastTime = time;

```

Please note: The game object stops upon arrival.

# Answer
You are specifying a time in seconds as an integer value, but you are not taking into account the game's frames per second.

If your game was running at 1 frame per second, it would work, because after two frames (thus, two seconds), your object would have travelled the specified distance.

It's a simple case of multiplying your time by your FPS:

```
int dst = 500;
float time = 2 * Gdx.graphics.getFramesPerSecond(); // in seconds
float speed = dst / time;

```

If your game is running at 60 FPS, the speed of the object would be `500 / 120`, or `4.16`.

Additionally, as you are using libGDX, your calculation of deltaTime is irrelevant as it is already provided:

```
float deltaTime = Gdx.graphics.getDeltaTime();

```
> 4 votes

---
Tags: physics, libgdx, movement, timing
---


title: Quake 3 Gravity

text:
# Question
Title: Quake 3 Gravity
From "Quake 3 Networking Primer":

> The server accepts client commands as they arrive. It makes one call to the VM per client command. This is the only time that players are ever updated. (That's why, when someone has a bad connection from their client to the server, they'll freeze in place or skip.) (See ClientThink() in g\_active.c)

If this is true, then how does the server handle jumps and gravity when clients dont send any input?

# Answer
In Quake 3 UDP sockets are used to issue player commands. This establishes the master gamestate which is responsible for being the "true" state of things. Each client has their own collection of 32 gamestates (snapshots) as well as a dummy snapshot for deltas. Game state variables are established before the map loads (like gravity and sit in the g\_\* namespace). These are effectively constant factors of the master state in the game. When changed they need to be updated via a reliable message--that is all players must receive the new state. AFAIK, g\_\* doesn't get applied until a map restart.

Each player is still computing their own "master" state in a way, but the global master state that happens per ACK or out-of-sync takes control. When you see skipping and such you're seeing the difference of snapshots being applied and the state correcting itself (more or less) as dropped packets (amounting to unACK'd snapshots) cause havoc.

Snapshots are ACK'd and the process effectively amounts to: copy the master gamestate to the next snapshot slot. Compare the snapshots. If something doesn't match the master state, a packet is not ACK'd, etc, then the comparison fails and the delta between the last good snapshot and the current snapshot is used to create snapshot 3 for the client. It's such a simple and elegant process because the same algorithm can be used to do full updates, partial updates, or resending old/new information.

Check out Brian Hooks' (original developer) article on it: http://fabiensanglard.net/quake3/The%20Quake3%20Networking%20Mode.html

or even Fabien's article: http://fabiensanglard.net/quake3/network.php

Both are fantastic resources.
> 1 votes

---
Tags: physics, networking, quake3
---


title: Texturing curves in blender

text:
# Question
Title: Texturing curves in blender
Im making a tree in blender with the sappling add-on, i've already textured the leaves, i want to know how to texture the trunk with a bark texture. Im using cycles render.

Thanks in advance. :)

# Answer
> 1 votes
(Side note: you might have better luck posting your question on https://blender.stackexchange.com/)

There are two methods you could use to do this. The first would be to make a procedural material. The wood texture on your tree would be generated as it is being rendered. The geometry node would be handy for this:

Red varies with x, green with y, and blue with z. You can use this to generate various textures:

The second way to do it would be to convert the curve into a mesh. Select your curve and press alt+c to do so:

You can then proceed to unwrap it like a regular mesh, then apply a wood texture to it:

Hope this helps, and good luck with your project!

---
Tags: 3d, game-design, textures, blender, 3d-modeling
---


title: Character controller going down slopes

text:
# Question
Title: Character controller going down slopes
When I go down slopes with character controller, if the speed is too high, the character just flies off the slope and lands at the bottom. I want my character to "stick" to the slope rather then just jump of it. I came up with code to do so, but it didn't turn out as I planned. Now the character just slides on the slope when I stop pressing the arrows (not staying at its place on the slope).

```
Physics.Raycast (transform.position, Vector3.down, out hit);
transform.position = transform.position
                     + new Vector3(0f, distance - hit.distance, 0f);

```

Thanks for the help, i couldn't figure this out all day.

# Answer
I know a few titles that have an "on the ground" mode that enforces some stickiness to handle problems like this. When the object is sticky the usual lateral forces work as expected, but the vertical (gravity) force is ignored and heights are forced to ground.

Part of this mode has enough smarts to unstick the object appropriately, for example when a jump is activated or some external impulse like getting hit activates a ragdoll.

In real life movement if you were running towards a 45deg ramp you too would go flying into the air. That's just physics. You can't really hack that with greater gravity because... why not just lock the object down with sticky in the first place if you're going to hack.

I believe that stopping this behavior artificially is warranted here to make gameplay more solid.
> 1 votes

# Answer
Try something like this, i haven't tested it yet, but i can't see why it wouldn't work

```
Physics.Raycast (transform.position, Vector3.down, out hit);

Vector3 temp = transform.position;
temp.y = hit.point.y + hoverDistance;
transform.position = temp;

```
> 0 votes

# Answer
Try increasing gravity dramatically so that there is a force keeping the player on ground.
> 0 votes

---
Tags: unity, unityscript
---


# Question
Title: How can I exploit multithreading in collision resolution?
I'm trying to speed up my collision resolution by using multiple threads.

I'v read through Box2D's source code and while it was challenging and educating, it didn't really point me to how I could use multiple threads.

I'm ready to make some sacrifices with accuracy. I am investigating this because I have boatloads of game objects.

My current implementation handles AABB checks for 100000 objects in about 10 ms. I have no idea if this number is good, but for my purposes it seems sufficient.

Next, I'm trying to figure out how to resolve collisions. How could I get power out of multiple threads here?

---

This is what i'm currently planning to do: (Do you see any issues with it?)

1. Calculate position for each object in separate threads based on manifold data
2. Update existing manifolds in separate threads
3. get New collisions for moved objects in separate threads
4. Repeat 10 times or until no changes

# Answer
I'm not sure what solver strategy you use but most physics engines including box2d solve islands of bodies that share manifolds. Only the interrelated bodies that can have impact on one another are solved together. Each island can be solved on a separate thread. Since island sizes change based on the number of interrelated bodies a job scheme consuming islands as threads are free is a good strategy. Havok works this way. Box2d is a good place to look for insight for building islands even if solving isn't multithreaded.

The other thing you could do is perform batches of narrow phase pair-wise collision in seperate threads since the input data is small and constant until the next step. The outputs are again limited to only the two in the pair.
> 2 votes

---
Tags: 2d, collision-detection, multithreading
---


title: What is the optimal texture size?

text:
# Question
Title: What is the optimal texture size?
I recently added a texture packager to my project that will pack a certain amount of textures into a single one, like this:

So for example this one is 582x1023 pixels in size. The goal of adding these packed textures was obviously to improve performance so I wanted to look up the optimal texture size for OpenGL (using LWJGL) textures. The things I found were that a widely supported maximum texture size seems to be 1024x1024, according to this for example. This strikes me as odd because obviously a lot of textures alone would be larger than that, so what happens with those? I am pretty sure most graphics cards support textures bigger than that. Can I reasonably expect most graphics cards to handle e.g. 4096x4096 textures (or maybe even larger than that)?

To come to my second point (I hope this still counts as one question, but it essentially boils down to the same issue): Should textures be sized to a power of 2 (256x256, 512x512, 1024x1024, 2048x2048, ..) and should I pad packed textures smaller than that to the next power of 2? According to this question from 2011 it is not a requirement but can improve performance and avoid minor bugs and this one from 2012 says that you definitely should pad textures. So I realize that these questions have been asked before but they are reasonably dated for the answers to have changed and further they each only partially answer my question. How do other projects / handle this?

**TL;DR:** What textures sizes can I expect most graphics cards to handle? What are the optimal texture sizes (or are there)? Should I pad textures width to the next power of 2?

# Answer
I'm going to take a stab at answering this, though YMMV. I use the Steam Hardware Survey ( http://store.steampowered.com/hwsurvey?platform=pc ) to determine what is the video RAM (VRAM) available on most computers. Looking at the results as of 2015-10-13 (today), nearly 85% of people have 1024 MB VRAM.

Your question is very broad, since it doesn't state target hardware (console, PC, handheld, mobile devices?) I'm going to talk about PCs and you can extrapolate for other platforms based on hardware specs.

Assuming 32 bits of color+alpha per pixel i.e. 4 bypes per pixel, 1 GB VRAM can maximally hold ~256 million pixels. This equates to 256 1K by 1K textures. This assumes (incorrectly) that you only want to hold textures in your VRAM, while there will be a whole host of other things (e.g. mesh data, if you're working in 3D) that you need to leave space for. You also probably want to allow for some more space for mip-mapping of textures, which usually works best if your textures are powers of two.

Modern consoles (XBOX One and PS4) have 4-8 GB of unified RAM, most handhelds and mobile devices have 1 - 2 GB of unified RAM, with restrictions on how much you can allocate as VRAM.

I would typically create 2K textures so that it worked on most PCs, allowing for the option to scale down for lower end devices. If you're writing a 2D game and want to target higher resolution displays (4K, retina iPad, etc) you can use 4K textures for the background, but for most other parts, it may be overkill.

Hope this helped and didn't muddy the waters.
> 7 votes

---
Tags: opengl, textures, performance
---


# Question
Title: How do I make a flickering engine exhaust animation using only bone animation?
I'm trying to replicate the flickering engine exhaust animation in this SketchFab model. SketchFab doesn't support particle systems, so the animation must be a simple bone animation.

Can someone help me understand how to achieve such an effect?

My best guess is animated opacity, but I don’t know how to replicate it. My final goal is to use it in a Unity 5 mobile game.

# Answer
They seem to be approximating that using partially transparent objects moving in and out of the engine.

Quick mock-up, slowed down:

The images attached to the moving bones just look like this:
> 1 votes

---
Tags: animation, skeletal-animation
---


# Question
Title: Transform.forward having problems after rotation
I have this script,

```
void Update () {

        float pitch, yaw, roll;

        pitch = Input.GetAxis ("Mouse Y");
        yaw = Input.GetAxis ("Mouse X");
        roll=Input.GetAxis ("Roll");

        transform.Rotate (-pitch, yaw, -roll);

        if (Input.GetKey (KeyCode.W))
            Rigid.AddRelativeForce (transform.forward * 50);
        else if (Input.GetKey (KeyCode.S))
            Rigid.AddRelativeForce (-transform.forward * 50);
        else if (Input.GetKey (KeyCode.D))
            Rigid.AddRelativeForce (transform.right * 50);
        else if (Input.GetKey (KeyCode.A))
            Rigid.AddRelativeForce (-transform.right * 50);
        else
            Rigid.velocity = Vector3.zero;

        if (Input.GetKey (KeyCode.Space)) {

            transform.rotation = Quaternion.Euler (Vector3.zero);
            Rigid.velocity=Vector3.zero;
            Rigid.angularVelocity=Vector3.zero;
        }

    }

```

My "Roll" is defined as 'q' and 'e' keys. "Rigid" is rigidbody object.

I simply want to implement 6DoF on this cube, the pitch, yaw and roll works fine , but when it comes to movement it behaves in very unusual way after the object is rotated, I tried moving by using localPosition still no result. I also used relative torque for rotation but it resulted in worse, that is why rotation is controlled by transform.rotation not torque.

I suppose I am not handling gimbal lock or something? Or am I doing it completely wrong?

# Answer
> 1 votes
From the docs on Rigidbody.AddRelativeForce:

> Adds a force to the rigidbody **relative to its coordinate system.**

So, you're accounting for the object's rotation *twice*:

* once by using AddRelativeForce (which expects the force to be expressed in local space and transforms it for you)
* and again by using transform.forward & right (which are worldspace vectors which already include the object's rotation).

This means the force vector is being rotated by the *square* of the object's rotation.

You can fix this by either sticking with AddRelativeForce and replacing `transform` with `Vector3`, or by keeping transform.forward/right but using `Rigidbody.AddForce` instead.

---
Tags: rotation, movement, transformation, unity
---


# Question
Title: Why do I see spaces between polygons in OpenGL, only on an Nvidia 720M?
I'm developing an OpenGL application that renders `.obj` 3D models. I use VBOs to render the polygons. Using the same code, the loaded models appear fine on all PCs, *except* on my Nvidia 720M.

My laptop sports an Intel HD 4000 embedded graphics GPU, and an Nvidia 720M. When I use the Intel GPU, it looks fine, but when I load it on the Nvidia 720M, spaces appear around polygons like so:

On Nvidia 720M GPU:

On everything else:

No other 3D application that runs on the Nvidia 720M GPU has the same issue. I am using the latest drivers.

Is this a problem with my application? How can I fix it?

# Answer
Just a hunch... is your GPU somehow doing polygon antialiasing? That would cause such artifacts. For example, if two neighbouring polygons each cover a particular pixel for 50%, the total coverage (alpha) for that pixel would be 75%, not 100%.

Try forcing the option off:

```
glDisable(GL_POLYGON_SMOOTH);

```

Or even:

```
glHint(GL_POLYGON_SMOOTH_HINT, GL_FASTEST);

```
> 8 votes

---
Tags: opengl, rendering, nvidia
---


# Question
Title: What are the basic equations in 2D physics collisions?
I'm making a 2D fighter, and I have gotten a basic engine, but right now I need to add the collisions, but I'm sure a basic AABB check will not be enough.

I'm sure it needs some basic 2D physics equations, but every resource I see on the web is extremelly complex or try to teach you everything you need to know to make a 2D physics engine.

So far, I'm sure it's related to momentum and forces, but don't know if those are enough for a 2D collision in a fighting game and what are the simplest ways to implement them.

# Answer
> 0 votes
You are asking for two subjects: the detection and the resolution of the collisions.

For detection in a fighting game, simple intersection tests for AABB are sufficient. Every animation can have several bounding boxes, and each box has a type (attack or body, for example). In every game frame you test intersection of all attack boxes of player1 against all body boxes of player2. And then the reverse.

After the detection phase, the resolution phase begins. In it, you apply the forces of the attacks that was registered in the previous phase (as well as damage and transition to hurt animations). You may storage all this data (damage, forces, target hurt animation) into the attack boxes.

See my animation editor below. It's in portuguese, but you can see the attack properties in the left panel: "ForçaX" and "ForçaY" (forces), Dano (damage), etc.

And for the physics simulation you can use Euler integration. Here's how I do it:

```
public void UpdatePhysics(Entity entity) {
    entity.Position = new Vector2(entity.Position.X + entity.Velocity.X, entity.Position.Y + entity.Velocity.Y);

    var horizontalVelocity = entity.Velocity.X;

    if (entity.Velocity.X != 0) {
        if (entity.Velocity.X > 0) {
            horizontalVelocity -= entity.Friction.X;

            if (horizontalVelocity < 0) {
                horizontalVelocity = 0;
            }
        } else if (entity.Velocity.X < 0) {
            horizontalVelocity += entity.Friction.X;

            if (horizontalVelocity > 0) {
                horizontalVelocity = 0;
            }
        }
    }

    var verticalVelocity = entity.Velocity.Y;

    if (entity.Velocity.Y != 0) {
        if (entity.Velocity.Y > 0) {
            verticalVelocity -= entity.Friction.Y;

            if (verticalVelocity < 0) {
                verticalVelocity = 0;
            }
        } else if (entity.Velocity.Y < 0) {
            verticalVelocity += entity.Friction.Y;

            if (verticalVelocity > 0) {
                verticalVelocity = 0;
            }
        }
    }

    entity.Velocity = new Vector2(horizontalVelocity + entity.Acceleration.X, verticalVelocity + entity.Acceleration.Y);
}

```

---
Tags: 2d, collision-detection, physics, fighting-game
---


# Question
Title: How to get the mouse events in an unreal engine editor plugin?
I would like to react to user inputs in an editor plugin, how can I do that? In a game I can use a custom Pawn or a custom PlayerController but how can I do it in the editor?

# Answer
> 0 votes
You can do it by extending FEdMode in your plugin:

```
class FPBEdMode : public FEdMode
{
public:
    const static FEditorModeID EM_PBPEdModeId;
public:
    FPBEdMode();
    virtual ~FPBEdMode();

    // FEdMode interface
    virtual void Enter() override;
    virtual void Exit() override;

    virtual void Render(const FSceneView* View, FViewport* Viewport, FPrimitiveDrawInterface* PDI) override;
    virtual void DrawHUD(FEditorViewportClient* ViewportClient, FViewport* Viewport, const FSceneView* View, FCanvas* Canvas) override;
    virtual void Tick(FEditorViewportClient* ViewportClient,float DeltaTime) override;

    virtual bool MouseEnter( FEditorViewportClient* ViewportClient,FViewport* Viewport,int32 x, int32 y );
    virtual bool MouseLeave( FEditorViewportClient* ViewportClient,FViewport* Viewport );
    virtual bool MouseMove(FEditorViewportClient* ViewportClient,FViewport* Viewport,int32 x, int32 y);
    virtual bool CapturedMouseMove( FEditorViewportClient* InViewportClient, FViewport* InViewport, int32 InMouseX, int32 InMouseY ) override;
    virtual bool InputKey(FEditorViewportClient* ViewportClient, FViewport* Viewport, FKey Key, EInputEvent Event) override;
    virtual bool InputAxis(FEditorViewportClient* InViewportClient, FViewport* Viewport, int32 ControllerId, FKey Key, float Delta, float DeltaTime) override;

    bool UsesToolkits() const override;
    // End of FEdMode interface

    FIntRect ViewRect;
    FViewMatrices ViewMatrices;

};

```

Note that you can get the ViewMatrices and the ViewRect in Render() to use those functions:

```
FSceneView::DeprojectScreenToWorld(
    ScreenPosition,
    ViewRect,
    ViewMatrices.GetInvViewMatrix(),
    ViewMatrices.GetInvProjMatrix(),
    RayOrigin,
    RayDirection
);

FSceneView::ProjectWorldToScreen(WorldPosition, ViewRect, ViewMatrices.GetViewProjMatrix(), ScreenPosition);

```

This enables to replace the PlayerController-\>ProjectWorldLocationToScreen() and PlayerController-\>DeprojectScreenPositionToWorld() that you would use in game.

You can also replace PlayerController-\>GetHitResultUnderCursor() with this:

```
 GetWorld()->LineTraceSingleByChannel(HitResult,
            RayOrigin,
            RayOrigin + RayDirection,
            TraceChannel);

```

---
Tags: c++, mouse, plugin, unreal
---


# Question
Title: Best practice for implementing overall / weekly / daily highscores?
So I'm setting up social leaderboards and I want there to be daily weekly overall high scores. The way the scoring works is each score is tied to a user after the user logs in so the scores need to always be linked to a user. I'm using the Parse BaaS with Unity C# and I've gotten overall highscores working by adding a highScore field to the ParseUser model. From the research that I've done so far based on google play services and game center has led me to the following solution.

Have 3 fields for the ParseUser model: overallScore, dailyScore, weeklyScore. Reset dailyScore and weeklyScore when appropriate

Is this an appropriate solution for what I'm trying to implement? Is there a more efficient or scalable way to do it?

# Answer
I think its better to have score submission time stamp associated with each score, so that you don't have to rely on resetting the score at the weekend or day end.

So basically the structure will have following fields

* User id
* OverallScore
* Weekly Highscore
* Weekly Highscore Timestamp
* Daily Highscore
* Daily Highscore Timestamp

Now lets consider the working , the user submits a score to the backend.

* For weekly highscore check if the timestamp in the database is older than the current week.
    + If **YES**, then replace the score with the newly submitted value straight away.
    + If **NO** , then compare the stored and submitted value
        - if stored value is **greater** then do not update the field
        - if stored value is **smaller** then store the new value and update the timestamp

Same procedure repeat for the daily highscore :)

To fetch the weekly highscore you need to query looking for the timestamp which belongs to the current week and order in descending order according to the score. Same for daily.

I usually follow this approach as its robust and doesn't depend on any kind of cron job or task scheduler for resetting the scores (which sometimes might not run and end up messing the result)
> 0 votes

---
Tags: unity, android, ios, leaderboards
---


# Question
Title: Good practice in implementing multi sprite (as skins) in 2d unity game
so, I want to make such functionality in my 2d game with unity :

> Multi skin character, with similar control and functionality, and with possible different gimmicks (such as crossy road's characters, which some modify game environment and / or have unique death animation, yet THEY CAN ONLY JUMP AROUND a.k.a only cosmetic).

Here's so far what I did :

> Make each character into separate gameobjects and prefabs, and then if I need to find a particular script in current active char, I use `Gameobject.Find()`. The problem is, if I need to apply a script, I need to \> manually attach it 1 by 1 to each char gameobjects, which I find will create problems if the character number grows.

Is that a good practice? Or there's any more good / best practice on this problem?

P.S.

1. I once read `Gameobject.Find()` is slow, so if possible, I want to avoid that.
2. I use bone-based sprite animation, so, I think, changing just the `Sprite` in `SpriteRenderer` component won't work.

Thank you.

# Answer
> 0 votes
Basically you just change the sprites through code depending upon the skin type. You should not put the code in Late Update as shown in the tutorial as its just for demonstration purpose. Call the function only once when you want to update the skin.

You can find the complete tutorial in this link - https://youtu.be/HM17mAmLd7k?t=1609

And the entire source code for the tutorial in this link - http://goo.gl/6oSzDx

---
Tags: sprites, unity, character
---


# Question
Title: 2DRaycast is shooting slightly in wrong directions
I wanted just a simple 2DRaycast, which points from my character to my mousePointer. So I found the following code in the Internet, most people seem to use it like that. So I tried it, but it isn't working for me like it is supposed to do, check the screenshot below. The direction is kinda weird, so I tried some variants of the variables and tried with Normalize, which didn't solve the problem.

```
    Vector2 test = new Vector2 (Camera.main.ScreenToWorldPoint (Input.mousePosition).x, Camera.main.ScreenToWorldPoint (Input.mousePosition).y);
    Vector3 test1 = (Camera.main.ScreenToWorldPoint (Input.mousePosition));
    //test.Normalize ();
    RaycastHit2D hit = Physics2D.Raycast (transform.position, test);
    Debug.DrawRay (transform.position, test, Color.red);

```

I tested both variables, test and test1, same things happen, even with Normalize and without it. The following Screenshot shows, what happens (The red thing is the mouse pointer).

Edit:

Solution:

```
    Vector2 test = new Vector2 (Camera.main.ScreenToWorldPoint (Input.mousePosition).x, Camera.main.ScreenToWorldPoint (Input.mousePosition).y);
    Vector3 test1 = (Camera.main.ScreenToWorldPoint (Input.mousePosition));
    //test.Normalize ();
    RaycastHit2D hit = Physics2D.Raycast (transform.position, test1 - transform.position);
    Debug.DrawRay (transform.position, test1 - transform.position, Color.red);

```

I use now the second variable, because we need the Vector3 here, because we substract with Transform.position which is a Vector3.

# Answer
Physics2D.Raycast documentation states :

Parameters:

**origin** The point in 2D space where the ray originates.

**direction** Vector representing the direction of the ray.

**distance** Maximum distance over which to cast the ray.

...

so try :

```
 RaycastHit2D hit = Physics2D.Raycast (transform.position, test-transform.position);

```

where

```
test-transform.position

```

is the ray direction
> 1 votes

---
Tags: unity, 2d, raycasting
---


# Question
Title: GLSL Unsigned Int Values Not Retrieved Properly
I have packed several values needed for shading a particular vertex into a single 32-bit uint. In the shader, it is unpacked like this:

```
vec3 color;
uint vertexData = data;
float sunlight, artificialLight;
bool occlusion;

artificialLight = float(vertexData & 31u);
vertexData = vertexData >> 5;
sunlight = float(vertexData & 31u);
vertexData = vertexData >> 5;
occlusion = bool(vertexData & 1u);
vertexData = vertexData >> 1;
color.b = float(vertexData & 127u);
vertexData = vertexData >> 7;
color.g = float(vertexData & 127u);
vertexData = vertexData >> 7;
color.r = float(vertexData & 127u);

```

The color produced by this extraction is much different from the originally intended color. For example:

```
130, 245, 90 --> 78, 125, 249   (These values are not exact)

```

I took the code and put it into my main c++ program and ran it with a debugger. It showed the right values.

```
130, 245, 90 --> 130, 245, 90

```

**EDIT**

I have taken a uint produced by my compressor and directly inputted it into my shader like this

```
vertexData = 2179293184;

```

Every vertex is shaded with the color of green this value corresponds to. So apparently, there is something going wrong with the transmission of the values. What might be causing this?

# Answer
> 4 votes
I suspect your vertex data is being converted to float (and back again).

You should use `glVertexAttribIPointer` to upload integer vertex data without converting to floating point. From the documentation:

> For glVertexAttribPointer, if normalized is set to GL\_TRUE, it indicates that values stored in an integer format are to be mapped to the range \[-1,1\] (for signed values) or \[0,1\] (for unsigned values) when they are accessed and converted to floating point. Otherwise, values will be converted to floats directly without normalization.
>
> For glVertexAttribIPointer, only the integer types GL\_BYTE, GL\_UNSIGNED\_BYTE, GL\_SHORT, GL\_UNSIGNED\_SHORT, GL\_INT, GL\_UNSIGNED\_INT are accepted. Values are always left as integer values.

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