texts: Texture mapping artifacts on certain surfaces

texts:
I am currently working on a 3d game engine, but am complete stumped on a problem involving texture rendering. Here is the rundown.

My game engine renders meshes of the OBJ wavefront type. I have created a OBJ mesh parser that simply looks through all the vertice/normal/texture indexes(Line by Line) and loads the corresponding data into the right places without altering it.

Mesh Parser Code: (NOTE pseudo codeish)

MY VERTEX STRUCTURE:
    struct VERTEX
    { D3DXVECTOR3 Pos; D3DXVECTOR3 Normal; D3DXVECTOR2 TexCoords; };

    if (line[i]->c_str()[0] == 'v' && line[i]->c_str()[1] == ' ') {

        float tmpx = 0;
        float tmpy = 0;
        float tmpz = 0;

        sscanf(line[i]->c_str(), "v %f %f %f", &tmpx, &tmpy, &tmpz);

        D3DXVECTOR3 myVec = {tmpx, tmpy, tmpz };

        vertices.push_back(myVec);

    }
    else if (line[i]->c_str()[0] == 'v' && line[i]->c_str()[1] == 't') {

        float tmpx = 0;
        float tmpy = 0;

        sscanf(line[i]->c_str(), "vt %f %f", &tmpx, &tmpy);

        D3DXVECTOR2 myTexCoords = { tmpx, tmpy };

        texCoords.push_back(myTexCoords);
    }
    else if (line[i]->c_str()[0] == 'v' && line[i]->c_str()[1] == 'n') {

        float tmpx = 0;
        float tmpy = 0;
        float tmpz = 0;

        sscanf(line[i]->c_str(), "vn %f %f %f", &tmpx, &tmpy, &tmpz);

        D3DXVECTOR3 myNorm = { tmpx, tmpy, tmpz };

        normals.push_back(myNorm);

    }

            sscanf(line[i]->c_str(), "f %d/%d/%d %d/%d/%d %d/%d/%d %d/%d/%d",
            &tmpindices1, &tmpTexCoordsIndex1, &tmpNormalsIndex1,
            &tmpindices2, &tmpTexCoordsIndex2, &tmpNormalsIndex2,
            &tmpindices3, &tmpTexCoordsIndex3, &tmpNormalsIndex3,
            &tmpindices4, &tmpTexCoordsIndex4, &tmpNormalsIndex4);

            verticeIndex.push_back(tmpindices1 - 1);
            verticeIndex.push_back(tmpindices2 - 1);
            verticeIndex.push_back(tmpindices3 - 1);
            verticeIndex.push_back(tmpindices4 - 1);

            texCoordsIndex.push_back(tmpTexCoordsIndex1 - 1);
            texCoordsIndex.push_back(tmpTexCoordsIndex2 - 1);
            texCoordsIndex.push_back(tmpTexCoordsIndex3 - 1);
            texCoordsIndex.push_back(tmpTexCoordsIndex4 - 1);

            normalsIndex.push_back(tmpNormalsIndex1 - 1);
            normalsIndex.push_back(tmpNormalsIndex2 - 1);
            normalsIndex.push_back(tmpNormalsIndex3 - 1);
            normalsIndex.push_back(tmpNormalsIndex4 - 1);

for (int i = 0; i < texCoordsIndex.size(); i++) {
    ModelToFill.Vertices[i].TexCoords = texCoords.at(texCoordsIndex.at(i));
}

for (int i = 0; i < normalsIndex.size(); i++) {
    ModelToFill.Vertices[i].Normal = normals.at(normalsIndex.at(i));
}

for (int i = 0; i < vertices.size(); i++) {
    ModelToFill.Vertices[i].Pos = vertices.at(i);
}

for (int i = 0; i < verticeIndex.size(); i++) {
    ModelToFill.Indices[i] = verticeIndex.at(i);
}

But now when my renderer renders the mesh it looks like this:

As You can see the texture coordinates are all messed up, (for some surfaces). The Bottom, Leftmost and back are messed up but the front and top are fine.

Now I should mention that my mesh is exported from blender with materials, and the mesh is also triangulated. Before importing I also performed the smart UV unwrap.

Finally, I should mention that the parts of the mesh which are not texture mapped correctly vary depending on the mesh.

MY QUESTION though quite general: What is the most probable cause of this issue, the mesh parser, form of blender mesh exporting, or renderer.


texts: Unity LineRenderer custom reapeted Texture with margin

texts:
I have a LineRenderer, which has 1 dot as texture, which is repeated over the whole line. Now I want to know, if there is some way to give this dots a margin, so that I can make the gap between them bigger.

For the moment there is no gap, I could make a new Texture and add the margin there, but I hope for some more dynamic way to do this.

Edit: Inspector View :


texts: How do I create tileable 3D Perlin/Simplex noise?

texts:
I have a library which provides functions for 1/2/3/4-D simplex noise. With that I successfuly created a tileable 2D cloud texture (see How do you generate tileable Perlin noise?).
Now I want to create a tileable 3D cloud volume. It only has to be tileable in 2 dimension of course.

How can I achieve this? Do I need higher dimension than 4D noise?


texts:
In my XNA-4.0-game (which somehow is a bit like MineCraft), I have got some big cubes with small textures (16x16px) on it. By default, XNA just scales them up smooth so there aren't any hard borders. But as the game is a retro game, I want these big pixels.
So how do I turn of that interpolation?


texts: C# Unity - Getting which function affects a GameObject

texts:
I have this little code that moves a GameObject over time:
 public void Move(Transform from, Transform to, float overTime)
     {
         StartCoroutine(_Move(from, to, overTime));
     }
     IEnumerator _Move(Transform from, Transform to, float overTime)
     {
         Vector2 original = from.position;
         float timer = 0.0f;
         while (timer < overTime)
         {
             float step = Vector2.Distance(original, to.position) * (Time.deltaTime / overTime);
             from.position = Vector2.MoveTowards(from.position, to.position, step);
             timer += Time.deltaTime;
             yield return null;
         }
     }

Which is easy as it is, I plan to use it for UI animations. However, things get interesting when I wish to use this for a bit more complex animations, or I want it to stop upon restart.
More complex animations:
I click a button which then moves to the side and bounches back. For this I need to know when the exact same method finished moving the button so I can restart it to bounce back.
Stop upon restart:
Say I hover my mouse over a button which moves then. However, if it's still moving, I want its current animation to stop, and a new one to start. For both of these I need to know which function affects which GameObject so I can manage that. Question is, how? Shall I use one script on each of the animated components which affects only that one? Or if I could use only one script on the whole Canvas, then how?


texts: Add logic if Shift is pressed nothing to do if not speed=100 to my BP

texts: I have followed tutorial on how to make 3rd person game but I cant figure out how to implement logic if Shift is pressed nothing to do and if its not set speed to be some value lets say 100


texts: Tried and true basic movement physics (jumping, not walking through stuff)?

texts:
If I sat down long enough, I'm sure I could make this happen, but I don't want to reinvent the wheel if I don't have to, especially if XNA has patterns in place for doing this.

For now, I'm working in a very low resolution world, minecraft style. Everything is a simple cube that's 1x1x1. Currently I can move and look around but the camera is floating above the cubes, it doesn't use the cubes to determine where the camera is or where the camera should not be.

I'm just looking for the simplest of physics, such as not walking through blocks, if I walk off a cliff the character (camera) should fall and land the proper height above the ground, and general movement physics that you would expect out of even the most basic of games.

My first approach was to have a BoundingSphere for the character and a BoundingBox on each cube but when I detect a collision between the sphere and any box, how do I correct the character's placement to not intersect anymore?

I'm open to any alternatives and techniques that are out there.


texts:
I'm trying to draw a bunch of translucent circles on a Swing JComponent. This isn't exactly fast, and I was wondering if there is a way to speed it up. My custom JComponent has the following paintComponent method:

public void paintComponent(Graphics g) {
    Rectangle view = g.getClipBounds();

    VolatileImage image = createVolatileImage(view.width, view.height);
    Graphics2D buffer = image.createGraphics();
    // translate to camera location
    buffer.translate(-cx, -cy);
    // renderables contains all currently visible objects
    for(Renderable r : renderables) {
        r.paint(buffer);
    }
    g.drawImage(image.getSnapshot(), view.x, view.y, this);
}

The paint method of my circles is as follows:

public void paint(Graphics2D graphics) {
    graphics.setPaint(paint);
    graphics.fillOval(x, y, radius, radius);
}

The paint is just an rgba color with a < 255:

Color(int r, int g, int b, int a)

It works fast enough for opaque objects, but is there a simple way to speed this up for translucent ones?


texts: How do I calculate the x,y of the rectangle after rotating?

texts:
I'm using SDL2. I want to draw a textured rectangle and I'd like it rotated so I'm using SDL_RenderCopyEx. However SDL2 doesn't give me the option of repeating texture so I need to manually do it myself. The problem is I have no idea how to do the math.
My texture us 20x20, so I make the rects 20x20, I chosen a fixed angle of 45, my rotation point is 10,5 which appears to make the left middle of the rect the point it rotates from. I can see the two rects aren't touching if the second rect is (firstX+15,firstY+15). However if I change one of them to 14 they touch and it looks solid
I don't understand how to find the numbers. I'm finding the angle but doing
double angle = atan2(mouseX - x, mouseY - y) * 180 / PI;

Making the second rect relative to the first by +15,+14 only works if it's a 45 deg angle but is complete wrong for other angles.
How do I figure out the x,y the subsequent rect based on the angle?


texts:
I know this isn't a "Is this legal" website, but because Marching Cubes is definitely a large subject in game development, and isn't really about a specific graphic/item, it would pass...

To the point!

Does anyone know whether Marching Cubes is allowed in a commercial game? If so is there anything i must do? Credit to someone/company etc?

Cheers.


texts: How do I make a sprite fire a bullet in a direction using SFML and C++?

texts: I'm learning game programming for the first time using sfml and c++. I have sucessfully animated my sprite in all four directions watching some video tutorials. But now i want my sprite to fire in a facing direction. I just want to do it a very basic way. It would be great if i could get some idea of it. I am using xcode 7.


texts: GLSL - Stretched vertices after translating

texts:
I'm trying to translate 3D object in my game engine.
I copied all formulas from my old, working game engine, where translation was working.

When I set position and rotation to 0, everything looks to be fine, but when I try to change position of my 3D object, something strange happens.
I'm not sure if it is projection matrix issue, or maybe transform matrix issue.

Position: x = 0, y = 0, z = 0
Rotation: x = 0, y = 0, z = 0

Position: x = 0, y = 0, z = 0
Rotation: x = 0, y = 45.0, z = 0

Position: x = 1.5, y = 0, z = 0
Rotation: x = 0, y = 0, z = 0

