texts: How to get character position in 2D map array by its position on canvas

texts:
My arrayMap consists of 0, 1 and 2. 0 is water and character is allowed to be on. 1 and 2 are ground and the collision should happen.

To get and check what array number the character is standing on, I take the character position and divide it by my tileset size which is 36px and use Math.floor to round the number. I place it like this: console.log(mapArray[Math.floor(boatPosX / 36)][Math.floor(boatPosX / 36)]); and I know if its 0, 1 or 2 he is standing on. Which is great so far. But my collision still doesn't work the way it should. Actually it acts so weird I don't even know how to fix it properly. If I put some 1 in my player start position, I get collision, but if I place it at 0 in array and move onto 1 myself, it doesn't work.

So it's giving me different results every time. I feel like I'm almost here but some stupid bug is ruining it all.

var mapArray = [
  [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
  [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
  [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
  [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0],
  [0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
];
function isPositionWall(ptX, ptY) {
  var gridX = Math.floor(ptX / 36);
  var gridY = Math.floor(ptY / 36);
  if(mapArray[gridX][gridY] == 1)
    return true;
}

var boatPosX = canvas.height/2 - 50;
var boatPosY = canvas.height/2 - 50;

function render(viewport) {
  context.save();
  context.translate(view.x, view.y);
  requestAnimationFrame(render);
  var oldPosX = boatPosX;
  var oldPosY = boatPosY;

  for (let i = 0; i < mapArray.length; i++) {
    for (let j = 0; j < mapArray[i].length; j++) {
      if (mapArray[j][i] == 0) {
        this.sprite.draw(
          background,
          190,
          230,
          26,
          26,
          i * this.sprite.width,
          j * this.sprite.height,
          this.sprite.width,
          this.sprite.height
        );
      }
      if (mapArray[j][i] == 1) {
        this.sprite.draw(
          background,
          30,
          30,
          26,
          26,
          i * this.sprite.width,
          j * this.sprite.height,
          this.sprite.width,
          this.sprite.height
        );

      }
      if (mapArray[j][i] == 2) {
        this.sprite.draw(
          background,
          200,
          20,
          26,
          26,
          i * this.sprite.width,
          j * this.sprite.height,
          this.sprite.width,
          this.sprite.height
        );
      }
    }
  }
  this.ship.drawimage(boat, boatPosX, boatPosY, 50, 50);

  if(isPositionWall(boatPosX, boatPosY)) {
    //boatPosX = oldPosY;
    console.log("collision");
  }
  console.log(mapArray[Math.floor(boatPosX / 36)][Math.floor(boatPosX / 36)]);
  context.restore();

};

function move(e) {
  if (e.keyCode == 39) {
    boatPosX += 5;
    view.x -= 5
    moveCount++;
    console.log(moveCount);
    console.log("right");
  }

That's parts of the code that are related to the question. If you need need more code, let me know. I'm looking for some directions what I'm doing wrong. Thanks.

Codepen: https://codepen.io/Limpuls/pen/deEGXX


texts: Drawing the same scene with perspective then orthographic projections

texts:
I have a scene that I'm rendering first with a perspective matrix. I then want to rerender it in a different viewport using an orthographic matrix for a top-down 2D view of the scene. I think I may be missing something because I get nothing rendered with the orthographic projection.

To setup the ortho projection I create the matrix with the near/far set to (-1,1) (not sure how it affects rendering) and then move the camera up and pitch it 90 degrees and rerender the vertices without modification.

I'm using OpenGL4 with glm to produce the matrices.


texts:
The first time the player clicks a button, my animation plays properly.

The problem is that when the player presses the button a second time, the animation does not play.

Here is the code I'm using to control my animation:

public Animator anim;

public Animator animsfirst;
public Animator animssecond;
public Animator animsthird;

public Animator reanimsfirst;
public Animator reanimssecond;
public Animator reanimsthird;
public Animator closeinstruct;

public void instructionpanel()      //(instruction panel open animation)
{
    anim.enabled = true;         //when button click instruction panel open
    animsfirst.enabled = true;
    animssecond.enabled = true;
    animsthird.enabled = true;
}

public void closeinstructionpanel()  //(instruction panel close animation)
{
    Debug.Log("animationrun");   //when button click instruction panel close
    reanimsfirst.Play("freverse");
    reanimssecond.Play("srevese");
    reanimsthird.Play("lreverse");
    closeinstruct.Play("clreverse");
}

Here is the animator controller setup for the animsfirst object:

And for the reanimsfirst object:

How can I resolve this issue?


texts: Libgdx draw a sprite in top of an isometric tile

texts:
I have this isometric map and im using IsometricTiledMapRenderer to render the map I have a OrthographicCamera. I know where each tile is in the isometric map, but the isometric map is kinda rotated?

So I was wondering how to convert Map Coordinates to Isometric and viceversa?

Here I tried to draw a color cube in each tile coordinates....

Thanks in advance, I have been struggling with this for 2 days, and my lack english vocabulary isnt helping with the research, please some one point me to something


texts: Why are my 2D positions "off" after adding a camera transformation in XNA?

texts:
My game's source is on github.

I am following this tutorial to create a 2D camera. After I adding the transformation to the SpriteBatch, all of my positions seem to be "off" when I move the ship (and hence camera) away from the screen center.

Any idea what might be wrong?


texts: How to make map generation with Perlin noise look more like an actual map

texts:
I have been following a guide on Perlin noise, but I can't post the link here because of my current reputation level. I will post code if needed.

When I get noise from this distribution, I tend to get a very large fraction of values near the 0.5 range and very few on the fringes. You can see this from a sample which I turned into a quick graphic in the image below. I scaled my noise function by the width of the screen and had it increment an array at index = noise by 1 every time it generated a noise value. As you can see, the distribution is hardly Normal, as the fringes just drop out entirely.

What is the best way to make this distribution wider towards the bottom, but not towards the top? I want most of the values to lie in a Gaussian distribution, but I can't just use a Gaussian distributed random number because I need values selected close to each other to be close to each other (Perlin noise).

How does this relate to games? I'm using the noise function to generate terrain and biome information. I have one noise array for elevation, one for temperature, and one for precipitation. I figured I could just overlay them and then determine the color of a square depending on a Whittaker plot, but with the current program, I end up only getting biomes in the midrange of the plot (Temperate forests), and I never get Tropical Rainforests or Taigas. Below are a few images of my generation:

(I need 10 reputation to post this many links and the zoomed out version shows the problem better)

And zoomed out:

Here is my code for coloration. eNoise is scaled to 0-100, mNoise is scaled to 0-400, and tNoise is scaled from -15-40:

if(eNoise[i][j] < 55f) { color = Color.blue; }
            else {
                if(tNoise[i][j] < -15f) { //Tundra
                    color = Color.blue.brighter();
                } else if(tNoise[i][j] < 12f) {
                    if(mNoise[i][j] < 20f) {
                        color = Color.orange; //ST Desert
                    } else if(mNoise[i][j] < 50f) {
                        color = Color.yellow; //TG and Des
                    } else {
                        color = Color.green.darker(0.5f); //Taiga
                    }
                } else if(tNoise[i][j] < 20f) {
                    if(mNoise[i][j] < 30f) {
                        color = Color.orange; //ST Desert
                    } else if(mNoise[i][j] < 110f) {
                        color = Color.yellow; //TG and Des
                    } else if(mNoise[i][j] < 220f) {
                        color = Color.green.darker(0.3f); //TD Forest
                    } else {
                        color = Color.green.darker(0.2f); //Temp RF
                    }
                } else {
                    if(mNoise[i][j] < 50f) {
                        color = Color.orange; //ST Desert
                    } else if(mNoise[i][j] < 110f) {
                        color = Color.green.brighter(0.2f); //Savanna
                    } else if(mNoise[i][j] < 250f) {
                        color = Color.green; //TS Forest
                    } else {
                        color = Color.green.brighter(0.5f); //Tro RF
                    }}}


texts:
I am creating a game in allegro5 and I have come across a problem. I have a character that fires a shotgun and there needs to be a delay before he can shoot again. The code for shooting his gun is in a function called

fire_shotgun();

and I cant find a way to create a pause before he shoots again without stopping the whole game by using

al_rest();

I am wondering if there is any way to do this.

P.S. my game is running on a 60FPS timer if that is of any use.


texts: Is there any online programmer's community, focusing on core game development?

texts:
I am looking for a stricktly/mostly programming oriented game community, focusing on core graphics, middleware, and research. Any suggestions?

Edit: I am specifically looking for people/community/group, having expertise in core game engine design/programming, directx/opengl reservoir.(And specifically targetting the programming part only).(The platforms can be anything from PC to xbox360/ps3/wii and even 3ds.)


texts:
My character is not sticking on the platform when jumping on it, but I don't know why. I checked, and I have rigidbodys and colliders. The problem appeared when I moved the game to another hard drive.

Here is mycode:

void OnCollisionEnter2D(Collision2D other)
{
    if (other.transform.tag == "MovingPlatform")
    {
        transform.parent = other.transform;
    }
}

void OnCollisionExit2D(Collision2D other)
{
    if (other.transform.tag == "MovingPlatform")
    {
        transform.parent = null;
    }
}

Why doesn't my character stick to the platform?


texts: UI: Main Menu options for mobile games. What options should be listed? What do users want to see?

texts:
When a user arrives at your main menu on your mobile touch phone game. What do you want them to see? What do they need to see?

Start, About, Load, Leaderboards, and Settings are just a few of the options that I "could" put on the Main Menu. The question really is what "should" be there and why?

My game is about surviving waves of enemies to get to the next level, with a twist of course.

What options could/should be shown on my Main Menu and why?

EDIT UPDATE:

Easy recognizable PLAY button.
Possible buttons include, but are not limited to Options, Stats/Achievements, Leaderboards, Level Solutions, and Promote Game.
Choose appropriate options for your type of game. (ie. Level Solutions good for puzzle games but not FPS)
Less is more, don't clutter the Main Menu to prevent users from getting confused. Weigh the benefits of an additional button against the risks of confusing users.
Symbols can be used to convey the meaning of a button, be sure to reach the largest audience possible.
Have as few clicks as possible to get into the game.


texts:
I am reading the paper Animated Mesh Approximation With Sphere-Meshes . The input of the algorithm mentioned in the paper is an animated surface mesh, but I do not know what an animated surface mesh is. I just learn a little about surface mesh, which may be an .off file on the disk.

What is an animated surface mesh? What kind of file format do animated surface meshes have on the disk?


texts: How do I make the camera focus on a moving game object with ITween?

texts:
I'm trying to write a solar system with Unity3D. Planets are sphere game objects rotating around another sphere game object representing the star.

What i want to achieve is let the user click on a planet and then zoom the camera on this planet and then make the camera follow and keep it centered on the screen while it keep moving around the star.

I decided to use iTween library and so far i was able to create the zoom effect using iTween.MoveUpdate. My problem is that the focused planet does not say properly centered as it moves.

Here is the relevant part of my script:

void Update () {
    if (Input.GetButtonDown("Fire1"))
    {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, Mathf.Infinity, concernedLayers))
            {
                    selectedPlanet = hit.collider.gameObject;
            }
    }
}

void LateUpdate() {
    if (selectedPlanet != null)
    {
            Vector3 pos = selectedPlanet.transform.position;
            pos.z = selectedPlanet.transform.position.z - selectedPlanet.transform.localScale.z;
            pos.y = selectedPlanet.transform.position.y;

            iTween.MoveUpdate(Camera.main.gameObject, pos, 2);
    }
}

What do i need to add to this script to make the selected planet stay centered on the screen?

I hosted my current project as a webplayer application so you see what's going wrong. You can access it here.


texts:
I have a question related to SSS and especially transmittance. I've looked at several papers about that topic, most of them from Jorge Jimenez, which are very interesting and, I admit, a bit hard for me.

Here is one of the papers : http://www.iryoku.com/translucency/

I have some difficulties to understand the way it works and the way it calculates the distance the light traveled through the object. I think that I understand the very big lines but I am also a bit confused as I am trying to integrate this into the Unity engine and I have some difficulties to match Unity engine available values such as the shadows maps, the shadows coords, etc... to make them fit the way they are used in the paper.

So here it is, I am a bit lost in the "in-between" and I hope that somebody might be able to help me.

Thanks a lot.

EDIT : added the shader code from referenced paper

float distance(float3 posW, float3 normalW, int i) {
  // Shrink the position to avoid artifacts on the silhouette:
  posW = posW - 0.005 * normalW;

  // Transform to light space:
  float4 posL = mul(float4(posW, 1.0), lights[i].viewproj);

  // Fetch depth from the shadow map:
  // (Depth from shadow maps is expected to be linear)
  float d1 = shwmaps[i].Sample(sampler, posL.xy / posL.w);
  float d2 = posL.z;

  // Calculate the difference:
  return abs(d1 - d2);
}

// This function can be precomputed for efficiency
float3 T(float s) {
  return float3(0.233, 0.455, 0.649) * exp(-s * s / 0.0064) +
         float3(0.1,   0.336, 0.344) * exp(-s * s / 0.0484) +
         float3(0.118, 0.198, 0.0)   * exp(-s * s / 0.187)  +
         float3(0.113, 0.007, 0.007) * exp(-s * s / 0.567)  +
         float3(0.358, 0.004, 0.0)   * exp(-s * s / 1.99)   +
         float3(0.078, 0.0,   0.0)   * exp(-s * s / 7.41);
}

// The following is done for each light 'i'.

// Calculate the distance traveled by the light inside of the object:
// ('strength' modulates the strength of the effect; 'normalW' is the vertex
//  normal)
float s = distance(posW, normalW, i) / strength;

// Estimate the irradiance on the back:
// ('lightW' is the regular light vector)
float irradiance = max(0.3 + dot(-normalW, lightW), 0.0);

// Calculate transmitted light:
// ('attenuation' and 'spot' are the usual spot light factors, as in regular
//  reflected light):
float3 transmittance = T(s) * lights[i].color *
                       attenuation * spot * albedo.rgb * irradiance;

// Add the contribution of this light:
color += transmittance + reflectance;


texts: How do I implement 2D shadows cast between layers?

texts:
How could I implement 2d shadows that are cast by objects in a different layer?

NOT like the dynamic lighting in the well known tutorial from Catalin Zima :

But like the shadows of the pipes in this video:

And like the shadow of the platform and the character in this video:

I would like to use the same kind of lighting in a scene with many layers and a lot of lights with different colors.

I could imagine doing this by drawing a black copy of the layer over the layers behind that layer, and adjusting it according to holes in the layers on which the shadow is cast. But I hope there is a less expensive, pixel-shader based approach for this.


texts: How can I make a custom mesh class in Unity?

texts:
I'm doing something in Unity where I need to specify the position and orientation of vertices with two Vector4s, and they're not just position and normal vectors. I've already written my custom shader and now I need to make mesh objects that can be fed into it.
So how do I make my custom mesh? Should I inherit from the mesh class? Will I still be able to use the normal mesh filter and mesh renderer components or should I replace those too? I am comfortable coding the data structure for my new mesh, the question is interfacing with the Unity rendering pipeline and sending the data to my shader in the right way.


texts: Unity: Why do my normals flip during an animation?

texts:
This problem boggles my mind. I have an animation running on a face object (imported from Blender). At a few points in the animation, the normals switch direction! It causes the mesh to blink.

Of course this animation won't work in its current state. Even odder, I slowed down the animation sample in Unity to 1 so I could isolate the frames it happens on. There are no keyframes on the face when this happens!

What could be causing this? It only happens on this one animation. I can't find anything with extensive web searching. I've also tried recalculating normals and applying transformations, but it doesn't help.

These screen shots depict the same two frames, one frame before it happens (left) and the frame when it happens (right), just from different angles.

I'd very much appreciate any input or guidance to fixing this!


texts: How to draw a rectangle or curve between two co-ordinates in libGDX

texts:
I am new to libGDX.I just want a Rectangle or a small curve drawn between the object and the clicked position .I know libGDX has RECTANGLE class.

I just want to draw a rectangle or a curved line to be drawn between the object and the clicked position like this >>>

click can occur anywhere inside the circle region(above red object or below the red object).
green cross represents the click position.
red one represents the object.

Problem is if i use shapeRenderer.rect(x, y, width, height); it will give me straight horizontal rectangle like the gray rectangle shown in the image. Therefore i will have to use shapeRenderer.rect(x, y, width, height, originX, originY, rotation); . I gave 0 for both originX and originY but what will be the rotation value ? I am stuck up in calculating the rotation value .

Currently i can think of two ways to do it :-

By using Rectangle >>> shapeRenderer.rect(x, y, width, height, originX, originY, rotation);
By using sprite image >>> batcher.draw(region, x, y, originX, originY, width, height, scaleX, scaleY, rotation, clockwise);

But in both the cases as u see i need the rotation value .How to calculate that ?
Or is there any other way we can achieve the same results maybe by using some sprite image or something ?


texts: GLSL - Stencil buffer - instanced geometry

texts:
I have geometry that have attached some "ID" data. I have generated stencil  buffer, that holds these IDs.
Now, in second pass, I render different geometry, but this time I need to mask it with already existing stencil. Each part of geometry can have different "ID". Is there a way, how to control stencil buffer test value from shader?

I give an example:

  render geometry with ID = 1, writes 1 to stencil
  render geometry with ID = 2 if ID in stencil != 1, writes 2 to stencil
  do some other rendering with stencil turn off
  render bunch of particles at one go, but some of them have ID 1, some of them ID 2 -> I want to mask them, so 1 is rendered only if 1
  is in stencil and 2 only if 2 is in stencil

I need this for OpenGL ES 2.0


texts: Unity3D - different object with the same mesh imported from Blender

texts:
I would like to instantiate different objects (i.e. poker chips with different values) that actually share the same mesh imported from blender. To this end I have copied the assets and changed the texture but all the assets automatically switch to the last texture I choose as they are actually the same entity.
What am i doing wrong?


texts: I am a High School student in Ontario and i am trying looking for college/university programs the are specifically about game design. There are quite a few at most colleges near me, but they are all BA's and I am looking for a BSc. The only one i have been able to find is at digipen but that is across the continent and more importantly outrageously expensive. Does anyone know of and programs in Canada or the US that offer a BSc in Game design?


texts:
So far I have this implementation of "FYTS".

However I am facing several problems.

    final int TICKS_PER_S = 60;
    double accumulator = 0.0;
    //The timestep
    final double dt = 1/(double)TICKS_PER_S;
    long previousTime = System.currentTimeMillis();

    //State previous;
    //State current;
    while(running){

        long currentTime = System.currentTimeMillis();
        double frameTime = (currentTime - previousTime)/1000;

        if(frameTime > 0.25){
            frameTime = 0.25;
        }
        previousTime = currentTime;
        accumulator += frameTime;

        while(accumulator >= dt){

            //previousState = currentState;
            this.gamePanel.update(dt);
            accumulator -= dt;
        }

        //Interpolation
        // final double alpha = currentState * alpha +
        //               previousState * (1.0 - alpha);

        //This is the draw call. Not yet using interpolation
        this.gamePanel.postInvalidate();
    }

Problem 1:

frameTime is always 0 meaning that the game is never updating. It seems obvious: In the beginning it is 0, but that should change, shouldn't it?

Problem 2:

Let's assume that Problem 1 wouldn't exist. I understand that you take an arbitrary frameTime and split it up into discrete timesteps and then update the game. But what's the point of updating in a separate nested loop anyways? Most of the time you are left with a little remainder at the end of finishing the inner update loop. That remainder is how much of the simulation is left to complete until the running loop starts again and takes a new frameTime on which a part of the simulation has to be performed on. But what does the interpolation do that's worth to even consider doing it Isn't the inner update loop just a waste of time?

Problem 3:

The outer loop is running without any limitations at max speed. Isn't that just wasting clock cycles (and draining the battery life on mobile devices)? Is there anything I could do to counteract that?


texts: Rendering a scene or prefab in a gallery style view in Unity3D?

texts:
I'm working on a project that is a bit like YouTube where someone browses some content, clicks on one and sees it in the youtube player while still seeing the rest of the content.

In my case the content is a Unity prefab that runs with interactions and gameplay, a bit like an interactive YouTube.

Is there a way to load these prefabs in a scene or something and have them displayed in a view port of some sort which substitutes the position of the player?


texts: White background in icon for Google Search on mobile device

texts:
We experience an issue with our game icon related to google search on mobile device. Here is a screenshot:

As you can see, our ccon has a white background on a green wall. We are aware that we have to use a 512x512 PNG with alpha channel.

The shown image is a 80x80 JPG which is, I guess, created out of our icon by using some background color. Could it be that we have to set this color somewere in the store or maybe in the app manifest?

Thanks for you help in advance ;)


texts: How do I render a word in the middle of the screen using FreeType and OpenGL?

texts:
I'm following this tutorial series on making a simple 2D clone of the classic Breakout game, but its author doesn't mention how to render a whole word or sentence in the middle of the screen. He simply uses hard-coded X and Y coordinates that obviously work for his screen, but not for mine (hence why the mere suggestion of using hard-coded values for something like this makes my skin crawl).

For more details on how he accomplishes the task, see this page of the aforementioned tutorial.

My version of his game has two major differences:

I am rendering the GLFW window in fullscreen mode instead of a 800x600 window.
I suspect that even if I were to use a 800x600 window, things still wouldn't look consistent across every device. As such I have made many changes to hard-coded values across the entire code base.

I'm a perfectionist so even though no-one else will probably ever run my game, I'm trying to eliminate the possibility of different results on different resolutions. But to do that has turned out to be a massive undertaking!

Here is the code that I'm having particular trouble with:

void TextRenderer::RenderText(string text, GLfloat x, GLfloat y, GLfloat scale, vec3 color) {
    // Activate corresponding render state
    shader.Use();
    shader.SetVector3f("textColor", color);

    glActiveTexture(GL_TEXTURE0);
    glBindVertexArray(vao);

    // Iterate through all characters
    for (auto c = text.begin(); c != text.end(); c++) {
        auto ch = characters[*c];

        auto xPos = x + ch.bearing.x * scale;
        auto yPos = y + (characters['H'].bearing.
            y - ch.bearing.y) * scale;
        auto w = ch.size.x * scale;
        auto h = ch.size.y * scale;

        // Update VBO for each character
        GLfloat vertices[6][4] = {
            { xPos,     yPos + h, 0.0, 1.0 },
            { xPos + w, yPos,     1.0, 0.0 },
            { xPos,     yPos,     0.0, 0.0 },

            { xPos,     yPos + h, 0.0, 1.0 },
            { xPos + w, yPos + h, 1.0, 1.0 },
            { xPos + w, yPos,     1.0, 0.0 }
        };

        // Render glyph texture over quad
        glBindTexture(GL_TEXTURE_2D, ch.textureID);

        // Update content of VBO memory
        glBindBuffer(GL_ARRAY_BUFFER, vbo);
        glBufferSubData(GL_ARRAY_BUFFER, 0,
            sizeof(vertices), vertices);
        glBindBuffer(GL_ARRAY_BUFFER, 0);

        // Render quad and advance cursors for next glyph
        glDrawArrays(GL_TRIANGLES, 0, 6);
        // Bitshift by 6 to get value in pixels (1/64th times 2^6 = 64)
        x += (ch.advance >> 6) * scale;
    }

    glBindVertexArray(0);
    glBindTexture(GL_TEXTURE_2D, 0);
}

I have tried adding a bool centreX and bool centreY param to the function, as well as another for loop before the main one like this:

if (centreX || centreY) {
    auto textWidth = 0.0f;
    auto textHeight = 0.0f;

    for (auto c = text.begin(); c != text.end(); c++) {
        auto ch = characters[*c];

        if (centreX) {
            textWidth += (ch.bearing.x * scale) + (ch.size.
                x * scale) + ((ch.advance >> 6) * scale);
        }

        if (centreY) {
            textHeight += (y + (characters['H'].bearing.y -
                ch.bearing.y) * scale) + (ch.size.y * scale);
        }
    }

    if (centreX) {
        auto lastCh = text.end() - 1;
        textWidth -= (characters[*lastCh].advance >> 6) * scale;
    }
}

But for the sentence, font and font size used I'm getting a textWidth value of 1952 while a screenshot of the rendered text is 1143 px wide :S

Where has my math or understanding of the original code gone wrong? My display is a high DPI one and I have my Windows scaling settings at 200%; could either of those things be the culprit?

MTIA!


texts:
I just started using blender again and I'd like to know if smoothing your model out adds a performance hit to your game?

By smoothing I mean when you hit ctrl+X (number from 1-9). The number of vertices stay the same, but the model gets considerably smoother the higher the number goes, i'm wondering if it's secretly adding tons of vertices in order to do this and would be a performance hit, or if it's doing something else that isn't a big deal to the performance of your game. Thanks.


texts: How to calculate continuous motion with angular velocity in 2d

texts:
I'm really new with physics. Maybe someone would be able to help me to solve the next problem:
I need to calculate position of an agent on the plane(2D) in next time step where time step is large(20+ seconds)
What I know about agent's motion:

Initial Position
Direction(normalised vector)
Velocity(linear function from time ) - object always moves along it's direction
Angular Velocity(linear function from time)

Optional:

External force direction
External force (linear function from time)

Running discreet simulation with t->0 is not an option.


texts: Procedural world  generation oriented on gameplay features

texts:
In large procedural landscape games, the land seems dull, but that's probably because the real world is largely dull, with only limited places where the scenery is dramatic or tactical.

Looking at world generation from this point of view, a landscape generator for a game (that is, not for the sake of scenery, but for the sake of gameplay) needs to not follow the rules of landscaping, but instead some rules married to the expectations of the gamer. For example, there could be a choke point / route generator that creates hills ravines, rivers and mountains between cities, rather than the natural way cities arise, scattered on the land based on resources or conditions generated by the mountains and rainfall patterns.

Is there any existing work being done like this? Start with cities or population centres and then add in terrain afterwards?

The reason I'm asking is that I'd previously pondered taking existing maps from fantasy fiction (my own and others), putting the information into the system as a base point, and then generating a good world to play in from it. This seems covered by existing technology, that is, where the designer puts in all the necessary information such as the city populations, resources, biomes, road networks and rivers, then allows the PCG fill in the gaps.

But now I'm wondering if it may be possible to have a content generator generate also the overall design. Generate the cities and population centres, balancing them so that there is a natural seeming need of commerce, then generate the positions and connectivity, then from the type of city produce the list of necessary resources that must be nearby, and only then, maybe given some rules on how to make the journey between cities both believable and interesting, generate the final content including the roads, the choke points, the bridges and tunnels, ferries and the terrain including the biomes and coastline necessary.

If this has been done before, I'd like to know, and would like to know what went wrong, and what went right.


texts: How should I calculate the score in Minesweeper: 3BV or 3BV/s?

texts:
I'm designing a minesweeper game, and I'm a bit confused as to how to calculate the score.

The objective of my game is to reveal all the non-flagged boxes. Marking the flag must not count toward the score. Just showing the number of seconds required to complete a board seems obsolete as I have a variable board size which is decided by the user. I studied the Wikipedia page on Minesweeper regarding the two scoring techniques.

But I don't understand how to calculate the 3BV. Is it just the number of left clicks done by user done during the game, or is the 3BV the minimum number of clicks required to complete the board? Also how can 3BV/s be judged: does a higher or lower score give a higher ranking?

Regarding my implementation

I used an integer array with all zeros and 9 designating a mine position. When a user click in the grid I calculate the nearby cells and then display the appropriate number and if he clicks on cell with value 9 then game is over.


texts: How to find monitor resolution with glfw3?

texts:
For a while now, I have been playing around with making a game using OpenGL, and glfw3. I have been perfectly happy to create windows at my native resolution of 1920x1080. I'm getting to the point where I want to share it with other developers, so I cannot keep hard coding the screen resolution in. I went looking for ways to find the maximum resolution of the available monitor, which glfw provides using the function glfwGetVideoModes(GLFWwindow*, int);. It supposedly finds all available displays for a monitor (resolution, color depth, refresh rate), and returns them as an array of possibilities.

void GetMaxMonitorResolution(int* w, int* h)
{
    int count;
    const GLFWvidmode* modes = glfwGetVideoModes(glfwGetPrimaryMonitor(), &count);

    int maxWidth = 0;
    int maxHeight = 0;
    for (int i = 0; i < count; i++)
    {
        if (modes[i].width > maxWidth)
            maxWidth = modes[i].width;
        if (modes[i].height > maxHeight)
            maxHeight = modes[i].height;
    }

    *w = maxWidth;
    *h = maxHeight;
}

The problem is, even though my monitor supports 1920x1080, it keeps creating a window at 800x600, the smallest resolution possible on my monitor. I am relatively new to C++, so I am only 80% sure how pointers work, especially pointers to arrays and the such. So if I am somehow messing up the pointers, or if it truly is a problem with glfw, I would appreciate any help.

EDIT: The documentation for glfw3 monitors is here and here, in case anyone was wondering.


texts: How to write reuseable components for pygame

texts: Is there a recommended way to write reuseable components for pygame? Simple example would be a FPS counter. Should I write a class which has an init, update and draw method and call them from inside a game loop?


texts: how can I add animated shadow on my flag?

texts:
this is my flag:

I need to adding shadow effect on my animated flag like below image but I don't know how can I do this:

here is my shader:

Shader "Custom/Flag" {
    Properties {
        _MainTex ("Texture", 2D) = "white" {}
        _Ambient ("Ambient", Range(0., 1.)) = 0.2
        [Header(Waves)]
        _WaveSpeed("Speed", Range(1,50)) = 20
        _WaveStrength("Strength", Range(0.0, 1.0)) = 0.0
    }

        SubShader {
        Cull Off
        CGPROGRAM

        #pragma surface surf Standard fullforwardshadows vertex:vert

        #pragma target 3.0

        struct Input {
          float4 pos : POSITION;
          float2 uv_MainTex: TEXCOORD0;
        };

        struct VertexInput{

          float4 vertex : POSITION;
          float4 texcoord : TEXCOORD0;
          float3 normal : NORMAL;

        };

            float _Ambient;
            sampler2D _MainTex;

            // Compute the diffuse light
            fixed3 diffuseLambert(float3 normal)
            {
                float diffuse = max(_Ambient, dot(normalize(normal), _WorldSpaceLightPos0.xyz));
                return _LightColor0.rgb * diffuse;
            }
            float _WaveStrength;
            float _WaveSpeed;

            // Deformation
            float4 movement(float4 pos, float2 uv) {
                float sinOff = (pos.x + pos.y + pos.z) * _WaveStrength +_Time.z;
                float t = _Time.y * _WaveSpeed;
                float fx = uv.x;
                float fy = uv.x * uv.y;
                pos.x += sin(t * 1.45 + sinOff) * fx * 0.5;
                pos.y = sin(t * 3.12 + sinOff) * fx * 0.5 - fy * 0.9;
                pos.z -= sin(t * 2.2 + sinOff) * fx * 0.2;
                return pos;
            }

        void vert (inout VertexInput v, out Input o){
            UNITY_INITIALIZE_OUTPUT(Input,o);

            float sinOff=v.vertex.x+v.vertex.y+v.vertex.z;
            float t=_Time*_WaveSpeed;
            float fx=v.texcoord.x;
            float fy=v.texcoord.x*v.texcoord.y;

            v.vertex.x+=sin(t*1.45+sinOff)*fx*0.5;
            v.vertex.y=sin(t*3.12+sinOff)*fx*0.5-fy*0.9;
            v.vertex.z-=sin(t*2.2+sinOff)*fx*0.2;

              o.pos = UnityObjectToClipPos( v.vertex );
              o.uv_MainTex = v.texcoord ;
        }
        void surf (Input IN, inout SurfaceOutputStandard o) {
            o.Albedo = tex2D(_MainTex,IN.uv_MainTex);
        }
        ENDCG
    }
    FallBack "Diffuse"
}

Update:

finally I use normal vector for shading but shadow isn't smooth how can I fix this:

v.normal.x+=sin(t*1.45+sinOff)*fx*0.5;
v.normal.y+=sin(t*3.12+sinOff)*fx*0.5-fy*0.9;
v.normal.z-=sin(t*2.2+sinOff)*fx*0.2;


texts:
So I've been making a 2D grid and pathfinder using SFML. Now I ran into a problem. I've been making a vector for the path nodes.

struct Node
{
    std::pair <int, int> node; // position of the node <x,y>
    std::pair <int, int> previous;
    bool iswall = false;
    sf::Vector2f rectCenter = sf::Vector2f(0, 0);
    sf::Vector2f position;

};

class Gridspot
{
    Node start;
    Node end;
    std::vector <Node> Openset
    std::vector <Node> Closedset;
    std::vector <Node> Path;
};

I then make a function so I can set grid cell's center:

void Gridspot::calculaterectCenter(sf::Vector2f& center, int i, int j)
{

    for (auto path : Path)
    {
        if (path.node == std::make_pair(i, j))
            path.rectCenter = center; break;
    }
}

in the main:

for (auto path : cell.Path)
{
    if (i == path.node.first && j == path.node.second)
    {

sf::Vector2f center(box[i][j].getPosition().x + box[i][j].getSize().x / 2, box[i][j].getPosition().y + box[i][j].getSize().y / 2);

                box[i][j].setFillColor(sf::Color::Magenta);
                cell.calculaterectCenter(center, i, j);

    }

}

the problem that I'm facing is that when I enter the value the vector element in question rectcenter variable doesn't change.


texts: One SKSpriteNode with multiple PhysicsBodies?

texts:
I am making a game similar to Lunar Lander, when you land with your ship on different objects, etc... The issue I am having is that I have a Player SKSpriteNode (my Ship) with a slightly complex collision system (bottom of the ship has different CategoryBitMask from other sides, etc.) and when I apply PhysicsBody(bodies: [physicsBodiesArray]) I cannot control CategoryBitMask for each element of the [physicsBodiesArray]... Because main PhysicsBody is applied to the Player it overrides all other Categories and such.

Here is my "createPlayer" function:

//Creating the player

    player = SKSpriteNode(imageNamed: "Bottle_02")
    player.size = CGSize(width: 130, height: 200)
    player.position = CGPoint(x: 0, y: 0 + player.frame.height / 2)

//Creating 2 collision objects and placing them

    var playerColTop = SKSpriteNode()
    var playerColBottom = SKSpriteNode()

    playerColTop = SKSpriteNode(imageNamed: "test_top")
    playerColBottom = SKSpriteNode(imageNamed: "test_bottom")

    playerColTop.position = CGPoint(x: 0.5, y: 0)
    playerColBottom.position = CGPoint(x: 0.5, y: 0 - playerColTop.frame.height / 2 - playerColBottom.frame.height / 2)

//Creating PhysicsBodies for the Array and assigning CategoryBitMasks

    let playerColTopPhys = SKPhysicsBody(texture: playerColTop.texture!, size: playerColTop.size)
    let playerColBottomPhys = SKPhysicsBody(texture: playerColBottom.texture!, size: playerColBottom.size)

    playerColTopPhys.categoryBitMask = PhysicsParams.Player
    playerColTopPhys.collisionBitMask = PhysicsParams.Ground | PhysicsParams.Walls
    playerColTopPhys.contactTestBitMask = PhysicsParams.Ground | PhysicsParams.Walls

    playerColBottomPhys.categoryBitMask = PhysicsParams.PlayerScore
    playerColBottomPhys.collisionBitMask = PhysicsParams.Ground | PhysicsParams.Walls
    playerColBottomPhys.contactTestBitMask = PhysicsParams.Ground | PhysicsParams.Walls

//Adding my PhysicsBodies and setting up the Player

    player.physicsBody = SKPhysicsBody.init(bodies: [playerColTopPhys, playerColBottomPhys])
    player.physicsBody?.categoryBitMask = PhysicsParams.Player
    player.physicsBody?.collisionBitMask = PhysicsParams.Ground | PhysicsParams.Walls
    player.physicsBody?.contactTestBitMask = PhysicsParams.Ground | PhysicsParams.Walls
    player.physicsBody?.restitution = 0
    player.physicsBody?.friction = 1
    player.physicsBody?.mass = 5
    player.physicsBody?.affectedByGravity = false
    player.physicsBody?.isDynamic = false

    self.addChild(player)

Thanks in advance!


texts:
I have an array of gameobjects (some questions) if player hit some triggers a question from the array is displayed randomly, I want to avoid duplication of displaying questions.

 public GameObject[] Q;
 public static int ColliderCounter = 0;
 int WrongAnswerCounter = 0;
 public int i,old;

 private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Obstcle")
        {
            i = Random.Range(0, Q.Length);
            old = i;
            ColliderCounter++;
            Q[i].SetActive(true);
            GetComponent<PlayerMovement>().enabled = false;
        }

    }

 IEnumerator waitWrongAnswer()
    {
            WrongAnswerCounter++;

            yield return new WaitForSeconds(3f);
            Q[old].SetActive(false);
            i++;
            Q[i].SetActive(true);
            old = i;
    }

And I want to know how to check if all questions are displayed do something.

Thanks in advance


texts: Animate/Interpolate and wait for completion.

texts:
I'm implementing a blackjack game in flash and so far the logic is fine but there is no animation for the cards so they just appear and disappear which doesn't look very pleasing to the eye. I want to add some animations for when cards are dealt where they slide across to their position one by one.

Is there a simple way to just tell a displayobject to interpolate from one position to another while waiting for it to complete?

My current thought would be to just do something like this:

on enter frame:
   if a card is animating:
      move it further towards its destination;
      continue;
   else (if it is done animating):
      process as usual;
   end;
end;

I believe this would produce the results I'd expect because the game should only continue after the card being dealt is where it should be. However, this feels like a weird approach and I'm probably over thinking it which is why I'd like to know if any of you have a better solution.


texts: What are the techniques used to save space with very large levels?

texts:
Some days ago I was thinking "how would I store the real world into a continuous game level ?".

I guess it must have been some challenge for RockStar engineers (for GTA 4 or Red Dead Redemption) or when developing RAGE (the ID game, not the rockstar engine), and I wonder how they solved it.

Of course current RAM and hard disk capacities don't allow it if you don't use high definition content, so you simplify by abusing the reuse of objects:

Use doodads for trees, barriers, bushes, benches, trashbins, etc
Use palettes instead of textures for the ground and walls and buildings
Use heightmaps for altitude
Use procedural method for modeling roads, houses, buildings, sidewalk, pavement
Also use procedural methods to model the insides of buildings: walls, ceiling, stairs, doodads.

These are the only things which make sense to me, but I want to know if they are other methods I'm missing, like for example reducing vertex precision while storing models, but requiring to make an exporter.


texts: How does Unity's Entity-Component System Work In Practice?

texts:
On the surface Entity-Component seems like a good way to program games. Everything is a game object and those game objects are made up of components. The attraction is components are very flexible, just requiring you to "add" them to a game object to inherit it's functionality.

So, obviously a good example might be a platform the character has to jump on. Maybe this thing has a collider, a moving component, maybe a rotating component, or maybe even a rigid "RotatingAndMovingPlatformComponent". Okay, that sounds great, just add all these components to the game object and that's it, you have this extra functionality. However, I find that this level of complexity is where it's usefulness ends.

Try this with menus, complex character movement with multiple states, abstract ideas like game modes or game state, and your flexibility and modularity are destroyed. Menus involve a lot of specifics, complex character movement often involves many states meaning either communication between these components is needed or there must be a controlling component made just for this type of character. On top of this, some components will need to rely on game state in some way.

I see very little benefit to programming this way over ordinary inheritance. The lack of object structures at compile time makes doing a lot of things very difficult and unreliable.

I feel the best and easiest way of going about things would be using larger components with more dependencies. I don't see this as a problem ( more like unreal 4's architecture ), but then I wonder what's the point in the Entity-Component architecture.


