texts: Creating a custom mouse cursor with LWJGL2 in Java

texts:
I have been trying to create a custom mouse cursor in my LWJGL2 application running under Linux and I am almost there. I have implemented the following method that I call right after creating the game window:

public void loadCursor(BufferedImage img) throws LWJGLException
{
    final int w = img.getWidth();
    final int h = img.getHeight();

    int rgbData[] = new int[w * h];

    for (int i = 0; i < rgbData.length; i++)
    {
        int x = i % w;
        int y = h - 1 - i / w; // this will also flip the image vertically

        rgbData[i] = img.getRGB(x, y);
    }

    IntBuffer buffer = BufferUtils.createIntBuffer(w * h);
    buffer.put(rgbData);
    buffer.rewind();

    Cursor cursor = new Cursor(w, h, 2, h - 2, 1, buffer, null);

    Mouse.setNativeCursor(cursor);
}

The resulting cursor is almost perfect, except for a horizontal blank line in the middle.

Note: The image is being flipped vertically in my code because otherwise the cursor is displayed upside down in OpenGL. I have seen other implementations that flip the IntBuffer instead of doing this in the for-loop but they lead to the same result for me.

I don't think it has to do with screen tearing either since I enabled VSync and the blank line is always at 50% of the cursor's height (there is no flickering).

Can anybody tell what I am doing wrong or if my code example is missing something essential in order to find the problem? Thank you!


texts: Control frustum near and far clip plane sizes in a Projection Matrix

texts:
I'm trying to achieve a dolly zoom effect.
My first try was the obvious one, the original "zoom in & dolly out" technique, which works nicely.
Except that there are cases which this is not possible due spatial conditions (E.g.: camera close to a wall)

If you pull back the camera too much you may occlude the view with some other objects (the red area).

To solve this I figured that I can't move the camera.
Instead, I have to change the frustum, making a larger near plane and a smaller far plane.

This way, it's possible to control de effect without moving the camera.

I know how to build the perspective and orthogonal projection matrices, and I was able to interpolate between them (interpolating each element separately).
This got me really near to solve the puzzle.

The only problem now is to set a distance from the camera to keep my frustum height, effectively locking the focus in an object/position.
But I can't figure this one out.

So, any ideas?

Aditional info

This is the matrices that I'm using:

4x4 matrix for orthogonal projection

   0         1         2          3
  -----------------------------------------------
0 | 2/(r-l) |         |          | -(r+l)/(r-l) |
  -----------------------------------------------
1 |         | 2/(t-b) |          | -(t+b)/(t-b) |
  -----------------------------------------------
2 |         |         | -2/(f-n) | -(f+n)/(f-n) |
  -----------------------------------------------
3 |         |         |          | 1            |
  -----------------------------------------------

4x4 matrix for perspective projection

   0           1         2              3
  -----------------------------------------------------
0 | 2n/(r-l) |          | (r+l)/(r-l)  |              |
  -----------------------------------------------------
1 |          | 2n/(t-b) | (t+b)/(t-b)  |              |
  -----------------------------------------------------
2 |          |          | -(f+n)/(f-n) | -2*f*n/(f-n) |
  -----------------------------------------------------
3 |          |          | -1           |              |
  -----------------------------------------------------

To interpolate them, I use something like this (pseudo-code):

interpolate (from, to, percentage)
{
    matrix = []
    i = 0
    while (i < 16)
    {
        matrix[i] = from[i] + (to[i] - from[i]) * percentage
        i++
    }
    return matrix;
}

projection = interpolate(perspective, orthogonal, 0.75)


texts: Obtain linear depth values on FBO and deal with small differences

texts:
I've a render target on which I have both a color and a depth attachment. In a second pass I need to run a filter whose width depends on the derivative and values of the depth.

Now, if I try, in the second pass where I'm accessing the texture on which I rendered on previously, to display the depth information all I have is a grey blotch:

http://imgur.com/UFm5oI6   (Don't pay attention to background, I'm showing just non-background values)

Before displaying it I modify it by:

float depthValue = texture(depthTexture, uv);
depthValue =(depthValue - 0.1)/0.9;

as my near clip is 0.1 and far one is 1.0

Instead, if I run the program with gDEBugger and look at the content of the depth texture what I see is a much cleaner result:

http://imgur.com/TtOgMY2

Why what I see is totally different? How gDEBugger show the values? Are the value I fetch from the depth texture wrong? Should I render depth values differently?

Moreover, the width of the kernel doesn't really change as it is computed based on depth value and depth derivatives and those two are practically identical, at least judging from what I see. Is there a way to make these differences more marked?

Sorry if it's a dumb question. Thank you.


texts: Problem with alleg42.dll / program crashes / Allegro & Codeblocks

texts:
I'm having a serious problem with allegro. The program should display random pixels on the screen and when I build and run it I get the following error message:

Below is the full code of my program:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "allegro.h"

#define Text_Color_Red makecol(255,0,0)
int main()
{
    int ret;
    int color_depth = 32;
    int x;
    int y;
    int red;
    int green;
    int blue;
    int color;

    //init allegro
    allegro_init();

    //install keyboard
    install_keyboard();

    //set color depth to 32 bits
    set_color_depth(color_depth);

    //init random seed
    srand(time(NULL));

    //init video mode to 640 x 480
    ret = set_gfx_mode(GFX_AUTODETECT_WINDOWED,640,480,0,0);

    if(ret !=0)
    {
        allegro_message(allegro_error);
        return 1;
    }

    //Display string
    textprintf(screen,font,0,0,10,0,Text_Color_Red,"Screen Resolution is: %dx%d -- Press ESC to quit !",SCREEN_W,SCREEN_H);

    //display pixels until ESC key is pressed
   //wait for keypress
    while(!key[KEY_ESC])
    {
        //set a random location
        x = 10 + rand() % (SCREEN_W-20);
        y = 10 + rand() % (SCREEN_H-20);
        //set a random color
        red = rand() % 255;
        green = rand() % 255;
        blue = rand() % 255;
        color = makecol(red,green,blue);
        //draw the pixel
        putpixel(screen, x, y, color);
    }

    //quit allegro
    allegro_exit();
}

END_OF_MAIN()

Error message: AllegroPixels1.exe has encountered a problem and needs to close.  We are sorry for the inconvenience.

Error signature: AppName: allegropixels1.exe    AppVer: 0.0.0.0    ModName: alleg42.dll
ModVer: 4.2.3.0    Offset: 0006c05c

I am using Windows XP inside a virtual machine under Parallels 7.0


texts: Deleting/Cleaning Screen-Objects with all child-objects in libGDX

texts:
For my game, Im using

libGDX
Ashley (ECS)
Box2D

Ive got a lot of screens but for simplification: MainMenuScreen and InGameScreen.

In InGameScreen Im init the ECS (Ashley) and create a lot of entities. Some have PhysicsComponent. The PhysicsSystem will catch them and call Box2D to spawn some objects based on the parameters within the PhysicsComponents.

So far so good.

Now, when the player dyes, I run setScreen(new MainMenuScreen()); from my "Main"-Class (MyGame.java).

the game starts and MyGame loading at first the MainMenuScreen
than the InGameScreen will get loaded (when player presses a key)
than the player dyes
MyGame recognized it and loading again (throu calling setScreen(...)) the MainMenuScreen
When Player press key: MyGame loading another round (setScreen(new InGameScreen))

I guess I have to do something like a complete clean up between switching screens. But how should I implement this? Just "deleting" the old InGameScreen-Object shouldent be enought, right?

Do I have to use the dispose()-Method?
Is it enough to instantiate everything new (in the init from InGameScreen) since it will instantiate all child-object new for its own like Box2DWorld world = new World();


texts: Terrain Navmesh build, rebuild smaller pieces of the bigger navmesh terrain. UNITY

texts:
when the area is very big and AI characters are required to walk a larger distance, it would be beneficial to have the large navmesh ready for finding a path.

when we change the height of the terrain in runtime small areas of the terrain should be updated.
so the buildnavmesh method is  kind of an overkill.
and the localnavmesh builder as a large type would be inefficient.
how do we dynamically change a small part of a larger navmesh?
advice or help would be highly appreciated.


texts: How should I detect collisions with objects on a "timeline"?

texts:
I'd like to replicate this game's mechanic of the player smashing walls with a precise timing to a background rhythm.

How should I check when each wall should be broken? Does the player animation use a hitbox, or does it use timing to detect if the smashing animation should play?


texts: Pitfalls in designing a coop dialog system

texts:
I like the complex, branching structure of games like visual novels and RPGs like Mass Effect. But I also like multiplayer cooperative games. So I thought, "What if there was a multiplayer dialog system?"

My thoughts on several ways it could work:

At a decision point, all players put in their vote on what to do. Out of the winning side, randomly pick one of the players who actually "speaks" the line.
At a decision point, a player is randomly selected to make the decision for the group.
At a decision point, a player is selected on a cycle to make the decision for the group.
Award the decision to the player with the most relevant skill set (ie. Rogues get the thiefly dialog options)

Clearly this could get complex. But I still want to explore this idea some.

I worry about balance in a few fundamental ways:

one player dominates the choice pool (boring for other players)
the dialog feels forced upon unrelevant players (breaks immersion)
players get the party into big trouble if they pick poor options, even if the majority of the party would choose a better option (tyranny of the minority)
a player most often gets outvoted (tyranny of the majority)

Which of my mechanics suggestions best avoid the pitfalls I mentioned? Or is there a better idea I haven't considered? Please also highlight mechanics that could annoy players.


texts: How to implement level transitioning for 2D Platformer (tile-based)

texts:
I'm making a 2D tile-based platformer in C++/SDL and I want the player to move to the next level when they run off the side of the level, but I'm not sure how to implement this. I have tried putting colliders on the tiles at the edge of the map but it seems like there could be a better than than designating special tiles.

I wasn't sure what to keywords to search for when looking for a solution so if you can point me to a useful guide that would be great!

I'm looking for something very similar to how Super Metroid handles level changing.


texts: How to Store the game score in android cocos2d

texts: I calculates the score in game project using android cocos2d, in that game after finishing the first level it goes to the next level, so i want to store that first level score and also add next level scores. how can i store that scores in android-cocos2d.


texts: Calculating the center of a turning circle

texts:
I'm trying to understand how to calculate the midpoint of a turning circle. In the attached picture, my unit is at location U. I want to compute the trajectory of the unit as it turns toward the starred location.

I understand that to achieve this I need to know the location of point P, whose coordinates are (a,b). I also understand that I can do this using some simple trig:

a = x - cos(theta) * r
b = y - sin(theta) * r

My problem is that I do not know the value of the angle Theta which sits between the sides of the right-triangle named "R" and "X-A". All I know is:

The radius of the turning circle.
The orientation of the unit.