Position: x = 3.5, y = 0, z = 0
Rotation: x = 0, y = 0, z = 0

I checked all formulas once again, checked transformation matrix output, projection matrix output, and everything seems to be fine.

Here is my vertex shader:

#version 400

in vec3 position;

uniform mat4 transformationMatrix;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;

void main(void)
{
  gl_Position = projectionMatrix * viewMatrix * transformationMatrix * vec4(position,1.0);
}

and fragment shader:

#version 400

uniform vec2 textureVec;

layout(location = 0) out vec3 out_Diffuse;
layout(location = 1) out vec3 out_Texture;

void main(void)
{
  out_Diffuse = vec3(0.5, 0.5, 0.5);
  out_Texture = vec3(textureVec, 0.0);
}

Projection matrix formula:

  float aspectRatio = static_cast<float>(windowSize.x) / static_cast<float>(windowSize.y);
  float yScale = static_cast<float>((1.0f / tanf(MathUtil::degToRad(fov / 2.0f))));
  float xScale = yScale / aspectRatio;
  float frustumLen = farPlane - nearPlane;

  projectionMatrix.m00 = xScale;
  projectionMatrix.m11 = yScale;
  projectionMatrix.m22 = -((farPlane + nearPlane) / frustumLen);
  projectionMatrix.m23 = -1.0f;
  projectionMatrix.m32 = -((2.0f * nearPlane * farPlane) / frustumLen);
  projectionMatrix.m33 = 0.0f;

View matrix formula:

  viewMatrix.setIdentity();
  viewMatrix.rotate(Vector3(1.0f, 0.0f, 0.0f), MathUtil::degToRad(transformComponent->rotation.x));
  viewMatrix.rotate(Vector3(0.0f, 1.0f, 0.0f), MathUtil::degToRad(transformComponent->rotation.y));
  viewMatrix.scale(Vector3(1.0f, -1.0f, 1.0f));

  Vector3 negativeCam = Vector3::negate(transformComponent->position);

  viewMatrix.translate(negativeCam);

And transformation matrix formula:

  transformationMatrix.setIdentity();

  transformationMatrix.translate(position);
  transformationMatrix.rotate(Vector3(1.0f, 0.0f, 0.0f), MathUtil::degToRad(rotation.x));
  transformationMatrix.rotate(Vector3(0.0f, 1.0f, 0.0f), MathUtil::degToRad(rotation.y));
  transformationMatrix.rotate(Vector3(0.0f, 0.0f, 1.0f), MathUtil::degToRad(rotation.z));
  transformationMatrix.scale(scale);

Same happens for "y" and "z" position axis, but object "rotates" in different axis.

I also checked my VAO loader, vertices, uniform values loader, and everything else.
If you need more code, let me know.


texts: Why don't game developers change game stories after launch?

texts:
Game developers have shown willing to remove and add game features, change art assets and remake parts of their games in following updates, but why don't they ever change the plot? Some times parts are added to the story, but only as attachments, never revisions.

Why is plot thought as a feature beyond editing, even if it would enhance player experience just as much as any graphical update or gameplay tweak?

P.S.: I would like to ask for a game-narrative/writing/story tag, and they are just as important part of game development as game mechanics.

P.S.²: This is as broad a question as why not to release source code. Therefore I think it is not too broad for answering.


texts: what should the size of a flash game in Facebook be

texts:
I'm developing a flash game and i want to put it in Facebook
,My question is the Proper maximum  size for it.
500 KB
1 MB ??


texts: Current state of the art for rendering large numbers of dynamic lights?

texts:
This is intended as a platform-agnostic question, but I currently use OpenGL (with sights on Vulkan) if it is relevant.
The last time I dealt with creating lots of dynamic lights (~10 years ago), the best option was deferred rendering. Which works, but you have all of the problems that come with it (no MSAA, transparency is difficult, G-Buffer size, etc.).
These days, it appears that the industry is moving away from deferred rendering. I've seen mention of clustered forward rendering, more recently there's some sort of voxelized rendering? And then the new stuff, UE5 using some form of software rasterization, and id Tech 7 using some form of forward rendering with per-pixel rejection.
At this point I don't know what the differences are, what to pursue, and what is limited to specific highly-optimized scenarios.
Are there any resources for getting up to speed on the current techniques? Is there a current "best" or recommended technique for modern hardware for rendering large numbers of dynamic lights?


texts: How can I reverse the effect of a transformation matrix?

texts:
I have recently been working on a game with using OpenGL and C++ through GLFW.

In the game I have an airship with a turret mounted on it. The airship moves around in world space coordinates and the turret 'follows' it.

The turret has it's own coordinate space for its look/aim direction. Basically, when the turret aims in direction (0,0,1), it aims parallel to the airships direction of movement.

To give the turret a world space target, I have a matrix that takes world space coordinates and transforms these to turret space coordinates.

As the turret fires, I want it to spawn projectiles in world space, so is there an elegant way of using my transformation matrix to convert turret space coordinates back to world space?

A more general way of asking the question might be: if I have a matrix M that takes coordinates from space A to space B. Is there an easy way to use M to get the coordinates from B to A?


texts: Any way to set up a grid for a board game in cocos 2d?

texts: My first idea was to create a 2d array for my columns and rows, but it seems like there should be a better, or possibly cleaner, way to achieve this. Each square on the grid is going to have a background image, probably a .png although I might just draw the images with a draw method. Basically, I want to be able to drag and drop images onto the individual grid squares. I've been searching for a solution and the closest thing I can find is the tiled map solution. That just seems like a little overkill for what I'm trying to accomplish. Also, I don't know if this helps but i need my grid to be 12 by 12 and take up the entire width of the iphone screen.


texts: Setting up 3d Collision for Primitive shapes

texts: Im having some trouble understanding how to set up collision detection between my first person camera and my primitive shapes which are made using the vertex buffer. Do i give my camera a boundingBox and all my objects a boundingbox then add them to a list and check the list for collsions or is there a better more understanding way to do this. My game is literally a maze game so all i really need is my camera to accept collisions against the primitive objects. Thanks in advance.


texts: How to load background image in sprite class in libgdx?

texts:
How can I insert a background image in sprite class?
here is my code..Thank's and advance

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;

public class Sprite implements ApplicationListener {
// Constant rows and columns of the sprite sheet
private static final int FRAME_COLS = 5, FRAME_ROWS = 1;
// Objects used
Animation<TextureRegion> walkAnimation; // Must declare frame type (TextureRegion)
Texture walkSheet;
SpriteBatch spriteBatch;

// A variable for tracking elapsed time for the animation
float stateTime;

@Override
public void create() {
    // Load the sprite sheet as a
    walkSheet = new Texture(Gdx.files.internal("cat2.png"));
    // Use the split utility method to create a 2D array of TextureRegions. This is
    // possible because this sprite sheet contains frames of equal size and they are
    // all aligned.
    TextureRegion[][] tmp = TextureRegion.split(walkSheet,
            walkSheet.getWidth() / FRAME_COLS,
            walkSheet.getHeight() / FRAME_ROWS);

    // Place the regions into a 1D array in the correct order, starting from the top
    // left, going across first. The Animation constructor requires a 1D array.

    TextureRegion[] walkFrames = new TextureRegion[FRAME_COLS * FRAME_ROWS];
    int index = 0;
    for (int i = 0; i < FRAME_ROWS; i++) {
        for (int j = 0; j < FRAME_COLS; j++) {
            walkFrames[index++] = tmp[i][j];
        }
    }
    // Initialize the Animation with the frame interval and array of frames
    walkAnimation = new Animation<TextureRegion>(0.075f, walkFrames);

    // Instantiate a SpriteBatch for drawing and reset the elapsed animation
    // time to 0
    spriteBatch = new SpriteBatch();
    stateTime = 0f;
}

@Override
public void resize(int width, int height) {

}
@Override
public void render() {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Clear screen
    stateTime += Gdx.graphics.getDeltaTime(); // Accumulate elapsed animation time

    // Get current frame of animation for the current stateTime
    TextureRegion currentFrame = walkAnimation.getKeyFrame(stateTime, true);
    spriteBatch.begin();
    spriteBatch.draw(currentFrame, 50, 50); // Draw current frame at (50, 50)
    spriteBatch.end();

}

@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void dispose() { // SpriteBatches and Textures must always be disposed
    spriteBatch.dispose();
    walkSheet.dispose();
}

}


texts: I would like to create a bird simulation that will use its wings to interact with the surrounding air. How can I achieve this?


texts:
I am beginner in android game development. I want my game to run only in landscape fullscreen mode (currently I have Optimus 2X with resolution 800x480 in landscape), and I don't know how to set it.

I found the fullscreen mode settings, and tried some landscape mod (set orientation:landscape in AndroidManifest), but the game is now crashing and its very unstable (eg. when i change phone orientation).

So is there any way to do that?


texts:
How to change A* work so that the path is more like a straight Euclidean distance? I read that you need to break some nodes, but how to implement this?

I need heuristic like this:

Is such a heuristic possible taking into account some obstacles on the map?


texts: When should I use color keying vs PNG transparency?

texts:
SDL (and other toolkits) can use color keying to make a certain color in an image transparent.  Alternatively, you could load a PNG image that supports transparency.

When should I use which?


texts: Find a specific child object in a prefab overrides list

texts:
When I select a prefab in the Inspector and open the Overrides drop-down menu, how can I find the particular child object I want to revert?
I can't find a filter box where I can type the name, so I don't need to deal with the very long list of objects.


texts: How do you set the target location for a navmesh using a GameObject?

texts:
I am trying to get a GameObject to navigate through a map and get to the exit.  I have created a navmesh for the map and given the player GameObject a navmesh agent. The exit is marked with a empty GameObject. Using the unity manual I made this script and atached it to the player:

function Start ()
{
    var agent: NavMeshAgent = GetComponent.<NavMeshAgent>();
    agent.SetDestination(GameObject.Find("exit"));
}

The porblem is that this script gives the error

"Assets/Scripts/enemy.js(4,29): BCE0017: The best overload for the method 'UnityEngine.NavMeshAgent.SetDestination(UnityEngine.Vector3)' is not compatible with the argument list '(UnityEngine.GameObject)'."

I think is is because unity wants a vector3 but I have given it a GameObject.
How can I get this to work with a game object?


texts:
Anyone please help me .i am working on sneakyjoystick class when i import these class some error are identified they are following :-

use of undeclared identifier 'GL_TEXTURE_COORD_ARRAY'

use of undeclared identifier 'GL_COLOR_ARRAY'


texts:
I have a shader which creates a circle inside of a plane mesh. I would like to get get rid of the parts around the circle, which are the r and b parts of the ALBEDO but I can't seem to figure out how to do it.
The only thing I've managed to find is ALPHA but that changes the transparency of the entire shader and not just parts of it.
shader_type spatial;