texts: Unity3d Run In Background setting not working in fullscreen standalone

texts:
I've ran in to an odd issue with my Unity3D game completely pausing in certain scenarios, even with the Run In Background player setting on.

For reference I'm on Windows 7 Ultimate using Unity 4.3.3

In The Editor:
If I tab out of the editor while the game is running everything keeps working fine.

*In Windowed Mode:*
If I'm running the standalone in windowed mode and tab out, everything keeps working fine.

However, if I grab the top bar on the window to move the window around, the game pauses until I release the window. Nothing updates, nothing runs while it's paused.

In Fullscreen Mode:
If I'm running the standalone in fullscreen mode and alt+tab out the game pauses. Not resuming until I tab back in to the game.

This is causing issues with the multiplayer aspects of my game, because the client stops sending messages to the server whenever they alt+tab out or move the window.

I know the graphics device is getting lost when I tab out, because I get this error in my log:

  HandleD3DDeviceLost
    HandleD3DDeviceLost: still lost
  Skipped rendering frame because GfxDevice is in invalid state (device lost)

But that should only cause the game to stop rendering, which is fine. I just need the update loop to continue.


texts: swift fast enumeration on MDLAsset not working

texts:
I load an MDLAsset from my main bundle and get an compile error when fast iterating the asset object.