How can I solve this problem and others like it more generally?


texts:
I saw this answer and I got what he has done, but how do I create a lightmap same as this one?

thanks in advance!

(from what lightmap should be built from (array?) and how do I calculate a lightmap like this?)


texts: I'm looking at developing a 2D sprite based platformer. Usually I make games in Gamemaker, because I find it very easy to use. I have never used Unity before but have heard a lot of good things. So, just wondering whether you can easily make this type of game in Unity?


texts: Positioning tile sprites so they connect seamlessly

texts:
What is the easiest and the most accurate way to combine tiles into a single platform in Unity, with no gaps, overlaps, or misalignment with the already-placed tiles, so that it looks like one continuous piece?

Here is what I mean:

I would like to be able to do the combination of platforms without the dragging by mouse.

I thought about doing it through the coordinates and a little bit of small calculations, but I was not able to find the width of the game object with the respect to coordinates in the Inspector.


texts: How to find two perpendicular lines given a single plane

texts:
Hey guys, i was wondering how i would go about finding the perpendicular lines relative to a surface normal.

For instance say i have (0,0,1) the expected output would be (1,0,0) and (0,1,0). What would be the best way of achieving this?

I realize that i will be using the cross product, but that requires two vectors, how do i get my first perpendicular line?

Thanks!


texts:
I recently downloaded the new Unity Hub 2.3.0 setup and since I hadn't used (or downloaded Unity Core) using the previous version of the Hub, I simply deleted the folder containing Unity Hub instead of uninstalling it like any normal person would. Now, every time I open the Unity Hub Setup and try and install it, it always shows the same "Installation Aborted, could not install successfully," error. I can't even uninstall the previous version from Windows Settings! I've tried changing the destination folder, but still doesn't work.

Any help is appreciated!

P.S. This error occurs when installing UnityHub, not the Unity Core Platform! I've also looked at all other similar posts.

Thanks.


texts: How can I do ambient occlusion for simple meshes with few vertices?

texts:
I want to do ambient occlusion for some simple buildings.

Since simple buildings have very few vertexes, how can I get good results? Is it possible with a per-vertex AO implementation?


texts:
I love writing video games for fun, and often do that.

I noticed, anyway, that most of the times implementing the gameplay itself doesn't take too much time to me (maybe because I already did that plenty times and know what and how to do for most of the things), but when I try to implement off-game stuff I get lost.

By off-game I mean what is not gameplay: menus, cutscenes between levels, world map to choose levels, saving and loading status, managing replays ... Only tried to write a few of these a few times, but always failed; that's why I never really completed and distributed a game.

Are these common problems? And where should I start to do this? Where could I find some books/guides about such stuff?


texts:
I'm working on a Heat Map generated from Perlin Noise. So far I've got 2 different outputs. Let's go step by step:

The result should be something like this:

This is the Perlin Noise I've got, easy to get, RED means hot and BLUE means cold, it's already generated in a spherical way.

And this is the gradient TEXTURE, it's based on Y axis as you can see.

At the moment they are generated in different functions in Unity, public Texture2D PerlinHeat() and public Texture2D GradientHeat(). I'd like to multiply them but you can't just simply do something like Texture2D * Texture2D, so I´m trying to figure it out and any help would be appreciated.

I'm using LibNoise as reference but as my gradient is not a noise module I can't multiply them.
By the way: How to make a noise gradient?
That´s the page that approach the best to my issue, as is about the same, I just don´t know how to implement everything that is said there.

Here is the code of the Gradient Texture, is pretty messy but it allows to change dynamically colors and heat ranges over the texture with just a change in the inspector.

    public Texture2D GetGradientHeat()
    {
        var texture = new Texture2D(heatMap.Width, heatMap.Height);
        var pixels = new Color[heatMap.Width * heatMap.Height];
        for (var x = 0; x < heatMap.Width; x++)
        {
            for (var y = 0; y < heatMap.Height; y++)
            {
                    if (y <= southPoleCap || y >= northPoleCap)
                    {
                        pixels[x + y * heatMap.Width] = coldest;
                    }
                    else if (y > southPoleCap && y <= southArcticCap || y < northPoleCap && y >= northArcticCap)
                    {
                        pixels[x + y * heatMap.Width] = colder;
                    }
                    else if (y > southArcticCap && y <= southArcticOuter || y < northArcticCap && y >= northArcticOuter)
                    {
                        pixels[x + y * heatMap.Width] = cold;
                    }
                    else if (y > southArcticOuter && y <= southMiddleOuter || y < northArcticOuter && y >= northMiddleOuter)
                    {
                        pixels[x + y * heatMap.Width] = template;
                    }
                    else if (y > southMiddleOuter && y <= southTropic || y < northMiddleOuter && y >= northTropic)
                    {
                        pixels[x + y * heatMap.Width] = hot;
                    }
                    else if (y > southTropic && y <= southMiddleInner || y >= northMiddleInner && y < northTropic)
                    {
                        pixels[x + y * heatMap.Width] = hoter;
                    }
                    else if (y > southMiddleInner && y < northMiddleInner)
                    {
                        pixels[x + y * heatMap.Width] = hotest;
                    }
            }
        }

        texture.SetPixels(pixels);
        texture.wrapMode = TextureWrapMode.Clamp;
        texture.Apply();
        return texture;
    }

Any help with this will be appreciated as I've been trying to do it during weeks and I´m not able to find any more documentation or a pseudocode that I can make work.

EDIT 2
So answer from DM Gregory just works like a charm, awesome. The resulting output is at follows, with that you can alter that noise strength and playing with the offsets, color multipliers, or other noise modules, you get such a nice output, thanks!


texts: Is UI anti-aliasing broken in Unity 5.6?

texts:
I have a project that was started in Unity 5.5. When I open it in 5.6, most 2D graphics look like they're not anti-aliased: left is 5.6, right is 5.5

What you see there are UI Images in a Canvas. The weird thing is that the red cross image looks OK, but the card with the red outline doesn't.

I've tried setting mipmaps to true, and Anti-aliasing set to 8x or 4x, with no difference. I hoped this was only in the editor, but a build shows the same jaggies.

Has some setting changed in 5.6 that I can edit so my graphics look anti-aliased again, or is this a bug?


texts: Well PokeMMO is a JAVA game project which basically is the original FireRed title for the GBA made online. They know this type of projects don't last long because of the copyrighted material used, but they somehow made their client extract resources from ROMS. So they don't offer any copyrighted material on their download. I wonder what technique they could be using for this? All I know is that they use LWJGL.


texts:
I want to automate some of my Unity build process. I know that setting up automatic builds for platforms is relatively easy, just start Unity headless and tell it to build platform X!

This is fine for most things however I have some platform specific things for a given platform. For example I have achievements for Steam, GoG and my own thing if you are running truly standalone. I can easy switch between them by setting #define STEAM_BUILD to make a build with steam features enabled. This is setup for each platform that I support.

At the moment I have to change the script manually and re-build every time. I want to make a build server do this all for me but how do I tell Unity to build my PC version with a certain #define X set?


texts: Procedurally-generated 2D curved roads on map

texts:
I've been experimenting with algorithms to automatically generate road maps for a game I am working on.

I'm using the "Kingdom Rush" games as a reference point as they have some great-looking maps.

I am new to procedural content generation, and was wondering if anyone here has any pointers. I have experimented with generating random road topologies, e.g. a few entrance/source nodes, several inner nodes (fork and merge), and some exit sink nodes, then using graph-layout algorithms to create an actual road map based on this information.

Here's one example using the Fruchterman-Reingold algorithm for road layout:

The blue graph uses some randomly-generated Bézier control points to make the edges look less straight.

Here's another example generated using the same algorithm but different random numbers:

The trouble is most of the results end up looking quite similar, and I am not sure what rules I can add to improve the controllability and diversity of the procedurally-generated maps.

Any advice appreciated.


texts: How to integrate android camera for LibGDX project? (deprecated material..)

texts:
I'm trying to use the Android camera in LibGDX. I tried using this implementation of the API, which is basically the only you will find on Google.

https://github.com/libgdx/libgdx/wiki/Integrating-libgdx-and-the-device-camera

However, most of it is deprecated. It uses GL10, and the methods it calls to connect to the camera are stubs. It is not usable, and the API has probably got easier to use since (but I'd rather not look at google documentation when this has probably been made before... or has it? nothing on Google anyway).

So, do I have to make my own implementation, or is there anything available that would make it any easier? Or is the 2013 implementation actually still usable somehow?

Thanks in advance.


texts: How to wrap ECS components to OOP in libgdx ashley?

texts:
Currently I am using builder-pattern to create my Entities

PooledEngine engine = new PooledEngine();

...

CharacterComponent character = engine.createComponent(CharacterComponent.class);
TextureComponent texture = engine.createComponent(TextureComponent.class);
SizeComponent size = engine.createComponent(SizeComponent.class);
TransformComponent transform = engine.createComponent(TransformComponent.class);
PhysicsComponent physics = engine.createComponent(PhysicsComponent.class);

Entity entity = engine.createEntity();
entity.flag = Constants.CHARACTER;

entity.add(character);
entity.add(texture);
entity.add(size);
entity.add(transform);
entity.add(physics);

engine.addEntity(entity);

Because PooledEngine class didnt support the creation of casting an Entity to another class that extends Entity. Example engine.createEntity(Character.class);, I am having hard thinking how do I wrap these components into single class.

Objectives

class interface ICharacter {
    void attack();
}

class interface IMoveable {
    void move();
}

class Character extends Entity implements ICharacter, IMoveable {

    private Body body;
    private Vector2 position;

    public Character() {
        PhysicsComponent physics = Mappers.physics.get(this);
        TransformComponent transform = Mappers.transform.get(this);

        body = physics.body;
        position = transform.position;
    }

    @Override
    public void attack() {

    }

    @Override
    public void move() {
        ...
        position.add(x, y);
    }

}


texts: Does game engines (like Unreal, Unity, Crafty) add value compared to pure js frameworks (react, ember..) for my isometric tile-based games

texts:
I'd like to create a huge tile-based board (say 100K tile). The game does not have any advanced graphics (you don't see the players or landscapes), the main difficulty is that it has 100K tiles to show; something like this (but with many more tiles) or like this

Also, I can't use any technique like in minecraft where I only show smaller "regions" at a time of the map - all of the map has to be shown on the screen at once (people will zoom)

Would a game engine (unity, unreal, crafty, etc) add anything compared to pure javascript frameworks (react, ember, etc) if the only thing you are using them for is to render a tile based board (no animated graphics or characters moving on the screen)? With each tile only showing the state of a tile (occupied or not).

I might need collision detection as 2 players can't be on the same tile (note: I don't think it would be too hard to do this in javascript)
And maybe GPU acceleration out of the box?