float circle(vec2 position, float radius, float feather)
{
    return smoothstep(radius, radius + feather, length(position - vec2(0.5)));
}

void fragment() {
    ALBEDO = vec3(0, circle(UV - vec2(0), 0.5, 0.005), 0);
}

Which currently looks like:


texts: Term for compositing textures according to colors in an index texture mask?

texts:
I have utilized a tool for a number of years that uses a "masking" technique to 'texture' a 2D graphic, by which it checks a series of solid colors to specify where to 'draw' textures in a final render. I have seen one other example of this in my searches on Google, and even that did not explain exactly what was happening or the name of this process. It seems to be used for creating sprites or video game graphics, as the only example I was able to find online was a gamedev postmortem discussing how they applied 'texturing' to some of their sprites. All I can do is show an example using the software I have (Which itself, barely explains what this process is called, just the way it works within the context of the software)

So in this case, the solid colors Black, Gray, Blue, and Green (In the "Mask" window at the bottom left) correspond to where specific textures/colors are going to be drawn in the final Hourglass graphic. There are additional colors available to use in this particular software, but I cannot for the life of me find any other software that does something like this. Let alone the name of the particular "colored mask/index" technique. It is capable of doing several other things by reading the colors in a mask, including rendering textures at angles or curves with the same kind of process.

The company I purchased the software from no longer exists, so there is no way to even contact them about their own software. Any ideas what this is even called? Or does anyone know any alternative way to do something like this?


texts: C# XNA: Effecient mesh building algorithm for voxel based terrain ("top" outside layer only, non-destructible)

texts:
To put this bluntly, for non-destructible/non-constructible voxel style terrain, are generated meshes handled much better than instancing? Is there another method to achieve millions of visible quad faces per scene with ease? If generated meshes per chunk is the way to go, what kind of algorithm might I want to use based on only EVER needing the outer layer rendered?

I'm using 3D Perlin Noise for terrain generation (for overhangs/caves/etc). The layout is fantastic, but even for around 20k visible faces, it's quite slow using instancing (whether it's one big draw call or multiple smaller chunks). I've simplified it to the point of removing non-visible cubes and only having the top faces of my cube-like terrain be rendered, but with 20k quad instances, it's still pretty sluggish (30fps on my machine).

My goal is for the world to be made using quite small cubes. Where multiple games (IE: Minecraft) have the player 1x1 cube in width/length and 2 high, I'm shooting for 6x6 width/length and 9 high. With a lot of advantages as far as gameplay goes, it also means I could quite easily have a single scene with millions of truly visible quads.

So, I have been trying to look into changing my method from instancing to mesh generation on a chunk by chunk basis. Do video cards handle this type of processing better than separate quads/cubes through instancing? What kind of existing algorithms should I be looking into?

I've seen references to marching cubes a few times now, but I haven't spent much time investigating it since I don't know if it's the better route for my situation or not.

I'm also starting to doubt my need of using 3D Perlin noise for terrain generation since I won't want the kind of depth it would seem best at. I just like the idea of overhangs and occasional cave-like structures, but could find no better 'surface only' algorithms to cover that. If anyone has any better suggestions there, feel free to throw them at me too.

Thanks,
Mythics


texts: Z Order in 2D with orthographic projection and texture atlas

texts:
I am working with a 2D game in OpenGL ES and have a question about z-order together with a texture atlas.

I am using an orthographic projection because I want pixel-perfect rendering of 2D sprites, however from what I can determine the draw order is really the only thing that will determine which textures (sprites) appear above or below their neighbors.

That is, the "z-index" is a function of the order in which the textures are drawn as opposed to the z coordinate on the vertex array being drawn.

So.. I have a texture atlas to save binding multiple textures for each draw call but this immediately creates a problem if there is more than one atlas in play.  If I need to draw textures from more than one atlas (typically the case if I have too many sprites to fit in a single atlas of a reasonable size), then I can't maintain a "draw order" across atlases unless I want to bind/unbind the atlas textures more than once.. which kinda defeats the purpose.

Does anyone have any clues as to what the best approach is here?  Currently I'm running under an assumption that I will have to declare different fixed "depths" (e.g foreground, background etc) in my 2D scene and assume that the z-order for sprites at a given depth is the same.  Then I can have as many atlases as I need at each depth and simply draw the depths in order (along with their associated atlases)

I'd love to hear what other people are doing.


texts: Railgun Ruby - is there a documentation?

texts:
I finally found Railgun Ruby on the web and installed it.

But I cannot find any documentations.

Does anyone have played around with it? Does anyone still have a good documentation about it?

I'd like to have a look at what it can do.

Thanks.

Yours, Joern.


texts: When prototyping, how can I more easily explore game behaviour?

texts:
I build indie games myself, but I'm usually out of energy once I've taken a newly developed game to a level where it's possible to play with behavior, so I settle for refinement instead of exploration. With awful results.

(picture from the Intercom blog)

For example, I find that the iteration cycles for tweaking behavior (i.e. linking and restarting a C++ application) are so long that they kill all creativity. I'm building a tool to deal with this.

What other ways exist to quickly explore game behavior? I'm interested in the methodologies used by indie developers as well as larger companies.


texts:
I'm using the following script to force aspect ratio of 16:9:

https://forum.unity.com/threads/force-camera-aspect-ratio-16-9-in-viewport.385541/

It works perfectly. However now my game objects are allowed to move off the edges. The camera of the game is fixed, and never needs to move or scale.

I have changed my code to WorldToViewportPoint for this but half my of character still goes off the edge.

void Update()
 {
     Vector3 pos = cam.WorldToViewportPoint(transform.position);
     pos.x = Mathf.Clamp01(pos.x);
     transform.position = Camera.main.ViewportToWorldPoint(pos);
 }
 private void FixedUpdate()
 {
     Vector3 pos = cam.ScreenToWorldPoint(Input.mousePosition);
     if (pos.x - transform.position.x > 0.5f)
     {
         transform.eulerAngles = new Vector2(0, 180);
         animateOgre(true);
         Vector2 move = new Vector2(1, 0);
         rb.MovePosition((Vector2)transform.position + (move * speed * Time.deltaTime));
     }
     else if (pos.x - transform.position.x < -0.5f)
     {
         transform.eulerAngles = new Vector2(0, 0);
         animateOgre(true);
         Vector2 move = new Vector2(-1, 0);
         rb.MovePosition((Vector2)transform.position + (move * speed * Time.deltaTime));
     }
     else
     {
         animateOgre(false);
     }
 }

My questions are:

How do I allow the whole character to stay within the Viewport?
How can I clamp within the fixed update method rather than making a
seperate update method.
Is there anyway to prevent character from moving when the mouse is
aligned up with the position of the character. Right now I'm using a
hacky solution to find if the x difference is > 0.5. (If i don't do
this the character just moves back and forth when mouse stops)


texts: Using XBox 360 controller in Unity game - game doesn't recognize axis movement

texts:
I have a problem with the usage of XBox controller in Unity game. I connected the controller to the PC and it works fine, I also managed to use it in the game itself - I'm using "A" button to fire and Start to start the game and they work properly. However the game doesn't recognize the x-axis movement. I'm not sure if the problem is in the input settings or my code. This is how the Horizontal movement is defined in the game:

This is the code that handles the movement:

   float x = Input.GetAxis("Horizontal");
        Vector3 newPosition = new Vector3(transform.position.x + x*playerXMoveSpeed, 0, 0);
        newPosition.y = transform.position.y;
        newPosition.z = 0;

        transform.position = Vector3.Lerp(transform.position, newPosition, playerXMoveSpeed * Time.deltaTime);

        var limit = animator.SpriteRenderer.bounds.extents;
        if (transform.position.x - limit.x < leftBorder)
        {
            var capped = transform.position;
            capped.x = leftBorder + limit.x;
            transform.position = capped;
        }
        else if (transform.position.x + limit.x > rightBorder)
        {
            var capped = transform.position;
            capped.x = rightBorder - limit.x;
            transform.position = capped;
        }

        OnMove(gameObject);

All variables are more or less self explanatory, the OnMove is a delegate that just applies the transform to the gameObject in question. The entire code is inside a void method called Move(). That method is called inside an if statement:

if ((Input.GetAxis("Horizontal") != 0.0f || Input.GetButtonDown("Horizontal")) && !IsContinueDisplayed)
        {
            FollowTouch();
        }

Like I said, the game recognizes the other buttons, but not the x-axis, it doesn't move the character. The Input.GetButtonDown is there just so keyboard input would be supported also (and it works properly).
Can you see the problem with this code or settings? Please advise.


texts:
I'm writing a 2D game with some fairly complex off-screen logic, with plenty of room for bugs. My usual habit is to write code with a lot of Asserts in it. When an Assert gets hit I drop into the debugger, have a look around, find and fix the bug. Works for me.

Problem is: how to get Unity Asserts to call into the Visual Studio debugger. So far they just seem to get generate a log message in the Editor Console, and then Unity carries right on as if they didn't matter. What use is that?

There is an 'experimental' option in the Unity VS settings, but it doesn't seem to do anything (good or bad).
Any suggestions? I can think of a couple of really hackish things to try, but surely there must be a right way?

After further experimentation:

Enabling Assert.raiseExceptions (only) makes Unity grind to a halt (instead of carrying on regardless) but otherwise no change. No trap into VS.
Enabling the experimental Exceptions mode (only) causes Unity to crash with a bug check on the first assert failure.
Doing 1+2 is the same as 1 only.

This is VS 2015 in case it matters.


texts: How do you script movement of two or more characters at the same time?

texts:
Its not quite clear how to move 2 characters at the same time from and to fixed positions.  Within the tutorials for RPG Maker MV users are shown how to script the movement of single characters at a time to fixed positions.  In the tutorials, users are also shown how to have multiple characters moving at the same time in random directions or possibly in repeating loops.  However, its not quite clear how to move 2 or more characters at the same time in a one-time scripted manner.

For example, at the start of a conversation, its normal to move the characters to specific screen positions so that they can begin uttering dialogue much like actors on a stage.  However, the only way I know how to do this is moving one character at a time, which you often see in many classic jrpgs.   In the modern age, however we have a lot more tools and resources at our disposal, so it doesn't seem necessary to move them one at a time. Why not just have them move at the same time so the player doesn't have to watch a second or two of rapid sequential movement?

Is there a way to script the movement of 2 characters at the same time to fixed positions so that they can begin speaking cutscene dialog?

How does one script simultaneous movement of characters that is not random or looped?

I don't have enough rep yet to create an rpg maker mv tag.


texts: OpenGL render shapes without texture file

texts:
I currently have beginner knowledge of OpenGL and something doesn't go into my head! How do I create shapes like eg. a triangle with rounded borders. Or a quad with rounded borders. Or some random irregular shape. How is something like that done?

The only thing I could think of is creating an empty texture2D and editing the pixel data per CPU, but is that the way to go or are there better ways to do something like this?


texts:
I am about to purchase quite a few model packs from a website for prototyping my game. In the contract it states that I must protect them as to prevent the public from gaining access to them.

I remember working with the Valve games, they used .gcf (game content file) that basically was an archive of all the content for each game. They packed in sound/materials/models/maps/etc. I figured it might not be a bad idea to develop something similar to this, and just write a small tool to let me add/remove files from it.

Problem is I really have no idea how to go about starting on something like this. I tried Google but I didn't even know what to search for. If anyone has any ideas, links that might be of use, or anything else I would greatly appreciate it.


texts: How can I replicate the color limitations of the NES with an HLSL pixel shader?

texts:
So since 256 color mode is depreciated and no longer supported under Direct3D mode, I got the idea to use a pixel shader instead to simulate the NES palette of all possible colors so that fading objects and whatnot don't have smooth fade outs with alpha channels.  (I know objects couldn't really fade out on the NES, but I have all objects that do fade in and out on a solid black background, which would be possible with palette swapping.  Also, the screen fades in and out when you pause which I know also was possible with palette swapping as it was done in a few Mega Man games.)  Problem is, I know next to nothing about HLSL shaders.

