title: Maya keyframe animation to unity

text:
# Question
Title: Maya keyframe animation to unity
Sorry guys! I am super new to this, and I'm trying to teach myself Unity. I have a very small knowledge of Maya from a 3d modeling course I took a year ago in college, and have made a very simple object and animated it using keyframes (2 keyframes to be exact) in maya, but I can't seem to figure out how to get that animation into Unity.

I've been playing around with this for hours now, and all the tutorials and such I find online are for really complex objects like people, and they have joints and stuff going on. Are joints required for an animation to work in Unity?

I've saved my maya file into my assets folder, but I don't see any animations in the import settings in Unity.

**Here is my object:**

**And it animates to this position:**

# Answer
I saw your post on Stack Exchange and followed you here. I can't comment yet as I just linked y SE account. You could also ask this on answers.unity.com, but whatever.

You have not used joints to animate it I see, but did you use a blend shape, or nothing at all (?). From your question, it sounds like you are keyframing mesh edits, which is not ideal. The "standard" approach to this would be to use either joints or blendshapes in Maya or just animate it in Unity.

Blendshapes is closest to what you are currently doing:

1) Create your base shape.

2) Duplicate it with ctrl+d.

3) Delete all history on both so they are clean.

4) Modify your copy to be the shape you want in the end. Delete its history again. (When you modify stuff you keep a history stack on the object. I'm telling you to delete them because they will bite you later if you don't.)

5) Select the copy, add select the base. Go Animation Shelf \> Create Deformers \> Blend shape options \> Advanced, select "Front of Chain". Click Create.

6) Your copy will be gone, but you will have a blendshape1 node for your base mesh in the channel box on the right (under Inputs). Click it. You should then have two fields beside it, Envelope and (when I tested this just now I created 2 cubes so my copy was named pCube2). DON'T delete history after this. You will delete the blendshape1 node from your model. Creating the blendshapes deformers should be the very last thing you do. So if you have more than one shape you want it to animate to, create all of them from copies of the original base mesh, then select all of them (base mesh last) then do step 5 onward. You will have a field in the blendshape1 node for each shape you combined.

7) Change the value of that second field to something between 0 (meaning not applied) and 1.0 (meaning fully applied). You can key those values. So goto frame 1, set pCube2 to 0, right click it and select key selected. Goto whatever other frame you want to goto and set it to 1, then right-click \> key selected.

8) If you are exporting as fbx then importing in Unity (instead of just importing the Maya file) then I think you have to bake the animations first (in the fbx animations section). When you do that it will let you select the frames you want to export as well.

Notes: Blendshapes are supported in Unity, but if you combine joint-based animation and blendshape animations together on the same mesh the joint-based/keyframe animation takes precedence, and your blendshapes will have to be hand keyed because your driven keys won't work in Unity. If you go that far.

Cheers.
> 2 votes

---
Tags: unity, maya
---


# Question
Title: How to change a Maya scene file's selected viewport renderer from the file itself (text edit)?
So I have been running Viewport 2.0 in my 2012 version of Maya for a couple weeks with no problem. Day before yesterday it started crashing on load with a random MSVC dll pointer error. It's common, but a work around doesn't exist. Anyone know how to modify my .ma scene file contents so that none of my viewports are running Viewport 2.0?

I can import my stuff to another scene, but it's not fun.

# Answer
> 1 votes
Nevermind. Just do a Find/Replace searching for *ogsRenderer* and replace it with *base\_OpenGL\_Renderer*.

---
Tags: maya
---


# Question
Title: How to get quaternion from two orthogonal 3D vectors?
I have a unit vector representing the direction I want to "look" and a unit vector for up. They are orthogonal. How can I get the quaternion that represents that orientation from those two vectors?

# Answer
If you have a method of getting the quaternion of the rotation matrix then just get the lookat matrix and use that method.

otherwise you can get the rotation `R1` from (0,0,-1) to the look vector, This results in a lookat transformation with an arbitrary up.

then find that arbitrary up with `R1*(0,1,0)` and then find the rotation between that and the resulting up with the look vector as the rotation axis.

Concatenate the results and that will be the final transformation.
> 1 votes

# Answer
Something like this should do it:

```
Quaternion CreateFromLookAxis(Vector3 forward, Vector3 up)
{
    var m2 = Vector3.Normalize(forward); // Just in case.
    var m0 = Vector3.Normalize(Vector3.Cross(up, m2));
    var m1 = Vector3.Cross(m2, m0);

    var r0 = m0.x + m1.y + m2.z;
    var result = new Quaternion();
    if (r0 > 0f)
    {
        var r1 = (float)Math.Sqrt(r0 + 1f);
        result.w = r1 * 0.5f;
        r1 = 0.5f / r1;
        result.x = (m1.z - m2.y) * r1;
        result.y = (m2.x - m0.z) * r1;
        result.z = (m0.y - m1.x) * r1;
        return result;
    }
    // else
    if ((m0.x >= m1.y) && (m0.x >= m2.z))
    {
        var r1 = (float)Math.Sqrt(((1f + m0.x) - m1.y) - m2.z);
        var r2 = 0.5f / r1;
        result.x = 0.5f * r1;
        result.y = (m0.y + m1.x) * r2;
        result.z = (m0.z + m2.x) * r2;
        result.w = (m1.z - m2.y) * r2;
        return result;
    }
    // else
    if (m1.y > m2.z)
    {
        var r1 = (float)Math.Sqrt(((1f + m1.y) - m0.x) - m2.z);
        var r2 = 0.5f / r1;
        result.x = (m1.x + m0.y) * r2;
        result.y = 0.5f * r1;
        result.z = (m2.y + m1.z) * r2;
        result.w = (m2.x - m0.z) * r2;
        return result;
    }
    // else
    {
        var r1 = (float)Math.Sqrt(((1f + m2.z) - m0.x) - m1.y);
        var r2 = 0.5f / r1;
        result.x = (m2.x + m0.z) * r2;
        result.y = (m2.y + m1.z) * r2;
        result.z = 0.5f * r1;
        result.w = (m0.y - m1.x) * r2;
        return result;
    }
}

```
> 0 votes

---
Tags: mathematics, quaternion
---


# Question
Title: Detecting a 3 x 3 grid and extracting its coordinates using Kinect
I'm interested in creating a DDR (dance dance revolution) game using unity3D and Kinect. However I need to do this without actually using a pressure sensor pad, just a mat with grids and numbers on it.

Here is what the Grid is supposed to look like:

I need to be able to track where the Mat is placed on the floor and a way to check which number is the user stepping on. The user feet coordinates can be tracked via skeletal tracking, however the **grid coordinates and boundaries need to be extracted**.

Is there a way to do this without using openCv and can opencv be used with Kinect and unity3d?

# Answer
> Is there a way to do this without using openCv

Yes, but it will be difficult to do without *some* kind of image processing library.

> can opencv be used with Kinect and unity3d

I believe you can use EmguCV, but don't quote me on that.

> I need to be able to track where the Mat is placed on the floor and a way to check which number is the user stepping on.

You *could* go about doing 2D computer vision from first principles (extracting edges, using them to infer where the mat is, perhaps dividing it into cells, etc.); the method would be similar (if not identical) to extracting a checkerboard. But I would highly discourage this, because it will not be robust at all. It's also possible to do this using 3D computer vision (finding the floor plane, extracting points of a certain color to infer the mat region), but again I highly discourage this.

Instead of doing *any* of that, I recommend you attach some nice, big April Tags or ARTags to each of the cells in your board. These are patterns that are explicitly made very easy to detect using computer vision. You will probably be able to find a library for such tags that is compatible with C# and potentially even Unity. The tags will give you the position/orientation of each cell with respect to the camera. You can use these to infer world-space regions that you can try to detect the user's feet in.
> 1 votes

---
Tags: unity, kinect
---


title: Center a 3D model to cursor's position

text:
# Question
Title: Center a 3D model to cursor's position
I am having a hard time understanding how to go about this. I have a 2D game with some 3D models in it. I want to move a 3D model to where the mouse cursor is currently at in every frame (In other words, center a 3D model in a specific Point(x,y)).

This is my drawing code to position the model in the center of the screen:

```
Matrix[] transforms = new Matrix[Model.Bones.Count];
Model.CopyAbsoluteBoneTransformsTo(transforms);
ModelMesh mesh = Model.Meshes[0];
BasicEffect effect = (BasicEffect)mesh.Effects[0];
Vector3 modelPosition = new Vector3(0, 0, 0);

effect.View = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);
effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f),
    aspectRatio, 1.0f, 10000.0f);
effect.EnableDefaultLighting();
effect.World = transforms[mesh.ParentBone.Index] *
    Matrix.CreateTranslation(modelPosition);

    mesh.Draw();

```

I suppose I would need a formula to convert the (camera position,model position, aspect ratio, field of view) into pixels ? Does anyone know how it works ?

# Answer
> 0 votes
This function takes in mouse coordinates and picks the model from the 3d scene by shooting a ray through it. Btw the screen size in world coordinates is 2x2 stretching from -1 to +1 on both the x and y axis. The screen size in pixels would be mClientWidth and mClientHeight. You'll see both those in "Compute picking ray in view space"

```
void Pick(int sx, int sy)
{
    float dist = MathHelper::Infinity;
    float tmin = 0.0f;
    XMMATRIX P = cam->GetProj();

    // Compute picking ray in view space.
    float vx = (+2.0f*sx / mClientWidth - 1.0f) / P(0, 0);
    float vy = (-2.0f*sy / mClientHeight + 1.0f) / P(1, 1);

    // Ray definition in view space.
    XMVECTOR rayOrigin = XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f);
    XMVECTOR rayDir = XMVectorSet(vx, vy, 1.0f, 0.0f);

    // Tranform ray to local space of Mesh.
    XMMATRIX V = cam->GetView();
    XMMATRIX invView = XMMatrixInverse(&XMMatrixDeterminant(V), V);

    // Make the ray direction unit length for the intersection tests.
    rayDir = XMVector3Normalize(rayDir);

    XMMATRIX W = XMMatrixIdentity();
    XMMATRIX invWorld = XMMatrixInverse(&XMMatrixDeterminant(W), W);
    XMMATRIX toLocal = XMMatrixMultiply(invView, invWorld);
    rayOrigin = XMVector3TransformCoord(rayOrigin, toLocal);
    rayDir = XMVector3TransformNormal(rayDir, toLocal);

    if (XNA::IntersectRayOrientedBox(rayOrigin, rayDir, scene["Main_Scene"]->instance[i].boundBox, &tmin))
        if (tmin < dist)
        {
            // The model of Main_Scene and instance i was hit.
            dist = tmin;
            tmin = MathHelper::Infinity;
        }
}

```

