texts: Why do my Box2D collisions fail when I have multiple fixtures on one body?

texts:
I'm creating my first libgdx / Box2D game where a player moves around using a mouseJoint.

My player has two fixtures, "main" and "question".

For some reason when I have these two fixtures, my player is no longer responsive to collisions or touch detection (i.e. I can't drag the player around). If I remove the "question" fixture, everything works.

Why is this? How can I fix it?

This is how I create the Player:

// create body
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(x, y);
bodyDef.fixedRotation = true;
body = world.createBody(bodyDef);

// player main body fixture
PolygonShape polygonShape = new PolygonShape();
polygonShape.setAsBox(bodyWidth / 2, bodyHeight / 2); // setAsBox takes half width, half height as params
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = polygonShape;
fixtureDef.restitution = 0.3f; // Bounciness - Keep value between 0 and 1.
fixtureDef.density = 3; // Mass p/sqm - Keep value between 0 and 100
fixtureDef.friction = 0.8f; // Slippery - Keep value between 0 and 1
bodyFixture = body.createFixture(fixtureDef);
bodyFixture.setUserData("player");

// player question fixture
polygonShape = new PolygonShape();
polygonShape.setAsBox(questionWidth / 2, questionHeight / 2, new Vector2(0,0), 0); // setAsBox takes half width, half height as params
fixtureDef.shape = polygonShape;
fixtureDef.restitution = 0.3f; // Bounciness - Keep value between 0 and 1.
fixtureDef.density = 3; // Mass p/sqm - Keep value between 0 and 100
fixtureDef.friction = 0.8f; // Slippery - Keep value between 0 and 1
fixtureDef.friction = 0.8f; // Slippery - Keep value between 0 and 1
fixtureDef.isSensor = true;
questionFixture = body.createFixture(fixtureDef);
questionFixture.setUserData("question");

I assume I'm doing something silly here—I'm still very much a noob when it comes to libgdx / Box2D.


texts: Grants a Higher Texture downsized a better quality than a texture with the downsized resolution?

texts:
if i use a texture in a game with a resolution of 128*128 for a tile which is actually 64*64 on screen and both textures show the same image just in different resolutions. One in 128*128 and one in 64*64. How big are the quality bennefits and is it a good idea to use the texture with the higher resolution even if it will be downscaled anyway?

Thx


texts: Get Specific depth values in Kinect (XNA)

texts:
I'm currently trying to make a hand / finger tracking with a kinect in XNA. For this, I need to be able to specify the depth range I want my program to render. I've looked about, and I cannot see how this is done. As far as I can tell, kinect's depth values only work with pre-set ranged found in the depthStream.

What I would like to do is make it modular so that I can change the depth range my kinect renders. I know this has been down before but I can't find anything online that can show me how to do this.

Could someone please help me out?

I have made it possible to render the standard depth view with the kinect, and the method that I have made for converting the depth frame is as follows (I've a feeling its something in here I need to set)

  private byte[] ConvertDepthFrame(short[] depthFrame, DepthImageStream depthStream, int depthFrame32Length)
    {
        int tooNearDepth = depthStream.TooNearDepth;
        int tooFarDepth     = depthStream.TooFarDepth;
        int unknownDepth    = depthStream.UnknownDepth;
        byte[] depthFrame32 = new byte[depthFrame32Length];

        for (int i16 = 0, i32 = 0; i16 < depthFrame.Length && i32 < depthFrame32.Length; i16++, i32 += 4)
        {
            int player      = depthFrame[i16] & DepthImageFrame.PlayerIndexBitmask;
            int realDepth   = depthFrame[i16] >> DepthImageFrame.PlayerIndexBitmaskWidth;

            // transform 13-bit depth information into an 8-bit intensity appropriate
            // for display (we disregard information in most significant bit)
            byte intensity = (byte)(~(realDepth >> 8));

            if (player == 0 && realDepth == 00)
            {
                // white
                depthFrame32[i32 + RedIndex]    = 255;
                depthFrame32[i32 + GreenIndex]  = 255;
                depthFrame32[i32 + BlueIndex]   = 255;
            }

         // omitted other if statements. Simple changed the color of the pixels if they went out of the pre=set depth values

            else
            {
                // tint the intensity by dividing by per-player values
                depthFrame32[i32 + RedIndex]    = (byte)(intensity >> IntensityShiftByPlayerR[player]);
                depthFrame32[i32 + GreenIndex]  = (byte)(intensity >> IntensityShiftByPlayerG[player]);
                depthFrame32[i32 + BlueIndex]   = (byte)(intensity >> IntensityShiftByPlayerB[player]);
            }
        }

        return depthFrame32;
    }

I have a strong hunch it's something I need to change in the int player and int realDepth values, but i can't be sure.


texts:
I just started learning 2D game development using CreateJS and I was reading this article about angular velocity to learn how to correctly move a sprite in both x and y axis.

I understand most of it except the angle adjustment.

I learned that mostly, in games, (0,0) starts at the upper left part of the screen rather than the bottom left that we are familiar with in Math. I also learned that postive y means moving down rather than up.

Is the angle adjustment related to those? Why is the value -90 degrees?


texts: How to get the fingerID (Touch) that is pressing a specific UI button. (Unity)

texts:
I want to displace a button along with the screen position that is pressing on it.

However, having multiple touches at the same time results in wanky behaviour.

So I want to limit the button's movement to the touch that started it.

I'm aware of the PointerEventData.pointerId but I couldn't figure out how to use it.


texts:
I'm looking at a basic diffuse light shader here http://en.wikibooks.org/wiki/GLSL_Programming/Unity/Diffuse_Reflection.

Diffuse light needs the normal vector in eye-space, so that it can dot it with the light position (also in eye-space), and figure out the diffuse contribution. (eye-space not world-space is used, because that simplifies calculating specular contributions).

The code calculates the normal vector in the following way:

        mat4 modelMatrixInverse = _World2Object; // unity_Scale.w
           // is unnecessary because we normalize vectors

        vec3 normalDirection = normalize(
           vec3(vec4(gl_Normal, 0.0) * modelMatrixInverse));

A linear algebra calculation shows that given a matrix M, Transpose(Inverse(M)) transforms normals.  The Wikipedia on normals page contains a derivation of the required formula: http://en.wikipedia.org/wiki/Normal_%28geometry%29#Transforming_normals (I've actually rewritten that section myself, as it was not lucid).

So does this mean that the 'vector * matrix' overload in GLSL is implemented as:

    Transpose(vector) * Matrix

just holding a row-vector instead of a column-vector in the output, i.e.:

    Transpose( Transpose(vector) * matrix )

or more simply:

    Transpose(matrix) * vector

?

I've also found what appears to be alternative: gl_NormalMatrix

But in lines 9-11 here http://pixelsorcery.wordpress.com/2010/07/13/fisheye-vertex-shader/ ) I see the following code:

normal = vec4(gl_NormalMatrix * gl_Normal, 0.0);
vec4 vVertex = gl_ModelViewMatrix * gl_Vertex;
light_dir = gl_LightSource[0].position - vVertex;

Would I be right to assume that gl_NormalMatrix gives a normal in eye-space, and gl_LightSource[0].position gives the light location also in eye-space?

http://www.opengl.org/discussion_boards/showthread.php/172231-gl_NormalMatrix-Replacement suggests gl_NormalMatrix is deprecated.

Does that mean the first implementation is the preferred approach?

EDIT: http://www.opengl-tutorial.org/beginners-tutorials/tutorial-8-basic-shading/#The_Diffuse_part


texts: How do mobile games implement time gates unhackably? Is it possible in offline games?

texts:
I'm thinking about porting my game to Google Play, and it would be free to play with time gates which are skippable if you watch an ad.

What are the ways of implementing an unhackable time gating?

Is it possible without internet connection? If yes, how?
If no, is there a way to implement it without custom backend, using Google Play's services?

Or should I care about this at all? Because...

It doesn't affect other players...
Most of the audience couldn't do it anyway, and if the game stays small, hacks couldn't really spread.
Then maybe I should just let them hack those time gates, it's a marginal revenue loss.

What do you think?


texts: What technical questions do you need to be prepared to answer before presenting an idea to venture capitalists?

texts:
A friend and I are planning on pitching an idea to venture capitalists in a few weeks at SIEGE 2010. He is handling the business plan side of things and all those related questions so I only need technical questions here. What types of things should I be prepared to answer about our project?

For reference its an economic game for mobile platforms(targeting android to start with).

EDIT-CLARIFICATION: I am aware that they may be more interested in non-technical questions, but my friend is handling that end. I am mainly concerned with technical questions as he should be able to field most of the rest.


texts: What is the Workflow? Blender -> Substance Painter -> Unreal Engine 4

texts:
My name is Jose and I'm pretty new to Game Art Development.

I know some intermediate UE4 (both C++ and Blueprints), but my weakest point has always been the workflow to import assets from Blender and Substance. Up to this point I have always bought external 3D assets.

As far as I know, the workflow is this (but I don't know if I'm correct):

BLENDER: Create a 3D model in Blender. Create the materials I need for each part of the mesh. UV unwrap it. Export as .fbx
SUBSTANCE PAINTER: Import the .fbx file into Substance Painter. Paint the 3D model. Export the .obj file AND the texture maps (albedo, roughness, metallic, normal, etc.)
UNREAL ENGINE 4: Import the .obj file AND the texture maps. Create a material based on these maps. Apply the material to the model.

I have a few questions now:

Is this workflow correct? Or is there something I'm misunderstanding?
What model do I have to import into UE4? The .fbx from Blender? Or the .obj from Substance? Is there any difference between these two?
When exporting the textures from Substance Painter, I can choose from a dropdown called config, to what game engine I'm exporting these textures to (Unity, Unreal, Lumberyard, Cryengine, etc.). What exactly does this option do? What is the fundamental difference in exporting textures to Unreal or to Unity, for example?


texts: LibGdx TextButtonStyle Offset not working correctly

texts:
I'm intending to give an animation to the TextButton by giving the pressedOffsetX and pressedOffsetY values:

TextButtonStyle buttonStyle = new TextButtonStyle();
buttonStyle.font = font25;
buttonStyle.fontColor = Color.WHITE;
buttonStyle.up = new TextureRegionDrawable(settingsAtlas.findRegion("achievements"));
buttonStyle.down = new TextureRegionDrawable(settingsAtlas.findRegion("achievements"));
buttonStyle.pressedOffsetX = 5;
buttonStyle.pressedOffsetY = -5;

And I created a button like this:

TextButton achievementsButton = new TextButton("ACHIEVEMENTS", buttonStyle);
achievementsButton.addListener(new ChangeListener() {
    @Override
    public void changed(ChangeEvent event, Actor actor) {
        // show achievements
    }
});

But when I click the button, only the text in it is animated. The button background stays in the same position. What might I be doing wrong here?


texts: Unity RigidBody2d.MovePosition() not working on dynamic rigid body

texts:
As it says, .MovePosition() won't move my character. I know other ways to move but I want .MovePosition() in particular as I think it will solve the camera's jittery movement when the player pushes through a collision.

This script works on a kinematic rigidbody but not on a dynamic one.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour {

    Rigidbody2D rbody;
    Animator anim;
    public float speed = 0;
    SpriteRenderer sr;

    void Start () {
        rbody = GetComponent<Rigidbody2D> ();
        anim = GetComponent<Animator> ();
        sr = GetComponent<SpriteRenderer>();
    }

    void Update(){
        sr.sortingOrder = ((int)Camera.main.WorldToScreenPoint (sr.bounds.min).y) * -1;
        Vector2 movementVector = new Vector2 (Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
        if (movementVector != Vector2.zero) {
            anim.SetBool ("isWalking", true);
            anim.SetFloat ("inputX", movementVector.x);
            anim.SetFloat ("inputY", movementVector.y);
        } else {
            anim.SetBool ("isWalking", false);
        }
        Vector2 newPos = rbody.position + movementVector *Time.fixedDeltaTime;
        rbody.MovePosition(newPos);
        //rbody.position = Vector2.MoveTowards(rbody.position, newPos, Time.deltaTime*speed);
    }
}

FYI I'm on Unity 5.6 if that helps.


texts:
I've searched around and it seems like most people are using tile-based map systems.
I suppose, this question is more theoretical than practical (I am not very concerned about memory or performance speed), but I want to know: what other ways can a map be created in a game?
A map being a graphic representation of terrain that can be navigated, has entrances and exits, and boundaries (no-go zones).

Besides using text files to store and arrays to load tile data, one idea I had, was to store a map entirely as a graphic file and use queries on the pixel colour to determine boundaries (i.e. you can only move in a certain direction if the way is bright enough in that direction).

What other creative map systems are out there?


texts:
I'd like to be able to render flexible lines, or ropes, as below:

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


texts:
I'm trying to build a simple networked game and I'm having trouble keeping a jump in-sync on the client and server.

I've read the free gaffer on games articles and it's helped somewhat but I'm still not completing grasping the theory behind how to keep physics in sync.

Right now I have a character that can move right and left. This is kept in sync perfectly by sending all of the inputs and then relaying them to the clients.

For the jump command..

- I send a packet indicating that i'm jumping.
- The client then predicts the jump
- The server begins to simulate the jump and tells the other clients that client X is jumping
- that then gets simulated on their clients

The issue is that if I keep on jumping on the spot eventually the jumps will begin to overlap. I came up with some makeshift solutions to that, but realized that if I started moving and jumping at the same time it wasn't simulating everything perfectly and sometimes the player would land on the tip of a platform on one client and miss it on the server/other client.

Right now everything is being done locally so there's virtually no lag. I figured the reason it's becoming out of sync is because of jitter.

I'm just a little confused in figuring out how to fix this. How do I get it so the client side prediction is 100% perfect in a local environment when incorporating physics?


texts: Pixel-perfect 3D sprite-picking on cylidrical-billboarded sprites?

texts:
Background Info

I have an OpenGL app where a player (just an AABB with an eye-height, look and move vectors), can walk along a 3D grid made of a square cells, essentially like a player walking along a Minecraft level.  The cells can also have differing heights, which qualifies it as a 3D level, rather than 2D.

On each cell, there is potential to be a static sprite, which is centered on that cell.  The sprite is rendered as a "cylindrical billboard" so that it's always facing the camera, but the base/bottom of the sprite is always rooted in the ground.  Like this https://www.youtube.com/watch?v=2-queKkSVnw

(The point I'm making is that these cylindrical billboarded sprites render a bit differently than standard sprites which would be coplanar to the view plane on the vertical axis, as well)

Here's a simple representation, where the green stick is the player, and the pink squares are the billboarded sprites which are centered on their cells.

(Note: normally, the camera view would be from the player's eyes, and thus all the pink sprites should be aligned with the player's view plane)

I also have an "arm reach" vector which is a line segment that extends outward from the crosshair a certain distance, in other words a line segment.  This line segment is slightly less than the width of one cell.  So, worst case scenario, then, is that this line segment is intersecting with three cells at once, like this:

Question

My question is how should I detect that the user's arm reach ray/segment is intersecting with a vertically billboarded sprite, knowing that the sprites may have transparent pixels?

I know that the first step would be to find which cells the ray/segment is overlapping, as shown in the previous pic as the green-highlighted cells.  The next step (in my case) shall be a 3D distance check from the player to the sprite location.  If too far, can't click it, no matter how you rotate the camera view (and distort the sprite).  After that, I'm unsure.  I assume I need to somehow first check if the ray is intersecting the billboarded sprite's "rectangle" (the pink rectangle) (I say rectangle in quotes because it will be a distorted rectangle in first person view, due to perspective angle), and then pixel-pick on the sprite and look for the transparent color, but I'm not sure how to do either of those steps.

Daggerfall somehow accomplished this.  Interacting with a billboarded sprite (i.e. a treasure pile) requires you to actually click on a non-transparent pixel of that sprite, or the click doesn't count.

Any sources on related techniques would be greatly appreciated.  Thank you for your time!


texts: Correct level of abstraction for a 3d rendering component?

texts:
I've seen lots of questions around this area but not this exact question so apologies if this is a duplicate.

I'm making a small 3d game. Well to be honest, it's just a little hobby project and likely won't turn out to be an actual game, I'll be happy to make a nice graphics demo and learn about 3d rendering and c++ design.

My intent is to use direct3d9 for rendering as I have some little experience of it, and it seems to meet my requirements. However if I've learned one thing as a programmer it's to ask "is there any conceivable reason that this component might be replaced by a different implmentation" and if the answer is yes then I need to design a proper abstraction and interface to that component. So even though I intend to implment d3d9 I need to design a 3d interface that could be implemented for d3d11, opengl...

My question then is what level is it best to do this at?
I'm thinking that an interface capable of creating and later drawing

Vertex buffers and index buffers
Textures
Vertex and Pixel "shaders"
Some representation of drawing state (blending modes etc...)

In other words a fairly low level interface where my code to draw for example an animated model would use the interface to obtain abstract vertex buffers etc. I worry though that it's too low level to abstract out all the functionallity I need efficiently.

The alternative is to do this at a higher level where the interface can draw objects, animations, landscapes etc, and implement them for each system. This seems like more work, but it more flexible I guess.

So that's my question really, when abstracting out the drawing system, what level of interface works best?


texts: How can I draw the inside of a box as well as the outside?

texts:
I have a 3D box in which I have some holes. The thing is that when I look through the holes, I can't see the wall of the box that should appear as the inner wall.

How can I draw this as well?


texts:
I'm researching shaders as I'm thinking about doing them for my final year project at Uni. I've looked at a lot of examples online and I think I get it. It's something that you apply to an object or scene in order to create a desired effect without changing the original object/scene, I think. I know that there are different types of shaders but that's the basic goal right?

Furthermore, what do shaders encompass? Are weather systems in games shaders? Particle effects? Landslides? I don't know where the line is drawn between animations/cinematics and shaders. Also I guess shaders which effect something in the game world, for example, a tower blowing up in BF4. The explosion itself would be shaders but the way the tower effects the world around it would be physics and collisions. Am I right?


texts:
Hi so i've recently learned the SFML graphics library and would like to use or make a non-rigid body 2D physics system to use with it. I have three questions:

The definition of rigid body in Box2d is

  A chunk of matter that is so strong
  that the distance between any two bits
  of matter on the chunk is completely
  constant.

And this is exactly what i don't want as i would like to make elastic, deformable, breakable, and re-connection bodies. 1. Are there any simple 2D physics engines,  but with these kinds of characteristics out there? preferably free or opensource?

2. If not could i use box2d and work off of it to create it even if it's based on rigid bodies?

3. Finally, if there is a simple physics engine like this, should i go through with the proccess of creating a new one anyway, simply for experience and to enhance physics math knowledge? I feel like it would help if i ever wanted to modify the code of an existing engine, or create a game with really unique physics.

Thanks!


texts: Want to develop my own primitive physics engine, don't know how to start with its high-level architecture. Suggestions?

texts:
Few years ago I tried to make a simple 3D game - billiards. Completed like 50%, stuck with physics. Basically, I only need to calculate balls rolling over flat surface, but it would be nice to make something more flexible.
I know all the formulas and laws (most of them, anyway). the problem is I have no idea of how to make good physics engine architecture-wise.
I tried google and other forums but didn't find what I was looking for. The only suggestion was to look at open-source engine, but I'm not that good a programmer to make heads or tails out of it...


texts:
I have a 2d physics engine, with three boxes: "body", "left wing" and "right wing".
The wing boxes are connected to the body using a hinge joint. The physics world has no gravity.

I'm attempting to rotate the wings around their hinge connection, as if the joint is motorized but I'm not exactly sure how to achieve that. If I exert force with a downward vector on the center of the wings, the body itself flies down. This is undesirable. With an actual hinge motor, only the wings will rotate about the hinge, affecting the body only when they hit it.

Which forces should be added to the wings, and at which origin points?

I'm using Phaser.io, with P2.js physics, but the question is platform-agnostic.


texts: What are the disadvantages of R-Trees in collision detection?

texts:
I was poking around in SQLite and discovered R-trees. A little digging revealed that R-trees are really just fancy AABB-trees.

Then I realize that the state of the art in collision detection (often a perf-limiting sub-system for physics simulation) is dynamic trees (simple AABB trees).

So this is indicating to me that we can produce more efficient physics with this as a drop-in replacement.

Here is a pretty convincing argument for R-trees from half a decade ago. To really distill it to the core, R-trees were developed for databases to optimize disk access where getting the right data into RAM is the happy place, and now we can recycle the technique to optimize memory access where keeping the right data in cache is the happy place.

Sadly it seems that this has not caught on. I wonder what the reasons are?

I also found no reference to this BVH method in my Real-Time Collision Detection (Ericson) text (though, that book is a bit older than 2010).


texts: OpenGL Fragment shader: not all fragments showing colors

texts:
I'm writing a simple 3D renderer and while the model loads fine, the colors are off. Quite a few fragments in the model show no color at all.

Here is the render:

The locations of the blacked out fragments change everytime I move my camera. From another angle:

Vertex shader:

#version 330 core
layout (location = 0) in vec3 pos;
layout (location = 1) in vec3 normal;
layout (location = 2) in vec2 uvCoords;

out vec2 texCoords;
out vec3 normCoords;
out vec3 fragmentPos;

uniform mat4 viewMatrix;
uniform mat4 projMatrix;
uniform mat4 modelMatrix; // Just an identity matrix for now

void main()
{
    normCoords = normal;
    fragmentPos = pos;

    texCoords = uvCoords;

     gl_Position = projMatrix * viewMatrix * modelMatrix * vec4(pos, 1.0);
}

Fragment shader:

#version 330 core

out vec4 frag_color;

in vec2 texCoords;
in vec3 normCoords;
in vec3 fragmentPos;

struct Light
{
    vec3 lightPos;
    vec3 lightColor;
};

uniform Light light;
uniform vec3 modelColor;

bool checkInf(in vec3 vect)
{
    return (isinf(vect.x) || isinf(vect.y) || isinf(vect.z));
}

bool checkNan(in vec3 vect)
{
    return (isnan(vect.x) || isnan(vect.y) || isnan(vect.z));
}

void main()
{
    float ambientValue = 0.05;
    vec3 ambientColor = ambientValue * light.lightColor;

    vec3 result;
    vec3 normalizedNormal = normalize(normCoords);
    vec3 lightDir = normalize(light.lightPos - fragmentPos);

    if(checkInf(normalizedNormal) || checkInf(lightDir) || checkNan(normalizedNormal) || checkNan(lightDir))
        result = vec3(0.5,0.5,0.5);

    else
    {
        float diffuseValue = max(dot(normalizedNormal, lightDir), 0.0);
        vec3 diffuseColor = diffuseValue * light.lightColor;

        result = (diffuseColor + ambientColor) * modelColor;
    }
    frag_color = vec4(result, 1.0);
}

After some playing around, I realized that the blacked out fragments were due to the diffuse lighting calculations. After some searching on the internet, I found this answer: answer that suggested it may be caused by normalized vector being Nan or infinity. To test that, I decided to check each normalized vector to see if it was Nan or infinity and if it was, set it to a grey color. But that didn't work.

Any help would be appreciated.


texts: Physics engine and squishing of stacked objects

texts:
I have a general question that seems to apply to most physics Engines (Box2D, Unity, Matter.js, …). I'm trying to make a tower of rectangular objects that are stacked on the [static/mass=infinity] ground, and the more blocks I have, the more they "squish".

I put together a test case in CodePen, which is reproduced here:

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;

//physics vars:
var phys = Matter;
var bod = Matter.Body;
var bodies = Matter.Bodies;
var engine;
var render;
var world;
var optionsForBodies = { // Florian
  restitution: 1,
};

var boxNumber = 0;

// --- TEMP ---
const keyState = {};
window.onkeydown = function (event) {
  keyState[event.code] = true;
};
window.onkeyup = function (event) {
  delete keyState[event.code];
};
// --- /TEMP ---

// Add bodies to matter
function loadMatter(){
  var floor = phys.Bodies.rectangle(100, 225, 200, 50, {isStatic: true});
  var blist = [floor];
  for (var i = 0; i < 13; i++) {
  // for (var i = 0; i < 2; i++) {
    var box = bodies.rectangle(100, 200 - i * 20, 56.8, 20, optionsForBodies);
    blist.push(box);
    boxNumber += 1;
  }
  phys.World.add(world, blist);
}

function drawMatter(name){
  var bodies = phys.Composite.allBodies(world);
  for(var i = 0; i < bodies.length; i++)
  {
    if(!bodies[i].render.visible)
      continue;
    var verts = bodies[i].vertices;
    if(verts.length <= 0)
      continue;
    context.fillStyle = "#aaa";
    context.strokeStyle = "#000";
    context.lineWidth = 2;

    var ofsx = 0, ofsy = 0;
    context.beginPath();
    context.moveTo(verts[0].x + ofsx, verts[0].y + ofsy);
    for(var j = 1; j < verts.length; j ++)
      context.lineTo(verts[j].x + ofsx, verts[j].y + ofsy);
    context.lineTo(verts[0].x + ofsx, verts[0].y + ofsy);
    context.fill();
    context.stroke();
  }
}

function updateMatter(ms){
  phys.Engine.update(engine, ms);
}

function clrCanvas(){
  context.fillStyle = "#fff";
  context.fillRect(0, 0, width, height);
}

var inter;

function init(){
  initMatter();
  clrCanvas();
  requestAnimationFrame(step);
}

function initMatter(){
  engine = Matter.Engine.create();

  world = engine.world;
  world.gravity.y = 3.0;
  render = Matter.Render.create({
    canvas: canvas,
    engine: engine,
    options: {
      width: 400,
      height: 300
    }
  });
  loadMatter();
}

var frameNo = 0;
function step() {
  var SCALER = keyState.KeyA ? 3 : 1;
  var SPEED = 16 * SCALER;
  if (frameNo++ % SCALER === 0) {
    updateMatter(SPEED);
    clrCanvas();
    drawMatter();
  }
  requestAnimationFrame(step);
}

init();
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.11.0/matter.min.js"></script>
<body>
<canvas id="canvas" width="400px" height="400px"></canvas>
</body>

To me what's happening is not obvious and I'd love an explanation in human words, since in real life if you stacked crates they would not squish inside each other, but it's a constant with EVERY physics engine, despite playing with restitution, slop, damping, density and many parameters.

Ideally I'd like those crates to be dense enough to absorb a big part of the shock (=not bounce much) of each other and never penetrate each other.

What concepts am I missing?

In the codepen above, try to select the canvas and then press the 'A' key, which reduces the framerate (increasing the dt from 16ms to 50ms) which increases the forces computed for the objects at each iteration and therefore penetrating even more each other.

Thanks!!


texts: How to rotate a gameobject to the specific angle

texts:
I have tree model that is being rotating .After certain angle it should stop rotating.I have done a sample code.But the tree is not stopping.

void Update () {

        //transform.Rotate (0f,0,0.5f*Time.deltaTime);
        //transform.Rotate (Vector3.forward,Time.deltaTime*5);
    transform.Rotate (0f,0f,time);
    Debug.Log(time);
    time+=0.5f;
   if(time==5.5f)
    {
        transform.eulerAngles=Vector3.zero;
    }

}

From the above code I need to stop the rotation when the z axis value is 5.5f.How can I do this . Please help me.


texts: Making body (box2d) a sprite (andengine) in Android

texts:
I can't make body (box2d) a sprite (andengine) and at the same time apply MoveModifier to sprite which is body. If i can make just body, it works namely the sprites can collide. If I apply just MoveModifier to sprites, the sprites can move where i want. But I want to make body (they can collide) and apply MoveModifier (they can move where I want) at the same time. How can i do it? This my code just run MoveModifier not as body at the same time.

    circles[i] = new Sprite(startX, startY, textRegCircle[i]);
    body[i] = PhysicsFactory.createCircleBody(physicsWorld, circles[i], BodyType.DynamicBody, FIXTURE_DEF);
    physicsWorld.registerPhysicsConnector(new PhysicsConnector(circles[i], body[i], true, true));
    circles[i].registerEntityModifier(
            (IEntityModifier) new SequenceEntityModifier (
                        new MoveModifier(10.0f, circles[i].getX(),  circles[i].getX(),
                                circles[i].getY(),CAMERA_HEIGHT+64.0f)));
    scene.getLastChild().attachChild(circles[i]);
    scene.registerUpdateHandler(physicsWorld);


texts:
I'm following this tutorial by thecplusplusguy and in the linked video he explain that for example for the world basement and walls we need to create the actual rendered (shown to the player) walls and then duplicate them, place them in the same coordinates as the rendered walls and call them collision (by defining their material to collision). Then it defines in the Object loader function that those objects with material == collision are collision planes and should not be rendered but just used to check collision.

Now I'm pretty confused. Why would we add this kind of complexity to a problem that can easily be solved by a simple loadObject(string plane_object, bool check_collision);:

Creating only the walls object (by loading .obj file in plane_object)
Define them also as collision planes whenever the check_collision is set to true

In this case we have lowered the complexity of his method and make it more flexible and faster to develop (faster because we don't always have to make a copy for each plane and flexible because we don't hardcode the Object loader). The only case in which this method could not work is when we need hidden collision planes, and for that we could modify the loadObject() function like this: loadObject(string plane_object, bool check_collision = true, bool hide_object = false);

Creating only the walls object (by loading .obj file in plane_object)
Define them also as collision planes whenever the check_collision is set to true
And add the ability to actually show the object or hide it based on hide_object.

The final question is: am I right? What would the possible problem encountered with my solution versus his?


texts: How can I store all my level data in a single file instead of spread out over many files?

texts:
I am currently generating my level data, and saving to disk to ensure that any modifications done to the level are saved.

I am storing "chunks" of 2048x2048 pixels into a file.  Whenever the player moves over a section that doesn't have a file associated with the position, a new file is created.

This works great, and is very fast.  My issue, is that as you are playing the file count gets larger and larger.

I'm wondering what are techniques that can be used to alleviate the file count, without taking a performance hit.  I am interested in how you would store/seek/update this data in a single file instead of multiple files efficiently.


texts: Unity 2D: How to make player grab a ledge, swing and jump to another

texts:
Since I'm not a native speaker, it's hard to explain in english what I want to achieve, so I'm gonna use a couple of images... basically I want to make an interaction of this type:

in a 2D game, so it should be something like this (forgive me for the quality, but I'm not a designer as you can see :D):

What should I do? Currently I'm looking at 2D Physics Joints, but I'm not sure about which one is the most appropriate and how should I configure my objects... in my mind I think that the ledges should have a trigger collider that once the player jumps and enters in the collider area, a joint is dynamically attached (but which one and against which object... the player? The ledge? Both?)... how should I make the player swinging forward and backward once hooked to the ledge? I'm really confused :/


texts:
I'm reading the "Introduction to 3D game programming with DirectX11" (Frank Luna) and i'm having problems with lighting.
I have this error: Effect version is unrecognized.  This runtime supports fx_5_0 to fx_5_0.
When i use the D3DX11CreateEffectFromMemory function i have that error and an exception (this->mFX was nullptr)
Can you help me? Thanks
EDIT: I have no D3DCompileFromFile

std::ifstream fin("Ligthing.fx", std::ios::binary);
        ///
        fin.seekg(0, std::ios_base::end);
        int size = (int)fin.tellg();
        fin.seekg(0, std::ios_base::beg);
        std::vector<char> compiledShader(size);

        fin.read(&compiledShader[0], size);
        fin.close();
        hr=D3DX11CreateEffectFromMemory(&compiledShader[0], size, //ERROR IS HERE
            0, device, &mFX);

        if (FAILED(hr)) {
            MessageBox(0, L"err", 0, 0);
        }


texts: Which 3D Authoring Application to Decide for

texts:
I have read a lot individual information about three key 3D Graphics Authoring Applications: Softimage, 3DS Max, Maya.

To me, it looks like each of them has its own way to accomplish the same goal, which brings me to the question, is any of them better than the other ones?

In other words, if am free to decide which one of the three tools to use as my primary graphics development tool (for games graphics, web, commercials, animations..) and if I depend to nobody, which application should I decide for? What criteria should I evaluate those three applications in accordance to?

As I have read a lot about Softimage, which is so far the most attractive to me because of its user interface and ICE, I came to question: Is the future of Softimage bright? is it not going to be merged or vanished over time? Lastly I checked, Autodesk offered Softimage as part of its key two packages: Maya, Max. It was not offered as standalone and competitive package to Max and Maya anymore.


texts: What is the purpose of a Direct3D vertex layout?

texts:
This tutorial (msdn) gives a description of a vertex layout.

This is an example of a input layout:

D3D11_INPUT_ELEMENT_DESC layout[] =
{
    { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
UINT numElements = ARRAYSIZE(layout);

It seems to me that it would be easier to bypass this and simply consider data sent to the vertex shader/pixel shader as a block of floats and allow the vertex or pixel shader to interpret it as it wants.

My question is this:

What is the purpose of a vertex
layout?
Is a vertex layout optional
in Direct3D 11?


texts: Instantiate prefabs at particular vectors using text file (Unity3D game)

texts:
I need to read a text file containing two pieces of information on each line, and use that information to instantiate a prefab at the correct location in a Unity3D game (c# script). The locations are either North, South, East, or West (each a particular vector).

For example, the first line of the text file might read:
landmark1, North

In a script, I need to instantiate landmark1 and assign it to case North vector.

The below script is what I've got so far. Basically, I can read from the text file but I don't know how to assign that information to different cases. I'm guessing I need to use an array somehow but I'm not sure how to do that here.

Any help would be appreciated. Thanks!

using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
using System.Linq;
using System.IO;
using System;

public class Landmarks : MonoBehaviour {

    //spawnable prefab gameobjects
    public GameObject castle;

    // Use this for initialization
    void Start()
    {

        StreamReader reader = new StreamReader(@"C:/Users/.../landmarks.txt"); //insert full path here
        String textContents = reader.ReadToEnd();

        // string[] dataArray =

        for (int i = 0; i < (textContents.Length); i++)
        {

            //set case if first line = "castle, North" then instantiate object castle at vector 'north';

        }
    }
}


texts: How do I change the level of my game by changing the file loaded?

texts:
I am making this 2d canvas game in JavaScript and I want to switch to file level2/level2.html when the boss of level 1 (level1/level1.html) is dead. This way I can have my stuff organized better.

This is the condition statement where I want to put the file change.

if(e.bosshealth <= 0){
  enemies = [];
  alert("LEVEL 1 COMPLETED");
  // I want the file switch to be here if possible.
}


texts: Using tex2Dlod to determine the appropriate size of the texture

texts: We have a top-down game with fixed camera position. We also use orthographic projection so every model in the game will always be viewed from the very same angle and from the very same distance. The question we want to answer is what size should our textures be for each model. I tried turning off mipmapping and clearly saw that the game does not use the highes mip level when drawing our stuff. I also know that tex2Dlod can be used to specify which mip texture level to use for sampling, so my plan is to gradually change this value to manually specify lower and lower mip levels until I see that decreasing it further reduces the quality of the picture. The problem is I cannot figure out how to set the mip level. The value passed to the tex2Dlod function is float4 and as I understood x and y hold te texture coordinates and w holds the mip level. But it should be set in fractional representation and I cannot know what the step size is. So basically I need to know what number I need to send into the function to gradually switch mip levels.


texts: EventManager adding data to the event message

texts:
Some backstory:

I decided it was time to start making a game. I've got a bachelor degree in computer sciences, but I didn't really get to code much during my studies.
I've started making a quick prototype with libgdx, checking how the library worked et al. Then at some point I decided I knew enough of the basics and that it was time to move on and start doing something more complex and flexible.

I've started wondering how organize the logic and the data, and so I found out about Entity-Component-System architecture.
Basically my implementation is something like this:

Entity: just an id (UUID).
Component: data. It can be a PositionComponent (float x, y), VelocityComponent (float x, y), RenderableComponent (texture t), ...
System: Has an update() function that runs the logic every frame, and listens to message..

I've then discovered the EventManager, and have been struggling in implementing it propely.
Right now, it has an evergrowing enum to identify the different types of events. I can feel it is a bad thing since every class that listesns to / receives events need to include that, but I can't figure out another way to handle it.

Question:

What does this eventmanager really do? It doesn't send any message other than "hey, wake up, something you care about happened, can't tell you what tho, check it yourself".
Every type of event needs custom data to work with.

So the question is, how to append data (of different types) to an event message?

Practical example:

I would have liked to change the Entity-Component-System architecture a bit. Basically Systems may require more than a component to work with.

For example the MovementSystem will need both PositionComponent and VelocityComponent,
 RenderSystem will need PositionComponent and TextureComponent.

So I wanted to create another object, the Node to hold all the components that a System requires, if the Entity has them.

To do so I need to keep a list of Nodes for every System, wich can be achived (I guess) with messages on ComponentAdded / Component events telling wich component has been added/removed and check if a node needs to be added/removed.

Conclusion:

I don't know if this architecture I tried to describe is actually any good, so I'm open for any complete refactoring suggestions.
My ultimate goal is to make a game, but I'm really interested in learning design patterns and techniques aswell, so I don't mind if I'm overengineering it.
There's no design behind the game yet, so for now I just want to do something 'general'.

It's my first post here, so sorry for my excessive usage of ThisThingIObviouslyDontKnowHowToUsePropely.


texts: Shader works in Editor but not on iPhone

texts:
I am using the next script for a painting asset found on this website.

As you render the faces of your mesh in the uv space of the mesh, you are reconstruction the islands one triangle at the time. On the edges of the island, it can be that due to underestimation the rasterizer doesn’t consider a pixel which is actually in the island. For these pixels, no pixel shader will be executed and you will be left over with a crease. (text and image taken form the website)

The basic idea is that every frame, after the paint texture has been updated, I run a shader over the entire texture, and using a filter and a pre baked mask of the uv islands, extend the islands outwards.

The problem is that it does not work on iPhone. There is no error, no weird coloring, it is like that script does not get applied. I am not sure where the problem is coming from..maybe the for loops or the command buffers used in c#.

Shader "Unlit/FixIlsandEdges"
{

    SubShader
    {
        // =====================================================================================================================
        // TAGS AND SETUP ------------------------------------------
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {

        // =====================================================================================================================
        // DEFINE AND INCLUDE ----------------------------------
            CGPROGRAM
            #pragma  vertex   vert
            #pragma  fragment frag

            #include "UnityCG.cginc"

            // =====================================================================================================================
            // DECLERANTIONS ----------------------------------
            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv      : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv      : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

                    sampler2D    _MainTex;
            uniform    float4        _MainTex_TexelSize;
                    sampler2D   _IlsandMap;

            // =====================================================================================================================
            // VERTEX FRAGMENT ----------------------------------
            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv     = v.uv;
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {

            fixed4 col = tex2D(_MainTex, i.uv);
            float map  = tex2D(_IlsandMap,i.uv);

            float3 average = col;

            if (map.x < 0.2) {                                    // only take an average if it is not in a uv ilsand
                int n = 0;
                average = float3(0., 0., 0.);

                for (float x = -1.5; x <= 1.5; x++) {
                    for (float y = -1.5; y <= 1.5; y++) {

                        float3 c =  tex2D(_MainTex, i.uv + _MainTex_TexelSize.xy*float2(x, y));
                        float  m =  tex2D(_IlsandMap, i.uv + _MainTex_TexelSize.xy*float2(x, y));

                               n += step(0.1, m);
                         average += c * step(0.1, m);

                    }
                }

                average /= n;
            }

            col.xyz = average;

                return col;
            }
            ENDCG
        }
    }
}

I've read somewhere that using tex2D in for loops is a big no no, so I changed that to a tex2Dlod but the same thing happens.

You can check out the Git project here

I am completely lost on this one and google isn't very helpful. Thank you for any comments.


texts: Collision test solution for hack&slash game

texts: I want to ask you what is the best way to deal with collisions in hack&slash game, I know that collisions must be very accurate. My first idea is to use sphere bounds ( I making hack&slash in 3d), but how to deal with hitting with sword some enemy, do you know some better solution for this type of game ?


texts: Implementing Multiplayer: entire world ticks or just changes?

texts:
i'm working an a very simple multiplayer experience (for now node.js, later will probably remake all in c++, but my question is more about theory).

All guides and tutorial i saw about making something multiplayer Always speak about sending all the "world" information, once per tick, deciding optimal tickrate, making smooth movements on client side with interpolation or stuff like that.

Honestly i thought of another way, and i really cant see why its never mentioned.
My idea would be the following:

Client sends to server when input happens; eg if you move with arrows, you send to the server a message only when your moving status changed. If you was moving right and then start moving upright, then you send a message about you changing your movement.
Server recives the messages, sets variable on player object for its movement, and sends to all other clients information about the change. Also sends current time and current position in the server at the moment of movement change.
Clients recive a movement status update, place the player object in recived coordinates moved by the new movement * ping delay. That way position in all clients should Always be up to date with the server.

Why should i send hundreds of positions to each client per each player every x milliseconds when i can just send the changes?

I feel like its about polling vs interrupt... (yeah i know its not polling anyway, but the concept is sending the change vs keep sending everything)


texts: How to securely store xml/json information about actors in a game?

texts:
I'm developing a 2D "small" offline rpg game, and to this point I have many actors (mobs, heroes, NPCs) and what I did, is created a class named "Actor" and each time I have a new actor I create a whole new class extending it.

I was thinking if I could limit it and go with a single class (prototype pattern?) were each instance of it gets its info and properties from stored files (name, weight, HP, attack, playable, ...)

I thought first to use xml to store every actor I have in the game, so it would be a lot easier to modify or add new actors, and this goes for also weapons, gear, potions, etc.

I'm afraid to use XML or JSON, because this would make the game content open and then anyone can modify it.

So, any thoughts on how to implement that, because i'm totally new to game dev?


texts:
I'm building a 2d engine in C# and I have several static sprites that have multiple color variations.  Ok, easy enough, I create the Texture2D images at start time, then stuff them into an array, and use an array index at draw time.

This caused a surprising performance hit for me.

I made a quick simple test app where it draws the same 32x32 texture 1,000 times.  The baseline call takes  1.0001ms

spriteBatch.Draw(testTexture1, new Vector2(100, 100), null, Color.White, 0, new Vector2(16, 16), 1f, SpriteEffects.None, 1);

But this version, takes 11.0011ms!

spriteBatch.Draw(testTextureArray[i], new Vector2(80, 80), null, Color.White, 0, new Vector2(16, 16), 1f, SpriteEffects.None, 1);

Ten fold longer!
Same performance with a List.

Why is this and is there anything I could use instead of an array?


texts: Does Steam provide persistent data storage to developers?

texts: Does Steam provide persistent data storage (for custom data) to developers? For example, would an online shooter be able to store player statistics (kills, matches, player deaths, etc.) on Steam servers?


texts: How can i access animation from animator in unity3D

texts:
I want to perform some specific functionalities if my character is in Idle state and IdleUnarmed animation is playing and !anyKeyDown. I do not know how to access that "IdleUnarmed" animation from animator. The code i am using is

int idle = Animator.StringToHash("Base Layer.Locomotion.Free Locomotion.Free Locomotion.Idle.IdleUnarmed");
        AnimatorStateInfo stateInfo = anim.GetCurrentAnimatorStateInfo(0);
        if (!Input.anyKeyDown && stateInfo.GetHashCode() == idle)
         {
            if (Time.time > currentTime)
            {

But it is not working. Anyone please help me to sort out this issue. Thank you


texts: Bodies do not stay sticked together by joint in retina display

texts:
I'm rehearsing on Box2D revolute joints. Everything's going pretty well except for one thing. For some reason bodies joined together with revolute joints do not stay sticked, they start getting apart from each other from the app start when I run it on retina device or simulator. On non retina device it works just fine, as expected. Here's the screenshot of the non-retina version:

And here's the behavior when I run the same app on retina device/simulator:

I'm taking content scale factor into account.


texts:
I can draw an animated sprite sheet without problems.
But when it comes to rotation, the single cell (which gets drawn) rotates around the center of the whole sheet.

How can I get my cell to rotate around its own center?
This is what I found on the internet:

  Copy the current frame to a buffer, rotate the buffer, then copy the
  buffer to the screen.
  Source

But I don't know what this means.


texts: How to cancel out simultaneous collisions in libGosu?

texts:
I am working on an Asteroids remake. When the player's bullets hit a large meteor, it should break apart into 2 smaller meteors. This works when the player is only firing one bullet, but when the player's weapon is upgraded, shooting multiple bullets, sometimes two bullets hit the same meteor at the same time, causing it to break into 4 smaller meteors, not 2 as intended.

Is there a way to cancel out one of the collisions when there are two simultaneous collisions - or a way to omit the creation of the unwanted extra meteors when two bullets hit the same meteor at the same time?

Here is how I have the collision detection set up currently:

Bullet.each_collision(Meteor1) do |bullet, meteor|
  Explosion.create(:x => meteor.x, :y => meteor.y)
  Meteor2.create(:x => meteor.x, :y => meteor.y)
  Meteor2.create(:x => meteor.x, :y => meteor.y)
  meteor.destroy
  bullet.destroy
  @score += 100
  Sound["media/audio/explosion.ogg"].play(0.2)
end

Following are screenshots demonstrating the situation:

In the first two images (above) the player fires one bullet at a time, the large meteor breaks into two smaller meteors, and the score increases by 100.

In the last two images, the player fires three bullets at a time, the large meteor breaks apart into four smaller meteors, and the score increases by 200, due to a simultaneous collision.


texts: What do I risk if I name my game the same as another company?

texts:
I came up with the best title for my game - a title that is catchy and also indicative of the gameplay, plus there isn't any other game on the market with a similar name. But after a Google search, I found a company in another country using the same name.
To put my situation better in context, imagine a game like Minecraft being in development, only to find out that there's another company called something like Minecraft Studios in a far-off country dealing with digital graphics and art for media (including games).
Aside from the legal aspect of it (lawsuits, cease-and-desists, etc.), what disadvantages would there be to have my game named the same as a company dealing in a similar field?


texts: How to Create a Perfect Dash (Quick Movement) in Pygame

texts:
I am trying to create 2d side scrolling platform similar to Megaman. Here is the progress so far:

Red box is the spriteholder while blue box is the hitbox of the character. The sprite I use is random idle sprite I found on the internet.

My question will revolve around the quick movement, where the character will accelerate faster than their usual speed for certain distance / time / sprite index.
This is my take currently on the problem:

def dash_left(self):
    self.sprite.index = 0
    self.sprite.rect.midbottom = self.rect.midbottom
    if self.dash_current_use > 0:
        self.vx = -1.5 * self.speed
        self.ax = (self.speed * 0.5)
        self.status = -3
        self.dash_current_use -= 1

on the def main():

if event.type == g.KEYDOWN:
    if event.key == g.K_q:
        player.dash_left()

if event.type == g.KEYUP:
    if event.key == g.K_q and player.vx < 0:
        player.stop_left()

The problem is that in my take, the dash will go continuously as long as the player pressed Q, or upon collision. My aim is for the dash to be able to stop itself, preferred when a certain distance has been passed or when ax (velocity variable from outside force) is greater or lesser - depending on the direction - than the vx (velocity variable from input.)


texts:
I love the features of XNA but I want to get into c++ game dev. The problem is that I now have to worry about everything from loading a png file to opening a window. This is a little bit annoying.

I would really like a c++ version of XNA to solve these issues for me.


texts: Rendering a fullscreen quad is leaving a one pixel line on the left and top

texts:
I am rendering a fullscreen quad using XNA. I am having an issue where the top pixel line and left pixel line are not rendered. It should be black in the picture. Can anyone tell me why this might be happening?

The effect's intent is to fade the screen out or in by adjusting the alpha of the pixel.

HLSL

float3 c;
float a;

float4 ShadeVertex(float3 pos : POSITION0) : POSITION0
{
    return float4(pos, 1);
}

float4 ShadePixel(float2 p : VPOS) : COLOR0
{
    return float4(c, a);
}

technique Simple
{
    pass FirstPass
    {
        VertexShader = compile vs_3_0 ShadeVertex();
        PixelShader = compile ps_3_0 ShadePixel();
    }
}

QuadRenderer.cs

internal sealed class QuadRenderer : GameComponent
{

    #region fields

    private VertexPositionTexture[] triangles;
    private short[] indexData = new short[] { 0, 1, 2, 2, 3, 0 };
    private GraphicsDevice gfx;

    #endregion

    #region constructors

    public QuadRenderer(IGameEngine engine)
        : base(engine)
    {
        this.gfx = engine.Device.Graphics;

        // texture coordinates semantic not used or needed
        this.triangles = new VertexPositionTexture[]
                     {
                       new VertexPositionTexture(new Vector3(1, -1, 0),
                                                 Vector2.Zero),
                       new VertexPositionTexture(new Vector3(-1, -1, 0),
                                                 Vector2.Zero),
                       new VertexPositionTexture(new Vector3(-1, 1, 0),
                                                 Vector2.Zero),
                       new VertexPositionTexture(new Vector3(1, 1, 0),
                                                 Vector2.Zero)
                     };
    }

    #endregion

    #region methods

    public void Render(Effect effect)
    {
        foreach (EffectPass p in effect.CurrentTechnique.Passes)
            p.Apply();

        this.Render();
    }

    private void Render()
    {
        this.gfx.DrawUserIndexedPrimitives(PrimitiveType.TriangleList,
                                           this.triangles, 0, 4,
                                           this.indexData, 0, 2);
    }

    #endregion

}


texts: XNA or SlimDX (DirectX 10) for multitouch rhythm game simulator

texts:
I'm looking to develop a multitouch rhythm game in C#. It is aimed to be a simulator for an existing arcade game, similar to this: http://www.youtube.com/watch?v=TAiNNpA3wwg So far, I've decided on several requirements for the game that should be present:

1) Unicode text display, without the characters being known beforehand (i.e. the displayed strings are not known at compile time, but entered in by the user).
2) Support for display of all the common image formats (PNG, JPG, BMP, and GIF) and playback of various audio (MP3, WAV, OGG, FLAC) and video formats.
3) Full multitouch support (I'd like to support as many simultaneous inputs as the user's hardware allows). VERY IMPORTANT, MUCH MORE SO THAN THE OTHER TWO.

I had been fiddling with XNA, but I've found drawing arbitrary Unicode text with SpriteFonts difficult (it hates it when you try and load the entire CJK Unified set). In addition, I haven't found an easy way to load certain formats like Ogg Vorbis audio in XNA.

So, with this in mind, I've started looking into using DirectX 10 via SlimDX. However, I'm very lost, and am unsure of how to start with it and if the features I need are even present in it. To top it off, SlimDX documentation seems to be very lacking, especially with me being new to game development. Which one of the two frameworks would be best for my goals?

P.S.: Any references to starting game development with SlimDX (June 2010) would be very helpful as well, especially in relation to Direct2D, which what I'll most likely be using.


texts: Determining if removal of a voxel will break up a group

texts:
I have the following situation: I have a 3d grid of voxels (on/off, the max size is probably 128x128x128). I know in advance that inside the grid, all the voxels that are turned on are interconnected, forming a single group.

Now I need to determine: when I remove a voxel (turn it off), will it break up the group?

My initial idea was to look at neighbors of the voxel that is removed and determine if they are still interconnected trough other voxels (see my other question: Algorithm to see if two voxels are interconnected). But there might be better/other ways to do this.

So what would be a good way to determine if removal of a voxel will break up the group it was part of?


texts:
This issue has been annoying me for a long time now and even after reading a lot of articles about it, I am still unable to fix the issue.

First, to my setup. I'm using LWJGL for a 2D project, rendering in immediate mode (yes, I know, FBOs, but I feel like it's too late to change it now). Textures can be scaled, rotated tinted and cropped in any way and are read from packed spritesheets that are multiples of 2 (the one in question is 512x1024 for example).

The Problem

Because there is no smoothing applied to the textures, scaled and rotated textures look quite ugly, showing jagged lines and black outlines. I tried improving it with using glEnable(GL_POLYGON_SMOOTH) (even though I know now that this is apparantly a bad practice, but I have no idea how to add multisampling to immediate mode rendering, other sites even state that multisampling is probably overkill for 2D games, which leaves me even more confused). This is what it looks like, with and without POLYGON_SMOOTH:

Quite clearly, there are multiple issues visible:

With POLYGON_SMOOTH disabled, there are horribly jagged lines and dark edges (that aren't there in the texture)
With POLYGON_SMOOTH enabled, the edges are no longer jagged, but the dark edges are still there and now there are those diagonal lines. After reading up on that a bit, I found out that it has something to do with how graphics cards render quads, which is as two triangles, and when smoothing is applied, this happens. To test that out, instead of drawing a single quad I draw two triangles which indeed moves the diagonal lines around.

The dark edges seem to be caused by something like like pre-multiplied alpha (according to this), but when I check the raw pixel data, it doesn't look pre-multiplied to me. A completely white texture with 0.5f alpha for example is represented as (in ARGB) 0x80FFFFFF. So applying the "fix" (using glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA) instead of the default glBlendFunc(GL_SRC, GL_ONE_MINUS_SRC_ALPHA)suggested in the article doesn't really work, because my textures aren't premultiplied alpha, so alpha components don't work anymore (same texture, black background):

Texture without alpha:

I do use custom shaders, so I guess I probably could make alpha work in some way by passing it to the shader and then multiplying the color by it, would that fix the dark edges (which would enable me to use GL_ONE, the "better" blend function)? That would still leave me with the issue of the diagonal lines though, which I seem to be able to move around, but not remove.


texts:
What alternatives exist of how an agent can follow the path calculated by a path-finding algorithm?

I've seen that the most easy form is go to one point and when the agent has reached this point, discard it and go to the next point.

I think that this approach has problems when the game has physics with dynamic objects that can block the travel between point A and point B, then the agent is taken from his original trayectory and sometimes go to the last destiny point is not the most natural behavior.

In the literature always I have read that the path is only a suggestion of where the agent has to go, but I don't know how this suggested path must be followed.

Thanks.


texts: Problem designing my pseudo-3D game with SFML

texts:
I am designing the game so the objects I create (Character, Enemy, Enemycast...) can inherit all from

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

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

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

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

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

So I got two questions

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


texts:
I have started with the Sony PSM SDK this week, I'm interested in creating a little 2D game and have been reading through the web about a so called "2D game engine" integrated into the SDK.

Some information I read suggested that it was added on January 2012, but I have been going through the documentation and haven't been able to find any reference to it.

Does anybody know if they finally introduced the 2D game engine for the PSM SDK?


texts: Translating object from y to y smoothly in Unity 2D

texts:
I am trying to make a game that has an object on screen, which moves from one Y coordinate to another. Right now, I do it through translations, but that does it instantly. I want to do this as a kind of animation, where it transitions smoothly from one Y coordinate to another. What should I do?

Here is an image of what I'm talking about:


texts: Updating XNA BoundingSphere - sphere moves in opposite Y direction?

texts:
In my players update method I calc the new world matrix then I update a boudingsphere by:

MyBoundingSphere = MyBoundingSphere.Transform(World);

However when the the model's World has moved vertically down MyBoundingSphere moves vertically up?! (i.e. MyBoundingSphere.Center.Y increases instead of decreases);


texts: Are constantly growing (in dimensional size) GameObjects a problem?

texts:
It's possible the following is fundamental to Unity, and not a problem?

I am using an example of a WheelJoint2D/Car from the Ray Wenderlich tutorials. Note from the pic below, the top level game object called "Car". It has children of "Body" which contains the wheel joints and the wheels (attached to the wheel joints). The top level "Car" GameObject is placed in the scene (here at X=6.4).

Now we run the game for a short time, and the car rolls forward as expected. From the inspector, we would see that X position of the Body and the wheels has changed, but note that the Car game object's X position has not changed:

So, in reality the game object "Car" has grown in the X-dimension. Granted this growth seemingly has nothing to do with physics simulation (as all the rigidbodies and joints are moving along as expected). One interesting side affect is that this growth might make scaling the parent object problematic.

But it seems that if this were an infinite runner, you would have an ever increasingly wide "Car" object. On the surface this seems undesirable, but is it really? And if so, how would you mitigate this (given that this game object hierarchy seems to be the prescribed way of using the wheel joints).


texts: Finding the "top" of a mesh representing the terrain

texts:
I'm generating a low-poly mesh for terrain, and for a given world coordinate I'd like to know where the "ground" is.

My game uses fairly standard infinite terrain - I generate noise values for world coordinates and use them to generate this mesh procedurally. This is done in chunks of 16x16.

I'm planning to begin decorating the terrain with plants and such and I need a good way to determine how high the ground is.

So for example, if I want a rock at x: 5, z: 5, what's the best/most efficient way to figure out the "height" of the ground at that location?

I've considered trying to inspect the mesh vertices, or maybe using a top-down ray cast and picking the collision point, but I'm looking for advice before I begin.

I've tried the raycast method, and it works perfectly, I'm just not sure how efficient that is. I'll profile if any alternatives seem worth comparing.


texts: How do I implement parallax scrolling in 2D?

texts: Suppose I have three layers: a foreground, an intermediate-ground and a background.  What is involved in using these three layers to create parallax scrolling?


texts:
As I calculate the length of the arc (green) between two angles;

I need a method like:

arc_lenght (xpos, ypos, radius, ang1, ang2) {
return arc_lenght
}


texts: Monogame resolution problem (without scaling sprites)

texts:
So I'm working on a project and started working on a scaling system for different resolutions.

I know if you change the monogame resolutions, that the texture won't scale but I noticed deformed pixels. I just changed the PreferredBackBufferWidth to 1920 and the PreferredBackBufferHeight to 1080 but my pixels are deformed.I did some research and tested some resolutions and the only ones that don't work are 1920x1080 and higher.(1920x1080 works in fullscreen)

Draw method for sprites:

public virtual void Draw(GameTime gameTime, SpriteBatch spriteBatch, Color color)
{
    spriteBatch.Draw(textureImage, position, new Rectangle(
    (currentFrame.X * frameSize.X),
    (currentFrame.Y * frameSize.Y),
    frameSize.X, frameSize.Y),
    color, 0, Vector2.Zero, 1, SpriteEffects.None, 0);
}

spriteBatch.Begin:

spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullCounterClockwise, null);

The first picture is the player head with the new resolution (without scaling the textures!) and the second picture is the player head with the default resolution (you can't see all the pixels at the bottom).

You can see that in the first picture a few pixels are deformed.

Question: Why doesn't 1920x1080 work in windowed mode (it works in fullscreen though) without deformation (I use a 1920x1080 monitor)? All I do is just enlarging the game window, I'm not scaling sprites...

-> is this because I have a 1920x1080 monitor?


texts: Client-side dice rolls in turn-based game

texts:
I'd like to create a turn-based multiplayer game on Android. I'm thinking of using Google Play Game Services and get rid of any other webservice to create and host games.

The problem is the game involves dice rolls. I don't believe GPGS offers the possibility for third party dice roll, so my first thought was to integrate them in the app, however this gives great opportunity for cheating.

I've read the answers given in this question: Fair dice over network w/o trusted 3rd party , but they require all players to participate in the roll, which isn't possible if everyone isn't in the app at the same time.

Is there any alternative solution? Or do I have to use a third party for this?


texts: Creating Multiple Instances of a camera at run time

texts:
I'm trying to create a bunch of different game objects from a settings file I'm passing in at run time. I've checked and my game is reading in settings fine. But when I run the program, I get the following error:

  ArgumentException: The prefab you want to instantiate is null.

But, I still get two cameras appearing in my scene. So I'm confused as to why this is happening.

Here is the code that is acting on the information received from the settings file:

public void CreateCamera()
{

for (int i = 0; i < testCamera.Count; i++)
{

    camera = Instantiate(gameObject.AddComponent<Camera>(), new Vector3(0, 0, 0), Quaternion.identity) as Camera;
    camera.name = testCamera[i].Name;
    camera.near = Convert.ToSingle(testCamera[i].Near);
    camera.far = Convert.ToSingle(testCamera[i].Far);
    camera.aspect = Convert.ToSingle(testCamera[i].AspectRatio);
    camera.fov = Convert.ToSingle(testCamera[i].FOV);
}

}

Following this, I also get the following message as well:

  Can't add component 'Camera' to GameObject because such a component is
  already added to the game object!

Can anyone help me in fixing these issues?


texts:
I am trying to render a 3D model using OpenGL. For the projection and transformation matrices, I am using glm. I've got my model on the screen and it works just like I intended it to; except one small problem.

I am setting the model's translation matrix as

glm::translate(glm::vec3(0, 0, 4))

to move the model a little bit forward so that I can see it. Since in OpenGL, by default, negative z is out towards the 'camera' and positive z is forward, I expected this to work but it doesn't. It only works if I set it to

glm::translate(glm::vec3(0, 0, -4))

But this seems weird to me, as I am setting my zNear to 0.01 and zFar to 1000. Is glm's z values flipped or am I doing something wrong here?

Here is my code:

glm::mat4 rotation = glm::mat4(1.0f);
glm::mat4 translation = glm::translate(glm::vec3(0, 0, -4));
glm::mat4 scale = glm::mat4(1.0f);

glm::mat4 modelMatrix = translation * rotation * scale;

glm::mat4 projectionMatrix = glm::perspective(70.0f, aspectRatio, 0.01f, 1000.0f);

glm::mat4 transformationMatrix = projectionMatrix * modelMatrix;


texts: How to lower the cost of realtime lights?

texts:
Besides Deferred rendering, what can I do to make realtime lights cheaper to render? I don't really need them but I could make good use of them in my game.
BTW I thought Deferred render would give me a bigger boost on scenes with many lights but I got kinda let down. Maybe my expectations were too high.


texts:
I am working with an open source project called Project Porcupine. The project is a game engine for a base building game that allows for one to extend the game. We have a system to read texture files, and use a .XML configuration file to parse the details of that file. This to me seems like a good use case for a custom inspector. Unfortunately, I can't figure out how to even configure the script to read in images as such, and google is letting me down. How can I write a custom editor for an image, even better if limited to a folder? Thanks!

EDIT

To clear things up a bit, I'm trying to make a custom inspector for images in the /StreamingAssets folder. These assets are included with the build, and thus editable in Unity, but I would like to make a tool to make editing these a bit easier. Right now the inspector looks like this, the problem I'm having is getting anything to appear on the inspector at all.

I've tried two things, first a Custom Inspector on TextureImporter, and using the following code, neither of which seemed to do anything. I would be happy to get anything printed in the Inspector, from that point I can figure out the rest, I hope. Thanks!

using UnityEditor;
using UnityEngine;

public class SpriteXmlViewer : AssetPostprocessor
{
    void OnPreprocessTexture()
    {
        GUILayout.Label("Hello OnInspectorGUI!");
        Debug.Log("Test");
    }
}

Lastly, I'm clicking on the following image for the display above:


texts:
I am implementing bullets into my game, and each bullet has a lifetime. Whenever the bullet has existed for a set amount of time or collides with an object, the bullet should be deleted. I implemented the timer properly and whenever the bullet reaches the end of its life, it gets deleted. The problem occurs whenever I shoot another bullet. This instantly causes a crash with the code:
Exception thrown at 0x044765D7 (nvoglv32.dll) in gravityGame.exe: 0xC0000005: Access violation reading location 0x00000000.
After some research, I've found that this usually means that I am trying to render something that is a nullptr. My thinking is that I am not deleting the previous bullet properly and this affects the new one. A single bullet object is created on startup, and every new bullet is copied using the following line of code:
std::shared_ptr<Bullet> bullet = std::make_shared<Bullet>(*std::dynamic_pointer_cast<Bullet>(modelsLoaded.at(i)));
The reason for the dynamic pointer cast is because it is in a vector of its base class that it inherits from. Whenever the bullet needs to get deleted, it is erased from the bullets vector using bullets.erase(bullets.begin()+index); and the object it is pointing to should go out of scope, there is nothing else pointing to it. I feel like somehow having that object getting deleted has an adverse effect on the other bullets in the vector, but I do not know how. A new object is created and all the data from the original bullet gets copied over. How could deleting a copy of an object mess with the other copied objects? The functions to create, and render the models are below.
Generate Model Function
    //binds id
    glGenBuffers(1, &VBO);
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &EBO);
    glGenTextures(1, &texture);
    glBindVertexArray(VAO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, verticesSizeTexture * 8 * sizeof(float), verticesTexture, GL_STATIC_DRAW);
    // position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);
    // color attribute
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
    glEnableVertexAttribArray(1);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indicesSizeTexture * 4, indicesTexture, GL_STATIC_DRAW);
    //texture
    glBindTexture(GL_TEXTURE_2D, texture);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
    glEnableVertexAttribArray(2);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);

Rendering Function
    unsigned int transformLoc = glGetUniformLocation(shader->ID, "location");
    glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(trans));

    glBindTexture(GL_TEXTURE_2D, texture);
    glBindVertexArray(VAO);
    glDrawElements(GL_TRIANGLES, indicesSizeTexture, GL_UNSIGNED_INT, 0);
    glBindVertexArray(0);

Destructor
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &EBO);

Update
After removing the contents of the destructor, the problem goes away. However, I would like to have some sort of destructor to allow for the proper freeing of memory.


texts: Unity 2D, do Touch event must happen in the update() function?

texts:
(Unity 5.1)

My Issue is when attaching a script to a gameObject, all the examples I've found are based with the update() function and it's pretty wierd for me, as a desktop games developer.

Is there anything like "OnMouseDown()" or other functions for a Touch platform game? Or do I must figure it out with Touch.GetInput from the update() function and that's it?

Sorry in advance if my question is a bit cliche, it's just driving me nuts because I can't find anything with the Unity API or code examples, and I just can't believe there is no some "OnTap()" function...


texts: I have a quastion about loading screen in unity. I don't want to make a scene between to levels [Main Menu > Loading Scene > Game level]. I want to use Canvas "Image"that run at the start of the game level and then disappear after few seconds [Main Menu > Game level]. Is this good idea ?


texts: Unity: Create large Terrain with accurate raycast detection?

texts:
I'm not using the Unity Terrain because it lacks certain features.

Amongst them, you cannot tile them:

You cannot create concave walls or make holes in it:

No custom textures, no detail textures, awful sculpting tools... the list goes on and on. So I imported my own Terrain as a Mesh. The collision works perfectly, however raycasting onto the Terrain is horribly inaccurate. Unity seems to compress the Mesh Collider depending on distance to player. See the video linked below. Since Unity is (by my knowledge) the only Game Engine that supports convex colliders, how do other game engines create Terrain colliders?

For a racing game or a RTS or RPG the colliders are no problem, but for a shooter it's unacceptable. Here's a video showing the problem:

https://youtu.be/coiFS6IT4wI

I've researched long and hard and there seems to be no known solution for this. So my question remains, if it's possible at all, how can i create large scale Terrains for Unity? This problem makes it completely impossible for me to create outdoor scenes. There HAS to be some kind of solution.

1) Raycasting script:

//Spread
        float spreadAmount = Mathf.Lerp(spreadMin, spreadMax, burstTimer / spreadThreshold); //Current Spread lerps between spreadMin and spreadMax by burstTimer (increases per shot)

        int i = 0;
        totalShotDamage = 0; //Buckshot sends 8 rays down the range. totalShotDamage gets total damage done by all rays. Needed for displaying damage text

        while (i < bulletCount) //Repeats Shooting Vector for bulletCount amount (needed for buckshot)
        {
            Vector3 shootDirection = shootOrigin.transform.forward; //Shoot Vector 100% accuracy

            shootDirection += shootOrigin.transform.right * (Random.Range(-spreadAmount, spreadAmount)); //Randomizes Vector horizontally, reduces accuracy
            shootDirection += shootOrigin.transform.up * (Random.Range(-spreadAmount, spreadAmount)); //Randomizes Vector Vectically, reduces accuracy

            Ray ray = new Ray(shootOrigin.transform.position, shootDirection); //Ray from Shoot vector
            RaycastHit hitInfo;

            if (Physics.Raycast(ray, out hitInfo, 2000, shootLayerMask)) //Sets range of gun & sends ray
            {
                Vector3 hitPoint = hitInfo.point; //Point of impact with any object
                GameObject go = hitInfo.collider.gameObject; //GameObject of impacted Object

                string targetTag = hitInfo.collider.gameObject.tag; //Tag of GameObject of impacted Object

                addHitParticleEffects(targetTag, hitInfo, enableBulletholes); //Add hitparticle effects based on Tag (IMPACTmaterial)
                damageEnemy(targetTag, hitInfo, damage, damageRollOff); //Damage enemy
            }
            i++; //total bullet count (needed for buckshot)
        }

2) Terrain Inspector Settings