texts: How to read rendered textures back without killing performance

texts:
I have an application where I need to render some OpenGL based dlls, read the rendered textures back, and send them to another directx based application that will render them in directx.

Right now, I am rendering them using FBOs, reading them back, and then sending the data across the network.  However, the "reading them back" step is killing the performance.

My basic loop is as follows:

while(true)
   ... render 5 to 10 textures ...
   foreach( texture in renderedTextures )
      bind texture
      glGetTexImage( data )
      push data onto a queue to send asyncronously

Commenting out the glGetTextImage call causes performance to improve drastically.  What techniques can I use to read the data back faster?


texts: How to enforce touching within a ring shape?

texts:
I'd like to have the player moving the finger within the shaded ring:

The game should be able to detect "out-of-boundary" events once the finger moves outside the ring. How can I accomplish this?


texts:
So, i managed to do deferred shading like yesterday or 2 days ago. I got pretty big impact which causes my fps to drop from 1000fps to around 300~fps for 25 lights (after some optimization, i don't know if this is even normal lol).

Then i read about this bounding volume, so then i implemented this with stencil cubes and it is capable of bumping my fps to 400~fps. The problem is whenever i enter those bounding boxes, lighting for fragments inside the box is now gone. Like so:

I resize the bounding box to half of the size for testing. And i already disable GL_CULL_FACE when rendering those bounding volume cubes. Here is how i handle the rendering:

glEnable(GL_STENCIL_TEST);
glDisable(GL_CULL_FACE);
for (int i = 0; i < sizeof(lights) / sizeof(Light); i++) {
    glStencilFunc(GL_ALWAYS, 1, 0xFF);
    glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
    glStencilMask(0xFF);
    glClear(GL_STENCIL_BUFFER_BIT);

    // Bind and unbind vao & shaders here for stencil

    // Setting up matrices and uniforms for bounding volume cube
    glDrawArrays(GL_TRIANGLES, 0, 36);

    // Bind and unbind vao & shaders here for lighting

    glStencilMask(0x00);
    glStencilFunc(GL_EQUAL, 1, 0xFF);

    // Setting up uniforms for light's properties
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
glEnable(GL_CULL_FACE);
glDisable(GL_STENCIL_TEST);

Though i don't think the code i supply above is where the problem lies. I think it is because the stencil only draws where the cubes is (the cubes walls) and not the volume inside of it.

Is there a way so that the stencil draws the volume too? Or perhaps a trick so that the lighting is still occur when i'm inside the bounding volumes?

Edit: I thought of checking cam position if it is inside those cubes, if yes then don't use bounding volume for that particular light. But i don't think that's the best solution here..


texts: How does professional audio fit into game design?

texts:
Do game designers typically seek the help of specialized music/audio specialists for soundtracks and sound design?  Is there a general need for professional audio work in game design, or is that something that only big budget game studios have a need for?

How would an audio engineer/musician/sound design type get involved with making game design projects?

I'm talking about someone who can record dialogue, create and record custom music and sound effects, and create a mix to fit all these elements together in a polished way.


texts:
I need to add collision to my tile map using MarteEngine. MarteEngine is built of of slick2D. Here's my tile generation code:
Code:

public void render(GameContainer gc, StateBasedGame game, Graphics g) throws SlickException
   {
      for (int x = 0; x < 16; x++) {
         for (int y = 0; y < 16; y++) {
            map[x][y] = AIR;
               air.draw(x * GameWorld.tilesize, y * GameWorld.tilesize);
         }
      }

   for (int x = 0; x < 16; x++) {
         for (int y = 7; y < 8; y++) {
               map[x][y] = GRASS;
               grass.draw(x * tilesize, y * tilesize);
         }
      }

   for (int x = 0; x < 16; x++) {
         for (int y = 8; y < 10; y++) {
            map[x][y] = DIRT;
               dirt.draw(x * tilesize, y * tilesize);
         }
      }

   for (int x = 0; x < 16; x++) {
         for (int y = 10; y < 16; y++) {
            map[x][y] = STONE;
               stone.draw(x * tilesize, y * tilesize);
         }
      }
      super.render(gc, game, g);

   }

And one of my tile classes (they're all the same, the image names are just different):
Code:

package MarteEngine;

import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;

import it.randomtower.engine.entity.Entity;

public class Grass extends Entity {

   public static Image grass = null;

   public Grass(float x, float y) throws SlickException {
      super(x, y);

       grass = new Image("res/grass.png");

       setHitBox(0, 0, 50, 50);

       addType(SOLID);
   }

}

I tried to do it like this:
Code:

for (int x = 0; x < 16; x++) {
         for (int y = 7; y < 8; y++) {
               map[x][y] = GRASS;
               Grass.grass.draw(x * tilesize, y * tilesize);
         }
      }

But it gave me a NullPointerException. No idea why, everything looks initialized right? I would be very grateful for some help!


texts: What is the most efficient way to work with lip sync/facial expressions in XNA?

texts:
I've been searching for an answer forever, but I haven't found one. What options are there for lip sync/facial expressions in video games made with XNA? I have a few models for a game I'm building, and I would like to know if it would be better to set up an animation for every dialogue, but that would be very time-consuming and the whole collection of files would result in a massive-sized program.

I was thinking about an automated lip-sync system, but I wouldn't know where to start! Any thoughts?


texts: Reducing noise from joystick at small deflections

texts:
I have placed in my level a cube, which is my player, and a camera, which will follow the  player.

I'm defining a direction A from camera to player and another B perpendicular to this one. So I get two perpendicular directions no matter where the camera is located, A and B.

So far so good. I'm multiplying the direction A by the value of the vertical axis of a PS4 joystick. And the B direction by the horizontal input.

Then I make a vector sum: C = (A * verticalInput) + (B * horizontalInput)

C faces the direction in which the player should face, regardless of the camera position, so I can move the camera anywhere and the joystick input always corresponds to the camera's view.

The issue is that when the input magnitude is very very small, the C vector oscillates rapidly in a small angle interval. The result is that the player "vibrates" when looking at that direction.

This effect disappears when the inputs are greater than 0.5, but I cannot use a value that large for a dead zone because I want my player to walk very slowly because he is a ninja! (And is about to make a stealth-kill or very slow movement to avoid noise).

In other words, how do I reduce the jitter from noisy joystick input?


texts: How to tell when animation is finished playing without events in Unity

texts:
I'm using the newest version of Unity. I have a turn based RPG type of game so everything is very sequential. The actor jumps in front of another actor, plays his melee attack animation, then jumps back. Currently I use events on the animation to tell when the attack animation is complete. The 2 side effects of doing it this way are:

I have to go into each animation and make an event at the end of them. It would be ideal to NOT have to do this. It would seem I should be able to just check in code if a certain animation is finished playing.
The control flow of my attack code becomes awkward. My attack method is a coroutine so I can read it very sequentially and it makes sense. Having this event to tell when the animation is complete ruins that flow. I have to basically make a bool variable and inside my finished event set it, and in my attack function do a while loop after I play the animation checking for that bool variable to change and yielding out until it does. Requiring this event ruins the logical flow of attacks. If I have many animations for whatever reason things get messier.

I noticed the Animator component doesn't have an isPlaying() like some other answers suggested. I think those answers were for older version of unity and older just playing animation clips not using the new Animator component.

There must be a better way to do this.


texts: Instant replay system by saving frames to memory in Unity

texts:
When designing an instant replay system that will playback the last n seconds of gameplay, I've seen people essentially record all of the game events and game object states and play it back. This seems like a very heavy weight solution. TowerFall achieves its instant replay by saving the last n seconds of the frame buffer and simply plays them back in order.

How would you achieve this in Unity? My initial attempt was to simply keep a Queue of Texture2D objects of the entire screen, ensuring the Queue never got larger then a few seconds worth of Texture2D objects.

However, I quickly discovered this was extremely inefficient as memory ballooned to several gigs and the frame rate dropped significantly. I know TowerFall wasn't developed in Unity, but it seems like it was able to efficiently achieve this, so I'm curious if my approach was just wrong?

Here is the code I used (from memory)

Queue<Texture2D> frames = new Queue<Texture2D>();

// 130 frames is the equivalent of ~5 seconds.
if (frames.Count > 130) {
    var trash = frames.Dequeue();
    trash = null;
}

var frame = new Texture2D (Screen.width, Screen.height, TextureFormat.RGB24, false);
// Read screen contents into the texture
frame.ReadPixels(Rect(0, 0, Screen.width, Screen.height), 0, 0);
frame.Apply();
frames.Enqueue(frame);


texts:
I have set up a tilemap system, and am rendering it in a way that lets me pan through the map using a camera offset. However, I have discovered it is incredibly inefficient, but am unsure of how  I can increase efficiency.

Here is my current rendering code:

float lastCamOffSetX = -1, lastCamOffSetY = -1;

public override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.Black);
    spriteBatch.Begin();

    int count = 0;

    int startCol = (int)camOffsetX/world.TileWidth;
    int startRow = (int)camOffsetY/world.TileHeight;
    int endCol = (int)(startCol + viewPortWidth - (camOffsetX/world.TileWidth));
    int endRow = (int)(startRow + viewPortHeight - (camOffsetY/world.TileHeight));

    if (startCol < 0) startCol = 0;
    if (startRow < 0) startRow = 0;

    if (endCol > world.Width) endCol = world.Width;
    if (endRow > world.Height) endRow = world.Height;

    for (int x = startCol; x < endCol; x++)
    {
        for (int y = startRow; y < endRow; y++)
        {
            int screenPosX = (int)((x * world.TileWidth) - (camOffsetX));
            int screenPosY = (int)((y * world.TileHeight) - (camOffsetY));

            Tile tile = world.Data[x, y];

            if (screenPosX >= -1 * world.TileWidth
                && screenPosX <= (viewPortWidth + 1) * world.TileWidth
                && screenPosY >= -1 * world.TileHeight
                && screenPosY <= (viewPortHeight + 1) * world.TileHeight)
            {
                Color color
                    = (tile.TileType == TileType.Land ? Color.Green : Color.Blue);

                DrawRectangle(spriteBatch, new Rectangle(screenPosX,
                    screenPosY, world.TileWidth, world.TileHeight), color);

                count++;
            }
        }
    }

    //Debug.WriteLine(count + " - " + (endCol-startCol)*(endRow-startRow));

    spriteBatch.End();

    lastCamOffSetX = camOffsetX;
    lastCamOffSetY = camOffsetY;
}

private void DrawRectangle(SpriteBatch spriteBatch, Rectangle coords, Color color)
{
    var rect = new Texture2D(this.GraphicsDevice, 1, 1);
    rect.SetData(new[] { color });
    spriteBatch.Draw(rect, coords, color);
}

Currently, I am only drawing tiles which are inside the screen/camera region. How can I improve the efficiency of my script?


texts:
I've been creating simple characters in Blender for a while, and now I want to add dynamic details to them. I managed to make a cloak with using UE4 cloth physics.

However I have trouble with smaller things. As english isn't my primary language, I don't even know how to name this issue properly. Example of things I want to achieve:

Simple polygon ponytail that bounces while running
Edges of clothes, like shorts are loose and also move while running
Accessories like bracelets or dangling keys on wrists / hanging from clothes which also move a bit while walking

Is this something I do in Blender and export, or is it something I add in Unreal?
What should I look for?

EDIT:
So far I found this thanks to a comment:
https://docs.unrealengine.com/en-US/Engine/Animation/NodeReference/SkeletalControls/AnimDynamics/index.html

But if anyone else has suggestions, please keep them coming.


texts: Can we access the internal array of a Android Bitmap?

texts: Does an Android Bitmap function similar to a BufferedImage? When you get the internal pixel buffer as an int[] or as a byte[] and update the values inside them, the image changes. Is that the same case as a Bitmap?


texts: Check if a 3D mesh is a rectangular prism

texts:
I have a mesh post-processor in Unity that automatically a convex mesh collider to objects that need one (mostly all).

Sometimes however there are objects that only need a box collider instead.

How can I detect if a mesh is a rectangular prism?


texts: How to calculate left/right oriented angle between two 2D vectors?

texts:
I would like to calculate angle between two 2D vectors. Here's a picture of what I'm trying to achieve:

I have an obstacle line segment AB and incoming moving PC. If I'm coming from one side C¹D¹ and angle ⍺ < π/2 (i.e. right side) then PC will turn left. On the other hand if ⍺ > π/2 then PC will turn right. But if PC will come from the other side C²D² it should work as well for angle β as per picture.

So what I need is to determine whether the angle between AB and CD is larger to the left or right basically.

I've tried these things, while having vectors defined as:

Vector2 ab = Vector2.Normalize(new Vector2(b.x - a.x, b.y - a.y));
Vector2 cd = Vector2.Normalize(direction);

1) To calculate angle using atan2, but it works only randomly (1/4 of cases).