How do I do it?


texts:
I'm working on a deferred renderer and need a bit of help getting normal maps working.
What I've been doing with them so far is just multiplying the normal texture with the object normals (gl_NormalMatrix * gl_Normal). That appears to be wrong.

I just need someone to explain how I can add the normal map the the normal gbuffer.

The offending line:

    vec3 normal = Normal * texture2D(normalTexture, gl_TexCoord[0]).rgb;

Edit: I managed to get it working :)

Solution:

vec3 Normal = normalize(gl_NormalMatrix * gl_Normal);
vec3 Tangent = normalize(gl_NormalMatrix[0]);
vec3 Binormal = normalize(gl_NormalMatrix[1]);
mat3 tangentToWorld = mat3(Tangent.x, Binormal.x, Normal.x,
                           Tangent.y, Binormal.y, Normal.y,
                           Tangent.z, Binormal.z, Normal.z);

and

vec3 normal = (texture2D(normalTexture, gl_TexCoord[0]).rgb * 2.0 - 1.0) * tangentToWorld;


texts: How to create a native windows menu / ribbon for a DirectX 11 app

texts:
I need to create menu items on top of my DX11 windowed app - similar to most windowed applications (File, Edit, etc...). How can I achieve this ? There is a hMenu handle to pass to the DirectX window creation function but I have no idea how to create this object.

Additionnaly I'd like to have 1 or several ribbons under the window menu with icons to trigger functionnality.

EDIT My menu is all good now and I chose to implement a windows ribbon, but I'm still having problems at creating the ribbon. Here is a screenshot of my app. The green color is the Direct3D clear color - I would like my ribbon to display under the menu (and eventually remove the menu after that).

My ribbon code being :

LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    PAINTSTRUCT paintStruct;
    HDC hDC;

    switch (message)
    {
    case WM_CREATE:
    {
        if (!SetupMenus(hwnd)) MessageBox(nullptr, TEXT("Failed to setup GUI."), TEXT("Error"), MB_OK);
    }

    // ...
}

bool SetupMenus(HWND hwnd) {

    // Create the menu
    // ...

    // Create the ribbon
    IUIFramework* pFramework = NULL;
    HRESULT hr = ::CoCreateInstance(CLSID_UIRibbonFramework, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pFramework));
    if (FAILED(hr)) std::cerr << "Fail #1" << std::endl;

    hr = pFramework->Initialize(hwnd, IUIApp);
    if (FAILED(hr)) std::cerr << "Fail #2" << std::endl;
}

outputs Fail #1. Why can't I create the ribbon ?


texts:
I am trying to animate a tilemap using Flixel 2.55. I found this code that apparently enables the use of sprites as tiles.

To my understanding, this loops over the tilemap's graphic and replaces the tile's pixels with the sprite's pixels each time they change. I have implemented the class and it's working, but not completely; the tiles get replaced, but do not animate unless the camera moves. Here's is the relevant part from LevelLoader.as, which only instantiates the AnimatedTilemaps (piece of code from forum) and pushes sprites into an array:

// AnimatedTile is just an extended FlxSprite
private var _waterTop1:AnimatedTile;

// Create ground tilemap
_groundTilemap = new AnimatedTilemap();
_groundTilemap.loadMap(_rawXML.Ground, Assets.OverworldGround, 8, 8);
FlxG.state.add(_groundTilemap);

_waterTop1 = new AnimatedTile(8, 8, Assets.WaterTop, 100);
// .Animate only adds and plays an animation, with a startAtFrame param.
_waterTop1.Animate('run', [0...47], 10, true, 0);

It seems as though the sprites are updating. I tried tracing the update()s, and they are running for both the sprites and the tilemap. The sprites are even changing frames. Using only AnimatedTiles and hard-placing them (giving a x and y) works and animates. What troubles me is that they only update when the camera moves.

I've been stuck on this for a week now. I am also open to other solutions for animating tilemap tiles.


texts: How to implement joints in and impulse based engine

texts: I have been writing a 2D physics engine (for fun and learning) for a while now. I have managed to implement collision detection along with collisions responses with angular impulse and frictional impulse. Right now I want to implement joints so I can use it to build things from ropes to cars. I am having a lot of trouble finding resources on how to do this. I am looking for an impulse based solution as I have been following this https://www.randygaul.net/2013/03/27/game-physics-engine-part-1-impulse-resolution/ which is basically everything on this wikipedia article in a nutshell https://en.wikipedia.org/wiki/Collision_response. I have searched around but can only find people talking about fixed joints or some non impulse based solutions. If someone could explain the theory/implementation or point me in the right direction that would be great.


texts: Mentality for the hard initial stage of game development

texts: I feel like there is a lot of excitement involving the initial steps towards developing games.  Kids (myself younger self included) get very excited about making games and talk for hours about the games in their imaginations.  Then comes the initial game making experience.  A lot can happen there.  It feels like a no-man's land where many enthusiasts fall away.  It seems to me that there are a lot of good, talented people out there who end up stuck in the mud.  Is that just the nature of competition and a necessary hurtle to greatness or should something be done to avoid it?  I feel that experienced game designers with a history of success could offer a lot of help, but then again, sometimes people are punished for our kindness.  However, I feel that having the right mentality would both help a person get through the hard times and make it easer to approach professionals.  Could I get some tips on crafting a positive and effective mentality regarding these issues during the early staged of a game design career?


texts: Jagged array - check if array index is out of range

texts:
Hey I am a bit confused about how to properly check a Jagged array for "index out of range exceptions"

Im quite sure im somehow supposed to use the .Length of the array but it confuses me to read this, because my tiles are of a TileType type (enum):

https://msdn.microsoft.com/en-us/library/system.array.length.aspx

https://stackoverflow.com/questions/37233225/c-sharp-how-can-i-check-if-a-multidimensional-array-has-a-value-and-its-index

https://stackoverflow.com/questions/25562496/how-to-check-if-multidimensional-array-row-contains-non-zero-value

What im doing is creating a grid of tiles and running through them after the fact and setting their values to have a collider (red in this case) if they are in the correct position. In order to do this I have to check the tiles surrounding the one I am currently on. This sometimes, albeit rarely, leads to an index of out range exception because the tile I am on is on the edge of the tile grid and thus it cannot find the tile I am looking for.