---
Tags: xna, c#, 3d, monogame
---


# Question
Title: OpenGL Post Processing Introducing Artifacts on Certain Systems
Playing around with God-Rays in my framework, I was greeted with the following artifacts on my laptop:

The artifacts themselves act almost like noise, flickering around the image rapidly. They also appear in colors that are not in the source image whatsoever.

Running the program on a PC yielded the correct results with no artifacts whatsoever. The program also experienced the same artifacts on another identical laptop (these laptops are distributed by my faculty, so they are going to be as identical in hardware and software as you can get).

I'm just not sure how to approach an issue like this one. I imagine the source of this issue will be very tricky to find, so I am just hoping someone can offer some advice to put me on the right track to isolating the issue.

Some potential clues:

* In Nvidia's Nsight frame capture system, the artifacts are not static! Even though I should be viewing a "screenshot" of the current frame-buffer, the artifacts are still dynamic and moving around like noise on an old TV.
* Multiplying the final result of the GodRay directly influences the amount of artifacts. If multiplied by zero, they no longer appear.
* The seam between the two triangles of the full-screen quad can be seen running from the top left to the bottom right.
* I have up to date Drivers. Version 347.52 on the NVS 5400M. I have also tried 347.25, but there was no difference.
* OpenGL is not generating any errors
* I am using an OpenGL 4.5 Core profile
* I have never had any graphical issues in other programs running on my laptop.

**Fragment Shader**

```
#version 450 core
#define NUM_SAMPLES 128

uniform float Exposure;
uniform float Decay;
uniform float Density;
uniform float Weight;
uniform vec2 LightPositionOnScreen;
uniform sampler2D uTex;

in vec2 texcoord;

out vec3 outColor;

void main()
{
    vec2 texCoord = texcoord;
    vec2 deltaTextCoord = LightPositionOnScreen - texcoord;
    deltaTextCoord *= 1.0 / float(NUM_SAMPLES) * Density;

    float illuminationDecay = 1.0;

    for (int i = 0; i < NUM_SAMPLES; i++)
    {
        texCoord += deltaTextCoord;
        vec3 tap = texture(uTex, texCoord).rgb;
        tap *= illuminationDecay * Weight;

        outColor += tap;

        illuminationDecay *= Decay;
    }

    outColor *= Exposure;
}

```

Thanks for taking the time to read my post! I will update if the source of the issue is found.

**Edit:** Issue solved by: chipgw

Initializing `outColor` to `vec3(0.0, 0.0, 0.0)` before the loop removed the artifacts.

# Answer
> 7 votes
My first thought is the `+=` to an uninitialized `outColor`. I think it'd be better to do the math on a temporary variable and put it in `outColor` once it's done.

---
Tags: opengl, glsl, nvidia
---


# Question
Title: OBJ file, face materials and drawing them with OpenGL
I'm implementing a model class which loads OBJ and MTL files, and ran into an issue or question with face materials.

Consider the following example: It's a cube with 5 sides Gray and 1 side Green.

```
mtllib Materials.mtl

o Cube
v -1.000000 -1.000000 1.000000
v -1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 1.000000 1.000000
v -1.000000 1.000000 -1.000000
v 1.000000 1.000000 -1.000000
v 1.000000 1.000000 1.000000

usemtl Green
f 7 8 4 3

usemtl Gray
f 5 8 2 1
f 6 7 3 2
f 8 5 1 4
f 1 2 3 4
f 8 7 6 5

```

The OBJ file obviously shares same vertices for adjacent faces even if the faces get different materials.

When drawing such a cube with OpenGL however, I would need to duplicate the vertices of the adjacent faces with different materials, since every vertex specifies the color it has - and I have two different colors for the same vertices here, depending on the face and the different material it has. If I wouldn't do that, the adjacent faces would smooth over to the different materials.

First: Did I get this correctly or am I missing an OpenGL "feature" here which lets me "specify" the color of a whole triangle / face rather than a single vertex?

Second: If not, is there an easier way to keep track of the faces materials and duplicating the adjacent vertices if they get different materials? What would be the easiest way to implement different materials on one object?

# Answer
You need two vertexes in such this case. There is no way around it. If the faces have a different texture then you will need a different vertexes to define them. To simplify it you could try to save the mesh in such way - check whatever modelling program you use. Sometime it may be as simple as telling it not to weld vertexes together.
> 2 votes

---
Tags: opengl, obj, materials
---


title: Store game events data with XML

text:
# Question
Title: Store game events data with XML
I am new in the game development and now I am at the stage when you need to fill the game content. I want to create the events that occur with the player (like in FTL). Now I make these events with the help of hardcoding, but I understand that this is a very bad style. I know there is another way, use data in XML files. Here is an example:

```
 <event name="SIMPLE_EVENT">
  <text>Event text</text>
  <battle name="MONSTERS_WEAK"/>
 </event>

```

This event show a dialog window and start battle with a random weak monster. I understand how to make this XML files, but I not so experienced with C# to write code that will convert data from XML to my C# classes. How to convert this xml to C# methods invocation? Something like: ShowDialogWindow("Event text"); StartBattle("MONSTERS\_WEAK"); Another example is:

```
<event name="ADD_FUEL">
 <text>Adding fuel</text>
 <item_modify>
     <item type="fuel" min="2" max="2"/>
 </item_modify>
</event>

```

This event show dialog too and add some fuel to the player.

I think its a some deserialization task? Anyway similar as FTL I need one class to represent all events in the game, using different XML data. I ask some advice with this, maybe tutorials, pattens or examples? Or maybe another solution of my task?

# Answer
> 1 votes
For the question of how to deserialize an xml file in c#, this question on stack overflow explains it pretty well: How to Deserialize XML document

The gist of it is, you need to create a class for each type you are going to represent in the xml files, in the example you gave it would be event, item, item\_modify and possibly battle, and define for each object properties corresponding to its content in the xml, for example every event had text.

From then on is a question of what you want to do with these events. Separate interpreting the xml files themselves from what you want the events to do. You should first define the scope of what events the game should have. If you are making a game, this would be rather simple because the event will simply have to serve the mechanics of the game (A simple retro RPG game would have things like random encounters events, gaining items or effects like poison and sleep). If you are making a game engine it might be more complicated as you need to design your events around an unspecific general goal.

The next question you should ask is what part of your game should handle these events. You can't simply send the events to whatever part of your game that is supposed to handle each event (for example, an inventory should handle all item events) because the question of what class should handle what event can only be answered after reading the event, so an intermediate must decide what part should get what event. The solution to this problem can vary wildly depending on your implementation so far but the simplest solution is this: whenever you read a new event, ALL classes that can handle events receive it, and each one handles it on it's own discretion.

You can implement such a system by having a single class (`EventReader`) with a method that receives a file name, and with a C# event that receives an instance of the class representing game events (`Event`).

```
public class EventReader{
    public delegate void GameEventHandler(Event e);
    public event GameEventHandler GameEventReceived;

    public void readEvent(String path){
        XmlSerializer serializer = new XmlSerializer(typeof(Event));

        using(StreamReader reader = new StreamReader(path)){
             reader.ReadToEnd();
             event = (Event)serializer.Deserialize(reader);
             if(GameEventReceived != null)
                 GameEventReceived(event);
        }
    }
}

```

Every class that wishes to handle game event can simply add the game event handling method to the game-event event on this class.

---
Tags: c#, xml
---


title: Pygame 2D Vector Math Mouse Input