Single angle = Math.Atan2(cd.Y, cd.X) - Math.Atan2(ab.Y, ab.X);

if (angle > MathUtil.PiOverTwo)
{
    RotateRight();
}
else if (angle < MathUtil.PiOverTwo)
{
    RotateLeft();
}

2) To use normals somehow. This works a bit better but only from one side I think. (1/2 of cases, better but not there)

Vector2 normal1 = Vector2.Normalize(new Vector2(-ab.Y, ab.X));
Vector2 normal2 = Vector2.Normalize(new Vector2(ab.Y, -ab.X));
Double angle1 = Math.Atan2(normal1.Y, normal1.X) - Math.Atan2(cd.Y, cd.X);
Double angle2 = Math.Atan2(normal2.Y, normal2.X) - Math.Atan2(cd.Y, cd.X);

if (angle1 > angle2)
{
    RotateRight();
}
else if (angle1 < angle2)
{
    RotateLeft();
}


texts: Position Text Mesh above parent transform in world space

texts:
I'm making an isometric-ish 2d game in Unity. I want to display text above a sprite during certain conditions. For this, I'm using a TextMesh instantiated as a child of the sprite.

In local space, this obviously means that when I rotate a sprite, its children rotate along with it. From the player's perspective, the label now appears to the side of the sprite, rather than staying above it.

I can always calculate the world space position of the TextMesh during LateUpdate(), but a) that solution requires a designer to know that a script will alter the local transform, and b) things built into Unity have more eyeballs on them, so I'd rather use that.

Is there a mechanism built into Unity such that I can set a child's transform in the inspector to e.g. position.y = 0.4 and have it render 0.4 units above the parent in world space? Edit: Additionally, I want it to follow the parent as it moves, so just calculating once on Instantiate() isn't quite what I want either.


texts: How can I predict player-to-projectile collisions in Box2D?

texts:
I'm making a real time shooting game with Box2D as the physics engine. The gameplay is mostly about trajectory, like Angry Birds. I want to make a slow motion effect and move camera to the player when he's killed, but the effect should start when the stone is still in the air, before the collision actually happens.

The magnitude of damage is only calculated at collision, based on impulse. Because it's a real-time game, the player must be able to move their character's physics body without lag.

How can I predict their death? Is it even possible? I could raycast, but what if another object moves to block its path?


texts: I need to increase the size of the field you make models in by at least 20. It really doesn't make sense why you cannot go beyond 126x126x126 because in the MagicaVoxel viewer, there are sample models of 1000x1000 so there's gotta be a way to make larger models in MagicaVoxel. Anyone know how?


texts:
I am writing isometric engine in c++. I decided to take a more realistic approach and make walls occupy space between two tiles, not a single whole tile, as shown in the picture below (just like in The Sims).

My problem is that I have no idea how to store the tile map related data in something that is not grid. In this situation I guess I will need to make it A* friendly, so there will be nodes and edges between tiles not divided by walls. Here is another picture showing what I want to achieve:

So here is the question(s):

How should I:

store the whole map, both tiles and walls
optimize it for rendering
use it for A* and other algorithms rather straightforward to implement on a simple grid but now using walls (edges) to determine visibility, collision etc.?


texts:
When I create two cubes from Unity > Component menu. And turn on AO the bottom cube is not shaded properly. I mean the upper cube is alright but the bottom cube does not have any shadow present. What am I doing wrong ?

Lighting setup:

Result:


texts: NullReferenceException in StartCoroutine method

texts:
Maybe it's a repeated subject in the community but other answers didn't solved my question...

I tried as the tutorial: http://answers.unity3d.com/questions/11021/how-can-i-send-and-receive-data-to-and-from-a-url.html and worked fine in start method but when I try:

public Class A
 {
 //    ...CODE...
 new B().JSONRequest(jsonString);
 }

public Class B
{

public void JSONRequest(string json) {
string url = URL.LOCAL.url;
Hashtable postHeader = new Hashtable();
postHeader.Add("Content-Type", "application/json");
UTF8Encoding encoding = new System.Text.UTF8Encoding();
WWW request = new WWW(url, encoding.GetBytes(requisicaoJSON.ToCharArray()), HashtableToDictionary<string, string>(postHeader));
 print("Request: "+request);

StartCoroutine(WaitForRequest(request));
}

IEnumerator WaitForRequest(WWW www)
{
    yield return www;
        // check for errors
        if (www.error == null)
        {
            Debug.Log("WWW Ok!: " + www.data);
        } else {
            Debug.Log("WWW Error: "+ www.error);
        }
    }
}

It gives me in the StartRoutine line:
NullReferenceException
UnityEngine.MonoBehaviour.StartCoroutine (IEnumerator routine) (at C:/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineMonoBehaviourBindings.gen.cs:61

Console prints Request: UnityEngine.WWW so it does not appear to be null. –


texts: How do I hide the bug image once it's hit by a bullet?

texts:
I have almost solved my problem. I am able to shoot a bullet and hit a bug and it then draws a collision bitmap. but then it redraws a bug, I want to clear the bug bitmap after the collision happens.

public Form1()
{
    InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
    timer1.Interval = 20;
    timer1.Start();
    timer2.Interval = 100;
    timer2.Start();
    this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer, true);
}
int x = 0, y = 0;
Bitmap bug_one = new Bitmap("bug_one.bmp", true);
Bitmap ship = new Bitmap("ship.bmp", true);
Bitmap bullet = new Bitmap("bullet.bmp", true);
Bitmap coll = new Bitmap("coll.bmp", true);
Bitmap black = new Bitmap("black.bmp", true);
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Left)
    {
        x-=5;
        if(x<=-350)
        {
            x = -350;
        }
    }
    if(e.KeyCode == Keys.Right)
    {
        x+=5;
        if(x>=375)
        {
            x = 375;
        }
    }
    if (e.KeyCode == Keys.Space)
    {
        if (y <= -530)
        {
            y = 0;
        }
    }
}
int count = 102;
public void Form1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.Clear(Color.Black);
    e.Graphics.DrawImage(ship, 350 + x, 530);
    e.Graphics.DrawImage(bullet, 375 + x, 520 + y);
    e.Graphics.DrawImage(bug_one, 350, 0);
    if (y <= -510 && x >= -15 && x <= 15 && count > 0)
    {
        e.Graphics.DrawImage(coll, 350, 0);
        count = 0;
    }
}
public void timer1_Tick(object sender, EventArgs e)
{
    y -= 5;
    Invalidate();
}
public void timer2_Tick(object sender, EventArgs e)
{
    count--;
    Invalidate();
}

This attempt almost works: when a bullet hits a bug it draws a collision image, but then all the bugs are cleared. I only want one bug to be cleared at a time.

    public void Form1_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.DrawImage(ship, x-25, 530);
        e.Graphics.DrawImage(bullet, x, y);
        if (collision)
        {
            return;
        }
        foreach (Bug bug in bugs)
        {
            e.Graphics.DrawImage(bug_one, bug.px, bug.py);
        }
        foreach (Bug bug in bugs)
        {
            if (x >= bug.px && y >= bug.py && x <= bug.px + bug.width && y <= bug.py + bug.height)
            {
                e.Graphics.DrawImage(coll, bug.px, bug.py);
                collision = true;
            }
        }
    }


texts: How can I store point voxel terrain in octrees

texts:
I am writing a voxel engine in LWJGL3 - binding for OpenGL 4 for JVM.
Recently I implemented an octree storage of cubic voxels.
In my implementation each leaf node of an octree has one voxel, voxels can't overlap each over.
But now I changed my mind and my goal is to create a dynamic point voxel engine.
How can I store point voxels in an octree ?
My reference is EverQuest Next Landmark.


texts: Change Time.timeScale during an animation event - Unity

texts:
I have an animation. A few seconds after this animation starts I set an animation event that is correctly being triggered. This animation event calls a method where I am trying to modify Time.timeScaleand set it to 0.05f.

This event is calling the following method:

public void Slowmotion()
{
    Time.timeScale = 0.05f;
    //Time.fixedDeltaTime = Time.timeScale * 0.02f;
}

But this Slowmotion method is not working.

Any ideas on what may be happening?