Type 'MDLAsset' does not conform to protocol 'SequenceType'

Documentation says it does support fast enumeration:

https://developer.apple.com/library/prerelease/ios/documentation/ModelIO/Reference/MDLAsset_Class/

Iterating over the asset is rather simple

for obj in asset {
    ...
}

I am using XCode7.1.1 and Swift2, is there something broken or what is it I am doing wrong?


texts: How to properly calculate y position when drawing from .fnt bitmap font?

texts:
I want to render text to bitmap to use it later as a decal texture. I've read through libGDX fonts drawing code and came up with this:

private void writeTextToPixmap(Pixmap destPixmap, Pixmap fontPixmap, BitmapFont.BitmapFontData fontData, int startX, int startY, String text) {
    int cursor = startX;

    char[] chars = text.toCharArray();
    for(int i = 0; i < chars.length; i++) {
        BitmapFont.Glyph glyph = fontData.getGlyph(chars[i]);
        destPixmap.drawPixmap(fontPixmap, glyph.srcX, glyph.srcY, glyph.width, glyph.height, cursor + glyph.xoffset, startY + glyph.yoffset, glyph.width, glyph.height);
        cursor += glyph.xadvance;
    }
}

The font was generated with Hiero using default settings.

But the result does not look as expected:
http://i.imgur.com/T7Isg2R.png