text:
# Question
Title: Pygame 2D Vector Math Mouse Input
The following code is supposed to move a player sprite (in this case it's an 8x8 red square) to the coordinates of where the mouse is clicked. I'm able to move the square in the general direction of the click but the sprites path does not always pass precisely through the point. I'd love someone to analyse the code and show me where I'm going wrong with this.

```
from __future__ import division
import math
import pygame

SCREEN = pygame.display.set_mode([700, 700])
SCREEN_HEIGHT = pygame.display.Info().current_h
SCREEN_WIDTH = pygame.display.Info().current_w
pygame.display.set_caption('Window Caption')
clock = pygame.time.Clock()

class Player(pygame.sprite.Sprite):
    def __init__(self, color=(255,0,0), dims=[8,8], (originx, originy)=(100,100)):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface(dims)
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.rect.centerx = originx
        self.rect.centery = originy
        self.speed = 10
        self.vx = 0
        self.vy = 0

    def normalize(self, (p1x, p1y), (p2x, p2y)):
        dx = p2x - p1x
        dy = p2y - p1y
        vlength = math.hypot(dx, dy)
        vnorm = (dx / vlength, dy / vlength)
        self.vx = vnorm[0]
        self.vy = vnorm[1]

    def update(self):
        self.rect.centerx += (self.vx * self.speed)
        self.rect.centery += (self.vy * self.speed)
        print self.rect.centerx, self.rect.centery, self.vx, self.vy # verify calculations

pygame.init()

sprites = pygame.sprite.Group()
player = Player()
sprites.add(player)

looping = True
while looping:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            print "Exiting..."
            looping = False
        if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    print "Exiting..."
                    looping = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            (left_click, middle_click, right_click) = pygame.mouse.get_pressed()
            mouse_pos = pygame.mouse.get_pos()
            if left_click:
                print "left click", (player.rect.centerx, player.rect.centery), mouse_pos
                player.normalize((player.rect.centerx, player.rect.centery), mouse_pos)
            if middle_click:
                print "middle click", mouse_pos
            if right_click:
                print "right click", mouse_pos

    SCREEN.fill((0,0,0))
    sprites.update()
    sprites.draw(SCREEN)

    # Redraw everything we've asked pygame to draw
    pygame.display.flip()

    # Set frames per second to 60
    clock.tick(60)

# Quit gracefully if we exit the main loop
pygame.quit()

```

# Answer
> 1 votes
It seems your player coordinates are in integers, in python integer division gives you a float as answer which explains why your player moves mostly in the right direction, but then when you store the new position you drop the decimal point so each frame your losing a bit more precision.

You either need to store the target location instead of a vector so you can compensate for the shift each frame, or you need to store the coordinates as floats instead. Hope that helps

---
Tags: vector, pygame, mouse
---


# Question
Title: How to restrict jumping to a single jump?
I'm making a VolleyBall game in HTML5 with PandaJs GameEngine and plugin is used physics and Box2D.

The problem is that players can jump, but they can jump over the net with multiple jumps. I have already implemented collision detection but i don't know how the restrict move space for player. I also attaching my screen shot here so look at this :

In the picture Player1 goes Player2 side and vise-versa.

# Answer
> 4 votes
The most common approach to this is to detect if the character is standing on a solid surface before allowing them to jump. This restricts players to a single jump since the first jump puts them in the air, then they're no longer on a solid surface, so the next time they try to jump, they can't.

For Box2D specifically you can see how to implement that here:

How do I use a JBox2D ContactListener to check if my character is standing on the ground?

---
Tags: physics, box2d, jbox2d
---


# Question
Title: Rotate heading relative to agent's local space
I'm having a little trouble translating a point in my game's world space to an object's local space.

I have a cannon in my game with a normalized heading vector that's always supposed to point in the direction of a target. The target is set by an incoming screen touch event.

My problem is that the coordinates I get from the incoming touch events are relative to the game world's axis centered at the world's origin, not relative to the cannon's position like I need. The angle I calculate to rotate the heading is relative to the world's X-axis, not the cannon's local X-axis, this means I can never rotate the heading by anything outside of 0 \< x \< 90.

I hope my crude drawing conveys what I mean. In the picture below, A is the cannon's position (with the blue heading vector), and B is the target's location (set by an event). The green line represents the angle the game is giving me, and the angle between red line and the heading is what I need to find (the little curved blue arrow).

Here's the code I use to calculate the heading:

```
 float xDistance = target.x - position.x;
    float yDistance = target.y - position.y;
    float angleToTurn = (float) Math.atan2(yDistance, xDistance);

    vec2RotateAroundOrigin(heading, angleToTurn);

```

Thanks in advance. Any help is greatly appreciated.

# Answer
> 1 votes
This is fairly easily solved with a bit of vector math.

You're interested in the vector from the cannon to the event point, but you have the cannons position and the event point from origo. Adding the cannons position to the vector pointing from the cannon to the event would equal the event from origo vector.

Or in other words:

```
OrigoToEvent = OrigoToCannon + CannonToEvent
OrigoToEvent - OrigoToCannon = OrigoToCannon + CannonToEvent - OrigoToCannon
OrigoToEvent - OrigoToCannon = (OrigoToCannon - OrigoToCannon) + CannonToEvent
OrigoToEvent - OrigoToCannon = CannonToEvent
CannonToEvent = OrigoToEvent - OrigoToCannon

```

From there on it's simply a matter of calculating the angle between the two vectors. I hope that is enough to get your code working

---
Tags: opengl, java, android, matrix
---


title: Collision detection with moving tilemap

text:
# Question
Title: Collision detection with moving tilemap
I have a player whose who's sprite is 48\* 32. I know the player's position. The player can move up and down based on user input.
I have a tilemap which moves. Here is an example of the array I use to draw the tilemap.

```
int[][] map0 = {
                        new int[]{1 ,2 ,1 ,2 ,1 ,2 ,1 ,17 ,1 ,2 ,12 ,13 ,1 ,2 ,1 ,2 ,8 ,9 ,10 ,11 ,1 ,2 ,1 ,2 ,1 ,2 ,1 ,2 ,1 ,2 },
                        new int[]{29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 },
                        new int[]{31 ,32 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,78 ,98 ,99 ,79 ,0 ,0 ,0 ,0 ,0 ,98 ,99 ,0 ,0 ,0 ,0 ,0 ,0 },
                        new int[]{31 ,37 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,95 ,96 ,96 ,96 ,96 ,97 ,0 ,0 ,0 ,0 ,100 ,101 ,0 ,0 ,0 ,0 ,0 ,0 },
                        new int[]{31 ,38 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,102 ,103 ,0 ,0 ,0 ,0 ,0 ,0 },
                        new int[]{31 ,32 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 },
                        new int[]{31 ,32 ,66 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 },
                        new int[]{35 ,36 ,67 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 },
                        new int[]{41 ,42 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 },
                        new int[]{41 ,42 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 },
                        new int[]{41 ,42 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 },
                        new int[]{41 ,42 ,64 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 },
                        new int[]{33 ,34 ,67 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 },
                        new int[]{31 ,32 ,0 ,0 ,66 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 },
                        new int[]{31 ,37 ,0 ,0 ,104 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 },
                        new int[]{31 ,38 ,0 ,0 ,105 ,0 ,0 ,0 ,108 ,109 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,108 ,109 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 },
                        new int[]{31 ,32 ,0 ,0 ,106 ,0 ,0 ,0 ,110 ,111 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,110 ,111 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 },
                        new int[]{31 ,32 ,0 ,0 ,107 ,0 ,0 ,0 ,56 ,57 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,56 ,57 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 },
                        new int[]{26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 },
                        new int[]{27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 },
                        };

```

Here is some code in my draw method:

```
for (int y = 0; y < map0.GetLength(0); ++y) {
    for (int x = 0; x < map0[y].Length; ++x) {
        sourceRect.X = 16 * map0[y][x];
        tilePos.X = 16 * x;
        tilePos.Y = 16 * y;
        spriteBatch.Draw(texture, tilePos + mapPos, sourceRect, Color.White);
    }
}

```

Each tile is 16\*16. The texture is a sprite sheet of tiles arranged in a horizontal position. map0\[y\]\[x\] gives the int in the map array. I multiply it with 16 to get the x coordinate of the tile in the sprite sheet. So the for loop draws the map on screen. In the update method I do `mapPos.X += -1f;` so that the whole map moves across the screen.
**Problem:** So my problem is how to detect collision between each tile in the tile map.(0 means transparent tile which the player cannot collide) I have tried looping through the whole map and check if player collides with a tile by using many if statements and coordinates. But this makes the game's fps go to 1.
Can someone suggest me a way to do this without freezing the game?

# Answer
To check your collision you simply take the players position and divide it with the size of each map element to get the index of where the player is in the map, then check for collision surrounding that. The player is 48x32 and the map is 16x16 so (48,32) / (16,16) = (3,2).

But since the player can move smoothly you need to add one more coordinate to each direction so you check both the tile he is half into to the left as well as the one to the right.

```
// Vector2 has overloaded division and addition functions so that:
// Vector2.One + Vector2.One is the same as new Vector2(1+1, 1+1)
// new Vector2(4, 9) / new Vector2(2,3) is the same as new Vector2(4/2, 9/3)
var playerTileSize = playerSize / tileSize + Vector2.One
var playerTilePos = playerPosition / tileSize

// But Vector2 holds float values and we are going to be using it with array
// indices, so lets extract the x and y components, width and height don't really
// need the ceiling call here since the player sprite is an exact multiple of the
// block sprites, but if you ever change the sprites size this code will keep working
int w = (int)Math.ceiling(playerTileSize.x)
int h = (int)Math.ceiling(playerTileSize.y)
// As for the offset, we want to make sure we grab the topleft index so we want
// to remove the decimal portion entirely. Of course (int) already does that,
// but I wanted to make it explicit that it is what we want to do.
int offsetX = (int)Math.floor(playerTilePos.x)
int offsetY = (int)Math.floor(playerTilePos.y)

// Now simply go through all the cells in the map that the player is covering in whole
// or partially, we can simply go over the width and height of the player sprite in the
// for loops and add the offset value we calculated above, it makes the for loops a
// little neater and easier to read
for (int y = 0; y < w; y++)
  for (int x = 0; x < h; x++)
    // And finally we need to "check the collision"
    checkCollision(map0[y + offsetY][x + offsetX])

```

In your question you said that it's a collision if the map0\[y\]\[x\] is anything but 0, so we can implement checkCollision with this rule as follows:

```
public static bool checkCollision(int mapTile) {
  return mapTile != 0;
}

```

This way you can change the collision detection later if you want. For instance, say you want tile 128 to be darkness but still not cause collisions, then you only have to change that one place instead of remembering to look for it everywhere.

> I have a player whose who's sprite is 48\* 32. I know the player's position.

I can only assume this statement means you know the position on the screen. It is a common start for developers to think of it in terms of screen position, but it makes more sense to describe the world, and the players position in it, in terms of its own coordinate system that is mostly unrelated to the screen position.

For instance you would have the players position in relation to the top left corner of the map and treat the shifting map as if a wall is coming up from behind the player, when the player touches the wall they die (at least that is how I guess your scrolling map would work).

```
spriteBatch.Draw(playerTexture, playerPos + mapPos, ...);

```

And for the death condition (in update)

```
if (playerPos.x - mapPos.x <= 0)
  playerDied();

```
> 2 votes

# Answer
> I have a tilemap which moves

First of all you start from wrong way. Player should move inside world and not world should mo around player. It's not a Futurama. In other words do

```
player.Position.X += dx

```

instead of

```
world.Position.X -= dx

```

It's mutch cleaner solution.

Next. Let's you have viewRect that is your visible part of world

```
Rectangle viewRect = new Rectangle(0, 0, screen_width, screen_height);

```

And you have your player position of tyte Vector2. You can simply calculate current view:

```
Rectangle currentViewRect = new Rectangle(
    viewRect.X + player.Position.X + drawOffset.X,
    viewRect.Y + player.Position.Y + drawOffset.Y,
    viewRect.Width,
    viewRect.Height);

```

Then you can determine visible tiles like I in my answer on this question.

In the same way you can determine tiles that you characted potentialy can intersetc and check only them. You use grid for keep tiles, so if you have coord in pixels you can find coord of grid cell.

```
Vector2 minTileCoord = new Vector2(
    (int)player.Position.X / tileWidth,
    (int)player.Position.Y / tileHeight);
Vector2 maxTileCoord = new Vector2(
    (int)(player.Position.X + player.Width / tileWidth,
    (int)(player.Position.Y + player.Height) / tileHeight);

```

And now you need only check tiles from maxTileCoord.X to maxTileCoord.Y by X and maxTileCoord.Y to maxTileCoord.Y by Y axis.
> 2 votes

---
Tags: xna, c#, collision-detection, monogame
---


title: Playing a sound once pygame

text:
# Question
Title: Playing a sound once pygame
I'm trying to play background music and the music keeps on starting. I tried to use `music.busy`, but I can't figure it out. I want it to check if sound/music is playing, then I want it to print "music is playing". If a sound/music isn't playing I want it to start up a new song and loop it.

```
def musica():
    if pygame.mixer.music.get_busy() == True:
        print("music is playing")
    if pygame.mixer.music.get_busy() == False:
        music.play(loops=-1)

```

# Answer
Seeing as your music is meant to loop indefinitely you could just assume the music is still playing after having started it once, something along the lines of:

```
need_music = true
def musica():
  if need_music:
    pygame.mixer.music.load( something )
    pygame.mixer.music.play(-1)
    need_music = false

```

From the look of your code your problem might be that the music isn't loading properly, by playing it only once you can tell if the problem is with the streaming, the music itself or your code and then figure out what is wrong from there.
> 1 votes

# Answer
The code looks mostly fine, although the more pythonic way to write it would be

```
def musica():
    if pygame.mixer.music,get_busy():
        print("Music is playing")
    else:
        music.play(loops=-1)

```

This could also eliminate any issues of it going into both `if` statements
> 0 votes

---
Tags: python, pygame
---


# Question
Title: Semi-transparent mouse cursor on Windows
I want to change the mouse cursor for a desktop game I am writing with libGDX. That is working well under Linux, however, under Windows semi-transparent cursor pixels are not being rendered at all. That means I am unable to anti-alias the cursor image.

For sure there must be a way to render semi-transparent mouse cursors under Windows, like it's possible under Linux. Any ideas what I could do to solve this issue?

# Answer
Apparently it is not possible to render semi-transparent cursor pixels under Windows. The workaround seems to be to hide the default cursor and render your own... (I am happy for better ideas though.)
> 1 votes

---
Tags: libgdx, mouse
---


# Question
Title: 3D OBB vs OBB Collision Detection and Response
(Edited, was a rather goofy, long question. I have since decided on using JBullet and I love it.)

How can I accomplish 3D OBB vs OBB collision detection in my game? I understand how AABB's detect being inside one another, and I understand how to rotate a point around another point. But once a collision is detected, how should a physics engine respond to that? It is the collision and resolution that I don't understand how to do; making the objects move/react appropriately.

# Answer
There are many ways to perform collision detection Cello Coder. The simplest may not be the best solution for your game and may cause bugs to show up...

I have never used LWJGL so there might be a library someone has made for collisions, but it really comes down to two ways.

1. easy way - buggy - perform a check to see if the mesh of object one is near object two pseudocode -\> obj1.pos +/- obj1.size intersects a bound that obj2.pos+/- obj2.size also intersects.
2. harder way - less buggy - calculate the velocity of the moving obstacles at each time there is an interaction and check to see if the two velocities(of the objects) intersect. If they do intersect calculate the time of intersection and set a condition to make those two objects interact accordingly.

If you are worried that 3D is a little bit different than 2D, just think of it as adding the third dimension and performing the math the same way, but adding in a third variable into the equation.

Does that make sense?
> 1 votes

---
Tags: collision-detection, 3d
---


# Question
Title: Unity polymorphism in editor through a list
So I have an `ItemDatabase` class which basically only has a list of `Item`

```
public class ItemDatabase : MonoBehaviour {
    public List<Item> Items = new List<Item>();
}

```

The `Item` class looks as follows:

```
[System.Serializable]
public class Item {

    public string Name;
    public int Id;
    public string Description;

    public Texture2D Icon;
}

```

Now I have some item types deriving from the `Item` class, for example `Consumable`

```
[System.Serializable]
public class Consumable : Item {
    public int Resore;
}

```

I next created a gameobject (empty) in my editor and hooked up my `ItemDatabase` to that object, providing a number of items in the list is no problem but I would like to make sure that - from my editor - I can choose a type of Item to put into the list, as of now, it only lets my add `Item` and not `Consumable` because it is a list of `Item`.

Can I also force the editor **not** to accept just `Item` by making it an *abstract* class?

# Answer
> 1 votes
You'll probably have to look into PropertyDrawers to get what you want. These are custom property drawers for Unity. The Unity inspector doesn't know how to render a lot of things by default and it may render things in a way that's not suitable to you, or doesn't have the information you need.

Depending on the features you need, you might need to expand into a custom inspector. This is similar to a Property Drawer, but it's for the entire MonoBehaviour script instead of the specific object type. This is where modifying the inspector gets really powerful, since you can add all kinds of automation or other features to the Unity inspector. It's a great chance to optimize your workflow and make Unity more powerful.

---
Tags: unity, polymorphism
---


# Question
Title: RPG - Accuracy Formula (HIT or MISS only)
I am creating the combat system of a simple RPG. The only two factors in this system are damage and accuracy.

Accuracy in this game simply means either the attacker HITS or MISSES. There is no partial damage or partial hits. The target has no chance of dodging the attack if the attacker HITS. A player's accuracy is represented with a percentage, e.g. 75% of the time the player will HIT.

In combat, the damage formula determines the damage inflicted on a target, but the damage will only be inflicted if the player HITS the target.

I have already created a damage formula; however, I do not know how to create a simple and practical accuracy formula. I have thought of this, but it's quite impractical because of how it will need to be manipulated if the player's accuracy improves/increases:

* An array is filled (Player's accuracy)% with 1's, remaining percent with 0's
* At random, one index of the array is chosen
* If it's a 1, the player HITS; if it's a 0, the player MISSES

I have looked around this network at accuracy/hit or miss formulas but they involve other factors such as dexterity and evasion. I've also looked elsewhere online, but again the formulas involve other factors.

Is there a simple and practical formula to accomplish this?

# Answer
A random number generator and a simple test is all you need, for example, in C#:

```
Random rnd = new Random();
int value = rnd.Next(100);
if(value < accuracyValue) {
    //We have a hit
} else {
    //We have a miss
}

```

This works when `accuracyValue` is a number between 0 and 100, representing the player's hit chance. For example, a hit chance of 75% would be `accuracyValue = 75;`.

We choose a random value between 0 and 100. For any number between 0 and 100, 75 of those numbers will be below 75 (because 0 is included). That means, choosing a random number between 0 and 100 gives us a 75% chance of getting a number below 75. This results in a simple way to get true or false at a specific percentage.
> 1 votes

---
Tags: rpg, mathematics
---


title: Importing code from unityscripts

text:
# Question
Title: Importing code from unityscripts
To encourage code reuse- i want to import methods and classes defined in my core unityscripts to be imported into other unityscripts. How do i go about this?

Note: An answer here seems too complicated for such a simple thing (i come from Python).

# Answer
> 2 votes
You can use inheritance for this. Have the methods and classes in a common base class that's extended by your classes that share this functionality.

Or you can use composition for this. Have the methods and classes in non-monobehaviour scripts. These will be instantiated as objects in your scripts that share this functionality.

Or you can keep these scripts contained in their own scripts at attach them as components to the objects where you want to use their functionality.

You have lots of options here, personally I'd go the inheritance route, but it depends on the kind of functionality you're sharing between scripts.

---
Tags: unity, unityscript, import, importing
---


# Question
Title: Dragging an object and moving it back to it's original position on release?
I'm making a small game, and I'm trying to add this mechanic where if you click on an object and move it, then you release the object it will snap back to it's original position. Currently, each object has a Vector2f, and I'd prefer that when you release it, it eases back to it's position, is this possible? I've tried to use atan2, but it doesn't work, since it only calculates an angle then keeps moving towards the angle, and doesn't stop.

Here's the code I have for it so far. When the object is released, the initialPosition Vector2f is set to the position that the object is released.

```
if (moveBack) {
    float angle = (float) Math.atan2(position.y - initialPosition.y, position.x - initialPosition.x);
    position.x += Math.sin(Math.toRadians(angle));
    position.y += Math.cos(Math.toRadians(angle));
}

```

# Answer
> 0 votes
There is no need to calculate the direction, instead you can use interpolate between the two positions. Interpolation is when you calculate a position between `start` and `end` using an `interpolant` which is 0 at the start and 1 at the end.

The simplest of these is linear interpolation, often shortened to lerp. Many game api's has this function somewhere but you didn't mention which one you use, it is very easy to write yourself though:

```
public float lerp(float start, float end, float interpolant) {
  return (1-interpolant) * start + interpolant * end;
}

```

As you can see, when the interpolant is 0 start is multiplied with 1 and end with 0. And the reverse for when interpolant is 1. And for a Vector2f:

```
public float lerp(Vector2f start, Vector2f end, float interpolant) {
  return new Vector2f(
    (1-interpolant) * start.x + interpolant * end.x,
    (1-interpolant) * start.y + interpolant * end.y)
}

```

Now you just need to store the point the item was let go from and the time remaining for the interpolation, something like this:

```
if (moveBack) {
  moveBackTime += timeSinceLastFrame;
  if (moveBackTime <= 1f)
    position = lerp(droppedPosition, initialPosition, moveBackTime);
  else {
    moveBack = false;
    position = initialPosition;
  }
}

```

---
Tags: java, physics, vector
---


# Question
Title: Are Textures cached by GPU or buffered from memory for every frame?
Are the textures buffered from memory(RAM) for each Draw Call/Frame or are cached in VRAM.

As per my research, I believe in the former case, if it is, then isn't the second approach a better option?

For example, in First Person Shooter games, the weapon is going to be rendered 98% of the time, so are those weapon textures cached by the GPU locally?

I am not sure about this, so I hope someone could explain this.

# Answer
> 1 votes
They're usually stored in GPU memory. In some cases, when the GPU has to evict them, they will need to be restored from CPU-side memory, but this is "uncommon" unless you are really thrashing the card.

You should never see them populated from CPU every frame under normal conditions unless you are also updating the texture CPU-side every frame.

---
Tags: gpu
---


title: Play vs. PlayOneShot

text:
# Question
Title: Play vs. PlayOneShot
For Unity `AudioSource` objects, what is the difference between the `Play` and `PlayOneShot` methods, besides their method signatures?

Is it simply that `PlayOneShot` won't stop an already playing sound from the `AudioSource`? So given a scenario where you can guarantee that a call to `AudioSource.Play()` won't occur again until its `isPlaying` boolean value is false, is there any reason to use `PlayOneShot`?

# Answer
You've already identified the main difference: PlayOneShot can play multiple sounds without cutting each other off. On the flipside however that means\* you can't stop the audio clip either; it'll just play all the way through, with no way to stop it early.

\*I think; I can't test this at the moment, but I recall that calling Stop() after PlayOneShot() does nothing.
> 6 votes

---
Tags: unity, audio
---


title: Get fragment from mouse position

text:
# Question
Title: Get fragment from mouse position
I have a painting app for texture artists that I am working on. I am able to paint to a flat canvas that updates the texture of a 3d object in an object viewer. Now I want to be able to paint directly to the 3d model.

One way I can think of is to get the uv coordinate from the mouse position, and use that as the position to paint onto my 2d canvas, which updates the 3d models texture.

Oh and only one object at a time is active, so that should make things a little simpler.

Is this the right approach? If it is then how should I start. Or is there a simpler/better way of painting directly to a 3d model? How does zbrush do it?

# Answer
Here are two approaches that I've used before:

---

The approach I prefer is to create an indirection map:

1. Render the UV coordinates themselves to a texture
2. Iterate the raw pixels of the 3D view which need to be updated.
3. Splat into the model texture for each UV pixel

---

The other approach I've had success with is un-projecting and raytracing

1. Invert your view matrix, and compute a ray that corresponds to the clicked point
2. Raytrace the scene, and find the target to paint onto
3. Compute the barycentric coordinates and UV coordinate of the intersection
4. Brush onto the model texture at the UV coordinate
> 3 votes

---
Tags: opengl, textures, raycasting, uv-mapping, picking
---


title: What is a "2.5D" environment?

text:
# Question
Title: What is a "2.5D" environment?
I don't understand the meaning of the term "2.5D." I'm specifically confused about the difference between 2.5D and 3D environments, even though I've read different definitions and articles about both. I understand the parts where 2.5D is like 3D but I don't get the parts where 2.5D is different.

So, *what does it mean for a game to be 2.5D?* For example, is the game shown here 2.5D?

# Answer
> 63 votes
The terms **2D** and **3D** (as you probably already know) refer to the number of spatial dimensions in a Euclidean world-space. This dimensionality must be an ordinal number; there is no such thing as a *half dimension*, so the term **2.5D** is really a nonsense term, and has no intrinsic meaning. That said, 2.5 is "somewhere between" 2 and 3, so 2.5D generally means something along the lines of "somewhere between 2D and 3D".

Personally, I use the term to refer to cases where a game's graphical and logical world-spaces have different dimensionalities. In particular, there are two different variants here:

* **2D logical & 3D graphical**. For example, a platformer with 2D game mechanics and physics, but rendered with 3D meshes and a perspective camera. Most remakes of classic arcade games like Pac-Man, Breakout, etc. fall into this category. Pictured below: Pineapple Smash Crew

* **3D logical & 2D graphical**. Examples include games like Gnomoria or SimCity 2000 which have 3D game worlds, but are rendered in a 2D isometric view. Pictured below: Xenonauts

Another common use of the term (though not one that I use) refers to games which utilize a combination of 3D and billboarded 2D graphics. In this case the term does not describe the logical dimensionality of the game at all. Virtually all 3D games use billboarding in some way or another, including particle systems, distant-object proxies, and in-world UI overlays. Therefore, the term is usually only used when a significant portion of non-background objects use 2D graphics, and the border between 2.5D and 3D is somewhat blurry.

# Answer
> 29 votes
The first game I'm aware of that had the term "2.5D" applied to it was Doom (although Wolfenstein 3D qualifies in some sense too).

Wolfenstein 3D was a basically 2D game with a 3D presentation. You navigated a 2D maze, all the floors were flat, all the ceilings were at the same height, there were no windows, doors were floor-to-ceiling and opened sideways, and you could never be on top of or below another object. The game used raycasting to figure out, for each column of the screen, how far away the wall was in that direction, and what texture the wall had; then a column of the wall texture was drawn with a height inversely proportional to the distance, and the space above and below painted with floor fill and ceiling fill. Enemies and objects were sprites, with a limited number of aspects, and their size again proportional to distance.

Doom used very similar technology to Wolfenstein 3D, but abused it to get a more 3D experience. The maps were *still* 2D, represented using 2D binary space partitioning (thus the .BSP map filename). What you saw on the automap when you hit tab was just a direct 2D rendering of the map. But each sector had an independent "floor height" and "ceiling height", and edges had top and bottom side textures (used when they had a lower ceiling height, or a higher floor height, than part of their surroundings). This allowed for stairways, windows, platforms, pools, and other effects — the engine just had to be able to keep a list of multiple sectors passed through before eventually hitting a wall, and their respective textures. But you still couldn't have real 3D architecture — you could make a "bridge" across some slime using a raised section of floor, but it would be impossible for anything to be *under* the bridge. A position in the game is still only X and Y. The only control the player has over their height is falling off of things, and elevators, which are simply sectors that are scripted to change their floor height. Enemies are still sprites (although I think they had more aspects), shots "auto-aim" in height because the collision detection is only 2-dimensional, and there wasn't a 3D model to be found in the game.

Heretic and Hexen used Doom-derived engines that took things even a step further, to the point that they were occasionally called "2.75D"; they had most of the same architectural limitations and sprite-based enemies, but added the ability for the player to look up and down (tilt the view, but only so far or else the engine would break) and to jump, fly, and crouch (changing their height independently).

# Answer
> 12 votes
## 2.5D

2.5D ("two-and-a-half-dimensional"), ¾ perspective, and pseudo-3D ar terms, mainly in the video game industry, used to describe either 2D graphical projections and similar techniques used to cause a series of images (or scenes) to simulate the appearance of being three-dimensional (3D) when in fact they are not, or gameplay in an otherwise three-dimensional video game that is restricted to a two-dimensional plane.

In my experience which definition is emphasized depends on the age of the person you are talking to.

1. Older gamers tend to use the 1st definition "*2D graphical projections and similar techniques used to cause a series of images (or scenes) to simulate the appearance of being three-dimensional (3D) when in fact they are not*"
2. Younger gamers use the 2nd definition "*gameplay in an otherwise three-dimensional video game that is restricted to a two-dimensional plane*".

Personally I use the 2nd definition. Trine, Donkey Kong, and Super Mario Bros Wii U would all be 2.5D in my opinion. Additionally the 2.5D Steam tag uses the second definition. I figure this is a good litmus test for how a typical gamer defines the concept) and as such **I believe the 2nd definition is more correct**.

# 3D

Any video game with 3D game graphics, that are computed in 3 dimensions. Note this makes it a super-set of the second 2.5D definition.

# Answer
> 7 votes
2.5D is just a convienient way of saying 2D that looks 3D.
I supose you could really blur the lines of the definition if, for example, you use a 3D engine but restrict gameplay to a 2D plane only, but personally I'd consider something 2.5D is it **looks** 3D but **acts** 2D.

# Answer
> 4 votes
The game screen shot you posted is a 3D game.

In a 3D game, the objects are drawn using vertices to draw actual 3D objects, which are then colored, textured, so forth.

In a 2D game, the objects are taken from sprites / sprite sheets, etc.

The difference between the two is how you can view them. A sprite is like a flat piece of paper. You can not view it at a different pitch or angle or the sprite will be skewed. On a 3D object, as the camera moves, you can see different parts of the object because the object is, well 3D.

In a 2.5D game you are combining both of these worlds. Keep in mind just because you can't move a camera to see different angles, doesn't make a game not 3D. It's the objects that are in it that determine this.

A good example of a 2.5D game is Ragnarok Online. What makes it 2.5D is that the world is mostly compromised of 3D objects. Buildings, landscape, etc are textured 3D objects. You can rotate the over head camera and see different sides of these objects at the same time. You can view the front side of a building as well as a left/right/roof area. The players however, are 2D sprites that are positioned to appear to be standing upwards. If you rotate the camera too much, the game must load a different cell of the sprite sheet for that character to change how it appears to be standing. You can not view different angles of the character because they aren't 3D. The angles are dynamically loaded in depending on the view of the camera.

http://sprites.technoized.com/images/sprite/ro/gm\_m.png

This is a sprite sheet from the game. If you were to just look at it, you would assume it's from a 2D game. Alone, you would be correct. But once it's placed into a 3D world, you have a 2.5D game.

# Answer
> 3 votes
2.5D is often another way of saying "isometric" -- 2D graphics drawn in a way to give the appearance of 3D, but not actually simulating 3D coordinates. See the wikipedia article on isometric graphics: http://en.wikipedia.org/wiki/Isometric\_graphics\_in\_video\_games\_and\_pixel\_art

The gist is that in 2.5D/isometric, you are still using a 2D coordinate system -- with x and y axes only to calculate your graphics. Your graphics may simply be 2D sprites, which are typically drawn such that you can see three faces, and then placed on the screen using (x,y) coordinates. Sometimes the sprites are even created by modelling in 3D, then creating 2D sprites of the 3D model from multiple angles.

Moving objects characteristically only have a few angles they can be viewed from. If you spin a character around in an isometric view, it won't smoothly spin, but you'll see several distinct angles, such as front, 3/4, side, and so forth. This is because each unique angle of view requires a whole new set of sprites.

Isometric games usually support only one camera angle, because of the limitations of this type of system. Another distinguishing feature of isometric games is that they do not typically have vanishing points. When viewing an object in real life, if the object is closer to you, the object will appear larger in your vision. If the object is farther away, it will appear smaller. In isometric games, all objects typically appear the same size no matter where they are located in space.

3D games in comparison, simulate all 3 axes -- x, y, and z. On a very low level, the computer is translating x, y, and z to x, y to be displayed on a monitor, but on a higher level, artists are actually manipulating points on 3 axes to represent objects. Since the computer has all the information about the shape of the object, it can dynamically calculate what that object looks viewed at any angle, and it can appear smaller or larger as you get closer or farther from it.

Some games are a mix of 2.5D and true 3D. An example I can think of is the Disgaea series, which features 3D backgrounds and 2D sprites.

# Answer
> 3 votes
I am not sure what would be the more accepted definition, but I and the folks at my previous company considered "any game which looks like isometric 3D, but is rendered via 2D sprites" to be 2.5D.

Now let me explain why we did that. Generally rendering a 3D world with a lot of objects in it will create too much pressure on the processing, lowering the FPS count. So to overcome this we generally created objects in 3D rendering software like Maya and rendered them as sprites. Which can be used in the game. Not to mention that the angle were considered while rendering. So to speak about this tech with publisher we normally used this term. A 3D world which looks like it's a 2D world is still technically 3D for us. So we generally didn't use the term for this method. I thought I should share my bit here.

# Answer
> 2 votes
Usually the term "2.5-D" refers to one of two very different styles of games.

It could either mean:

1) A game that uses 2-D rendering techniques, but controls in 3 spacial dimensions. Usually uses graphical tricks to appear as though it were actually rendered in 3-D. This was very common in the 90s, but not so much today. (Examples: "DOOM", "Duke Nukem 3D", "Wolfenstein 3D")