3) LOD Settings

There are no LOD Settings (yet). Individual Planes of the whole Terrain and objects on top of it simply pop in and out of existence depending on the Players position.


texts: How can I switch between texture atlases based on the iOS version?

texts: How can I switch between atlases (with different resolutions) in Unity based on the runtime iOS version?


texts: What are the legal issues when using free Unity Assets on a commercial game?

texts:
In the unity asset store one can find tons of thousands of assets, a lot of them being distributed for free.

When using a free Unity Asset is it implied that you can do anything with it(commercial or not)?

Is there any legal agreement concerning free Unity Assets?


texts:
Possible Duplicate:
  Where can I go to find a game graphic artist?

I'm pretty good programmer, and I want to create new pixel-art-game. I know how to program, visualise and optimize the game. But I can't draw! I think there is a lot of people like me... So.. I'm looking for an artist, who can draw pixel-art sprites.

Where I can find "free" pixel-art artist, who just want to create a game (I think that he should have the similar problem, but instead of looking for artist he looks for programmer).


texts:
My question is probably something you guys have heard before - "How do you add SpriteFont's in Monogame's content manager?" The simple answer to this is, right click the 'Content' folder, go on 'Add New Item' and then you'll find it there. In my case however, there is no SpriteFont.

As far as my development environment goes, I am using Windows 7 and Visual Studio 2012. Upon getting Visual Studio, I installed MonoGame 3.2. My project is a MonoGame Windows Project (C#). As far as I can see, there are absolutely no options to add SpriteFont's to the MonoGame content manager. Right clicking the Content folder and going on Add New Item simply gets me this:

No sign of SpriteFont anywhere, whether I look under Visual C# Items or Online. What am I doing wrong?

The above is my content manager. If I go on Edit, New Item and then add my SpriteFont this way it will add, however the moment I go on Build, it will say 'MGCP has stopped responding'. This makes me think something is missing... A certain something called XNA Game Studio 4.0. I did some research and found a couple tutorials that tell you to install this, which makes me wonder if it is indeed needed. A friend of mine however is adamant that XNA Game Studio is not needed and that the only thing I need is VS 2012 and MonoGame.

Am I doing something wrong? Am I missing something? And is the answer to all my problems XNA Game Studio 4.0?


texts:
Is it possible to have a 2D isometric game in Unity, but also have 3D prefabs in the scene?
Will that work or should I make the game in 3D with an isometric camera?


texts: Distinguishing between multiple objects with the same name in a text based adventure game/interactive fiction

texts:
I'm in the middle of writing my own parser in Python. I've managed to make some simple commands, with simple prints to make sure they work. Since I intend there to be combat, I needed to write a command for attacking something. I just completed that.

My issue is: What should I do to allow the player to choose which of a given enemy they attack? It is fairly simple when they are different types of enemies (e.g. a goblin and a troglodyte), but how should I distinguish between two of the same type (e.g two troglodytes)?

Suggestions I have had so far: Give each of them a significant feature (color, height, relative direction) but that only so far; name each of them (so you attack "bob" or "steve"); or the one I have been favoring the most, give them each a number (so there would be troglodyte1, troglodyte2 etc.)-this might break some immersion, though.


texts: Finding the last GO in a set of generated objects?

texts:
I currently generate the maptiles using Tags purely, which works great but doesnt satisfy my needs. I want to delete tiles that i dont need(since my player will only be going to the right)  but I have a problem with checking when to delete old tiles so that i can generate new ones. My idea would be checking how close the player is to the last tile given and then delete the first, but i cant do that with tags since tags are given in the order that unity finds the GOs with that tag and not from left to right AFAIK. What would be the best way to get the last ground tile? (the one that got generated last).

using UnityEngine;
using System.Collections.Generic;

public class MapGenerator : MonoBehaviour

{
    private GameObject[] groundTiles;

/// <summary>
///  Represents the minimum amount of active tiles needed
/// </summary>
public int ActiveTiles;

void Start()
{
}

void Update()
{
    groundTiles = GameObject.FindGameObjectsWithTag("ground");

    if (groundTiles.Length < ActiveTiles)
        SpawnTile();
}

public void SpawnTile()
{
    GameObject tile = (GameObject)Instantiate(groundTiles[groundTiles.Length-1]);

    Vector3 tmpVec = tile.transform.position;
    tmpVec = tile.transform.position;
    tmpVec.x += 1;
    tile.transform.position = tmpVec;
}

public void DespawnTile(int tileIndex)
{
    List<GameObject> tmp = new List<GameObject>(groundTiles);
    tmp.RemoveAt(tileIndex);
    groundTiles = tmp.ToArray();
}
}


texts:
Sorry about the vague title, it's kind of hard to say what I want to do in a few words.

In my top-down game, I'm having a problem implementing proper collision for walls facing north (that is, you can actually see the surface of the wall, as opposed to the other directions, where you can see just the top).

I have a proper bounding box that detects the alpha values of the sprite, and generates a proper bounding box around only the visible pixels, like so:

http://a.pomf.se/kfrxtm.mp4

However, when dealing with walls, I run into a problem.
With my current implementation, there are two options I have:

Set the walls so that the player can pass through them. This leads to the player walking "on" the walls, like so:

Set the walls so that the player can not pass through them. This leads to the player's head colliding on the bottom of the wall, like so:

In the image, the player can not move forward any more.

My solution to this, would be to place the bounding box around the player's feet. However, this would interfere with my alpha-based system, and other collision systems (enemies hitting the player, etc.)

How should I approach this?

If my question is unclear, I can provide more images and descriptions of what I'm trying to achieve.


texts: Unity game crashing when dialogue with NPC initiated

texts:
I have 3 NPCs in my "Game". When the player walks up to any of them, they're supposed to have their own dialogue; I've tested this, and they do.

I tried to create a display that shows this dialogue text using a TextMeshProUGUI attached to a blank GameObject called dialogDisplay (tagged DialogDisplay). There is one DialogDisplay object in the scene that I'm trying to get each of my NPC's to use. I tried to make the display object inactive in the NPC Start() function, and enable it when it's time to display the NPC's next sentence.

When I run my game, I get an error on line 21, where SetActive() is called: "Object Reference Not Set to an Instance of an Object".

Here's the NPC script (DisplayNextSentence() is at the bottom, where dialogDisplay is used):

public class NPC : Character {
private bool charInRange;
public Dialogue dialogue;
public bool talkedTo = false;
private Queue<string> sentences;
public TextMeshProUGUI textPro;
public GameObject dialogDisplay;
private bool isTalking;

// Use this for initialization
void Start () {
    charInRange = false;
    textPro = FindObjectOfType<TextMeshProUGUI>();
    dialogDisplay = GameObject.FindGameObjectWithTag("DialogDisplay");
    dialogDisplay.SetActive(false);
}

// Update is called once per frame
void Update () {
    //if player is in range and presses space, triggers NPC dialogue
    if (charInRange && Input.GetKeyDown(KeyCode.Space))
    {
        TriggerDialogue();
    }
}

//if Player gameObject is in NPC collider, player is in range
void OnTriggerEnter2D(Collider2D other)
{
    if(other.gameObject.tag == "Player")
    {
        charInRange = true;
    }
}

//if player exits NPC collider, player is not in range
void OnTriggerExit2D(Collider2D other)
{
    if (other.gameObject.tag == "Player")
    {
        charInRange = false;
    }
}

//if NPC has been talked to before, displays next sentence; if not, loads dialogue and displays first sentence
private void TriggerDialogue()
{
    if (!talkedTo)
    {
        talkedTo = true;
        StartDialogue(dialogue);
    }
    else
    {
        DisplayNextSentence();
    }
}

//loads a queue with lines from Dialogue and displays first sentence
public void StartDialogue(Dialogue dialogue)
{
    sentences = new Queue<string>();

    foreach (string sentence in dialogue.sentences)
    {
        sentences.Enqueue(sentence);
    }

    DisplayNextSentence();
}

//displays next sentence in the queue
public void DisplayNextSentence()
{
    string sentence;
    bool done = false;

    //if last sentence in the queue, display it again
    if (sentences.Count == 1)
    {
        sentence = sentences.Peek();
        textPro.text = sentence;
        Debug.Log(sentence);
        return;
    }

    sentence = sentences.Dequeue();
    textPro.text = sentence;
    dialogDisplay.SetActive(true);
    while (!done) {
        Debug.Log("In WHile Looop");
        if (Input.GetKeyDown(KeyCode.A))
        {
            done = true;
        }
    }
    dialogDisplay.SetActive(false);
}
}

Grateful for any insight or tips you can provide. Happy to provide further information if it helps. Thank you!


texts: Error drawing two VAO, each one using different shader programs (vertex + fragment shader) in OpenGL Core 4.3 / GLSL 430

texts:
I am trying to draw over a GL_TRIANGLE_FAN one texture to render video frames, using shaderProgram1, and render above it some points (GL_POINTS) using shaderProgram2.

By this way: (OpenGL Core 4.3)

void GLViewer::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(handleShaderProg1);

    glUniform...(); //Set Uniforms for shaderProg1... <-- FIXED

    glBindTexture(GL_TEXTURE_2D, textureHandle); //Bind texture
    glBindVertexArray(vaoHandle1); //Bind VAO
    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
    glBindVertexArray(0); //Unbind VAO
    glBindTexture(GL_TEXTURE_2D, 0); //Unbind texture (used in shaderProg1)

    glUseProgram(handleShaderProg2);

    glUniform...(); //Set Uniforms for shaderProg2... <-- FIXED

    glBindVertexArray(vaoHandle2);  //Bind VAO
    glDrawArrays(GL_POINTS, 0, 25);
    glBindVertexArray(0);  //Unbind VAO
}