Here is a small peice of the code:

 void SetTilesValuesForRooms()
{
    // Go through all the rooms...
    for (int i = 0; i < rooms.Length; i++)
    {
        Room currentRoom = rooms[i];

        // ... and for each room go through it's width.
        for (int j = 0; j < currentRoom.roomWidth; j++)
        {
            int xCoord = currentRoom.xPos + j;

            //// For each horizontal tile, go up vertically through the room's height.
            for (int k = 0; k < currentRoom.roomHeight; k++)
            {
                int yCoord = currentRoom.yPos + k;

                // Make the left wall have colliders
                // this line is the culprit
                if (xCoord == currentRoom.xPos && tiles[xCoord - 1][yCoord - 1] == TileType.Wall || tiles[xCoord - 1][yCoord] == TileType.Wall)
                {
                    tiles[xCoord - 1][yCoord - 1] = TileType.Red;

                    if (yCoord == currentRoom.yPos + currentRoom.roomHeight - 1 && tiles[xCoord - 1][yCoord] == TileType.Wall)
                    {
                        tiles[xCoord - 1][yCoord] = TileType.Red;

                        if (tiles[xCoord - 1][yCoord + 1] == TileType.Wall)
                        {
                            tiles[xCoord - 1][yCoord + 1] = TileType.Red;
                        }
                    }
                }

Im quite interested to know how I would properly go about checking if the tile I am about to correct is out of range or not.

thank you.


texts:
I'm trying to code a simple audio playback test game (which will be used in my actual project), and everything works fine, except for the fact that after the audio has finished playing, the game will crash with a 'stopped working' dialog.

Here's the code that's used to load and play the audio. Regardless of whether it's in LoadContent or not, the crash still happens.

List<SoundEffect> soundEffects;
FileStream soundStream = new FileStream("test.wav", FileMode.Open);
soundEffects.Add(SoundEffect.FromStream(soundStream));
soundStream.Dispose();
SoundEffectInstance soundeffectinstance = soundEffects[0].CreateInstance();
soundeffectinstance.Volume = 0.35F;
soundeffectinstance.Play();

The audio file is a 2 seconds long beep. The game works fine, and the graphics draw fine too. I should also mention that the SoundEffectInstance's State property doesn't seem to work properly as well.

I'm using Visual Studio 2010 with .NET 4.0, and MonoGame framework 3.4.0.459 (MonoGame.Framework.WindowsDX, from NuGet), because that's the only thing I can use without Visual Studio telling me to upgrade to .NET 4.5.

I am unable to debug, as when I debug, the 'stopped working' dialog appears again (for some reason I cannot debug any projects directly through the Debug option in VS), and the debugger hook gets confused.

Is this an upstream issue, or is there just something wrong with the way I load the audio file? (P.S. I'm not using the Content Pipeline due to the nature of my project)


texts: Find position in arc depending on the direction of the agent

texts:
So what I am trying to do is to find a random point on the (green") arc around the enemy:

Sorry for  the bad drawing but

Red (no go)
Green ( Points the allied can go to)

I know that unity has the following function:
Radius = 5;
_randomDirection = (Random.insideUnitCircle * _target.position).normalized;
Vector3 finalPosition = _target + _randomDirection + Radius;

However, this is for a full circle. How can I achieve the closest half circle?


texts: Component based architecture - Rendering approach?

texts:
I'm planning to use a component based architecture for a new 3D game engine I plan to work on, however I don't know how to approach the rendering side of things.

I can see two options here:

Every renderable game object has a RenderComponent, which stores a mesh and OpenGL-specific stuff like VBOs and VAOs. When the time comes to have update() called, it will use OpenGL to render itself.
Every renderable game object has a MeshComponent. When it's time to render, the Renderer would go through a list of all MeshComponents, extract vertex and material information, and render it.

Which option would be most flexible if I want to implement things like post-processing (bloom, motion blur), skyboxes, LOD, blending/transparency or implementing a deferred renderer?


texts: Can I detect collision on specific collider?

texts:
I'm a beginner with Unity and I'm developing my very first 2D game. My game character needs to have an automatic right/left movement but I'm struggling with the colliders on the walls (I made a tilemap object and set a collision for each wall on it). I need my character to detect the collision on the Right wall and turn to the left but I just can't find a way to name (I don't even know if you can do this) and detect a specific collider/collision so I can make an if statement on the player script.

How can I detect a specific collision/collider and refer this on my player script?

Here is the code I'm using for it (it isn't working):

void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.collider.gameObject.name == "Right Facing Wall")
    {
        runForwards = false;
    }
    else if (collision.collider.gameObject.name == "Left Facing Wall")
    {
        runForwards = true;
    }
}


texts:
I want stretch my game on two monitors. I use Unity 5.3. This version support the multi-display. But, one camera = one monitor.
So, have two perspective cameras (at the same position).  I search a "camera horizontal shift" option for create stretch effect. I don't find this option. Is-there a trick ? A solution ?


texts: (Pacman) Loading 151 dots (picturebox) in form. What's the easy way?

texts:
I'm making pacman clone for school project and I'm having a bit of a struggle with loading dots into the map. I want to put 151 dots (picturebox) onto a map to a specific location, so that later on I could check if there is collision between Pacman and dots using function intersectWith.

I feel like this isn't really the most friendly way of doing it, but currently I don't have any other idea.

So, how does one put many picturebox on a form (if there is a way), and put them in array where I could check for intersection.

This is just some brief, probably wrong code, how I'm imagining this to work:

for(int i = 0; i < 151; ++i)
{
    dot[i] = Resources.dot;
    drawingArea.Load(dot[i]);
}

Thank you all!


texts:
I'm using Unity 5 and I'm getting an error in a YAML file. The error is "Unable to parse YAML file: [mapping values are not allowed in this context] at line 1"  This comes up every time I open the engine.

I've seen some say to open the YAML file and change some stuff in it. But I can't even find the YAML files. I've also seen that it's caused by meta file issues and version control. The project is local but I don't know if it matters if it's local or cloud based.

Does anyone have a solution for this issue?


texts: How are imaginary numbers useful in video game creation?

texts:
I learned about imaginary numbers in school and they seemed so impractical, so I asked my teacher what they were used for and he said "video game creation".

I just want to know if this is true and if so how is it used during the creation process.


texts:
I'm having trouble understanding some of the math behind normal map textures even though I've got it to work using borrowed code, I want to understand it.

I have a terrain based on a heightmap. I'm generating a mesh of triangles at load time and rendering that mesh.

Now for each vertex I need to calculate a normal, a tangent, and a bitangent. My understanding is as follows, have I got this right?

normal is a unit vector facing outwards from the surface of the triangle.
For a vertex I take the average of the normals of the triangles using that vertex.

tangent is a unit vector in the direction of the 'u' coordinates of the texture map.

As my texture u,v coordinates follow the x and y coordinates of the terrain, then my understanding is that this vector is simply the vector along the surface in the x direction. So should be able to calculate this as simply the difference between vertices in the x direction to get a vector, (and normalize it).

bitangent is a unit vector in the direction of the 'v' coordinates of the texture map.

As my texture u,v coordinates follow the x and y coordinates of the terrain, then my understanding is that this vector is simply the vector along the surface in the y direction. So should be able to calculate this as simply the difference between vertices in the y direction to get a vector, (and normalize it).

However the code I have borrowed seems much more complicated than this and takes into account the actual values of u, and v at each vertex which I don't understand the need for as they increase in exactly the same direction as x, and y.

I implemented what I thought from above, and it simply doesn't work, the normals are clearly not working for lighting.

Have I misunderstood something?
Or can someone explain to me the physical meaning of the tangent and bitangent vectors when applied to a mesh generated from a hightmap like this, when u and v texture coordinates map along the x and y directions.

Thanks for any help understanding this.


texts: Help with modifying a geometry grass shader to allow removing areas?

texts: So I have this geometry grass shader from a roystan tutorial I followed but it applies the grass effect to the entire mesh at once. I need to find a way to only apply grass to set areas much like how the unity painting vegetation tools work. I had an idea of using a "guiding" texture that the shader would follow which would only apply grass onto set areas on the texture e.g areas that are green but I'm not sure how to implement it. I would appreciate any advice!


texts: How to use delta time when your speed needs to be always the same?

texts:
I am using Bezier curve, and that curve positions the entity when the step reaches 1, so anthing between 0 and 1 is his travelling distance.

So in my game, according to the speed I set, I want the entity move 0.01f steps towards the target, this means, the entity will reach the target position after 100 steps.

But if I will use delta time, this will change from time to time.

How can I use delta time correctly in this case?

I'm using libGDX.


texts: UI object catches click event even by clicking outside of that object

texts:
I'm running to a weird issue where I have a Canvas and some objects on it which are adding as prefabs. Each object has a OnClick event attached to it. The problem comes in when I click somewhere in Canvas only to see one of those prefabs catch the click event (and I don't know which one got it).

The whole thing was working good, till it wasn't anymore. I'm not sure if I did something or maybe it happens after updating Unity.

Here's some more details:

I guess the problem happened after installing Unity Pro 2017.1
I've changed the ordering layers in some different ways and problem still was around!
I'm using IPointerClickHandler for receiving click events.
I've removed UI elements one by one in play mode to check if it makes any differences. The problem stays until I remove the last object which has the script for receiving click event.
Maybe it worth mention that the prefabs are adding to a parent with grid layout group.

Has anyone ran to this issue before or has any idea why this would happen?

UPDATE

Screenshot included:


texts: How to do game dev without downloading binaries?

texts: I am trying to start a student club for game development. My initial plan was to have students start by modifying an existing Open Source game, such as Sauerbraten, Tux Racer, or SuperTux. The students all have Windows computers, the problem is they're locked from installing any binaries such as these games, which would be needed to get started. So is there some option for creating a collaborative project that wouldn't require downloading of binaries to do?


texts: What is a reasonable way to avoid GC issues in Unity?

texts:
I've been reading about how garbage collection is a big problem when programming games using C#, Java, and the like - if you have a large amount of objects, the GC will run sporadically and scan through all the non-static objects you have, deleting them from memory as necessary. This can bog down your framerate or cause the game to crash if you've got a lot of objects.

From what I've read, the problem can be mitigated by statically declaring many objects during the game's initialization and storing them in an object pool (swapping out "active" and "inactive" static objects as needed so that the GC is never run). But I know it's also generally bad practice to use static objects (since it can become unclear what's what in memory, etc, etc) and I'm wondering if there's a middle ground.

So I guess I've really got 2 related questions:

Is object pooling using static objects the best way to avoid GC?
Under what circumstances should a Unity game be developed with some kind of GC avoidance in mind - when you're expecting to have 100 objects? 1000? 10000+?


texts: Is it worth making component based entity system?

texts:
I've been reading about component based entity-system for couple days now and I'm not quite sure if it is worth implementing in my next game. I haven't started making the game yet, but I have bunch of ideas for it. In my imaginations the game will be very similiar to QUBE and Portal (1). 3D puzzler, no enemies, no weapons ( although there may be some "guns", just like portal has portal-gun ). The "basis" of the levels would be constructed from voxel-like data just like in QUBE, but there may be some models aswell ( although, since this is one-man project and I'm no artist, the models will be simple and there wont be many of them ).

I couldn't imagine that I'll ever have more than 20-30 different entities, if even that many.

This is a project that I expect to be working with for a long time, so I'm now trying to properly research all the possible "engine"-architectures before I actually start making the game. I want the game to be flexible and that I could easily implement more features as I progress.

Questions:

After reading this, do you think I should implement component-based entity system or not? If yes, why?
If I were to implement component-based entity system ( or in a matter of fact, any entity-system at all ), what would "terrain"/"voxel data" be? Would it be entity?

EDIT: I forgot to mention, the other option would be just simple inheritance-based entity-system. The game will be done using C# + XNA ( and WPF for the level-editor ).


texts: What am I suppose to use instead of Unity Resources if I have to load and unload sprites at runtime?

texts:
I recently read this guide posted in the Unity website about Resources. It is clear from the get-go that it is discouraged to use Resources unless you are prototyping something.

My game is like a 2D RPG, and it has over five thousand monster sprites (yes, a lot). As far as I'm concerned, it makes perfect sense to put all the sprites in the Resources folder, and just load the ones that I need (using their name) when a battle starts and then unload them.

The Unity article makes one point that might support my approach:

  Generally required throughout a project's lifetime

Well, I'm not so sure about it - in a single game session it's entirely possible that thousands of those sprites will not be used at all as the player simply doesn't encounter those monsters.

The article goes on to talk about why is it discouraged to use Resources:

  This operation is unskippable and occurs at application startup time
  while the initial non-interactive splash screen is displayed.
  Initializing a Resources system containing 10,000 assets has been
  observed to consume multiple seconds on low-end mobile devices, even
  though most of the Objects contained in Resources folders are rarely
  actually needed to load into an application's first scene.

And it is indeed true - my game does in fact take several seconds to load on some low-end devices, especially Android ones. It is also true that none of those sprites of mine need to be loaded at startup.

So I am willing to stop using Resources - but I am at a loss now: the article doesn't mention a reasonable alternative to this.

Here are the (unreasonable) approaches that I have thought of:

  Create a component with a collection of all the sprites, that way they are all loaded without using Resources.

Yeah but I have five thousand sprites. This sounds extremely tedious.

  Same as the previous suggestion, but use Texture Packer or something similar to pack lots of sprites into different sheets - this way I have to do less work.

My sprites are large and packing them won't be a huge help - I'd still end up with a thousand or so sheets.

My point is, I just can't have 5000+ sprites preloaded. I need to load them at runtime via  Resources, but Unity clearly discourages it. Is there a solution to this?


texts: Virtual screen size with libgdx and GLES 2

texts:
I've been trying to use a virtual screen size for my libgdx desktop-android game. I'd like to always use a 16:9 aspect ratio but with a virtual screen size so everything would adapt automatically depending on the device size.

This post illustrates the process pretty well but my game crashes when camera.apply(Gdx.Gl10) is called. This is because I'm using GLES 2.0 (for not having to use multiple of 2 texture sizes). As stated in the OrthographicCamera doc, the apply method only works with GLES 1 and GLES 1.1.

Is there another way of applying my GL transformation to the camera so I can use a virtual screen resolution? Having to resize everything manually it's a total pain.

Thanks a lot.


texts: How does one specify raster operations in XNA?

texts:
I'm looking for a way to add a sprite using a particular logic operation (like XOR). I can't find anything on Google and I'm not sure where to look in the documentation.

I've looked into SpriteBatch.Begin(...) and its Draw method and several options in the GraphicsDevice class, but I'm not recognizing anything capable of this. I'm still pretty new to XNA so I may just not have recognized the terminology to do this.


texts: Making a crosshatching effect in Unity Shader Graphs

texts: I'm learning Shader Graph and am trying to experiment with toon shading effects. One thing I'd love to do is make a traditional art styled crosshatching effect either inside shadows or at the edge of shadows. However, I'm lost as to how to do that. I have a sample crosshatch texture I can use as a texture2D but I'm unsure how to use this as an input in shadows and to which nodes to hook it up to. I'm very new to dabbling in shaders so I'd appreciate any tips.


texts: How to prevent the player from clicking too fast

texts:
I'm having trouble with some bullets in my game, the M1911, which is supposed to be semi-auto is only capable of shooting one projectile per mouse click (trying to learn how to do multiple ones at once). The problem is, if the player clicks the mouse ridiculously fast it causes the bullet to reset its position back to the player (not intended).

Basically I want to limit the clicks, or implement a cooldown after the left mouse buttons pressed which prevents the player from clicking at all during a certain timeframe (or until the bullet hits something).

I want it so that when LMB is pressed it starts a timer.


texts:
What is the good way to share assets between platforms (android, desktop, etc) ?

by default there is an assets folder in each platform folder.


texts: How can I make EaselJS' skew behave like canvas'?

texts:
The skew property of a bitmap in EaselJS (given as angle) rotates the image such that it also flattens. I'd like to skew it without "squashing" it, as canvas does.

JSFiddles, to demonstrate:

Canvas skew | EaselJS skew


texts: Does research exist on the impact of vibration in mobile games?

texts:
I've implemented vibration for various player collisions in my mobile game, but I feel like this is not a common thing on mobile even though it is on consoles.

Is there any research on the positive or negative benefits of using vibration feedback in mobile games that would suggest guidelines for when it is and isn't appropriate to use?


texts: How can I generate random meaningful words in a typing game?

texts:
I want to make a typing game where users have to type the words displayed on the screen. But I don't know how to generate meaningful English words not gibberish.

What technique can I use to achieve this?


texts: How to divide hex grid evenly among n players?

texts:
I'm making a simple hex grid based game, and I want the map to be divided evenly among the players. The map is created randomly, and I want the players to have about equal amount of cells, with relatively small areas. For example, if there's four players and 80 cells in the map, each of the players would have about 20 cells (it doesn't have to be spot-on accurate). Also, each player should have no more than four adjacent cells. That is to say, when the map is generated, the biggest "chunks" cannot be more than four cells each.

I know this is not always possible for two or three players (as this resembles the "coloring the map" problem), and I'm OK with doing other solutions for those (like creating maps that solve the problem instead). But, for four to eight players, how could I approach this problem?


texts: Player with Character Controller and children colliders won't collide properly

texts:
I have a player that consists on a root object with the Character Controller attached and some children with its components. Those have box colliders attached.

When moving the player I want to be able to collide with other objects using the box colliders, but it won't, instead it will only collide with the Character Controller.

As you can see in the image, the red object didn't stop when the collider crashed with the framed cube, but it did when it did with the Character Controller.

There is any way to use the player colliders instead of the Character Controller for collision detection?


texts: Libgdx, TweenEngine - continous rotation animation without stopping/delay

texts:
I have a probably dumb question.

I'm trying to create a LoadingCircle so I just picked one image (you can see in the attachment) and made some sequences to rotate it:

 Tween.to(loadingCircle, SpriteAccessor.ANGLE, 1f).targetRelative(25).repeatYoyo(Tween.INFINITY,0).start(tweenManager);

And SpriteAccessor:

case ANGLE:
   returnValues[0] = target.getRotation();

case ANGLE:
    target.setRotation(newValues[0]);

It rotates of course, but 'to()' method gets the 'time' parameter. Now, the animation rotates the image, but slows down and stops rotating after the given time and starts from the beginning - speeds up and again - slows down.

Is it possible somehow to set the rotation to be continous, that it won't slow down and repeat the action? It's caused by the interpolation I think.

If you could point me the way I would be grateful!


texts: glDrawArrays (layered rendering using geometry shader) only draws one point

texts:
I have been debugging this for a while but I can't seem to find the issue.

I created a framebuffer for layered rendering like this

GLuint buffer;
glGenFramebuffers(1,&buffer);
glBindFramebuffer(GL_FRAMEBUFFER,buffer);

glFramebufferTexture(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,textures[0],0);

GLenum blub[] = {GL_COLOR_ATTACHMENT0};

glDrawBuffers(1,blub);

where textures[0] is a 3D texture for layered rendering. The texture is texture complete, using nearest for min and mag filtering, no mip mapping, clamp to edge for s,t and r. I can sample from it fine (I initialize the texture to a color based on the z coordinate inside the 3d texture, it's initialized fine as well). The size of the 3D texture right now is 32x32x32 texels.

The framebuffer is framebuffer complete (checked it using glCheckFramebufferStatus).

Then I create and fill a buffer with vertex data for the points like this:

vector<vec2> points;
points.push_back(vec2(0.0f,0.0f)); //should draw in the middle
points.push_back(vec2(0.5f,0.5f)); //3/4th in each direction
points.push_back(vec2(-0.5f,-0.5f)); //opposite of second point
points.push_back(vec2(-0.95f,-0.95f)); //first texel on the bottom left

glGenBuffers(1,&result);

glBindBuffer(GL_ARRAY_BUFFER,result);
glBufferData(GL_ARRAY_BUFFER,points.size()*2*sizeof(float),&points[0],GL_STATIC_DRAW);

where vec2 is the vec2 floating point vector class provided by GLM.

Then I render it by doing this:

glViewport(0,0,textureSizeX,textureSizeY);
glBindFramebuffer(buffer);
glUseProgram(shader);
glBindBuffer(GL_ARRAY_BUFFER,_pointbuffer);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0,2,GL_FLOAT,GL_FALSE,0,0);
glDrawArrays(GL_POINTS,0,4);

where shader is a shader constructed from vertex, geometry and fragment shaders. It compiles fine without warnings. Depth and stencil testing are disabled. textureSizeX and textureSizeY are the width and height of the 3D texture.

Vertex shader:

#version 430

layout(location =0) in vec2 pos;

void main()
{
    gl_Position = vec4(pos.xy,0,1);
}

Geometry shader:

#version 430

layout(points) in;
layout(points, max_vertices = 1) out;

void main()
{
    gl_Layer = 0;
    gl_Position = vec4(gl_in[0].gl_Position.xy,1,1);
    gl_PointSize = 1.0f;

    EmitVertex();
    EndPrimitive();
}

Fragment shader:

#version 430

out vec4 outcolor;

void main()
{
    outcolor = vec4(0,1,0,0);
}

However, only the first point is drawn, as expected in the middle of layer 0 of the 3D texture. I can move around the coordinates of the first point and get the expected results. The points after the first point are always ignored, however. What am I doing wrong?

Hardware is GTX 770 with driver version 331.82 (latest version). Tested it on GT 555M (Notebook GPU), same results. The OpenGL device context is version 4.3.

edit: Tried so far: When I extend the attribute input of the vertex data to a vec4, and change the argument in glVertexAttribPointer accordingly, as expected the z and w components of the vec4 contain the coordinates of the second point, so the positions seem to be in memory as expected.

Similarly, if I change the offset using glVertexAttribPointer (e.g. putting (void*)(sizeof(vec2)*3) as the last parameter), the respective point is drawn.

Just to test if something may be wrong with the rasterization in general, I tried emitting triangles instead of points in the geometry shader. This works as expected.


texts: Why is this Procedural Content Generation while that other isn't?

texts:
I'm reading the online Procedural Content Generation book and on chapter 1, page 2 there's one example of what PCG is and another of what PCG is not and I can't tell them apart.

This is PCG according to them:

  game engine middleware that rapidly populates a game world with vegetation

This is NOT PCG according to them:

  a game engine capable of integrating automatically generated vegetation

Also on page 1 they explicitly said they do not consider a game engine PCG

  A key term here is “content”. In our definition, content is most of what is contained in a game: levels, maps, game rules, textures, stories, items, quests, music, weapons, vehicles, characters, etc. The game engine itself is not considered to be content in our definition.

My guess is the PCG example is a code in a game (or it could be a code that adapts to any game) that recognizes the game map and populates it with vegetation according to it. And the not PCG example for me would be like an option available from the game engine were the developer can add the vegetation offline via the user interface.

The last one is a very very wild guess from me, I'm pretty sure I'm wrong cause at first glance they both sound like PCG. Please help me differentiate them.


texts: Looking for very simple implicit integration example

texts:
I am trying to design a robust cloth system. I have no problem at all simulating things like that using forward integration such as euler, midpoint, runge-kutta, verlet, etc. However, I just can't wrap my head around implicit methods.

I don't understand how you formulate the equations in linear algebra terms.
I'd really like to see a VERY simple tutorial, and an actual example of how to construct the equations, and then solve for a very simple system (for example, 3 particles connected by 3 springs).

I looked into David Baraff's Large Steps in Cloth Simulation, and I can kind of follow it, but going from equations to code is a weak spot of mine.

I can use a package like eigen to solve, but I'd also really like to see some code for something like conjugate gradient descent. I don't care about efficiency at the moment, I just want to be able to clearly understand what's going on.

Thanks


texts:
How to use glunproject in my android app?

I have the following parts in my engine:

A projection matrix
A view matrix for the camera
A model matrix for each of the objects in my world. This matrix is calculated from the parent objects model matrix and the objects own model matrix. These matrices are calculated from a translation, rotation and scale matrix. (this all works fine)

These matrices are then multiplied and passed to my vertex shader.

Now I understand glunproject needs the model matrix and the projection matrix and can caluclate a near and far 3d coordinate depending on the camera viewport settings ( for the near and far plane)

Do I need to use glunproject for each of the objects in my world and then check if the ray produced by these near and far coords intersects my object?
This seems quite expensive on the cpu?

What is the proper use for glunproject


texts: To implement a game object that expires, should I store the start time and total, or store the remaining time?

texts:
Example:
There is a bomb (like in Counter Strike) which explodes after 45 seconds. Should I—

store the 45 seconds in a variable, and decrease it by the delta time at every update, or
store the time when the bomb was planted, and check at every update if it is less than or equal to the current time minus 45 seconds?

How do I choose which approach to use?


texts: How can I stop detecting input from the user in Unity? I want to achieve the following: "do not detect Input.GetMouseButtonDown" In C#?


texts: How to make the player unable to change some of the game elements?

texts:
I am making a text turn based RPG fighting game in which you create your own spells. You also share them as JSON files with your friends. Sharing is required to win.
The game is designed so that it isn't a problem if a spell is copied and shared one billion times

I do not want players to edit the files or the spell creator. The only reason is to not ruin others' experience.
I wouldn't mind at all if there were no multi-player elements in the game.

Is there a way to make some game elements unable to be modified ?

My game is interpreted in Lua and has some bash integrated into it for file managing.
It is also GNU/Linux only.


texts: How can I make the Player animation appear smooth?

texts:
I'm using GLFW for my window and input related work. I'm calculating delta time and multiplying it with my player speed and then finally adding it to the current position of the player. The thing is that, though it makes my motion frame independent the player movement appears to slow and speed up interchangeably. Well the reason would be the different values of delta time at each frame. What should I do to smooth out this animation?

Here is the relevant code, and a capture of what's going on:

float deltaTime = 0;
float oldTime = 0;

//The direction in which the player will move
int playerX = 0;
int playerY = 0;

//callback method for keyboard events
void keyboard_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
    if (key == GLFW_KEY_W && action == GLFW_REPEAT) {
        playerX = 0; playerY = 1;
    }
    if (key == GLFW_KEY_S && action == GLFW_REPEAT) {
        playerX = 0; playerY = -1;
    }
    if (key == GLFW_KEY_D && action == GLFW_REPEAT) {
        playerX = 1; playerY = 0;
    }
    if (key == GLFW_KEY_A && action == GLFW_REPEAT)
    {
        playerX = -1; playerY = 0;
    }
}

//update player's position
void update() {
    player->move(playerX, playerY, TIME_PER_FRAME);
}

//set up glfw keyboard callback function and other stuff
void init() {
    glClearColor(0, 0, 0, 0);
    player->bindVertexAttributes(shader.getAttributeLocation("position"));
    glfwSetKeyCallback(window->getGLFWWindow(), keyboard_callback);
}

//wait logic
float expected_frame_end = glfwGetTime() + TIME_PER_FRAME;
void wait() {
    while (glfwGetTime() < expected_frame_end) {

    }
    expected_frame_end += TIME_PER_FRAME;
    playerX = playerY = 0;
}

//rendering function
void render() {
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    player->setUniformMatrixLocation(shader.getUniformLocation("projectionMatrix"), shader.getUniformLocation("transformationMatrix"));
    shader.useProgram();
    update();
    player->render();
    wait();
    shader.stopProgram();
}

//main function
int main(int argc, char** argv) {
    init();
//main loop
    while (!glfwWindowShouldClose(window->getGLFWWindow())) {
        render();
        window->swapBuffers();
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}


texts: glsl fragment shader work diffrently on different devices

texts:
i'm making a 2d android game where i have a mechanics that allow the player to move the camera away from the main character, and to not allow him to explore the hole world, a have create a Fog shader, know the shader works very well on the emulator, and in the desktop application from libgdx, but once i run it on real devices it give me a defferent output, in Xperia SP the for never get heigher and make every thing visible, and in a Galaxy S3 the Fog act like a Circle and make every thing invisible.
my question is : are shader work differently from gpu to one other.


texts:
This question isn't gamedev per se but it is definitely relevant. Still, if it's off-topic, please direct me to the proper SE page.

This question has probably already come up many times but I'd like to take a complete approach here and also up-to-date (whatever I may find online might be from 1/5/10 years ago and so isn't of much value to me).

So - is DirectX free for commercial use? What do I mean by that? Is it free to download DirectX SDK (or whatever it's called nowadays) and develop my game? Are there any fees involved in publishing and selling my game if it uses DirectX? And in the spirit of covering it all - using DirectX implies using Windows (which isn't free) and maybe Visual Studio? To that last one - is it absolutely necessary to use VS? Also, is it practical to use any other IDE? And are there any other (implied) costs like that "using Windows" one?

Update:

My friend sent me this EULA snippet saying that it's only free if I'm the only user of the software I develop so this must mean I have to pay for DX for commercial use.

  SOFTWARE PRODUCT.  You may install and use the SOFTWARE PRODUCT on an
  unlimited number of computers, including workstations, terminals or
  other digital electronic devices ("COMPUTERS") to design, develop, and
  test software application products for use with Microsoft operating
  system products including Windows NT Workstation 4.0, Windows NT
  Server 4.0, Windows 95 and subsequent releases thereto
  ("Application").  You may install copies of the SOFTWARE PRODUCT on up
  to ten (10) COMPUTERS provided that you are the only individual using
  the SOFTWARE PRODUCT on each such COMPUTER.


texts: Optimizing Box2D for a couple hundred static bodies

texts:
I searched but could not find anything similar (Yet) around the web, so here I am asking my question:
In my game I use around 3 to 4 hundred static bodies with like 10 dynamic bodies in the Box2D world. The problem is that after 100 static bodies it cant manage 60 frames / second. My understanding is that static bodies calculate faster then dynamic ones.
My rendering is pretty much bound to the iterator, so optimizing the game through removing objects entirelly is not really an option.
Is there a way I can speed up the physics sim for static bodies? I think about something like statics far from dynamics would be just jumped in the world step...
So generally I want to speed up the sim of static bodies, or completely not simulate them without removing them from the BodyIterator.
I am open to any suggestions.
Thanks for your help!


texts: Collision/Intersection of (2D) Ray to Line Segment

texts:
Given a ray (r0, r1) and a line segment (a, b), I need to calculate the normal of the line segment based on the direction of the ray. For example, in the following picture:

The correct normal given the ray (from picture) and segment should be normal n1. Here is the algorithm I am using to calculate the point of intersection:

public static Vector2? lineSegmentIntersection(Vector2 r0, Vector2 r1, Vector2 a, Vector2 b)
{
    Vector2 s1, s2;
    s1 = r1 - r0;
    s2 = b - a;

    float s, t;
    s = (-s1.Y * (r0.X - a.X) + s1.X * (r0.Y - a.Y)) / (-s2.X * s1.Y + s1.X * s2.Y);
    t = (s2.X * (r0.Y - a.Y) - s2.Y * (r0.X - a.X)) / (-s2.X * s1.Y + s1.X * s2.Y);

    if (s >= 0 && s <= 1 && t >= 0 && t <= 1)
    {
        // Collision detected
        // Return the point of intersection
        return new Vector2(r0.X + (t * s1.X), r0.Y + (t * s1.Y));
    }

    return null; // No collision
}

Ideally, I would like to modify this algorithm to calculate the proper normal. Further, I know how to calculate the normals n0 and n1:

norm0 = new Vector2((b.Y - a.Y), -(b.X - a.X));
norm1 = new Vector2(-(b.Y - a.Y), (b.X - a.X));

What do I do next to determine which of those two normals to choose? I get the feeling this is fairly simple and I've been looking at it for too long...


texts: How to make a gaussian blur effect in UDK

texts: I want to make a plane shape (surface) that have a gaussian blur applied to it and this plane is transperant, so all objects behind it looks like they are having a gaussian blur effect.


texts: Design constraints for games that the elderly (65+) get engaged with

texts:
I'm a newbie in game design and gaming in general (Tetris, board games, this sort of things). But have observed that the elderly got very much engaged with bubble shooter and solitaires (quite different approaches). I've tried to look for something similar, and have tried to initiate some in these games, but nope, the shooter is always preferred.

Does anybody know of general criteria, design constraints, or (even better) concrete examples of games that the elderly like to play, apart from these two?

Note: agreed, not correctly tagged, but can't find something that fit, nor can I propose new ones.


texts: How do I avoid pathfinding characters getting stuck in corners?

texts:
I used A* pathfinding to return a list of Tiles to get from an enemy to the player. After that, I wasn't sure how to actually move the enemy.

What I ended up doing was get the first Tile in the path. Then, check all 8 directions from the enemy's current tile. If the path tile is in the enemy tile's adjacent bottom square, move like this. If it's the right square, do that, etc. When the tile of the enemy is the same as that tile in the path, remove it from the path, and repeat for the next one.

This works, except my character sometimes gets caught around corners. This is because it thinks it should be moving horizontally (the next tile in the path is above it) when it's actually more of a diagonal movement to actually get to it.

I need to know two things:

Is there a better way I should do the movement after calculating the tiles in the path?
What are some ways to deal with the corners and diagonals? I was thinking perhaps some sort of random movement, but it's kind of janky. In the end, don't care how silly it is as long as the enemy doesn't get stuck!

Really new to all of this, so would appreciate some advice!


texts: How to setup a particular blend state where the alpha channel is additive?

texts:
I would like to set a blend state to be "additive" and do the following:

Result.R = Source.R + Destination.R;
Result.G = Source.G + Destination.G;
Result.B = Source.B + Destination.B;
Result.A = Source.A + Destination.A;

So I've tried setting a blend state to:

IsBlendEnabled = 1;
SourceBlend = BlendOption.One;
DestinationBlend = BlendOption.One;
BlendOperation = BlendOperation.Add;
SourceAlphaBlend = BlendOption.One;
DestinationAlphaBlend = BlendOption.One;
AlphaBlendOperation = BlendOperation.Add;

I was thinking it would do:

Result = Source*BlendOption.One + Destination*BlendOption.One;

But I doesn't work (I've tried so other combinations as well). The color (RGB) channels are adding up correctly but the alpha channel is not (it's not affected by the blend finally, but still not adding up). I'm drawing three overlapping quads with different colors (red, green, blue) and alpha of 0.1. But result alpha is not 0.0-0.3 (0.0 = no overlap, 0.1 = one quad, 0.2 = two quads overlap, 0.3 = three quads overlap) as I would expect.

Is it even possible to setup blend state to accumulate alpha on render target?

Note: I would like to have a color map (RGB) being mixed and alpha channel indicating how many quads are overlapping (0-3 quads => 0.0-0.3 alpha value).


texts:
I have the following basic code:

public void simpleInitApp() {
    Box b = new Box(1, 1, 1);
    Geometry geom = new Geometry("Box", b);
    Texture cube1Tex = assetManager.loadTexture(
    "/home/glados/codes/3/assets/Textures/map/oldParchment.jpg");

    Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
    mat.setTexture("ColorMap", cube1Tex);
    geom.setMaterial(mat);

    rootNode.attachChild(geom);
}

which is supposed to simply attach a texture to the cube loaded from Textures/map/oldParchment.jpg

My resource setup is as following:

running this gives the following error:

com.jme3.asset.AssetNotFoundException: /home/glados/codes/3/assets/Textures/map/oldParchment.jpg (Flipped) (Mipmapped)
    at com.jme3.asset.DesktopAssetManager.loadAsset(DesktopAssetManager.java:283)
    at com.jme3.asset.DesktopAssetManager.loadTexture(DesktopAssetManager.java:346)
    at com.jme3.asset.DesktopAssetManager.loadTexture(DesktopAssetManager.java:356)
    at mygame.Main.simpleInitApp(Main.java:27)
    at com.jme3.app.SimpleApplication.initialize(SimpleApplication.java:226)
    at com.jme3.system.lwjgl.LwjglAbstractDisplay.initInThread(LwjglAbstractDisplay.java:130)
    at com.jme3.system.lwjgl.LwjglAbstractDisplay.run(LwjglAbstractDisplay.java:207)
    at java.lang.Thread.run(Thread.java:744)

Anybody know what I'm doing wrong?


texts:
How can I display objects in a 3D perspective projection that look like as if their size does not change, despite of the camera's position?
I am using DirectX 9.0. I know of PositionTransformed declaration usage, but I was thinking of scaling the objects in every frame as the camera zooms in/out to achieve this.
Is there a way to know the "scale" of a perspective projection?

An example usage would be to show lines with constant width. E.g. roads on a map.

Update, I've found the solution

check the accepted answer.


texts: Find meeting point of 2 objects in 2D, knowing (constant) speed and slope

texts:
I have a gun which fires a projectile that has to hit an enemy. The problem is that the gun has to be automatic, i.e. - choose the angle in which it has to shoot, so that the projectile hits the enemy dead in the center.

It's been a looooong time since school, and my physics skills are a bit rusty, but they're there. I've been thinking to somehow apply the v = d/t formula to find the time needed for the projectile or enemy to reach a certain point. But the problem is that I can't find a common point for both the projectile and enemy trajectories. Yes, I can find a certain point for the projectile, and another for the enemy, but I would need lots of tries to find one where the two points coincide, which is stupid. There has to be a way to link them together but I can't figure it out.

I prepared some drawings and samples:

A simple version of my Flash game, dumbed down to the basics, just some shapes:

http://axonnsd.org/W/P001/MathSandBox.swf - click the mouse anywhere to fire a projectile.

Or, here is an image which describes my problem:

So... who has any ideas about how to find x3/y3, thus leading me to find the angle in which the weapon has to tilt in order to fire a projectile to meet the enemy?

EDIT

I think it would be clearer if I also mention that I know: the speed of both Enemy and Projectile and the Enemy travels on a straight vertical line.


texts: Calculate hockey puck bouncing off rubber bumper

texts: I am very new to game development (or any type of development for that matter) and I am trying to figure out how I would calculate a hockey type puck bouncing off a rubber bumper placed at a 45 degree angle. The puck could hit the bumper at any angle during play. Any help with this is greatly appreciated.


texts:
So, I have a Model stored in MyModel, that is made from three meshes. If you loop thrue MyModel.Meshes the first two are children of the third one. And was just wondering, if anyone could tell me where is the problem with my code.

This method is called whenever I want to programmaticly change the position of a whole model:

public void ChangePosition(Vector3 newPos)
{
    Position = newPos;

    MyModel.Root.Transform = Matrix.CreateScale(VectorMathHelper.VectorMath(CurrentSize, DefaultSize, '/')) * Matrix.CreateFromAxisAngle(MyModel.Root.Transform.Up, MathHelper.ToRadians(Rotation.Y)) *
        Matrix.CreateFromAxisAngle(MyModel.Root.Transform.Right, MathHelper.ToRadians(Rotation.X)) * Matrix.CreateFromAxisAngle(MyModel.Root.Transform.Forward, MathHelper.ToRadians(Rotation.Z)) *
        Matrix.CreateTranslation(Position);

    Matrix[] transforms = new Matrix[MyModel.Bones.Count];
    MyModel.CopyAbsoluteBoneTransformsTo(transforms);

    int count = transforms.Length - 1;
    foreach (ModelMesh mesh in MyModel.Meshes)
    {
        mesh.ParentBone.Transform = transforms[count];
        count--;
    }
}

This is the draw method:

foreach (ModelMesh mesh in MyModel.Meshes)
{
    foreach (BasicEffect effect in mesh.Effects)
    {
        effect.View = camera.view;
        effect.Projection = camera.projection;
        effect.World = mesh.ParentBone.Transform;
        effect.EnableDefaultLighting();
    }
    mesh.Draw();
}

The thing is when I call ChangePosition() the first time everything works perfectlly, but as soon as I call it again and again. The first two meshes(children meshes) start to move away from the parent mesh.

Another thing I wanted to ask, if I change the scale/rotation/position of a children mesh, and then do CopyAbsoluteBoneTransforms() will children meshes be positioned properlly(at the proper distance) or would achieving that require more math/methods?

Thanks in advance


texts: Perspective correct texture mapping in iOS Metal

texts:
I tried various ways of getting the interpolation work and generate a perspective correct image, but none of the suggested ways works.

My current code is:

struct VertexStruct
{
  float4 normalizedPosition [[ position ]];
  float4 texCoord;
}

vertex VertexStruct testVertex(device float4 *vertices [[ buffer(0) ]],
                                     uint vid [[ vertex_id ]])
{
  VertexStruct outVertices;

  outVertices.normalizedPosition = ...;

  outVertices.texCoord = float4(vertices[vid].x, vertices[vid].y, 0.0, 127.0);

  return outVertices;
}

fragment half4 testFragment(VertexStruct inFrag [[ stage_in ]],
                            texture2d<half, access::sample> volume [[ texture(0) ]])
{
  float2 texCoord = float2(inFrag.texCoord.xy * (1.0 / inFrag.texCoord.w));
  constexpr sampler s(coord::normalized, filter::linear, address::clamp_to_zero);
  return volume.sample(s, texCoord);
}

Texture is 128x128 and vertices are:

0,0
0,127
127,0
127,127

In theory, the 4th parameter, w, should help with perspective correct interpolation. This trick has been reported to work in OpenGL ES, but in my case if I have it or not, nothing changes.

What I get is:

Blue is the clear color, while anything inside the black trapezoid is the content of the texture. The red trapezoid should be centered in the black trapezoid. If you open it with Photoshop and trace the diagonal of the black trapezoid, it will pass exactly true the diagonal of the red trapezoid.

It means that the two triangles that are rendered don't read the texture with perspective correct sampling. It is the classic problem of texture mapping, but I can't get my head around it.

Can anyone see the error?


texts: When importing a character to Unity, textures and meshes don't appear

texts:
I'm relatively new to Unity, and I'm left with doing this as my last step towards my task - importing my animated character to a game engine and program the movements.

The problems that I have noticed are the missing textures and meshes, you can see in the first picture how it should look like in Blender, and what results I get in Unity:

The apple here doesn't have any holes, I think only one material got imported, and it doesn't look right. Textures are missing, the leaf near the stem is completely filled with gray texture. At least the animations work perfectly...

Download link to my .blend file - https://pasteall.org/blend/6c14ec0d9446404b81251585f83f3551


texts: Making player movement direction follow players facing direction

texts:
if (controller.isGrounded) {
                        moveDirection = new Vector3 (Input.GetAxis ("Horizontal"), 0, Input.GetAxis ("Vertical"));
                        moveDirection = transform.TransformDirection (moveDirection);
                        moveDirection *= speed;
                        if (Input.GetButton ("Jump"))
                                moveDirection.y = jumpSpeed;

                }
                moveDirection.y -= gravity * Time.deltaTime;
                controller.Move (moveDirection * Time.deltaTime);

This works. I can manover my player in any direction.

With the awsd keys i can create 8 directions. I would like player to rotate towards the direction of the keys pressed. This is a top down game. So W+D would take you diagonally right/up. S+D would take you diagonally right/down.

I want the player to rotate into that direction, but also move the direction it is facing. Like a car. So if it is facing a complete different direction then it would actually move not in the target direction for a while until it has the target direction. Am i making sense?

      if (moveDirection != Vector3.zero)
    {
transform.rotation = Quaternion.LookRotation (moveDirection);
                        }


texts: Why would the same script attached to multiple scenes not work the same way in some of the scenes?

texts:
I have 4 scenes in my Unity Project. And in each scene I have identical sliders, what I want to do when Advance_Trial is called via a button press, the sliders' value resets to 0. However, this only works for two of the scenes. For remaining two it doesnt work, I checked if Advance_Trial is attached to the button gameobject which calls it and it is (in all scenes).  There are no errors messages in the console either.
How do I correct it?
Also, when the else portion is executed the sliders are not inactive meaning, the sliders are still visible. This happens for the same two scenes for which the sliders do not reset.
Am I missing something? Or do I need to check something in individual scenes?
Please see my code below.
public Slider[] sliders;

    public void Start()
        {

            sliders = FindObjectsOfType<Slider>() as Slider[];

            for (int s = 0; s < sliders.Length; s++) //Resets the sliders
            {
                sliders[s].gameObject.SetActive(false);
            }
    }
     public void Advance_Trial()
        {
            for (int s = 0; s < sliders.Length; s++)
            {
                sliders[s].value = 0;
            }

            int stimIndex = UnityEngine.Random.Range(0, signals.Count + 1);
            string text = stimIndex.ToString();
            byte[] data5 = Encoding.ASCII.GetBytes(text);
            client.Send(data5, data5.Length, remoteEndPoint);
            Debug.Log("<color=yellow>Signal played is:</color>" + stimIndex);
            Debug.Log("<color=magenta>NUMBER sent to MAX is:</color>" + text);

            Debug.Log("<color=magenta>Index removed was :</color>" + signals[stimIndex]);
            signals.RemoveAt(stimIndex);

            if (signals.Count > index)
            {

                Debug.Log("<color=orange>Yay! Keep Listening!</color>");
                index++;
            }

            else
            {

                Debug.Log("<color=green>All Trials finished</color>");

                for (int s = 0; s < sliders.Length; s++)
                {
                    sliders[s].gameObject.SetActive(false);
                }

                EndSessionPanel.gameObject.SetActive(true);
            }

        }