2) A game rendered entirely in 3-D, but that controls exclusively along one or more 2-D planes. This style remains very popular to this day. (Examples: "Little Big Planet", "New Super Mario Bros.", "Trials HD")

One thing to note is that when using the model-view-controller architectural pattern, the first style of game has a "model" that represents data in 3 dimensions but a "view" that only displays it to the user in 2 dimensions; the second style of game is the other way around.

# Answer
> 1 votes
In 2.5D you use 2D assets/rendering techniques to give the sensation of a 3D environment.

Now, with that definition, in the following potentially ambiguous scenario, some elaboration is required:

Game A

Using 3D graphics, GPU accelerated and all (the game objects are meshes, not images), with a fixed camera angle. Lets make it even worse, the projection is orthographic, the classical 63.43 degrees. The only way to notice at first glance that graphics aren't 2D is because 3DGC, except that you render them with extreme care, are easily differentiated from hand drawing sprites, not matter the projection used to render them. You may experiment with different render techniques, parameters, shaders, etc, and you will have a hard time trying to hide the fact that they are 3D meshes.

Game B

A port of Game A, but targeting platforms that are known to have hardware that does not handle 3D graphics very well or does not handle it at all. Then the port replaces meshes with sprites. It still uses 3D Bounding Boxes for collisions, for example, and objects have a position property with x,y and z values, as the game logic was mostly not touched or not touched at all, only the rendering code was altered.