Usage:

    Pixmap pixmap = new Pixmap(1024, 1024, Pixmap.Format.RGBA8888);
    BitmapFont.BitmapFontData fontData = new BitmapFont.BitmapFontData(Gdx.files.internal("data/couriernew.fnt"), false);
    Pixmap fontPixmap = new Pixmap(Gdx.files.internal("data/couriernew.png"));
    writeTextToPixmap(pixmap, fontPixmap, fontData, 300, 400, "ga");


texts: How to make sure Sun Shafts are emitted only from background elements?

texts:
Currently I have a game scene entirely made of standard sprites using the default material.

I use the Unity standard effect named Sun Shafts.

I have tried many combinations of shaders and other settings. I get the sun shafts to shine properly from the whiter areas in the far background which is fine.

But I noticed they also are emitted from white areas on the characters and foreground which completely defeats the purpose of the sun shafts.

Is there a way to get the sun shafts to be emitted only from elements which are far away of from objects defined in advance?


texts: Exporting distinct images from a sprite sheet using GIMP

texts:
I have recently found that in Photoshop there is a script that enables you to export individual images on different layers into distinct png images on disk.

Is it GIMP capable of doing the same thing and how?

I have a sprite sheet (png image) and there are 36 perfectly aligned images in 4 rows (64x64 pixels each). I have to cut and export 36 times.