texts:
Alright, I'm currently thinking about registering my game with Steam's new Greenlight program. Only problem is I don't have a trademarked title yet and I read the government's registration process can take a little while. (and $$ I don't have at the moment) So naturally, this got me wondering if it is a sound idea to proceed without one.

So my question is are there any serious pitfalls I should worry about if I start advertising without a trademarked title? (Assuming it doesn't infringe upon anyone else's property of course)


texts: GUI Layering (Enemy health bars appear above Inventory)

texts:
I have set up an enemy prefab that gets instantiated during Start. Each enemy object has a health bar GUI object attached to a Canvas which is a child of these spawned enemy objects. So, when I spawn 10 enemies, 10 health bars get spawned as well. I have another GUI object for the inventory which I can open and close at the press of a button. When I open my inventory and there are enemies behind it, their health bars show on top of my inventory. I would like to layer the GUI objects such that these enemy health bars do not appear above my inventory. How do I do this? I have tried ordering them differently in the hierarchy as per someone's suggestion in a forum post, but that didn't seem to work.

Again, every enemy object has its own Canvas of which the health bar is a child.
The inventory GUI object is attached to a different Canvas which has no parent.


texts: How to display height information in tilemap

texts:
I want to create a hexagonal tilemap and show regions of different height in the same screen. What ways can you think about to indicate which height a tile is on. (current, lower, higher?)

Several tilemap games avoid this by having special mountain tiles, but that allows for ~2 heights and I would like for more differentiation.

Another approach is to just draw the tiles of current height, but this does look very strange if the map is very bumpy (lot's of holes).

I have not found a nice way to whiten or blacken tiles that are lower or higher than the current viewpoint.
Any ideas?


texts:
I'm developing an action rpg with some University colleagues. We've gotton to the monsters' AI design and we would like to implement a sort of "utility-based AI" so we have a "thinker" that assigns a numeric value on all the monster's decisions and we choose the highest (or the most appropriate, depending on monster's iq) and assign it in the monster's collection of decisions (like a goal-driven design pattern) .

One solution we found is to write a mathematical formula for each decision, with all the important parameters for evaluation (so for a spell-decision we might have mp,distance from player, player's hp etc). This formula also has coefficients representing some of monster's behaviour (in this way we can alterate formulas by changing coefficients).

I've also read how "fuzzy logic" works; I was fascinated by it and by the many ways of expansion it has. I was wondering how we could use this technique to give our AI more semplicity, as in create evaluations with fuzzy rules such as
IF player_far AND mp_high AND hp_high THEN very_Desiderable
(for a spell having an high casting-time and consume high mp) and then 'defuzz' it. In this way it's also simple to create a monster behaviour by creating ad-hoc rules for every monster's IQ category.

But is it correct using fuzzy logic in a game with many parameters like an rpg? Is there a way of merging these two techniques?
Are there better AI design techniques for evaluating monster's chooses?


texts: How do I force a game object to move along projectile trajectory, like in Angry Birds?

texts:
I am a new Android game developer. I want to force my game object to move in a projectile trajectory, like in Angry Birds.Related example here
and my example You can see an example in the image.

I used jbox2d to write a little bit of code, but I don't know how to make it work. How do I force movement along a projectile trajectory?

My code is below:

    private static class ProjectileEquation {

        public float gravity;
        public Vector2 startVelocity = new Vector2();
        public Vector2 startPoint = new Vector2();

        public float yogx(float t) {
            return startPoint.x + t * startVelocity.x;
        }

        public float yogy(float t) {

            float u = (float) -4.97741939970554;
            float v = (float) 30.88079;
            float tt = 1/6f;
            float n = (u+v)/2*tt;

            return startPoint.y + n * t *startVelocity.y + 0.5f *(n*n+n)
                * t * t * gravity;
        }
    }

    private static class Controller {
        public float power = -66f;
        public float angle = 585f;
    }
}

 public float P2M(float xPixels) {
    return xPixels * metersPerPixel;
}

public float M2P(float xMetres) {
    return xMetres * pixelsPerMeter;
}

public float MaxHeight(){

     if (projectileEquation.startVelocity.y > 0){

            return projectileEquation.startPoint.y;
     }
        return projectileEquation.startPoint.y;
        }

public void Update() {
    projectileEquation.startVelocity.set(controller.power,controller.power);
    projectileEquation.startVelocity.rotate(controller.angle);
     //     bd = bodies;

}

    @Override
    protected void onDraw(Canvas c) {
        super.onDraw(c);

        MaxHeight();

        Update();

        float t = 0f;
        x = c.getWidth()/2;
        y = c.getHeight()-20;

        float timeSeparation = this.timeSeparation;

        for (int i = 0; i < trajectoryPointCount; i++) {

            float x = this.x +  projectileEquation.yogx(t);
            float y = this.y +  -projectileEquation.yogy(t);

            t += timeSeparation;

            if(A) {
                c.drawBitmap(bmp, x, y, null);
            }else if(B) {

                float bX = M2P(body.getPosition().x);
                float by = c.getHeight() - M2P(body.getPosition().y);
                body.setActive(true);

                c.drawCircle(bX, by, M2P(body.m_fixtureList.m_shape.m_radius), circlePaint);
            }
        }
    }

public class jbox2d {

    public float targetFps = 30.0f;
    public float timeStep = (1.0f / targetFps);
    private int interations = 2;
    public Body body;
    private World world;
    private BodyDef bodydef;

    public void Create(){

        Vec2 gravity = new Vec2(0,-10f);
        boolean doSleep = true;
        world = new World(gravity, doSleep);
    }

    public void addboll() {

        bodydef = new BodyDef();
        bodydef.type = BodyType.DYNAMIC;
        bodydef.allowSleep = true;

        bodydef.position.set(8.24f,10f);

        body = world.createBody(bodydef);
        body.setActive(false);
        float tt = 0f;

        Vec2 stx = new Vec2();
        Vec2 sty =new Vec2();

        for (int it = 0; it < 20; it++) {

            stx = M2P(projectileEquation.startVelocity.x);
            sty = M2P(projectileEquation.startVelocity.y);

            stx = M2P(projectileEquation.yogx(tt));
            sty = -M2P(projectileEquation.yogy(tt));

            body.setLinearVelocity(new Vec2(stx,sty));
            body.applyLinearImpulse(body.getLinearVelocity(), body.getWorldCenter());

            tt += timeSeparation;
        }

        CircleShape circle = new CircleShape();
        circle.m_radius = (float).42;

        FixtureDef fixturedef = new FixtureDef();
        fixturedef.density = 1.0f;
        fixturedef.restitution  = 0.9f;
        fixturedef.friction = 0.2f;
        fixturedef.shape = circle;
        body.createFixture(fixturedef);

    }

    public void update(){
        world.step(timeStep, interations, interations);
    }
}


texts: How exactly do slopes and edges work in this scenario?

texts:
So this sort of behaviour probably exists in other games, but the old Kirby games - Kirby's Adventure and Kirby's Dreamland 2 - is where I noticed it.

So, when dealing with regular block platforms, Kirby's hitbox acts like a simple rectangle, as you'd expect, as evidenced by the fact that you can stand like so:

On the other hand, when dealing with slopes of any kind, standing on them looks like this:

As you can see, if we were still using the rectangular hitbox, it would be halfway in the ground. This sort of behaviour is easily explained, however, buy a hitbox shaped like a 'diamond' or a 'plus'. (This is probably so that it doesn't look like Kirby is hovering in midair when walking on slopes)

Platforms such as these show perfect consistency with the 'diamond' hitbox model:

However, of course, the first screenshot shows that it's not possible for a diamond-shaped hitbox to be used all the time, or you would be able to 'slide' off any corner as if there was a slope there.

In fact, formations such as this show that it can't even be based on particular tiles, at least not 'full' tiles. (16x16, Kirby's size) (Otherwise you couldn't walk all the way up that slope)

Another model I've come up with is that the hitbox is always rectangular, but all slopes in the game are actually 'sunk' deeper than the tiles would have you believe. However, the stake-shaped platforms in the third & fourth screenshots invalidate this model, since then you wouldn't be able to stand at the top middle like you see there.

By the way, slopes on the ceiling work symmetrically, as can be seen in water stages.

While it seems intuitive to the player, how could we program a similar collision system ?

N.B. I am not asking for speculation on the internal workings of Kirby (unless someone here actually developed the collision system for those games - unlikely). Just a general approach.


texts: Distance travelled by gameObject and behavior depend on device's performance?

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

Here's the code:

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


texts: Why doesn't my SpriteRenderer's color change when setting .color = new Color(166, 33, 33)?

texts:
I need to change the color of my SpriteRenderer, and so I looked up how to do it and come up with this code:

spaceOne.GetComponent<SpriteRenderer>().color = new Color(166, 33, 33);

(In case you are wondering, yes I checked that 'spaceOne' is correctly linked to a GameObject.)

This should change the color, but it doesn't. As I was writing this, I found that replacing new Color(166, 33, 33); with Color.red; actually does change it to red.

So now I am wondering, why does the new Color(166, 33, 33); code not work, and how can I fix it?

P.S. I made sure that it wasn't something simple, like it being RGBA rather than RGB, but no, it still doesn't work with new Color(166, 33, 33, 255);.


texts: Trying to use 3D vectors for a 2D ping pong game

texts:
I am trying to setup a virtual ping pong table, and am getting a little stuck in trying to understand how to do 3D vector math and render it in 2D.

So far, my plan is for the ball: X = up/down, Y = left/right, and Z = forward/backwards

So as a simple start, I am just trying to move the ball forward:

ball.vel.x = 0;
ball.vel.y = 0;
ball.vel.z = 1;

in my update function:

ball.position.x += (ball.vel.x / ball.vel.z) * delta;
ball.position.y += (ball.vel.y / ball.vel.z) * delta;

Which obviously makes no sense since 0 / anything is 0.. my ball will never move forward...  So I am fundamentally missing something here.  What do I need to do so that my Z velocity will actually move the ball's position?


texts: What is the best method to serve a real time game on websockets?

texts:
The game consists of a world with just one force, gravity. All the players can do is jump and set their velocities with arrow keys. Physical AABBs and sphere's are used for collision.

What is the best method to serve this game on websockets? Dead-reckoning? Sending positions only for play back?


texts:
I'm making an RPG game where players and enemies can collide with walls.
Right now it pushes the player off the wall when he tries to 'go through' it.
However, I detect which way he should be pushed based on his current direction.
This means that enemies can still push him through walls.
Also if the player moves diagonally, detection doesn't work properly. This is a problem...

I'm using SFML and these Collison-Detection methods: https://github.com/LaurentGomila/SFML/wiki/Source:-Simple-Collision-Detection-for-SFML-2

Specifically I'm using this method:

bool BoundingBoxTest(const sf::Sprite& Object1, const sf::Sprite& Object2)
{
    OrientedBoundingBox OBB1 (Object1);
    OrientedBoundingBox OBB2 (Object2);

    // Create the four distinct axes that are perpendicular to the edges of the two rectangles
    sf::Vector2f Axes[4] = {
        sf::Vector2f (OBB1.Points[1].x-OBB1.Points[0].x,
        OBB1.Points[1].y-OBB1.Points[0].y),
        sf::Vector2f (OBB1.Points[1].x-OBB1.Points[2].x,
        OBB1.Points[1].y-OBB1.Points[2].y),
        sf::Vector2f (OBB2.Points[0].x-OBB2.Points[3].x,
        OBB2.Points[0].y-OBB2.Points[3].y),
        sf::Vector2f (OBB2.Points[0].x-OBB2.Points[1].x,
        OBB2.Points[0].y-OBB2.Points[1].y)
    };

    for (int i = 0; i<4; i++) // For each axis...
    {
        float MinOBB1, MaxOBB1, MinOBB2, MaxOBB2;

        // ... project the points of both OBBs onto the axis ...
        OBB1.ProjectOntoAxis(Axes[i], MinOBB1, MaxOBB1);
        OBB2.ProjectOntoAxis(Axes[i], MinOBB2, MaxOBB2);

        // ... and check whether the outermost projected points of both OBBs overlap.
        // If this is not the case, the Seperating Axis Theorem states that there can be no collision between the rectangles
        if (!((MinOBB2<=MaxOBB1)&&(MaxOBB2>=MinOBB1)))
        {
            return false;
        }
    }
    return true;
}

Note that the method only checks if the sprites collide, not how or where they collide.
I don't know how exactly the collision detection works, I've tried printing out the OBB values but they're nonsensical to me.

Should I somehow modify the function, or is there another way of doing collision direction detection? I'm stuck here.

UPDATE

I managed to actually check for which direction the player was colliding with the wall.
I have a really odd problem now:
It only works properly on the last wall I place.

I have 4 booleans (canWalkUp, canWalkDown, canWalkLeft, canWalkRight) to check for if the player is holding down both left and right, or up and down - so they don't negate each other. This prevents wonky movement.
I also have 4 booleans to check if the player is currently colliding with a wall.

The code which handles player-boundary collision is as follows:

void EventHandler::collisionPlayerBoundary(std::shared_ptr<Entity> player,     std::shared_ptr<Entity> boundary)
{
std::vector<sf::Vector2f> distances = Collision::BoundingBoxDistance(player->sprite, boundary->sprite);
float pushSpeed = 75;
if(distances.at(0).y < 20) //push left!
{
    std::cout << "pushing left" << std::endl;
    player->pushX = -pushSpeed;
    player->canWalkRight = false;
    player->collidingRight = true;
}
if(distances.at(1).y < 20) //push down!
{
    std::cout << "pushing down" << std::endl;
    player->pushY = pushSpeed;
    player->canWalkUp = false;
    player->collidingUp = true;
}
if(distances.at(0).x < 20) //push right!
{
    std::cout << "pushing right" << std::endl;
    player->pushX = pushSpeed;
    player->canWalkLeft = false;
    player->collidingLeft = true;
}
if(distances.at(2).x < 20) //push up!
{
    std::cout << "pushing up" << std::endl;
    player->pushY = -pushSpeed;
    player->canWalkDown = false;
    player->collidingDown = true;
}
}


texts: Pack of resources in one big file with XNA

texts:
Is it possible to pack all the little .xnb files into one big file?
Given the level of abstraction of the XNA Framework I though this would come out of the box but I can't find any well integrated solution.

So far the best candidate is XnaZip but in addition to having to compile the resources in a post-build event, and a little trouble porting the game to XBOX I have to rename all the references to resources I have already implemented.


texts:
How do I pass to my vertex shader an array of N elements?

From what I see I can only pass float arrays of 3|4 elements, vectors 2|3d and matrices, but I want to pass a POD array and use it like this:

void ShaderFunction(float* array,int count)
{
    for (int i = 0;i < count;i++)
    {
        DoJob(array[i]);
    }
}

So far all of my tests fail.


texts: Smooth seams and banding of overlapping lights in deferred rendering

texts:
I have finally managed to get on screen multiple lights with a deferred renderer, but the result is somehow disappointing. In particular I have severe banding problem

Other than having clear banding for a single light, the seam of overlapping light volumes are in some case disturbing.

Currently my bounding sphere scale is calculated solving the quadratic equation with a min light intensity of 0.01 and using the attenuation terms of each light source (in the screen above, every light have an equivalent volume).

The attenuation in the shader is simply  1 / (const + linear * dist + quadr * dist * dist) . The position is reconstructed from a 32bit depth buffer and the lighting is in view space.

The light passes are blended together with simply

glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_ONE,GL_ONE);

Is there a way to fix this issue easily?

Thank you!


texts: Question on methods in Object Oriented Programming

texts:
I’m learning Java at the minute (first language), and as a project I’m looking at developing a simple puzzle game.

My question relates to the methods within a class. I have my Block type class; it has its many attributes, set methods, get methods and just plain methods. There are quite a few.
Then I have my main board class. At the moment it does most of the logic, positioning of sprites collision detection and then draws the sprites etc...

As I am learning to program as much as I’m learning to program games I’m curious to know how much code is typically acceptable within a given method. Is there such thing as having too many methods?

All my draw functionality happens in one method, should I break this into a few ‘sub’ methods? My thinking is if I find at a later stage that the for loop I’m using to cycle through the array of sprites searching for collisions in the spriteCollision() method is inefficient I code a new method and just replace the old method calls with the new one, leaving the old code intact.

Is it bad practice to have a method that contains one if statement, and place the call for that method in the for loop?
I’m very much in the early stages of coding/designing and I need all the help I can get!
I find it a little intimidating when people are talking about throwing together a prototype in a day too! Can’t wait until I’m that good!


texts: When storing voxels in chunks, how do I access them at the world level?

texts:
I'm not looking for how to store the voxels, data wise; I'm looking for the theory. Currently, my voxel engine has no global list of tiles. Each chunk has its own list, and its "hard to do things" like collision detection or anything that may use tiles that are outside of its own chunk. I want to start using height maps, but I have a problem. If each chunk has its own list, then it will be pretty difficult to implement the height maps.

Should I store a global list of voxels, independent of the chunks? Then, I can just easily perform collision detection and terrain generation. However, it would probably be harder to do things such as frustum culling.

So how should I store voxels?


texts:
I have some code to load DDS image files into OpenGL textures, and I'd like to extend it to support the BC6 and BC7 compressed formats introduced in D3D11. Since DirectX and OpenGL disagree about whether a texture's origin is in the upper-left or lower-left corner, my DDS loader flips each image's pixels along the Y axis before passing the pixels to OpenGL.

Flipping compressed textures presents an additional wrinkle: in addition to flipping each row of 4x4-pixel blocks, you also need to flip the pixels within each block. I found code here to flip BC1/BC2/BC3 blocks, and from the block diagrams on MSDN it was easy to adapt the BC3-flipping code to handle BC4 and BC5. The BC6 and BC7 formats look significantly more intimidating, though. Is there a similar bit-twiddling trick to flip these formats, or would I have to fully decompress and recompress each block?

UPDATE: It turns out the texture flip was only necessary because my texture coordinates were being incorrectly inverted at export time. Removing both flips made the code both simpler and faster (thanks Humus!). Flipping BC6/BC7 blocks may still be an interesting challenge, but it's no longer relevant to my original scenario.


texts:
I'm trying to get a 2d tilemap rendering but somethings not clicking with me about the 2d coordinates...

Here's my basic tilemap class -

public class Map : MonoBehaviour {
public Transform tilePrefab;

public int mapWidth;
public int mapHeight;
public Transform[,] map;

// Use this for initialization
void Start () {
    map = new Transform[mapWidth, mapHeight];

    for (int y = 0; y < mapHeight; y++)
    {
        for (int x = 0; x < mapWidth; x++)
        {
            Transform tile = Instantiate(tilePrefab, new Vector3 (x, y, 0), Quaternion.identity) as Transform;
            tile.parent = transform;
            map[x, y] = tile;
        }
    }
}

But this is rendering the tilemap from the origin -

I want that tilemap to be dynamically centered on the camera like -

What I can't seem to work out is how to dynamically work out the coordinates to move that tilemap so that it's centered in the camera after it has been created?

Any additional help, or pointers to some decent resources would be much appreciated, cheers.


texts:
I've been building a 3D engine from scratch using C# and I've tried to show the result to a friend of mine using Teamviewer. When my demo game starts he doesn't see it.
He can only see the last active program on my screen (for example visual studio from which I started the game)

The game engine launches a windows form at start, then directx binds to this form.
It's a fullscreen application with no windows forms borders etc.

Why doesn't teamviewer pick this up?


texts:
I am creating a breakout game in c#.
Everything is working fine excepting one feature

My blocks are destroyed after the second hit ,but if the ball hits the side (left or right) of the block , the block is destroyed instantly..

Example here

What's the feature needed to avoid this problem ?
Thanks in advance !
Here is the code where the "action"  is happening :

foreach(Control x in this.Controls)
        {

            if (x is PictureBox && x.Tag == "block")
            {
                if (ball1.Bounds.IntersectsWith(x.Bounds))
                {
                    x.Tag = "Hit";
                    bally = -bally;
                }
            }
            else
            {
                if (x is PictureBox && x.Tag == "Hit")
                    if (ball1.Bounds.IntersectsWith(x.Bounds))
                    {
                       bally = -bally;
                        this.Controls.Remove(x);
                        if(score<=5)
                            speed = speed + 1;
                    }
            }
        }

x - my blocks

Point pt = ball1.Location;
if (pt.X < 0 || pt.X > ClientRectangle.Width - ball1.Width)
            ballx = -ballx;


texts: Normally, a physics frame in pink (see image below) gives the body for detecting hit signal. It usually either falls down or lifts up depending on the gravity orientation. The question is: Is it possible to move or manipulate sprite through X and Y coordinate without needing to use the gravity code from a physics engine like bodyeditor-loader-sources.jar (e.g. ballBody.setGravityScale(100.1f);) so that I can move simply either by dragging, change the value initially, or moving it by D-pad?


texts: Generating a set of islands in real time

texts:
With thismethod I can create multiple separated islands just by randomly choosing a point as the center for a gradient. Now what I want to do is to have a system of real time generation like the one in Minecraft.

When I generate a new chuck, some random points inside of it are chosen to be the center of a gradient. However, if one of these points gets positioned near the border of the chuck, the gradient will cross the border and affect the other chunk. But if that other chunk was already generated and visited by the player, I couldn't update that chunk to include the new gradient, so I would end up with something that looks like this:

What could be a method to avoid this?


texts: Why does gameObject.transform.eulerAngles = new Vector3... work?

texts:
Apparently gameObject.transform.eulerAngles is accessing a copy, so changing it shouldn't do anything, and in fact using .Set doesn't work. But why does =new Vector3 (..) work?

EDIT: Given the answers - I think I should update the question. What seems inconsistent to me, is the fact that "new Vector3" works as a setter the way I would want it to, but not using "new" and .Set doesn't. It doesn't seem very intuitive that "new" is understood as "ah, he's trying to set this property of a property" that way want - the choice of word doesn't seem very intuitive at least.

I suppose it makes sense in the ".Set" case - you might want to intentionally use the .Set of the Vector3 returned. Essentially, it might be useful to interpret A.B.Set as (A.B).Set, as this is the "natural" way to interpret it, as opposed to some other "ordering" (which could symbolically be expressed as A.(SetB) or something like that).

But in the other case - I don't know why omitting "new" doesn't work. It would seem like a natural choice to interpret (A.B.C)= as "he wants to set the property" - what else could be intended by this? I can't think of a reason why someone would want it to do something else than what happens when you add "new" - i.e. assuming that A.B gives you the copy of the property B of A, and assuming it's not some sort of simple object like a Vector3, why would you want to set this copy of the property to something? In what scenario could that be a useful, efficient way of doing something?

But thinking about it again, I suppose the reason might be the same as with .Set -the code A.B.C= is simply understood as ((A.B).C)=, because that's the most natural, basic way to interpret it, is that right?


texts: How can I create a pressure pad in order to open a door?

texts:
I'm making a 2D platformer with Unity. I want to create a pressure pad in order to open a door and I want the door to open when the player is on the pressure pad and close in few seconds after the player leaves the pressure pad. I've tried different ways but none of them worked. In this case, the door should be open upwards and close downwards. Also, I already created some animations (idle, open and close) for the door but don't know how to make a connection between these two objects then play the animations at the proper time. Thank you in advance.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class PressurePad: MonoBehaviour
{
    public UnityEvent OnActivate;
    public UnityEvent OnDeactivate;

    int objectsInContact;

    IEnumerator Timer()
    {
        yield return new WaitForSeconds(6);
        OnDeactivate.Invoke();
    }
    void OnTriggerEnter2D(Collider2D other)
    {
        objectsInContact++;
        if (objectsInContact == 1 && OnActivate != null) OnActivate.Invoke();
    }

    void OnTriggerExit2D(Collider2D other)
    {
        objectsInContact--;
        if (objectsInContact == 0 && OnDeactivate != null) OnDeactivate.Invoke();
        StartCoroutine(Timer());

    }

}


texts: Using canvas graphics instead of traditional sprites in phaser

texts:
I'm trying to learn Phaser (total beginner with mild JS experience) and I'm following tutorials and such where everything is using sprites. I'm trying to get by with basic canvas shapes instead of creating sprites, but I'm having trouble implementing them in some situations.

I have a working player shape:

var playerGraphic = this.game.add.graphics(100, 100);

// set a fill and line style
playerGraphic.beginFill(0x555555);
playerGraphic.lineStyle(2, 0xffffff, 0.5);

// draw a shape
playerGraphic.drawCircle(0, 0, 20);
playerGraphic.drawCircle(5, 5, 10);

this.player = this.game.add.sprite(this.game.world.centerX, this.game.world.centerY, null);

this.player.addChild(playerGraphic);

But I'm unsure if this is the correct way of doing it.

I'm also struggling to get a tiled background to work, as it doesn't seem to work in the same way as above:

this.game.background = this.game.add.tileSprite(0, 0, this.game.world.width, this.game.world.height, null);

this.game.background.addChild(bgGraphic);

Any advice/help?


texts: Google leaderboards, up to a maximum of 70?

texts:
I see in the doc that the limit for the number of leaderboards on Google Play Services is 70. However, I am able to create more than 70 leaderboards and they are all working when I test my app. Is this limit still up to date? Does this mean that if I publish my game some of the leaderboards will be deactivated or something?
Thank you in advance if you know the answer. I just want to make sure of what I can expect for when I publish my game.


texts: How can I look up an object given only the name of its type?

texts:
This question came from a fellow developer on Twitter, and I figured StackExchange would be a better format for explaining & sharing the answer. To paraphrase the question:

I'm setting up an in-game dev console in my Unity game, where a user should be able to call any method on any MonoBehaviour in the scene.

I want to use something like FindObjectsOfType<>, but because it's coming from a string input by the user, the class name is unknown at compile time.

I also want this to work universally, on any MonoBehaviour, not just ones I've specially instrumented or registered with the console system.

Is there a way to find instances of a type with a particular name, and call methods on them, using something like reflection?


texts: RK4 integration and Continuous Collision Detection

texts: I'm using this method to detect collision between two AABBs. The algorithm is simple, fast and works great. It uses the relative velocity between the two objects to calculate TOI. This works fine with Euler, but now i'm trying to switch to RK4, which makes it hard for me to determine the TOI since i can't just divide the distance between the two AABBs by their relative velocity. Since RK4 is so popular, how do people deal with this issue? How to calculate a TOI for a swept AABB with RK4?


texts:
I have my player's animation controller managing two simple states: idle-walk.
States are switched via bools and everything works fine aside from the fact that the idle state doesn't render the first run of the animation loop.

To make it more clear when I start the game, in the animator I see the idle animation properly starting immediately (the azure bar loads immediately) but the player gets actually animated only after the first run of the animation, and the same goes when exiting the walk animation back to idle.

This is the animation structure, that very first idle cycle run in the controller but the player actually stands still...

Here's the function that move the player and set relative bools for animation switching:

public void MovePlayer(float horizontalInput)
{

    bool onEdge = playerTransform.position.x <= -2.5f || playerTransform.position.x >= 2.5f;
    float animSpeed = Mathf.Clamp(Mathf.Abs(horizontalInput) * 1f, 0.5f, 1f);
    anim.SetFloat("movingSpeed", animSpeed);

    if(horizontalInput < -0.2f && !onEdge)
        anim.SetBool("movingL", true);
    else if (horizontalInput > 0.2f && !onEdge)
        anim.SetBool("movingR", true);
    else
    {
        anim.SetBool("movingL", false);
        anim.SetBool("movingR", false);
    }

    nextPosX = Mathf.Clamp(playerTransform.position.x + (horizontalInput * playerSpeed * Time.deltaTime), -2.5f, 2.5f);

    playerTransform.position = new Vector2(nextPosX, 0);
}

The movingL/R bools are set true when the horizontal input pass a certain threshold and are set to false (back to idle) under that threshold. Hope this is clear enough...


texts: Lightmapped prefabs for procedural content

texts:
I'm doing a game with procedural content from handmade prefabs, but I ran into a problem as Unity bakes the scene instead of objects when lightmapping with Beast. So when the prefabs are instanced they are without lightmaps.

Is there a way to get lightmaps for dynamically created prefabs with Unity's built-in lightmapper?


texts: D3D11/C++ Inaccuracies in uv interpolation in pixel shader. How to avoid?

texts:
I'm trying to draw a quad with a texture onto the screen such that texels and pixels perfectly align. Sounds pretty easy. I draw 2 triangles (as TRIANGLE_LIST, so 6 vertices) using these shaders:

struct VSOutput
{
    float4 position     : SV_POSITION;
    float2 uv           : TEXCOORD0;
};

VSOutput VS_Draw(uint index : SV_VertexId)
{
    uint vertexIndex = index % 6;
    // compute face in [0,0]-[1,1] space
    float2 vertex = 0;
    switch (vertexIndex)
    {
        case 0: vertex = float2(0, 0);  break;
        case 1: vertex = float2(1, 0);  break;
        case 2: vertex = float2(0, 1);  break;
        case 3: vertex = float2(0, 1);  break;
        case 4: vertex = float2(1, 0);  break;
        case 5: vertex = float2(1, 1);  break;
    }
    // compute uv
    float2 uv = vertex;
    // scale to size
    vertex = vertex * (float2)outputSize;
    vertex = vertex + topLeftPos;
    // convert to screen space
    VSOutput output;
    output.position = float4(vertex / (float2)outputSize * float2(2.0f, -2.0f) + float2(-1.0f, 1.0f), 0, 1);
    output.uv = uv;
    return output;
}

float4 PS_Draw(VSOutput input) : SV_TARGET
{
    uint2 pixelPos = (uint2)(input.uv * (float2)outputSize);
    // output checker of 4x4
    return (((pixelPos.x >> 2) & 1) ^ ((pixelPos.y >> 2) & 1) != 0) ? float4(0, 1, 1, 0) : float4(1, 1, 0, 0);
}

where outputSize and topLeftPos are constants and expressed in pixel units.

Now for outputSize = (102,12) and topLeftPos = (0,0) I get (what I would expect):

But for outputSize = (102,12) and topLeftPos = (0,0.5) I get:

As you can see there is a uv-discontinuity where the two triangles connect and interpolation of uv is inaccurate. This basically happens (in x and y) only at positions around the .5 (actually below .49 it correctly snaps to texel 0 and above .51 it snaps correctly to texel 1, but in between I get this artifact).

Now for the purpose I need this for it is essential to have pixel perfect mapping.
Can anyone enlighten me why this happens?


texts: problem loading Collada DAE model using Assimp in OepnGL 4.4

texts:
I am loading a model in my OpenGL application using Assimp library like this :

bool CGameObject::LoadModelFromFile(char* sZFilePath)
{
std::string fn = sZFilePath;
std::string td = "\\";
std::string mfn = _getcwd(NULL, 0) + td + fn;
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(mfn,
    aiProcess_CalcTangentSpace      |
    aiProcess_Triangulate           |
    aiProcess_JoinIdenticalVertices |
    aiProcess_SortByPType);

if (!scene) {
    return false;
}

const int iVertexTotalSize = sizeof(aiVector3D) * 2 + sizeof(aiVector2D);
int iTotalVertices = 0;

for(UINT i = 0; i < scene->mNumMeshes; i++) {
    aiMesh* mesh = scene->mMeshes[i];
    int iMeshFaces = mesh->mNumFaces;
    for (UINT f = 0; f <iMeshFaces; f++) {
        const aiFace* face = &mesh->mFaces[f];
        for (UINT k = 0; k < 3; k++) {
            aiVector3D pos = mesh->mVertices[face->mIndices[k]];
            Model.vertices.push_back(pos.x);
            Model.vertices.push_back(pos.y);
            Model.vertices.push_back(pos.z);
        }
    }
}

// VAO
glGenVertexArrays(1, &m_vao);
glBindVertexArray(m_vao);

// VBO
glGenBuffers(1, &m_vbo);
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
glBufferData(GL_ARRAY_BUFFER, this->Model.vertices.size() * sizeof(GLfloat), &this->Model.vertices[0], GL_STATIC_DRAW);
glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);

// unbind buffers
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);

// return success when everything is loaded
return true;
}

and then render it like this :

for (GameObject::iterator i = GameObjects.begin(); i != GameObjects.end(); ++i)
{
    CGameObject* pObj = *i;
    glUniformMatrix4fv(MatrixID, 1, GL_FALSE, GetMVPMatrix(pObj->position));

    glBindVertexArray(pObj->m_vao);
    glVertexAttrib3f((GLuint)1, 1.0, 0.0, 0.0); // set constant color attribute
    glDrawArrays(GL_TRIANGLES, 0, pObj->Model.vertices.size());

}
.
.
.

// function used to set MVP matrix
GLfloat* GetMVPMatrix(glm::vec3 position)
{
glm::mat4 Model = glm::translate(mat4(1.0), position);
glm::mat4 MVP3 = Projection * View * Model;
return &MVP3[0][0];
}

I created and exported my model using Blender. if I use OBJ format then it is rendered correctly :

but with DAE format it is like this :

My model has 5 meshes and debugging in Visual Studio shows that all 5 meshes are loaded.

Loading the DAE file in assimp_viewer shows the model file has been exported correctly :

Where am i doing it wrong ?


texts:
So I had this idea of creating a 2D game where the player would just climb a tower the furthest he could.

I do already have a camera and a scene class somewhat ready, but I'm not sure how I would add the side sprites and make it so I dont use all the memory on the 10th update.
Could anyone please shed some light on this?


texts: Sprite disappears after adding a material to it

texts:
I have background which is FirsLayer, order in layer 0 and platform over it which is FirstLayer, order in layer 1.

Once I add a material to the platform, the layer doesn't seem to change but it gets rendered behind the background.

The material that I add:

1)Why do I get such results?

2) How can I add the material to the platform and still keep it above the background?