But only the points defined in vbo2 are rendered over the black glClearColor. Without using the shaderProgram2, all are rendered, texture and the points above it.

Is mandatory to use a FBO and two pass deferred rendering? If not, what could be the problem?

SOLVED : After an OpenGL debugging, I discovered a newbie bug...

In my case, I needed to pass the uniforms to the shader every time the current shader program will be changed to another shader program. I was thinking that the uniform variables will keep alive after another call to glUseProgram. I was wrong...


texts: Storing component vectors to avoid matrix and quaternion inaccuracies?

texts:
I read that I "should really be storing the component vectors (rotation, translation, scale) in addition to the quaternion and matrix forms." The reason for this is that, over time, compound numerical numerical errors can build up over time from floating point limits.

This seems a bit excessive to me. I was planning on creating a Transform class that just manipulated a glm::mat4 model matrix. But now I'm concerned that this might not be the best way, however I don't really understand why. Could someone explain why and now numerical errors can build over time using quaternions?

And what should I really be doing instead? Store component vectors, but convert euler rotations to quaternion using glm::angleAxis while setting rotations, and then return a glm::mat4 model matrix that combines these things upon request? That's a whole lot of matrix math flying around every frame. I guess I could check to see the glm::mat4 has changed before assembling a new one but maybe there's a better way.