As the sprites of Game B are renders of the 3D assets of Game A and, to make things more ambiguous, Game A doesn't do anything that requires complicated shaders, in 99% of all GPUs out there you cannot differentiate a frame from Game B of a frame from Game A.

In 2.5D, interaction between game objects are limited to the set of situations where the illusion of 3D cannot be compromised. To represent two characters hugging, for example, you will have to create a single image file with the two characters interacting, as trying to represent the hug action only using a single image per character would be too hard or impossible. Maybe you can come with a character body divided in parts and draw them in the correct order. In 3D this problem does not exists (there exists another, that is posing the two characters correctly so they do not penetrate in the mesh of the other character).

Now, to visualize this, imagine that Game A and B have a bug that in some situation allows the player character to pass through another game object, allowing us to differentiate between the 2.5D one and the 3D one easily.

---

Game B, 2.5D Render, sprites are ordered by the z value of its position vector. In this example positive z is down and negative z is up. z-axis and y-axis are parallel but z is scaled by a factor of 0.5 of y. So if the visible area is from 10y to -10y, in the same area we have from 20z to -20z. Objects with a greater z will be drawn latter, so they will be seen as being in front of objects with lower z. Shadow of player character looks weird because shadows are in a superior layer than the floor, but in an inferior layer that all the other objects, so the player character shadow never is on top of the cube.