Can be GIMP of some help here? I don't have Photoshop.


texts:
I have to find components of a matrix for 3D transformation. I have a first system in which transformations are made by multiplying:
M1 = Scale x Rotation x Translation.
I want to have the same transformations in an engine who compute like this:
M2 = Scale x Translation x Rotation
So when I enter the same values there's a problem du to the inversion of translation and rotation.

How can I compute the values in the last matrix M2 for having the same transformation?

Thanks


texts: How do I make camera move at same speed when rotating and moving forward

texts:
I made a camera in DX9. To move forward I press the Up arrow. To rotate on the Y axis I use the mouse. When I perform these movements on their own the camera moves at the speed I want.

However, if I hold down Up and move the mouse at the same time then the camera moves a lot faster than it should. I want it to move at the same speed as it does when only the Up arrow is pressed.

I think I need to normalize something somewhere but not sure what and not sure where. Have tried various combinations without success so if anyone can point me in the right direction that would be great. Thanks.

I've post code below.

#define KEY_DOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0)

LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
    if( KEY_DOWN(VK_UP))    MovePlayer(D3DXVECTOR3(0, 0, -1.0f));
    if( KEY_DOWN(VK_DOWN))  MovePlayer(D3DXVECTOR3(0, 0, 1.0f));

    switch( msg )
    {
        case WM_MOUSEMOVE:
        ProcessMouseInput();
    }
}

void  MovePlayer( D3DXVECTOR3 in_vec )
{
    D3DXMATRIX CameraRot;
    D3DXMatrixRotationY(&CameraRot,D3DXToRadian(AngleY));
    D3DXVECTOR3 CameraRotTarget;
    D3DXVec3TransformNormal(&CameraRotTarget,&in_vec,&CameraRot);
    CameraPos +=  (m_timeElapsed * CameraRotTarget);
}

void ProcessMouseInput()
{
    GetCursorPos( &CurrentMouseState );

    if ((CurrentMouseState.x != GameMouseState.x) || (CurrentMouseState.y != GameMouseState.y))
    {
        int dx = CurrentMouseState.x - GameMouseState.x;
        int dy = CurrentMouseState.y - GameMouseState.y;
        AngleY+=m_timeElapsed*dx*7.0f;
    }
    GameMouseState = CurrentMouseState;
    // Set back to window center in Render function
}

VOID UpdateCamera()
{
    D3DXVECTOR3 CameraOrigTarget(0, 0, -1);
    D3DXVECTOR3 CameraOrigUp(0, 1, 0);

    D3DXMATRIX CameraRot;
    D3DXMATRIX CameraRotX;
    D3DXMatrixRotationX(&CameraRotX,D3DXToRadian(AngleX));
    D3DXMATRIX CameraRotY;
    D3DXMatrixRotationY(&CameraRotY,D3DXToRadian(AngleY));
    CameraRot = CameraRotX * CameraRotY;
    D3DXVECTOR3 CameraRotTarget;
    D3DXVec3TransformNormal(&CameraRotTarget,&CameraOrigTarget,&CameraRot);

    D3DXVECTOR3 CameraTarget;
    CameraTarget = CameraPos + CameraRotTarget;

    D3DXVECTOR3 vUpVec( 0.0f, 1.0f, 0.0f );
    D3DXMatrixLookAtLH( &matView, &CameraPos, &CameraTarget, &vUpVec );
    g_pd3dDevice->SetTransform( D3DTS_VIEW, &matView );

    D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI / 4, 1.0f, 1.0f, 100.0f );
    g_pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );
}


texts:
I'm a game developer enthusiast. I've decided to implement a game, however I'm pretty confused about all the movement mechanics (kinematics). Here goes a couple questions:
Velocity x acceleration x speed:

How do you apply acceleration/deceleration to your movement?
When moving (player input), do we either increase the velocity vector or the acceleration/speed value, or actually both? How does it really work?
How do you apply object weight to the movement?
How do you apply friction & gravity to the movement (should be applied to both axis, as this is going to be a 2D top-down view)?

Questions might be quite simple and/or stupid, but I'm just beginning (and also re-studying physics).


texts: Understanding log/exp formula for RPG experience

texts:
While looking for examples of RPG experience formulas I came across this one
How to create adjustable formula for RPG level up requirements?, and I would really like to figure it out because I don't seem to get the same results. I'm trying to understand the maths behind it because actually we are using UDK and Unreal scripts for our project.

Thank you in advance for your time.


texts:
I have the following OnMouseDown() function:

private void OnMouseDown()
{
    Debug.Log("This turret is: " + thisTurret.ToString());
    if (EventSystem.current.IsPointerOverGameObject())
    {
        return;
    }

    if (thisTurret != null)
    {
        buildManager.SelectTurret(thisTurret);
    }

which send to the following functions:

public void SelectTurret(GameObject turret)
{
    if(selectedTurret == turret)
    {
        Debug.Log("Selected turret is: " + selectedTurret.ToString());
        DeselectTurret(selectedTurret);
        return;
    }

    selectedTurret = turret;
    Debug.Log("Selected turret here is: " + selectedTurret.ToString());
    Debug.Log("Pasted turret here is: " + turret.ToString());
    if (oldSelectedTurret == null)
    {
        oldSelectedTurret = selectedTurret;
    }

    //Debug.Log("Selected turret is: " + selectedTurret.ToString());

    if (oldSelectedTurret != selectedTurret)
    {
        turretUI.Hide(oldSelectedTurret);

        //Debug.Log("Old in if Selected turret is: " + oldSelectedTurret.ToString());

        oldSelectedTurret = selectedTurret;
    }
    //Debug.Log("Current Selected turret is: " + selectedTurret.ToString());

    turretToBuild = null;

    turretUI.SetTarget(selectedTurret);
}

public void DeselectTurret(GameObject turret)
{
    if(turret != null)
    {
        Debug.Log("Turret to deselect is: " + turret.ToString());
        turretUI.Hide(turret);
        selectedTurret = null;
    }
    else
    {
        Debug.Log("Turret to deselect is null!");
    }
}

it should deselect the turret if clicked twice but instead it select the turret on first click and don't execute on second click


texts: component Initialization in component-based game architectures

texts:
I'm develping a 2d game (in XNA) and i've gone slightly towards a component-based approach, where i have a main game object (container) that holds different components.

When implementing the needed functionality as components, i'm now faced with an issue -- who should initialize components?

Are components usually passed in initialized into an entity, or some other entity initialized them?

In my current design, i have an issue where the component, when created, requires knowledge regarding an attached entity, however these 2 events may not happen at the same time (component construction, attaching to a game entity).

I am looking for a standard approach or examples of implementations that work, that overcome this issue or present a clear way to resolve it


texts:
In libgdx, the game loop is the render() method. But why is that, and is there a way where I can make an update() method that is called 60 times a second? As in the update() method, I would add the game logic, and leave the rendering to the render method.
Basically, separate methods, and the update() method called 60 times per second using Libgdx with java.


texts: How do I support variable screen ratios using AndEngine?

texts: When displaying a background, AndEngine produces black bars above the image on certain devices.  How do I support variable screen ratios for different devices using AndEngine?


texts:
I've been trying to understand cellbased maps and how they work, i have googled alot but can't seem to find any explanation for it.

With cell based maps i mean the ones where you do height and everything like walls roof floor in each cell.
If possible i would appreciate an explanation from a Javascript perspective, but only a theoretical explanation can do.

So why do we use them? how do they work?
Is it just like a normal array with more information?


texts: Rending 2D Tile World (With Player In The Middle)

texts:
What I have at the moment is a series of data structures I'm using, and I would like to render the world onto the screen (just the visible parts).

I've actually already done this several times (lots of rewrites), but it's a bit buggy (rounding seems to make the screen jump ever so slightly every x tiles the player walks past).

Basically I've been confusing myself heavily on what I feel should be a pretty simple problem... so here I am asking for some help!

OK!
So I have a 50x50 array holding the tiles of the world.
I have the player position as 2 floats, x ([0, 49]) and y ([0, 49]) in that array.
I have the application size exactly in pixels (x and y).
I have an arbitrary TILE_SIZE static int (based on screen pixels).

What I think is heavily confusing me is using a 2d orthogonal projection in opengl which maps (0,0) to the top left of the screen and (SCREEN_SIZE_X, SCREEN_SIZE_Y) to the bottom right of the screen.

    gl.glMatrixMode(GL.GL_PROJECTION);
    gl.glLoadIdentity();

    glu.gluOrtho2D(0, getActualWidth(), getActualHeight(), 0);

    gl.glMatrixMode(GL.GL_MODELVIEW);
    gl.glLoadIdentity();

The map tiles are set so that the (0,0) in the array is the bottom left.

And the player has to be in the middle on the screen (SCREEN_SIZE_X/2, SCREEN_SIZE_Y/2).

What I've been doing so far is trying to render 1-2 tiles more all around what would be displayed on the screen so that I don't have to worry about figuring out rendering half a tile from the top left, depending where the player is.

It seems like such an easy problem but after spending about 40+hours on it rewriting it many times I think I'm at a point where I just can't think clearly anymore...

Any help would be appreciated. It would be great if someone can provide some very basic pseudo code on keeping the player in the middle when your projection is mapped to screen coordinates and only rendering basically the tiles that you would be any be see.

Thanks!


texts: How to smooth the model/texture look from a distance?

texts:
(First of all, I really didn't know how to title my question so it tells exactly what I mean so if anyone has a better title feel free to edit my question or leave a comment.)

Look at the water in the screen:

See all the annoying white pixels? That's the specular. It looks nice up close:

But when I move the camera away from water it starts to look bad. Actually, the same problem occurs elsewhere (e.g. with grass or rocks) but it's not as bad as with the specular.

I think I know why it looks the way it does but I don't know how to make it look better, more smooth, something like this:

Well, blur helps but blur is an expensive post-process and it's not the way I want to do it.

How can I make it look better, less pixelated and more natural?

Edit: I mentioned that I have the problem with e.g. grass. The grass' shader only uses a texture. The water's shader, however, uses normal mapping and based on the mapped normal it calculates light's specular component.

Update: Following Tording's advice I've used NVIDIA DDS plugin to generate mipmapped normal map DDS file and I've used that instead in my project. Although I'm not sure if I prefer the result to the previous one:

I realize that my normalmap texture and/or my water shading technique might be to blame, though. :P But my point is - using mipmapping might solve my problem (a lot of sharp pixels/noise) but it also introduces new problems.


texts: How to measure the refresh rate of a display in OpenGL ES?

texts:
I am working on OpenGL ES application which is rendering 60 frames per second which is equal to my Monitor refresh rate.

My problem is: if I make Swapinterval 0, I am getting a FPS value above 200. I am able to reduce it to 60, but I have taken this value statically (from the command line, or hard coded).

How to calculate the refresh rate of the monitor programmatically so that I can control FPS?


texts: Do mods for games like Skyrim look good on a resume?

texts:
As a lot of people know, Bethesda just came out with their Creation Kit for developing mods to Skyrim.

I've been developing for a while, I have a couple of games released including one that's doing well in the App Store. My goal is to get a job at a studio like Bethesda, Bioware, or Valve. Right now my work shows I can do some of the harder parts of a game engine, but I have nothing directly in the RPG field which is where I want to be.

Would building a mod for Skyrim help my resume enough to justify the time it takes to do it, or would my time be better spent making another non-RPG game from scratch? This mod would be a full side game completely separate from the game's world. My usual thought of mods is they are for fun and don't really help the resume as much as more raw projects, but with how open the creation kit is, it seems you can really go a long way in development.

Before I get any duh or subject to opinion answers, this question is about my lack of knowledge on the perception of notable mods to games. My assumption is there is a general consensus to if mods can be impressive and help a resume which already has some (decent) content for the level of job it's after. Also, I have no intention of starting an RPG from scratch if anyone is crazy enough to offer that as a solution, this is for my resume only.

Lets assume the mod I would make would be impressive for a mod. If that was up for debate, the answer to this might come out a bit gray.


texts: Allocating Entities within an Entity System

texts:
I'm quite unsure how I should allocate/resemble my entities within my entity system. I have various options, but most of them seem to have cons associated with them. In all cases entities are resembled by an ID (integer), and possibly has a wrapper class associated with it. This wrapper class has methods to add/remove components to/from the entity.

Before I mention the options, here is the basic structure of my entity system:

Entity

An object that describes an object within the game

Component

Used to store data for the entity

System

Contains entities with specific components
Used to update entities with specific components

World

Contains entities and systems for the entity system
Can create/destroy entites and have systems added/removed from/to it

Here are my options, that I have thought of:

Option 1:

Do not store the Entity wrapper classes, and just store the next ID/deleted IDs. In other words, entities will be returned by value, like so:

Entity entity = world.createEntity();

This is much like entityx, except I see some flaws in this design.

Cons

There can be duplicate entity wrapper classes (as the copy-ctor has to be implemented, and systems need to contain entities)
If an Entity is destroyed, the duplicate entity wrapper classes will not have an updated value

Option 2:

Store the entity wrapper classes within an object pool. i.e. Entities will be return by pointer/reference, like so:

Entity& e = world.createEntity();

Cons

If there is duplicate entities, then when an entity is destroyed, the same entity object may be re-used to allocate another entity.

Option 3:

Use raw IDs, and forget about the wrapper entity classes. The downfall to this, I think, is the syntax that will be required for it. I'm thinking about doing thisas it seems the most simple & easy to implement it. I'm quite unsure about it, because of the syntax.

i.e. To add a component with this design, it would look like:

Entity e = world.createEntity();
world.addComponent<Position>(e, 0, 3);

As apposed to this:

Entity e = world.createEntity();
e.addComponent<Position>(0, 3);

Cons

Syntax
Duplicate IDs


texts: Does passing uniform constants from technique into shader cause branches?

texts:
I am trying to find a way to organize my evergrowing number of shader techniques/functions (I am coding in sm_3.0). One way is to do this:

float4 PS_Crossroads(PS_INPUT input, uniform bool left_right) : COLOR0
{
    if (left_right)
        GoLeft();
    else
        GoRight();
    ...
}

technique LEFT
{
    pass Pass1
    {
        VertexShader = compile vs_3_0 VertSh();
        PixelShader = compile ps_3_0 PS_Crossroads(true);
    }
}

technique RIGHT
{
    pass Pass1
    {
        VertexShader = compile vs_3_0 VertSh();
        PixelShader = compile ps_3_0 PS_Crossroads(false);
    }
}

My question is will this cause a branch at runtime or will the compiler be smart enough to split it into two separate techniques?

Thanks.

P.S. Ok I won't post this as answer, because we already have an answer by someone much more experienced than me, but from my humble tests (on different PCs) and my humble Google research, this approach (using uniform constants) is efficient and indeed forces the compiler to create different shader versions for each branch, removing flow controll completely from the finall compiled shader. I tested the compiled shader codes with Nvidia NSight.


texts: On the faq for the current preview release, http://unity3d.com/unity/preview/faq it says that while networking is not currently supported for flash compilation, we can write our own in AS3 using the Flash API. I can't seem to find the docs for this API or figure out the right way to work in both AS3 and Unity. Can anyone point me in the right direction?


texts:
Creating resolution independent sprites is tough and memory consuming.

How can .svg assets be used in unity for any kind of 2d game?

What are alternatives to .svg that can be used in unity?

Can sprites with various shapes be generated within unity?

Would like creating universal art asset that'll support all devices with different resolutions.(we'll handle the aspect ratio )


texts:
I'm trying to create a particle system in OpenGL, and as such I need to use billboards.

I need these billboards to face the camera at all times.

The tutorials I've been following only rotated the billboard on 1 axis, such as billboards being used as grass or plants, but I need a method of rotating the quad to always face the camera, even when looking down on it.

The Original Scene:

Desired Scene:

While searching for an answer, I only really found the technique of turning the mat3 component of the camera's view/model matrix back to an identity matrix. This isn't quite what I need, as the point's location in space never change then.

Incorrect Scene:

How can I calculate a new rotation matrix that will successfully rotate a quad always towards the camera, or modify an existing matrix?

In the geometry shader I have access to the camera's position, the perspective matrix, and the view/model matrix.

I didn't include any shader code because it is really trivial; I create vertices that are an offset of the desired point's position based on the desired size. So if the quad should be 50 x 50, the vertex is the position offset by 25 on X and Y, multiplied by the Camera's Perspective x View matrix.

Solution:

mat4 VP = pMatrix * vMatrix;
vec3 CameraRight = vec3(vMatrix[0][0], vMatrix[1][0], vMatrix[2][0]);
vec3 CameraUp = vec3(vMatrix[0][1], vMatrix[1][1], vMatrix[2][1]);

vec3 Pos = gl_in[0].gl_Position.xyz;  // The desired point for the billboard

vec4 v1 = VP * vec4(Pos + CameraRight * 0.5 * Size + CameraUp * -0.5 * Size, 1.0);
vec4 v2 = VP * vec4(Pos + CameraRight * 0.5 * Size + CameraUp * 0.5 * Size, 1.0);
vec4 v3 = VP * vec4(Pos + CameraRight * -0.5 * Size + CameraUp * -0.5 * Size, 1.0);
vec4 v4 = VP * vec4(Pos + CameraRight * -0.5 * Size + CameraUp * 0.5 * Size, 1.0);


texts:
Im working on a simple game for windows phone.
There is one item in the game where the player can click on a enemy and shoot him. Well there is a 1:2 chance for the user to shoot the enemy and when he fails I want to tell this to the user. A Popup would stop the gameflow so I don't really want that.
What are other possible ways to do that ?
It doesn't need to be a lot of text just "Miss !" or "You missed !".


texts: How can I rotate the camera for a player walking around the surface of a sphere?

texts:
I'm making a 3D game where the player can walk across the surface of a planet.

I am having a problem correctly rotating the camera's frame of reference, so that the camera is oriented correctly anywhere on the planet.

My strategy so far has been to create a quaternion that represents the rotation from an "up" vector (i.e. north pole) to the current position vector of the camera:

var up = new THREE.Vector3(0, 1, 0);
camera.quaternion.setFromUnitVectors(up, camera.position.clone().normalize());

To get the final rotation of the camera, I apply the rotation of where the player is looking:

camera.quaternion.multiply(sensor.getState().orientation);

This means that wherever the player is, if they look down they will look towards the center of the planet.

I then apply that rotation to the up vector to get the direction the player is looking:

var direction = up.clone().applyQuaternion(camera.quaternion);

Assuming the player is looking directly forward, if the player travels in that direction, I would expect them to walk around the planet in a straight line.

This works correctly near the north pole, however as I approach the south pole, the camera seems to rotate laterally (from the perspective of the player), finally as I reach the south pole the camera rapidly rotates 360 degrees around the pole.

What is causing this and how can I avoid it?


texts:
I'm trying to make a script where once a player triggers a collision they are teleported to another position that is determined by a empty game object. I think it has to do something with the transform function but I haven't been able to figure it out.

There isn't a good example of this type of behavior in c#. Most examples are written in java and that confuses me even more lol.

Here's what I got so far that works

using UnityEngine;
using System.Collections;

public class  colision: MonoBehaviour {
    public Object WarpExit;
    void OnTriggerEnter(Collider other)
    {Debug.Log("ENTERED WARP ZONE");}

    void OnTriggerStay(Collider other)
    {
        Debug.Log("IN WARP ZONE");
        //Warp player

    }
    void OnTriggerExit(Collider other)
    {Debug.Log("EXITED WARP ZONE");}
}


texts: How to solve Sweep and prune false positives concerning large floor plane

texts:
I am developing a 3d sweep and prune module for a project, and it is producing false positives.

The pair generation code is as follows:

    for (unsigned int i = 0; i < mXExtents.size(); i +=2)
    {
        if (mXExtents[i]->mOwner->getID() != mXExtents[i + 1]->mOwner->getID())
        {
                tempXPairs.push_back(new Pair(mXExtents[i]->mOwner, mXExtents[i + 1]->mOwner));
        }
    }
    for (unsigned int i = 0; i < mYExtents.size(); i +=2)
    {
        if (mYExtents[i]->mOwner->getID() != mYExtents[i + 1]->mOwner->getID())
        {
                tempYPairs.push_back(new Pair(mYExtents[i]->mOwner, mYExtents[i + 1]->mOwner));
        }
    }
    for (unsigned int i = 0; i < mZExtents.size(); i +=2)
    {
        if (mZExtents[i]->mOwner->getID() != mZExtents[i + 1]->mOwner->getID())
        {
                tempZPairs.push_back(new Pair(mZExtents[i]->mOwner, mZExtents[i + 1]->mOwner));
        }
    }

Where each object has a unique ID in the world. This works fine with small objects, but I have encountered a problem, where, If the ground is represented by a finite (albiet large) axis aligned plane, false positives and negatives are generated, preventing the Narrow-phase from doing it's job.

As you can see, each axis list is traversed in sets of 2 elements, and the unique ID's are compared. If they do not match, then a pair is generated for that axis.

Without the ground plane, The order of each list would be Amin, Amax, Bmin, Bmax etc. which would not generated false positives. However, with the addition of the ground plane, the order becomes  Pmin, Amin, Amax, Bmin, BMax, PMax.

Even if A and B are far away from one another on the axis in question, the pair is still generated. Additionally, If there is a genuine overlap on that axis, eg. Pmin, Amin, Bmin, Bmax, Amax, Pmax, then genuine intersections are missed.

Also, I've just encountered another problem: Even when traversing the lists one element at a time, In the case of objects stacked on an axis, collisions can be missed. The following image illustrates this:

If anyone else has encountered this problem, I'd like to hear how they solved it.


texts:
How do I simulate water droplets realistically falling, gathering, and flowing down a window? For example, see http://www.youtube.com/watch?v=4jaGyv0KRPw. In particular, I want to simulate how smaller droplets merge together to form larger droplets that have enough weight to oppose the surface tension and flow downward, leaving a trail of water.

I'm aware of fluid simulation, but how would it be applied in this situation?


texts: 2D Collision detection: rewinding to moment of first intersection

texts:
I am working on a collision system in a Platformer tile-based game. All tiles are AABB.

I am trying to implement "Rewind to Moment of First Intersection" mentioned in this post's second point.

The following case is to be considered:

Without vectors for clarity:

With vectors:

I am trying to find the vector \$\vec{w}\$, which is the vector \$\color{red}{\vec{v}}\$ multiplied by a factor \$f \in (0, 1) \$. All other vectors are known.

\$\color{red}{\vec{v}}\$ represents the reversed movement (or velocity) vector between current and previous frame, whereas \$\vec{w}\$ represents \$\color{red}{\vec{v}}\$ scaled in such a way, that translating the player object over \$\vec w\$ leaves the player in the moment of first intersection.

\$\color{green}{\vec{a}, \vec{b}}, \color{blue}{\vec{c}, \vec{d}}\$ represent the penetration depths of colliding objects on corresponding horizontal/vertical axises.

Tiles' width and height is also known.

Assuming that tiles are AABB, strictly-aligned, immovable and all share the same width/height - how do I find the vector \$\vec{w}\$?

Seeing pseudocode would be awesome.

I am also having surprisingly hard time finding any collision solving learning materials that would suit my needs; if anyone knows such materials, I would be thankful for sharing.


texts: Passing multiple colors to a pixel shader in DirectX

texts:
I have a pixel shader that sets the output color based on the interaction of an input texture, sort of like:

if (case1)
{
    output.Color = float4(0, 0, 0, 0);
}
else if (case2)
{
    output.Color = float4(0.5f, 0, 0, 1);
}
...

There can be up to four cases, meaning that the output color will be one of four different input colors, but 90% of the time only one or two colors will be used.

An additional detail that may be important is that the shader has a constant buffer with a few values that can change up to per-frame. These values, and the colors, are selected out of a dictionary that is roughly like:

StyleID: 1
Color1: 0, 0, 0, 0
Color2: 0.5, 0, 0, 1
...two other colors...
Width: 0.8
...other properties...

There are around a thousand different styles to select from. My question is: what's the best way of passing these values to the shader, and why? There are two designs that occur to me offhand.

On the CPU side, the current style is looked up in the dictionary. It assigns the various properties to members of the cbuffer, including however many colors associated with that style (1 to 4). The shader uses these values.
During initialization, the the entire style dictionary is built in to a separate, large constant buffer, something like:

.

cbuffer Styles
{
    float4 Color1[n];
    float4 Color2[n];
    float1 Width[n];
}

Where n is the number of different styles. Then the CPU just pushes the style ID to a different buffer variable (or perhaps to the unused color semantic), and the shader resolves the colors and properties to used based on this.

I'm using shader model 4.0 level 9_3.


texts: Algorithm to make an entity follow tile edges in a tilemap

texts:
I'm implementing something like the electric balls seen in this video https://www.youtube.com/watch?v=MWyB56AlAWw (skip to 1:55 and you will see this electrical balls follow tile edges in the tilemap).

I have an algorithm working but I feel like it is a bit of a mess. I could summarize it as:

1) Setup