P.S. For further clarification if somebody didn't understand, I expected the sprite to stay on its original position(i.e. not to go behind the background when a material is being added to it)


texts: Designing generic render/graphics component in C++?

texts:
I'm trying to learn more about Component Entity systems. So I decided to write a Tetris clone. I'm using the "style" of component-entity system where the Entity is just a bag of Components, the Components are just data, a Node is a set of Components needed to accomplish something, and a System is a set of methods that operates on a Node. All of my components inherit from a basic IComponent interface.

I'm trying to figure out how to design the Render/Graphics/Drawable Components. Originally, I was going to use SFML, and everything was going to be good. However, as this is an experimental system, I got the idea of being able to change out the render library at will. I thought that since the Rendering would be fairly componentized, this should be doable. However, I'm having problems figuring out how I would design a common Interface for the different types of Render Components. Should I be using C++ Template types?

It seems that having the RenderComponent somehow return it's own mesh/sprite/whatever to the RenderSystem would be the simplest, but would be difficult to generalize. However, letting the RenderComponent just hold on to data about what it would render would make it hard to re-use this component for different renderable objects (background, falling piece, field of already fallen blocks, etc).

I realize this is fairly over-engineered for a regular Tetris clone, but I'm trying to learn about component entity systems and making interchangeable components. It's just that rendering seems to be the hardest to split out for me.