---

Game A, 3D Render. Depth buffer (also known as z-buffer) is used for pixel precision depth testing. So, an object does not need to completely occlude another, not even a triangle needs to completely occlude another, we have pixel precision depth test. We can rotate the game objects in any way and still get realistic results when they interact.

In resume: in 2.5D an sprite is either in front or behind another sprite. In 3D, a mesh is made of triangles, but triangle is not the minimal unit when testing for depth, you can have pixel precision. Of course, camera rotation in 2.5D is impossible as assets were created for a fixed camera angle, while in 3D is natural, if the angles of the camera are restricted by design in a 3D game is another subject.

---

There are different tricks to give the sensation of being in a 3D world when you only can render 2D graphics, I only presented a quickly crafted example using some assets of an abandoned project of mine.

Why not just use 3D always and forget about 2.5D?

Well, I can think in some examples of why a developer may prefer the 2.5D approach:

* Maybe they do not know, or do not like, 3D APIs (Direct3D, OpenGL, there are others).
* Maybe the target platform does not handle well 3D graphics (old desktop computers, 2D consoles).
* Your team can do amazing sprites but not 3D models.

How much you can approximate the results of 3D graphics using 2.5D?

There is a performance and programming complexity horizon. When you approximate to that horizon you start to doubt if your project is really possible in 2.5D or if you have to go full 3D. For example, you can use z-buffering in 2.5D (in theory), but can you pay the video memory cost (old desktop computer with onboard graphics, not powerful mobile devices)? Do you want to pay the storage cost of having an extra image to save the z-mask of every sprite?

Good candidates for 2.5D are RPG games, think Baldur's Gate series, or RTS, thinks Age of Empires 1 and 2 (AoE 3 is fully 3D and easily to differentiate).

Useful references:

Z-Buffering: http://en.wikipedia.org/wiki/Z-buffering

Orthographic projections: http://glasnost.itcarlow.ie/~powerk/GeneralGraphicsNotes/projection/orthographicprojection.html

---
Tags: 2.5d, terminology
---


# Question
Title: What are 'physically-based' lighting/rendering/materials?
What's the difference between physically based lighting, physically based rendering and physically based materials? How they are different from deferred and forward rendering? And physically based rendering is used in films and deferred rendering is used in games?

# Answer
> 5 votes
Physically based rendering basically means that you strive to have realistic materials and lighting calculations. The way you do this can vary a bit (or a lot) depending on application, but the main idea is that no material can reflect more light back than hits it, and preferably you want to measure the Bidirectional reflectance distribution function (or BRDF) of the materials you use.

To get the best results you need to spend a lot of processing power to get the lighting just right, which means it is much more applicable for films, especially mixed actor/CGI films where the difference in lighting would be much more noticeable.

For games it is very easy to make a shader which glows without casting any light or that reflects three times the light that hits it, but since these are impossible materials in real life it won't look right if the rest of your scene is realistic looking (if you use cel/toon shaders or other non realistic things this wouldn't apply of course).

You can make a game strive for physically based rendering as well, with both forward and deferred rendering, the biggest hurdle is the lighting and shadows calculations. Using a BRDF shader is relatively easy, calculating the way the sunlight through a window lights up an otherwise dark room is much harder to get right in realtime.

For a much more in depth discussion on the subject, see The Physics of Light and Rendering | A Talk by John Carmack

# Answer
> 1 votes
Those terms are very imprecisely defined, and their definitions will vary from person to person, or from engine to engine.

There is a quick and easy introduction at this page, you may want to take a look at it.

I've only done games, so I can't tell you much about films. This being a game development Q/A, it is unlikely that you will find many people with experience in the film industry.

However, I hypothesize that for filmmaking, since a film does not need to be rendered in real time, you can use models and algorithms orders of magnitude slower that give much better results than what you can use for games.

For films you could also probably hand pick scenes and do manual postprocessing on them, or cheat a lot in the parts that are not visible to the spectator. In games you most likely won't be able to do that.

Apart from that, I assume gamemaking and filmmaking is very similar, in terms of the techniques used for rendering.

Regarding deferred and forward rendering, these terms loosely refer to the order in which rendering is performed, and cannot be compared with "physically based lighting".

To put it simply, there are lighting techniques that require deferred rendering, while others can be done with forward rendering. Some lighting techniques can be physically based or not (the definition varies according to the author).

---
Tags: rendering, lighting, materials, pbr
---


title: Resetting scene state

text:
# Question
Title: Resetting scene state
i was wondering what are the best practices for restarting the game, say for example in a platformer game when you die the game restarts and you have to reposition all the characters or reset the traps or what have you.

I thought two ways for doing this:

1) You have some level or scene manager that has a reference to all the things that should react to a game state change ,for example when restarting level, you would tell every character to reposition itself or something like that.

2) You have events. Every character or entity will subscribe to this level manager to an event like "OnLevelRestart" using delegates or function pointers, then when the manager restarts the level, it would trigger the event and all the ones who have subscribed to that event, will be informed and reset their own state.

The first approach seems more flexible because i have a reference to those objects, and i can send other kind of messages to them. so if in the future i want to do something different with those objects i already have the ability to do so. Now the second approach is...there, seems of course less flexible than the first option, but apart from that i don't have anything against it. The good thing is that the manager doesn't need to know all the objects that need to reset, so i can create new entities and register to those events ( and from this perspective, it seems flexible too).

Im concerned about the scalability and maintainability of those options in the future. Is there a "best practice" for doing this ? or is just "whatever fits yout project" ? Thanks.

My sincere apologies if this question doesn't meet the requirements to be asked on this site.

# Answer
You want to use separation of concern which means it would be the scene managers responsibility to reset the scene. It already loaded the scene and created the game objects that fill the scene, you can/should reuse the code you wrote for that already.

Simply keep track of which object matches up with the loaded data, if you don't have an object already (your loading the scene for the first time) then you create one. Then after that you reset it's state (possibly using `GameObject.reset(position, hitpoints, aiState)`)

Since you didn't mention which language your using, here is some pseudo code describing what I meant:

```
function loadLevel {
   levelInfo = LevelFormat.load(file)
   createStaticLevelObject()
   resetLevel()
}

function resetLevel {
   for each object in levelInfo.dynamicObjects {
      if not levelObjects.exists(object.identifier) {
        levelObjects(object.identifier) = new LevelObject(object.visualInformation, etc)
      }
      levelObjects(object.identifier).resetTo(object.startInformation)
   }
}

```

Of course, simply dropping the entire level and reloading it is also a possibility, in the worst case this means loading it from the disk, but unless the level information is quite large it won't make a noticeable difference for the player and then you can just skip the check if an object exists or not.
> 1 votes

---
Tags: architecture
---


# Question
Title: Are there places in the gaming industry for people who are artistic and programmers?
Are there jobs, where you can switch from project to project between artistic roles (like sprite animations, concept art, visual development or even sound design) and programming roles?

# Answer
> 6 votes
I can think of a few edge cases:

1. Tech Artists are basically the people who work to bridge the gap between programming and art. The actual responsibilities of the role varies between teams and companies. One team might use a tech artist largely for building plugins for their art tools, another tech artist might be there who mostly does rigging, etc. You'll generally find tech artists on large teams, but not every team has them. This is probably the closest thing to an actual career path you'll find that combines both art and programming, but it's still a bit niche.
2. Prototyping. Being able to put together both the code *and* the art assets means you're in a really good spot to quickly build prototypes and iterate on them and you won't need a lot of outside support. That said, I'm not sure how many full-time jobs you'll find doing exclusively prototyping.
3. Start-ups with small teams. If you only have three to five people to build your entire game, you'll inherently have to cover multiple jobs. However, doing the job of two people carries the same stress level of, well, doing two jobs at once.
4. Solo indie development. One example game is The Fall, which was basically made by an individual artist/programmer. I'm sure "make your own job" probably wasn't the answer you're looking for, but for the sake of completeness, it's worth noting.

---
Tags: software-engineering, art, jobs
---


# Question
Title: Physics bodies randomly losing Velocity along an axis after impact
This just started occurring and seems to randomly happen during, and between, game sessions. A dynamic moving body collides with a static body and instead of bouncing off looses (almost completely) its Velocity along the collision's normal. This means the dynamic body starts moving along the static body's surface it just collided with, and is most noticeable on the rare occasions it does a 90 degree turn upon hitting a second wall right ahead.

This behaviour is very erratic, and almost seems to come and go between builds with the same code on my content (although it could just be chance), so I'm wondering if it could be an issue with the cocos2d libraries?

For reference, the way I'm setting up these bodies:

For both types it starts with:

```
PhysicsBody *pawnBody = PhysicsBody::create();
PawnBody->setDynamic(true);
pawnBody->setContactTestBitmask(0xFFFFFFFF);
setPhysicsBody(pawnBody);

```

Then the static body code does:

```
myBody->removeAllShapes();
PhysicsShapePolygon *colPolygon = PhysicsShapePolygon::create(&spriteVertices[0], 4,
                                                     PhysicsMaterial(0.f, 1.f, 0.f));
colPolygon->setContactTestBitmask(0xFFFFFFFF);
myBody->addShape(colPolygon, false);
...
getPhysicsBody()->setDynamic(false);

```

And the dynamic body code does:

```
getPhysicsBody()->removeAllShapes();
PhysicsShapeCircle *circle = PhysicsShapeCircle::create((getScale() *
                                                   mySprite->getContentSize().width) / 2,
                                                   PhysicsMaterial(0.f, 1.f, 0.f));
circle->setContactTestBitmask(0xFFFFFFFF);
getPhysicsBody()->addShape(circle);
...
myBody->setVelocityLimit(moveSpeed);
myBody->setDynamic(true);

```

I believe they are both set up correctly to achieve fully elastic collisions, and I'm sure this was working at some point through a slightly different flow (they didn't share the initial build code). Has anyone experienced any similar behaviour?

# Answer
> 0 votes
It sounds very similar to the problem you get if the velocities are slower than the minimum velocity threshold for elastic collisions. You haven't specified the scales you are using, but you are using the sprites sizes which presumably are fairly small.

To fix this you need to lower `b2Settings::b2_velocityThreshold`, setting it too low will prevent objects from coming to a rest but you can set it to `0` to see if it fixes your problem. If it does then find the lowest value that prevents the problem but still allows the system to come to a rest.

---
Tags: c++, collision-resolution, cocos2d-x, chipmunk
---


title: Controller vibration with Monogame

text:
# Question
Title: Controller vibration with Monogame
Is there a simple way to make a connected Xbox controller vibrate with Monogame? I know that GamePad.SetVibration is not implemented but it seems like this would be a common enough problem that there would be an easy answer.

# Answer
You should be able to use SharpDx and its XInput implementation to set the vibration on the controller, but I'm not entirely sure how well this would work in practice.
> 1 votes

---
Tags: monogame
---


# Question
Title: Should my game handle collisions in the Player object?
I'm making a 2D platform game. Right now I'm just working on making a very generic Player class. I'm wondering if it would be more efficient/better practice to have an ActionListener within the Player class to detect collisions with Enemy objects (also have an ActionListener) or to handle all the collisions in the main world.

Furthermore, I'm thinking ahead about how I will handle collisions with the platforms themselves. I've looked into the double boolean arrays to see which tiles players can go to and which they can't. I don't understand how to use this class and the player class at the same time.

# Answer
After a few years of research, game programming, trial and error, I've come back to answer my own question. I've found that the best way is to do this is using the Artemis Entity Component system. For those interested, research in component based architecture. It changed my life (for the better).

Create a Collision Component and attach it to the "Player" entity. Then create another class, the CollisionSystem, where you handle all Entities that have the Collision Component. In the CollisionSystem, do all of your fancy logic, intersection checking, collision handling, etc.
> 0 votes

# Answer
tl;dr I recommend handling the collisions "in the main world"

I can tell you what I'm doing in my platformer (still early in development). It seems to work pretty well.

I have an Updater class which handles basically *all* of the game logic for updates. That means:

* Processing keyboard input to adjust player movement
* Collision checks
* Collision reponses

I tried to write this stuff mostly in functional style (i.e., static methods) so I'm not dependent upon state and side-effects to perform basic update functions.

About 2 years ago when I first hacked together a prototype for a platformer, I had most of the collision and response in the Player class (or an abstract base class). This turned Player into a cluttered mess. When I recently did a re-write, I decided move all of that logic out of the Player (and other types of entity classes). Now, each entity class is more or less just a container for state; there's very little logic. For me, I find this much easier to maintain. (It also forces me to write simpler and more general code.)
> 4 votes

# Answer
Have you looked into physic engines like Farseer? Then Farseer would do the whole collision detection for. You just have to add the player as dynamic body and all the platforms as static bodies.

Hope I helped you!
> 0 votes

# Answer
Actually, if you're using Java, I'd recommend this tutorial:

http://www.youtube.com/watch?v=NIUKHHVF9ek&feature=relmfu

This guy helped a lot with my own sidescroller that I'm working on. I'd assume a lot of the same scrolling implementations would be the same for a platformer, except you'd be able to visit past places on the map, collide with a platform image, etc.

As for your more specific question about collisions, Mr.JavaHelp does go over it in the tutorial, but not in great detail. Basically, you can just keep the actionListener in the Board (World) Class and have the key methods in the Player Class. Here's an example of the Player Class Key Events:

```
    public void keyPressed(KeyEvent e)
{
    int key = e.getKeyCode();

    if(key == KeyEvent.VK_LEFT)
    {
        vx = -4;
    }
    if(key == KeyEvent.VK_RIGHT)
    {
        vx = 4;
    }
    if(key == KeyEvent.VK_UP)
    {
        vy = -4;
    }
    if(key == KeyEvent.VK_DOWN)
    {
        vy = 4;
    }
    if(key == KeyEvent.VK_SPACE)
    {
        fire();
    }
}

```

And for a collision box, try some if statements in a checkCollision method such as (Rectangle1).intersects(Rectangle2){ }; Make a rectangle with the Rectangle Rec1 = Player.getBounds(); method if you can.

I just learned this and it seems to be working quite well so far. Just trying to implement a Title Screen with a Start Button actually...
> 0 votes

# Answer
Store your physics shapes in you `Player` / `Enemy` classes. This could be part of a physics component in a architecture.

Perform you physics update in with a dedicated physics engine. Either your own, or one of the several already available.
> 0 votes

# Answer
The way I'm doing it is I'm grouping all the collidable objects in the world inherit from a superclass, and I'm letting each entity, meaning both the player and platforms detect the collision from the method in the superclass.

The collision detection method is called whenever an entity moves.

The method that the entities use to handle the collision however, is specific for each subclass, since the player will react differently to a collision than a platform. So in each subclass, the 'collision happened' method is implemented differently.

When a collision is detected, the superclass of the entity signals the other entity that there was a collision, and calls the opposite entity's 'collision happened' method.

Then again, you could as others say use an already made library. I implemented my own system since I need simple physics and didn't want to complicate things.
> 0 votes

---
Tags: java, collision-detection, events, platformer
---


# Question
Title: Importing z-brush cube to 3ds max causes shadow issues
I have created cube model in z-brush then I exported it to .obj format. Seems vertex count is the same as in 3ds max as in z-brush.

In all my viewports I see cube, but in perspective I see not a cube but some like "extra shadows" on the each side of cube, like cube has not plane sides.

When I render it it also has not plane sides and some ugly shadows. How can I fix it, maybe I should know some tricks about it.

# Answer
> 1 votes
Probably your problem is due to normals not being per-face but smoothed.

You can apply Smooth with AutoSmooth after import with 30 degrees threshold to your model or maybe use a better exchange format.

You can use 30 degrees in most cases for half-smoothed objects. If you need blockiness just decrease it. (Or if you need smoothness increase it)

---
Tags: 3dsmax
---


# Question
Title: Why does the projection matrix transform object points into a unit cube in computer graphics?
This semester I both took a computer vision and a computer graphics seminar. But only now before the exams I realize that there seems to be a fundamental difference between projection in both topics.

In computer vision we learned the math to map an object point from 3D to a *plane* using a 4x3 matrix, which seems logical to me:

```
|u|   |p_11 p_12 p_13 p_14|   |X|
|v| = |p_21 p_22 p_23 p_24| x |Y|
|w|   |p_31 p_32 p_33 p_34|   |Z|
                              |1|

```

However in computer graphics one usually uses a 4x4-matrix. The very nice explanation on Coding Labs has a picture depicting the outcome of said transformation: it depicts a unit-cube containing the transformed objects (distorted according to the projection).

But a unit-cube certainly isn't what is rendered on to the flat 2D screen. Is there something going on internally that just isn't mentioned? Why is this done?

# Answer
The application of the projection matrix is not the end of the transformation pipeline in computer graphics.

Applying the projection matrix to a set of geometry in computer graphics puts the object in *clip space*, which is a 4D parallelepiped (typically visualized as a unit cube). This space is useful because it makes the equations describing the view frustum *extremely* simple. For example, in D3D they (typically) end up becoming

```
-w <= x <= w
-w <= y <= w
0 <= z <= w

```

essentially due to the fact that the planes of the frustum are the planes of a "unit cube" and thus have trivial equations. This means clipping against that frustum is also extremely easy.

Clipping is an important part of the graphics pipeline, because it allows you to ensure the set of triangles to be rasterized is entirely within view, and thus avoid expensive checks and breaks in the tight loop of the rasterization routine. At the same time, clipping is a thing you need to test every triangle in the scene for, so arranging your pipeline to make it fast is important.