The ball starts always falling
I have an enum holding what side the ball is engaged to (side of tile it is traveling. It could be Top,Bottom,Left, Right and None). This var is inited to "None" at start.

2) While the ball is falling, as soon as it touches a tile we set the engaged var to bottom (the ball is engaged to a tile that is at the bottom) and we make it move to the left.

3) Now we have 2 cases

the ball collides with another tile while moving to the left. In this case we set the engaged var to Left and start moving it upwards.
the ball gets into a situation where there's no tile at the bottom to continue going to the left. In this situation we use the engaged var to know what edge of the tile we were moving along. In this particular case as we where engaged to a bottom tile we fix the ball position to be right at the left of the last valid tile and start moving it down.

This applied to all possibilities makes the ball run across all the tilemap.

I would like to know if there's a more clean way to do this without all this "mini cases" or a better way to accomplish this.

Cheers


texts: How to make the capsule collider that comes with character controller follow the animations

texts: I'm making a 3D endless running game like subway surf. When I swipe/press down arrow the slide animation starts but the capsule collider isn't following along as it doesn't slides along with the character. Searched a lot on this on the forums, one possible answer is to attach the collider with some bone. I tried doing so, but couldn't make it. As I'm fairly new to Unity please provide some insights to how to overcome this situation. Here are the screen shots of the collider not following the sliding animation


texts: How can I assist players navigating narrow grid junctions?

texts:
I'm looking for a technique to help the player navigate a narrow path while the character is in constant motion. When changing direction in junctions, it's pretty hard to time the direction change for a successful turn. With bad timing, the character just gets stuck as pictured.

How can I make this easier for the player? (This is for a university assignment.)


texts: Fbx animation without bones or single skeleton

texts:
SkinnedModel sample nicely shows how to import single root bone skeleton and run in XNA.

My question are:

Is it possible to have animations played in XNA if there no bones are used in model (which can easily be done in 3dmax with auto key frames)?
Is it possible to have multiple independent bones laying around, connected to independent meshes and animated, all played in XNA?
Can SkinnedModelProcessor be downgraded to this level ?


texts:
I've finally managed to write a working Lua version of Perlin's improved noise for Love 2D. However, when I run it, i get this:

Which is just fine, I guess. But I would like something that looks more like this:

How can I achieve this?


texts: How many datapoints are there generally in terrain height maps?

texts:
I've created my own heightmap with data from USGS. The heightmap is pretty large, but the point density is low, resulting in a low-poly terrain.

While performance is excellent, the physics engine I'm using doesn't particularly like how much distance is between each point, resulting in clipping.

Regardless, what is the point density like for games like H1Z1 or any other game that uses a height map on a large world?


texts: Lower WebCamTexture dimension without requesting

texts:
Handling image with high resolution / dimension can cause heavy lag in low spec computer . So i need to lower the dimension of the image to make it less lag for processing . I know i can do it with WebCamTexture.request(width/height) , but if the camera does not support low dimension image , the result image dimension will be still big .
I've tried to convert it to Texture2D using WebCamTexture.GetPixels() and uses lower width and height for the Texture2D , but it breaks the image and the result was unexpected .
I also have tried to set the WebCamTexture to an object , and get that object captured by in-game camera , and resize the image that was captured by the camera , but then it means the high dimension image is doubled (WebCamTexture and image from the in-game Camera) and doubled the lag than just using WebCamTexture .
Can anyone here help me please ? i will upvote for any attempt to help .


texts: Overlapping Vertex in DynamicVertexBuffer draw priority?

texts:
I am creating a voxel game, and I have recently run into an issue. My world is drawn by a DynamicVertexBuffer, which just consists of vertices for the blocks themselves. On top of that, I switch vertex buffers to my  "Selected" vertex buffer which draws a white outline of a block for now. (This includes alpha but I have it turned off until I figure this glitch out).

This issue I run into is here:

Rather than the selected buffer overwriting my world block, it sort of does depending on the angle. Sometimes I see no overlap, sometimes weird glitches like shown above.

I was wondering, what can I do to prioritize the "Selected" buffer so that it is drawn on top of anything else sharing coordinates? Note that I did have this working, when everything used a basic effect. After switching to my own custom effect.fx (which supports fog and lighting, if that has anything to do with it), I run into this issue.

Any help is appreciated, thank you!

EDIT:

Just got the "flickering" of sorts to stop, I changed the DepthStencilState of the buffer to:

GraphicsDevice.DepthStencilState = DepthStencilState.None;

The only downside here is that it draws all 6 sides of the selected block now and it overlaps the world completely, again I don't know if this would be the right way to do it but any help would be appreciated:

The above picture is flat with the rest of the terrain around it, as you can see it draws the two sides that wouldn't actually be visible as well.


texts:
so I have some walls which are cubes stretched along a direction.and I have some windows and doors that are suppose to snap to a wall and don't let go until the desired location is out of the snapping range.and in the meantime I want the Objects to move along the wall but never detach from it.

if I wasn't clear enough let me know.


texts: Libgdx: different speed on different devices

texts:
I am running a simple Libgdx app that I have wrote, on my Android phone and Android tablet and I am getting the unexpected result of having different velocities when a body is moved. To move the body I am using a "drag" movement in this way (snippet):

private Body ballBody;
private int ballX1, ballY1;

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    ballX1 = screenX;
    ballY1 = screenY;
    return true;
}

@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
    Vector2 v2 = new Vector2(ballX1 - screenX, screenY - ballY1);
    v2.scl(0.25f);
    ballBody.setLinearVelocity(v2);
    return true;
}

@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
    return false;
}

Render part with some of my attempts to fix delta-time and FPS:

private static final int SCREEN_HEIGHT = 16; //320;
private static final int SCREEN_WIDTH = 24; //480;
private static final int BOX_VELOCITY_ITERATIONS = 6;
private static final int BOX_POSITION_ITERATIONS = 2;
private static final float BALL_RADIUS = 0.1f;
private static final float MAX_FPS = 1 / 60f;
private static final float PIXELS_TO_METERS = 20f;
private static final long ONE_SECOND_NS = 1000000000;

private int maxUpdates = 10;
private long lastTime = System.nanoTime();
private World world = new World(new Vector2(0, -9.8f), true);