texts: I have BoxCollider2D and EdgeCollider2D how can I make the BoxCollider2D bounce only from the EdgeCollider2D and only once?


texts:
I have an problem where I instantiate a GameObject and it keeps on instantiating a million times over, even though I put the line of code under the start function.

I am trying to have the player collide with the coin(then a point is added to your score) , then the coin deletes itself and then re-instantiates at a random coordinate, but I cant get past the initial instantiation.

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

public class Coin : MonoBehaviour {
public GameObject coins;
Vector2 randomPosition;
public UIScript _UIScript;

// Use this for initialization
void Start () {
    _UIScript = GameObject.FindWithTag("UI").GetComponent<UIScript>();
    randomPosition = new Vector2(Random.Range(-8f, 8), Random.Range(-4f, 4f));
    Instantiate(coins, randomPosition, Quaternion.identity);
}

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

}
private void OnTriggerEnter2D(Collider2D coinCollision)
{
    switch(coinCollision.tag)
    {
            case "Player":
            collisionWithPlayer();
            break;
    }
}
private void collisionWithPlayer()
{
    _UIScript.highScore = _UIScript.highScore + 1;
    Object.Destroy(coins);
}
}


texts:
I am using Ogre for my rendering engine, and I planned on just using the .mesh format that is setup by default with Ogre. However, I recently purchased a large number of 3d assets from a company, only to find out that they use 7 blend weights where as Ogre has a max limit of 4.