Computer vision is generally unconcerned with these details of rasterization, and thus doesn't need to take this detour.
> 1 votes

---
Tags: transformation, projection, projection-matrix
---


# Question
Title: How do I efficiently deal with entities moving between chunks?
I am working on a game in which entities need to be stored in chunks.

This is the basic chunk format:

```
public static Entity [row][column][entities] chunkEntities;

```

However, some of my entities move. How do I handle an entity switching chunks as a result of moving, and what is the most efficient way of doing so?

# Answer
If you need to store entities in chunks it's probably better to actually store them in the chunks rather than a separate array.

```
public class Chunk {
    public int SizeX;
    public int SizeY;
    public Entity[] Entities;
    public Chunk[] Neighbors;
}

public class Entity {
    // ...
    public Chunk CurrentChunk;
    // ...
}

```

You can still maintain the Chunks in row/column format elsewhere, but this way each chunk will be aware of its neighbors as well. When an entity leaves its CurrentChunk's Size bounds, remove it from CurrentChunk, add it to the corresponding neighbor, and change its CurrentChunk.

You'll have to repeat that, of course, if an entity somehow moves an entire chunk's size in a single frame.
> 1 votes

---
Tags: java, entity-system, entity-component, entity
---


# Question
Title: Interfacing with bill/note acceptors in unity
What ways are there to interface a unity game with a bill acceptor/validator? Usually this type of devices are connecting to a computer using a serial port and communicate over ccTalk protocol. But what ways exist of incorporating this type of devices in Unity?

# Answer
There is nothing built in to Unity for interfacing with this particular hardware.

However, Unity can interface with the serial ports, for example with `System.IO.Ports` in C#. You will have to either find a library to interface with this hardware and hook it up in Unity, or you'll need to write your own interface using the hardware support built into your scripting language of choice.
> 2 votes

---
Tags: unity
---


title: Drawing faded lightmap in 2D polygon

text:
# Question
Title: Drawing faded lightmap in 2D polygon
I have been making a 2D visiblity algorithm by following this tutorial http://simblob.blogspot.se/2012/07/2d-visibility.html

I have managed to create the light vertices and it works fine when I draw it in a single color, but I want to use a shadow map to get "faded" lights like this:

Mine looks like this now:

where the blue dot is the light center and the green is the lighted area.

How can I "apply" a sprite to this like this one?

My code lies here: http://github.com/doodlemeat/bugfree-octo-sansa

# Answer
> 0 votes
Set the UVs from the (X,Z) or (X,Y) vertex coordinates of your light mesh (depending on your world setup) relative to the light center.

```
vertex.uv = vec2(0.5, 0.5) + (vertex.pos.xy - light_center.xy) * scaling;

```

Assign that fading texture to your light mesh and set the texture mapping to clamp (or clamp to edge)

Use the scaling value to control the fading distance.

Note that unless you want to add some 2D pattern to it you don't need a 2D texture for this. A 1D texture would do fine with the brightest at U=0 and darkest at U=1. Where you apply the distance from center to the U coordinate (with scaling).

Not all systems support 1D textures. Alternatively you can use a 2D (N x 4) texture in the same way. It will save on texture memory access.

You can also calculate the color fade directly in the shader without using a texture.

---
Tags: 2d, sfml, shadows
---


title: FBO and VBO for performance

text:
# Question
Title: FBO and VBO for performance
I discovered VBO's recently and changed my code to use them instead of immediate mode. Now I'm rendering 25000 squares and it's really slowing down my FPS. If I drew all the squares VBO's to an FBO, then bound it to a single VBO, would it increases performance? The 25000 squares is more of a stress test, im trying to optimize my rendering code for snow. Edit : Each snow particle draws one of three static VBO's, this helped performance.

# Answer
You should have only 1 VBO that contains all of your squares and render it in one single draw call.

Use a texture atlas to combine all your snowflake textures.

Also, look into using a geometry shader to do point sprite expansion, this can reduce your VBO to a single vec4 encoding it as (position.x, position.y, position.z, angle). Have the geometry shader generate the UVs and vertex coordinates from that point+angle.
> 3 votes

---
Tags: opengl, java, rendering, lwjgl, vbo
---


title: minecraft source code for use in mods

text:
# Question
Title: minecraft source code for use in mods
So I am teaching a class where we will be using java to make minecraft mods. To keep things simple, we are using a third party program to set up the under-the-hood stuff for us (that way we don't have to worry about imports and forgetting small parts of the syntax). I would like to give my students some samples of cade from the game that does things that the third party program program cannot do. In my previous modding work with eclipse, I remember there was a way to see (but not edit) the code for the things that are built into the game (blocks, mobs, functions, etc.). Currently my eclipse is acting up and I can't look at that code that way. Is there another way to see that without eclipse (my forge is working fine)? If someone could help with this that would be great.

# Answer
Well using the Minecraft Coder Pack, you can get the recreated source code of Minecraft, if that's what you want to get.
> 0 votes

---
Tags: java, minecraft-modding, modding
---


title: How to move a car over an environment

text:
# Question
Title: How to move a car over an environment
At the moment I'm writing a little OpenGL application. For now I have a car which can drive down a road. This works really good because I simply put the car on the street plane. Now let's say on the road is a little ramp and my car should be able to drive along that ramp. How can I do this? At the moment I only have translation along the z axis. Let me describe how I would do it:

* Calculate angle between ramp and street normal
* Rotate car by this angle and translate it

First of all: Is there an easier way to do it? My main problem from this idea is how should I get the normal from the triangle the car is interacting with? And of course I can not rotate the car the full angle at the beginning because then a part of the car is under the ground. So what is the usual way to do this?

# Answer
> 4 votes
There is no usual way. It all depends on how precise you want your simulation to be.

A very cheap way:

You can improve on this by using it as a **starting point** and then adjusting the position more realistically.

To rotate the vehicle as it moves have each wheel rotate the car by using its opposite wheel as the pivot point.

If it becomes too problematic due to corner cases you should look into using a ready-made physics system. Proper physics are a big headache.

It does not remove the need for the solution above as you will need to properly position vehicles initially before the physics system takes over if you don't want cars to spawn in the air or partially **into** the ground and fly off when the physics system freaks out.

# Answer
> 3 votes
Just about the easiest way to do this is to calculate the cars position from the road, and it's rotation with the normal of the road, like you mentioned yourself. This will cause your car to stick to the road even if you create an abrupt fall in the road however.

To solve jumps on the road you either have to simulate falling yourself by keeping track of the last height the car had and if the new height is less than that, start applying gravity to a fall speed and ignore the roads angle until the car lands again.

Or you could look into using a physics engine like bullet physics, it's a bit more complex and sounds like overkill for your scenario, but if your planning on adding obstacles, other cars and perhaps simulate losing traction, then it might be the easiest option in the long run.

---
Tags: collision-detection, movement
---


# Question
Title: How to calculate a score algorithm based on elapsed time?
I'm trying to calculate an alogirthm based on elapsed time to calculate score based on a music beat. I have the music beat divided into 4 because that's the time measure of that beat. So If the user presses the correct key at the third beat, which is of course when the perfect beat would be, I'd like it to obtain the best score. I've tried doing this:

```
score=percent(bpmt.elapsed,bpm/3);
int scoref(int int1,int int2) {
return int1*100/int2;
}

```

`bpmt.elapsed` being how much time was elapsed between the start of that beat and the time that the user pressed the key and bpm being the total number of milliseconds of that particular beat.

Can anyone tell me a better way to do this please? I think it requires more advanced math and it's kind of beyond me.

# Answer
Most rhythm games actually have a pre-recorded or procedurally generated rhythm track, but this is okay *for testing*. This is because many songs' tempos very over time, the downbeat (the very first beat heard in the song or measure) can take some time to get to, and typically we want to have more complex input than a single key press.

That said, assuming ideal conditions where

1. The rhythm starts immediately
2. Never drops out and comes back off-measure
3. And the tempo never changes

...each beat will be found at `n * (bpm/60) * 1000` milliseconds, where `n` is the n-th beat. You then need to tweak your score thresholds. Here are a few as an example:

* Miss: 60 \> t \> 80 ms, -4 pts
* Bad: 40 \> t \> 60 ms, -3 pts
* Okay: 20 \> t \> 40 ms, 0 pts
* Great: 10 \> t \> 20 ms, 1 pts
* Great: 0 \> t \> 10 ms, 2 pts

Those will probably need to vary based on song speed.

Now, on each frame:

```
nextBeat = (beatCounter+1)*(bpm/60) * 1000;
previousBeat = (beatCounter)*(bpm/60) * 1000;
timeUntilNext = nextBeat - curentTime;
timeFromPrevious = currentTime - previousBeat;

```

where `beatCounter` is incremented according to the above ranges - ie whether the beat was hit, how much time has passed, etc.
> 1 votes

---
Tags: algorithm, timer
---


# Question
Title: Creating a queue for BeginInvoke method - loading chunks
I have a voxel game similar to Minecraft. I have a funciton PushLoadedChunks(Direction) that pushes all of the loaded chunks forward, backward, left, right. This is done with sfd.BeginInvoke(PushLoadedChunks, null, null).

This works great until I fire two of these quickly, which happens if the user goes diagnol. It errors out because two threads are pulled trying to modify the same data, both writing to the same thing because they try to load the same chunks. I wanted to do something like this:

Create one standard thread and a queue to push through. Instead of invoking PushLoadedChunks, I wanted to add it to the queue and have that single thread work through each chunk one after another, proving to be slower performing but more stable code.

I am struggling because Invoke seems to wait for the chunks to return which works, but freezes my player until it is loaded. I need reference in creating a "queue" of sorts, or help setting up a single thread to run each method when they are called and wait until one is finished to do another.

Does anyone have any advice or resources I could look at to see the best way to complete my task?

# Answer
My solution of problem.

See *chunkGenerationThread* for chanks generation and *processBlockUpdatesPackagesThread* for update chunks when user set or remove blocks.

There are lot of code, but allmost no comments. In general, how it works: set/remove block -\> add changes to queue package -\> wait untill Update and send package for processing to queue -\> in separate thread check queue and process changes and update mesh -\> use new mesh :)

If you want, for details ask in comments or in chat.

Perhaps it's not the best implementation (LOL), but it works. Most of time. I'm still working on it.
> 1 votes

---
Tags: xna, c#, voxels, minecraft-modding
---