@Override
public void render() {
    ballIsNotMoving = ballIsNotMoving();
    if (ballIsNotMoving && ballBody.getPosition().x > landscape2d[20] && ballBody.getPosition().x < landscape2d[28]) {
        newHole();
    } else if (ballBody.getPosition().x > SCREEN_WIDTH + ball.getWidth() / 2 || ballBody.getPosition().x < - ball.getWidth() / 2) {
        resetBallPosition();
    }

    camera.update();
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    Gdx.gl.glClearColor(34/255f, 167/255f, 240/255f, 0);

    fixTimeStep();

    world.step(MAX_FPS, BOX_VELOCITY_ITERATIONS, BOX_POSITION_ITERATIONS);

    shapeRenderer.setProjectionMatrix(camera.combined);

    // Set the sprite's position from the updated physics body location
    ball.setPosition(
            ballBody.getPosition().x - ball.getWidth() / 2,
            ballBody.getPosition().y - ball.getHeight() / 2);

    polySpriteBatch.setProjectionMatrix(camera.combined);
    polySpriteBatch.begin();
    pitch.draw(polySpriteBatch);
    polySpriteBatch.end();

    createStartArea(shapeRenderer);

    fixFPS();

//        debugRenderer.render(world, camera.combined);
}

private boolean ballIsNotMoving() {
    float speedNow = ballBody.getLinearVelocity().len();
    recentSpeed = 0.1f * speedNow + 0.9f * recentSpeed;
    if (recentSpeed < 0.20f) {
        stopBallMovement();
        return true;
    }
    return false;
}

private void fixTimeStep() {
    long time = System.nanoTime();
    long timeDelta = time - lastTime;
    float timeDeltaSeconds = timeDelta / (float) ONE_SECOND_NS;
    lastTime = time;

    // Update the game state in capped time steps (in case we're running too slow)
    int updateCount = 0;
    while (timeDelta > 0 && (maxUpdates <= 0 || updateCount < maxUpdates)) {
        // Update using a time step in seconds
        float updateTimeStep = Math.min(timeDeltaSeconds, ONE_SECOND_NS * MAX_FPS);
        float updateTimeStepSeconds = updateTimeStep / (float) ONE_SECOND_NS;

        world.step(updateTimeStepSeconds, BOX_VELOCITY_ITERATIONS, BOX_POSITION_ITERATIONS);

        timeDelta -= updateTimeStep;
        updateCount++;
    }
}

private void fixFPS() {
    long sleepTime = Math.round((ONE_SECOND_NS / MAX_FPS) - (System.nanoTime() - lastTime));
    if (sleepTime <= 0)
        return;
    long prevTime = System.nanoTime();
    while (System.nanoTime() - prevTime <= sleepTime) {
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

The app start with the same resolution for both devices. Any idea about how to get the same speed?


texts: Getting Sprites from a SpriteSheet with Rows and Columns

texts:
I am having trouble reading a spritesheet with rows and columns. If it is just one row, then my code works fine. The sheet looks like this:

Source: Character animations, clothes, armor, weapons, skeleton enemy, combat dummy

Right now, it only works with the first row. I can't figure out how to move it down to the next row. I know I have to change my SourceRect for the x and y but don't know to what.

Here's my code:

class SpriteSheet
{
    public Texture2D Texture { get; set; }
    public Vector2 Origin { get; set; }
    public Rectangle SourceRect { get; set; }
    public Vector2 position;

    private float timer, interval;
    private int currentFrame;
    private int spriteWidth, spriteHeight, spriteSpeed;
    private int rows, columns;
    private KeyboardState currentKBState, previousKBState;

    public SpriteSheet(Texture2D texture, int spriteWidth, int spriteHeight, int rows = 1, int columns = 0, int currentFrame = 1)
    {
        Texture = texture;
        this.currentFrame = currentFrame;
        this.spriteWidth = spriteWidth;
        this.spriteHeight = spriteHeight;
        this.rows = rows;
        this.columns = columns;

        spriteSpeed = 100;
        interval = 200;
    }

    // Handle movement of sprite
    public void Update(GameTime gameTime)
    {
        previousKBState = currentKBState;
        currentKBState = Keyboard.GetState();

        // Get the sprite from the sheet
        // THIS LINE NEEDS TO BE CHANGED I THINK
        SourceRect = new Rectangle(currentFrame * spriteWidth, 0, spriteWidth, spriteHeight);

        if(currentKBState.GetPressedKeys().Length == 0)
        {
            if (currentFrame > 0 && currentFrame < 9)
                currentFrame = 0;

            if (currentFrame > 9 && currentFrame < 18)
                currentFrame = 9;

            if (currentFrame > 18 && currentFrame < 27)
                currentFrame = 18;

            if (currentFrame > 27 && currentFrame < 36)
                currentFrame = 27;
        }

        // Animate Up
        if (currentKBState.IsKeyDown(Keys.Up))
        {
            AnimateUp(gameTime);

            // Check boundary
            if (position.Y > 25)
                position.Y -= (float) (spriteSpeed * gameTime.ElapsedGameTime.TotalSeconds);
        }
    }

    private void AnimateUp(GameTime gameTime)
    {
        if (currentKBState != previousKBState)
            currentFrame = 1;

        timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;

        if(timer > interval)
        {
            currentFrame++;
            if (currentFrame > 8)
                currentFrame = 0;

            timer = 0f;
        }
    }
}


texts: What are the advantages of tangent space normals over object space normals?

texts: What are the advantages of normals in tangent space to normals in object space for calculation of bump mapping?


texts: Making the AI take different paths to each other

texts:
I have a top down 2d game where the AI spawn at the edges of the map and run towards the center.

I'm using A* and a node mesh to do the pathfinding.

Right now, the AI spawn at a point on the edge of the map and all take the same path which is the shortest route to the center.

Now I want them to be more surprising and interesting and take different paths to each other.

I can immediately think of two ideas for doing this but wanted to know if there are other ways or better ways that people often use?

When one enemy spawns and generates a path to the center, temporarily increase the cost of all the nodes on that path, then slowly decrease them back down over time. Then the enemy AI that spawn later will be forced to take a wider path.
The above approach will lead to AI just taking a wider and wider path though and still be very predictable. So I thought I'd also introduce a number of intermediate goal nodes around the map. When the AI spawn they randomly pick one of the intermediate goals and head there first before heading to the center of the map. Combining this with the above approach of increasing the costs might look pretty good?

What approaches have people found work best to getting the AI to vary the paths they take, look convincing and surprising?


texts:
I am porting my Unity console game to android. It is roughly 2.5GB.
Assuming that the size cannot be reduced further, is it possible to have Unity generate two .obb files since the limit for each is 2GB? Right now it seems to only produce one 2.5GB .obb, but from my understanding, it is possible to have up to two .obb files.
The files are AssetBundles located in StreamingAssets.
I really didn't want to use Play Asset Delivery, but if I must, then it still has a global limit of 2GB. Therefore I would have to put some of my bundles in StreamingAssets, and some in Asset Bundles, which doesn't sound very ideal.


texts: Unity3d: Find a point on the line which has shortest distance from the third point

texts: So, initially, I had points A and C. To get point B, I had to shoot a raycast down from point A and get the hit.point, which is point B now. Point D is somewhere between the raycast I shot from A and perpendicular to C. How do I find the point D.


texts:
I'm curious about how I should be drawing my game world. I'm going to have a map, let's say 1000 by 1000 tiles in size, with many players on it. Each player will be at a position in a map, and when they move I want their sprite to stay in the centre of the screen (so I want the map itself to move).

Is it efficient to do this by drawing a map 1 square bigger on each edge than the game window itself, then having the extra bits chopped off? Or should I be slicing and dicing sprites?

If you're curious as to what sorta thing I'm looking at, think tibia.com crossed with Pokemon, with graphics somewhere in between, and a turn-based attack / defence system.


texts:
While I was developing my game on Linux (I'm using an ARM system), I decided that I want to cross-compile it to Windows. Yet, I get an error while I try to link Allegro (version 4.2) to the compiler.

I have installed MinGW32 (x86_64-w64-mingw32-c++ in the terminal) and have moved the bin / include / lib folders from the Windows Allegro version to the /usr/x86_64-w64-mingw32-c++/ folder.

When I enter into the command line:

x86_64-w64-mingw32-c++ *.cpp -o W_Survival `allegro-config --libs`

It returned to me a linking error:

/usr/bin/x86_64-w64-mingw32-ld: unrecognized option '-z'
/usr/bin/x86_64-w64-mingw32-ld: use the --help option for usage  information
collect2: ld returned 1 exit status

The compiling is all the same as I would do it using g++. the only thing different is that I have it set to compile for windows.

Is there anything that I did wrong?
All help is appreciated :)


texts: Top-Down mapping with GLEED2D: Collision and Faux 3D

texts:
This is just a theoretical question. I was thinking of using GLEED2D to map a top-down game (I haven't decided on what type, but that shouldn't matter for this question.). I chose GLEED2D because I was getting tired of tile-based maps, and wanted to try something new.

However, two questions come to mind: How would you implement collision, and how would you display faux 3d? (I can't come up with a better name. It's where in RPGs and other topdown games you can have a bottom wall that obscures your character if you walk up to it. Say there's a pillar on the map. On a tiled map, it takes up one tile of space that you can't move on to, but the sprite itself is taller than one tile, so it covers character when you are behind it.)

An idea I had was to use the primitive shapes such as the Path to define areas where the character should collide. But then there's the faux 3d issue, which I can't figure out. Maybe GLEED2D isn't meant for it?


texts: How can I communicate changes to a 2D tile-based world state in a P2P context?

texts:
Suppose two players in a game want to build a city together on a blank tile-based game world simultaneously in a peer-to-peer connected context.

When a player clicks on a tile it changes the state (or tile ID) of that tile, which is saved into a text file for later reading by the renderer.

For example, in the image below a player has modified some tiles from "empty" (1) to "road" (2):

What method should I employ to transmit these changes to connected peer-to-peer clients?


texts: How to determine collision direction between two rectangles?

texts:
I am trying to figure out how to determine the direction a collision occurs between two rectangles.

One rectangle does not move. The other rectangle has a velocity in any direction. When a collision occurs, I want to be able to set the position of the moving rectangle to the point of impact.

I seem to be stuck in determining from what direction the impact occurs.  If I am moving strictly vertically or horizontally I manage great detection.  But when moving in both directions at the same time, strange things happen.

What is the best way to determine what direction a collision occurs between two rectangles?


texts:
I have a ball that you can make jump,

I have a sneaking suspicion I'm doing this wrong. It works now, to the extend that gravity pulls the object down toward the ground, but I'm having trouble manipulating the speed of the object.

What this is, is a ball jumping and falling towards the ground.

I have another function called "jump" that just adds a value to it's yVel

I can increase gravity, and it falls faster.

I can increase the jSpeed speed, and it'll rise up longer, but not faster

But I can't get it to do everything faster. It just looks painfully slow, which may or may not be because of my emulator running at 11 fps, on average.

Is it just my emulator, or is it something on my end?

float time = elapsedTime/1000F;
 if (speed < maxSpeed){
            speed = speed + accel;
            }
            if(mY + mVelY < Panel.mHeight){ //0,0 is top-left
            mVelY += (speed);
            }

            if (!(mY + height >= Panel.mHeight)){
            mVelY = mVelY  + gravity ;}

            mX  =  (float) (mX +(mVelX * time));
            mY =  (float) (mY + (mVelY * time));