I don't know much about modeling and animation (which is why I purchased the art) but just from thinking, it is probably fairly difficult to change something like this in the model without having to reanimate it.

So this led me to think about a custom model format. I know the basics of what is stored, verts/polygons/etc, but I am wondering if this is something I am right in thinking I probably need to do? If so, are there any good resources on developing a custom model format? Tutorials/samples/anything would be great. So far all I have found is http://www.falloutsoftware.com/tutorials/gl/gl6.htm which is helpful but not complete.


texts: How do I implement a subclass of CCSprite?

texts:
Can someone tell me how to subclass CCSprite on Android?

I've added this snippet of code into my CharacterSprite:

public static CharacterSprite sprite(String fileName) {
  return new (CharacterSprite)CCSprite(
    CCTextureCache.sharedTextureCache().getTexture(fileName)
  );
}

But getTexture() can't be found. Can someone help me please?


texts:
I have a shader which uses multiple passes to determine the thickness of an object at each point. I want to use this thickness value in order to sample from a texture, which will determine the color of the screen at that point. However, since the calculation is performed in two passes, I don't have any way to access the one value which results at the end, which is what I would be using to index the uv for the texture.
Thanks for any help in advance!

{
Properties
{
    _MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
    Pass
    {
        Cull Back ZWrite On ZTest Always
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag

        #include "UnityCG.cginc"

        struct appdata
        {
            float4 vertex : POSITION;
            float3 normal : NORMAL;
        };

        struct v2f
        {
            float2 depth : DEPTH;
            float4 vertex : SV_POSITION;
        };

        v2f vert (appdata v)
        {
            v2f o;
            o.vertex = UnityObjectToClipPos(v.vertex);
            o.depth = -UnityObjectToViewPos(v.vertex).z * 200 * _ProjectionParams.w;
            return o;
        }

        sampler2D _MainTex;

        fixed4 frag (v2f i) : SV_Target
        {
            float c=1-i.depth;
            fixed4 col = fixed4(c,c,c,1);
            return col;
        }
        ENDCG
    }
    Pass
    {
        Cull Front ZWrite On ZTest Always
        BlendOp RevSub
        Blend One One
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag

        #include "UnityCG.cginc"

        struct appdata
        {
            float4 vertex : POSITION;
        };

        struct v2f
        {
            float2 depth : DEPTH;
            float4 vertex : SV_POSITION;
        };

        v2f vert (appdata v)
        {
            v2f o;
            o.vertex = UnityObjectToClipPos(v.vertex);
            o.depth = -UnityObjectToViewPos(v.vertex).z * 200* _ProjectionParams.w;
            return o;
        }

        sampler2D _MainTex;

        fixed4 frag (v2f i) : SV_Target
        {
            float c = 1-i.depth;
            //fixed4 col = tex2D(_MainTex,c.xx);
            fixed4 col = fixed4(c,c,c,1);
            return col;
        }
        ENDCG
    }
}
}


texts: Structure of Visual C++ Projects in Visual Studio

texts:
In particular, I was wondering if it was possible for Visual Studio to treat source files in different directories as all in the same directory. I first saw this after purchasing the Introversion Software Humble Bundle which gave people access to their source code for their previous games from Subversion. I noticed with one of their games that it was split into physical folders for different parts (like "\world", "\lib", ect.), but in Visual Studio the files were put into filters with the same names as the physical folder and all of the files were treated as if they were in the base directory. I also noticed that they included files in the VS project that weren't even in the base project folder. This is what I mean:

Things like the \data folder are included with the folders from \source, even though they are in different directories and levels.

What I also want to know is how to go about including folders and files from different locations and treat them all like they are all in the same place. But most of all, I would like to figure out how they made all source files act like they were all in the base folder, instead of the separate physical folder that they are, as shown by the #includes in the files:

Image Here

As you can see, the app.h/.cpp files are in the "\app" folder, but the includes are able to reference things from "\lib" without including "..\lib" to go up a folder, effectively treating all of the source files like they originate in the base folder.

TL;DR: How does one include multiple folders from different places as filters, and how do you treat all source files like they originate from the same place.

Any help is greatly appreciated, as this will help me organize my project better.
Thanks.


texts: In Unity, can I make a GameObject within a prefab disabled by default?

texts:
If I create a simple object hierarchy in my scene...

-ExampleGameObject
--Child1 [is active]
--Child2 [is not active]

...how can I accurately store this as a prefab? If I drag ExampleGameObject to a new prefab, then instantiate that prefab, both Child1 and Child2 will be active, which isn't what I want.


texts: My crossword is a table made with <td> tags. The input boxes are textboxes (input="text"), styled with CSS. My question is how do you get the focus to the next cell/textbox by using the keyboard arrows. (Up, down, right, left, and backspace)


texts: Libgdx Resizing Textures for Different Platforms

texts:
I'm using viewports to handle different screen resolutions to support multiple platforms (desktop, android, etc.) in my libgdx powered game. I made all image assets for Full HD resolution and thought it will be easy to scale down them for lower screen resolutions. The thing is when I resize them (scale up or down) they are pixelated very badly. I tried to use TextureFilter.Linear and TextureFilter.MipMapLinearLinear (enabled mipmaps). The result is still not satisfying. Then I came across this post made by an administrator on libgdx forums:

http://badlogicgames.com/forum/viewtopic.php?p=107267#p107267

He says it scales the texture 60 times a second.

1-) Does it really gets scaled 60 times a second? If so why isn't it scaled only one time at program start? How can i do this?

2-) Since all games which support multiple platforms somehow need to achieve the rescaling, what is the best way to do it? My image editor program can resize it without pixelating so I think there should be a way.


texts: Upgrading Unity from 5.1 to 5.3.4 has broken game, specifically models made in Blender

texts:
I recently decided to upgrade Unity after putting it off for some time as I have a rather sizable project started in 5.1.  I knew there would be some hurdles, however, I have had very little luck in getting the game back up and running in the new version.  My Blender model animations seem to be gone and many of the faces are disappearing.  For example a characters arm is just missing and other similar issues across models.  The warning I'm getting seems to be due, at least in part, to a shader I'm using attached to a prefab, however, when I change it to even the standard shader Im still getting the warnings and the issues persist.

My question is:  Is there something I'm missing in the upgrade process that can make the transition easier, because right now, it would seem I need to recreate all of my Blender assets and reassign all of my materials and not be able to use some of my shaders?

The process in which I upgraded was very simple.  I just opened the project folder with the new version of Unity and rebuilt the project for the new version.

Any help from anyone who has experience migrating projects between different versions of Unity would be appreciated.