One advantage I'd have by storing the component vectors is trying to return what the current component vectors actually are. Pulling that from a glm::mat4 seems tedious. I know I can decompose a matrix, but I don't want all the decomposed components when I'm just trying to return, for example, a rotation. But... as I understand it, it needs to be decomposed fully in order to get any of the component vectors. In other words, it's all or nothing.

To restate my questions:

What sort of use case makes matrices and quaternions lose their accuracy over time and why?
How can I avoid this problem (or what should I be doing)? Hoping for something fast AND accurate.


texts: How to create installer package with custom artstyle?

texts:
When you publish a finished game you might consider making, for example, a Windows installer package.

I have found quite a few applications that can do that. But I couldn't find any that support changing the appearance of an installation process.

Many games support that, so I have been wondering where could I find an application like this? I doubt that every game studio creates its own one.

Preferably the one that supports Unity files.

EDIT:
Examples


texts: Having the same texture data in different ID3D11Texture2D

texts:
Sorry if this has been answered elsewhere - I'm rather new to DX.  My question concerns conservation of resources - specifically textures in VRAM.  I assume that upon returning from a call to CreateTexture2D, a copy of any textures data supplied has been copied elsewhere, likely VRAM.  Does DX11 have any facility for having multiple ID3D11Texture2D objects which point to the same data?

This might at first seem silly, but imagine a ID3D11Texture2D which is an array of textures.  In one material, an artist has chosen to blend three identically sized maps, saved on disk as A.dds, B.dds, and C.dds.  Then imagine they have another material which also uses three maps, but this time A.dds, B.dds, and D.dds.

The shader code knows the diffuse texture is a texture array, and also has the number of layers baked (three in each case).  I would essentially like to set up just two ID3D11Texture2D objects, one for each material, but I don't want to waste VRAM for two identical copies of A.dds and B.dds.

I could use explicit texture arrays, of course, but this reduces the number of resources available to the shader and can complicate code somewhat more than would otherwise be needed.