texts: I'm trying to work with setInterval inside a loop and it doesn't work the i want it to

texts:
I am making a 2d canvas game in Javascript. I am trying to make the enemies that are coming to my hero to shoot a bullet every 3 seconds.

for (var i = 0; i < enemyBullets.length; i++) {
            enemyBullets[i].show();
            enemyBullets[i].move();
        }//which this statement , whenever there is a bullet added to the array , it gets drawn on the canvas and updated.

function Enemy(x, y) {
       this.shoot = function(){
            var ebullet = new enemyBullet(this.x, this.y);
            enemyBullets.push(ebullet);//here i have the enemy object and the function which adds the bullet to the array.
        }

here is how i use the enemy.shoot function in the draw() function which is in requestAnimationFrame();:

function lol(){
            for(var v = 0; v<enemies.length;v++){
                enemies[v].shoot();
            }
        }
setTimeout(lol,3000);//this is what ive tried so fa

when i do this , the enemies are shooting not a single bullet every 3 seconds but after 3 seconds of the beggining of the program , they start adding infinity bullets to the array and i don't know how to handle it.


texts:
I am making a platformer game in JBox2D and LWJGL that has a scrolling camera, but I have hit a wall with the boundaries of the camera.

Essentially what I have right now is a Box2D world that is being draw on the screen, a viewport being moved by gluLookAt and several boundaries specified by Box2D edges that also help keep the player from moving out of bounds. It looks a bit like this:

What I'd like to do is "push" the camera when ever it comes in contact with the edge, but otherwise be centered on the player.

I've tried a couple of methods for this, such as finding the min and max width and height, and simply doing an easy box hit test, and moving the screen accordingly, but that has it's limitations, such as if the world is not in a rectangular shape e.g.

Another method I've tried is doing something where I raytrace from one vertex to another of each edge, and if it comes into contact with the screen, I "push" the screen out of the way, but that hasn't quite worked either

    Fixture fixture = boundary.getFixtureList();
    Vec2 point = null;
    boolean hit = false;
    fixtureLoop:
    for(int i = 0; i < boundary.m_fixtureCount; i++)
    {
        EdgeShape edge = (EdgeShape)fixture.getShape();
        Vec2 origin = new Vec2(edge.m_vertex1.x*Main.OPENGL_SCALE, edge.m_vertex1.y*Main.OPENGL_SCALE);
        Vec2 direction = new Vec2(edge.m_vertex2.x*Main.OPENGL_SCALE, edge.m_vertex2.y*Main.OPENGL_SCALE).sub(origin);
        for(float t = 0; t < 1.0f; t += 0.001f) //Raytrace loop
        {
            point = origin.add(direction.mul(t));
            //See if point is within screen bounds
            if(point.x > screenX-Main.WIDTH/2 && point.x < screenX+Main.WIDTH/2 && point.y > screenY-Main.HEIGHT/2 && point.y < screenY+Main.HEIGHT/2)
            {
                hit = true;
            }
        }
            //If hit, find closest vertex
        if(hit)
        {
            float shortestDistance = Float.MAX_VALUE;
            Vec2 vertex = new Vec2();
            for(int v = 0; v < screenVertices.length; v++)
            {
                float distance = point.sub(screenVertices[i]).length();
                if(distance < shortestDistance)
                {
                    shortestDistance = distance;
                    vertex = screenVertices[v];
                }
            }
            Vec2 displacement = point.add(vertex.sub(new Vec2(screenX, screenY)));
            screenX = displacement.x;
            screenY = displacement.y;
            break fixtureLoop;
        }
        fixture = fixture.getNext();
    }

What I have here is my attempt that I have played around with WAAAY too much. Essentially what I'm trying to do is detect if and edges are hitting the screen, find the point where they hit, find the closest screen vertex, subtract them to find the displacement between them, and apply it to the screen so that they're no longer in contact: (The screenVertices array is essentially 4 vertices that look like Vec2(screenX+WIDTH/2, screenY+HEIGHT/2), etc)

I was wondering if anyone could help me out, I'm not sure if I'm having logic problems, code problems, or both. Absolutely any help would be appreciated, thanks!


texts: How to make a moving camera in 2d with p5.js

texts:
I am trying to make a hill climb racing clone. My code: https://editor.p5js.org/saathvik/sketches/-XOFPcukt
When I move the car, I want the camera to follow the player, so he can't go off screen.


texts: Implementing Browser in Unreal Engine 4.10

texts:
I am looking to add some oauth to a game I am working on. I can get the user auth to work in the browser that comes with UE4, however there is not any capability to detect changes to the currently loaded URL so I can grab the token after the user loggs in. So I'm trying to create one. I created a new C++ class that extends UWebBrowser, added this line to the Build.css file

PublicDependencyModuleNames.AddRange(new string[] {"Http", "UMG"});

And I have this in my browser .h file so it will be available to use in blueprints

virtual const FText GetPaletteCategory() { return FText::FromString("Oauth Browser");

Now I just need to be notified of when the URL changes so I can grab to auth token but I can't seem to find a way to implement for that. I have read that it can be done though. Can anyone shed more light on this subject for me? I'd appreciate it.


texts: Switch from left click to right click to make character walk in the Top Down Example, in UE4?

texts:
When creating a new project in the Unreal Engine 4, you can choose to create a project already with some added features and things (Top Down Example):

This project has a character (which I changed its appearance) and it moves around the map when I click the left mouse button:

I looked at the blueprints of the project, but I did not identify where the command is that makes the character walk, so I'd like it to walk when I right-click.

Alls blueprints of project:

M_Cursor_Decal:

TopDownCharacter:

TopDownController:

TopDownGameMode:

The circled blocks of reds are the ones I suspected could be where I should make the modification, but no information on them gave me the certainty that that was where I was supposed to change.

I still do not create projects in C ++ programming mode, because I do not have Visual Studio 2017.

Some links from websites where I spent before coming here and that can help you to help me:

https://docs.unrealengine.com/en-us/Engine/Blueprints

https://www.youtube.com/watch?v=EFXMW_UEDco

The video is 2015, so although it's good, I did not take it so well, because I know that with all this time that has already happened, a lot is different.

Sorry for any translation errors, I'm not English speaker.


texts: Using Kinect I've extracted coordinates(x,y,z) of user, I'm in search of method which can help me out transferring motion of Skeleton to any 3D model(AVATAR) using OpenNI and OpenGL.


texts:
I've recently released my first free to play game on Android and I've spent a few £ on advertising to try and get players involved and see what happens.

Below are my retention stats courtesy of Google. Judging by the colour coding 50% is good <30% is not so good, but in reality I have no real idea what these numbers should look like. So this question has two parts really.

What are ok/good numbers for Days 1, 2, 7 and 30? So I know what I should be targeting, and what are good ways to increase my numbers to get the to that level. There are the obvious things such as notifications, but what are the less obvious strategies that a novice is unlikely to think of?


texts:
I am trying to predict a ball(sphere) movement. The formula of force which I know is

Force=Mass*Accelaration

What I want is how can I get distance or displacement by giving particular force? I want to consider drag, angular drag and friction also included in the equation. Or if it can be vice-versa, calculating force needed by providing distance.

The equation I could find doesn't include drag and friction, thus they are not as accurate as I needed. Any help in generating the exact formula would be appreciated.


texts: Warcraft III, SharpCraft C# plugin: Usage of native "TimerStart"?

texts:
about:

Blizzard Warcraft III [furthermore abbreviated as WC3]
related version: WC3: The Frozen Throne 1.26.0.6401 (german Patch 1.26a)
MindWorX Sharpcraft [furthermore abbreviated as SC]
related version: 1.2.4.0

issue:

I'm trying to use the native "TimerStart" from the WC3 "common.j" package inside a SC plugin written in C#. what gives me problems is the last argument from the native ("code handlerFunc"). as there is no native for creating functions, I dont know how to use it properly, can you give an example? for reference of the "code"-argument (it isnt even declared in the "common.j") i used Vexorians thread on wc3c.net, part: "I. The code type". here is the native like declared in "common.j":

native TimerStart           takes timer whichTimer, real timeout, boolean periodic, code handlerFunc returns nothing

in the SC plugin I initialized the native like this:

private delegate void TimerStartPrototype(JassTimer whichTimer, JassRealArg timeout, JassBoolean periodic, JassCode handlerFunc);
private static TimerStartPrototype TimerStart = WarcraftIII.Jass.GetNative("TimerStart").ToDelegate<TimerStartPrototype>();
//native TimerStart           takes timer whichTimer, real timeout, boolean periodic, code handlerFunc returns nothing

additionally in SC plugin, I created a void to pass to the last argument of the native: (note that "StopCamera" is another native from "common.j" i also initialized in the SC plugin but not showing here, because it is done in the same way "TimerStart" was.)

private delegate void StopCameraFuncPrototype();
private void StopCameraFunc() {
    StopCamera();
}

usage of the native "TimerStart" in SC plugin: (note that the variable "jTim_mouseWheel" is a "JassTimer" created somewhere else in the SC plugin.)

TimerStart(jTim_mouseWheel, (JassRealArg)0.01, false, (JassCode)StopCameraFunc());

when im trying to run WC3 with SC, the SC console window prints that it couldnt compile the appropriate plugin *.cs-file due to not being able to convert void to JassCode. by simply renaming "void" into "JassCode" I get the error, that not all code paths return a value...


texts: What certificate do I need for my client-server game?

texts:
I have a multiplayer game with a custom client app and an application server (no browser or website). I need

the data that passes between them to be encrypted both for the login data obviously and for the game actions.
that the server answer only to requests from my clients and that the clients get information only from the server.

From what I read, I need 2 certificates for that. Can I use self-signed certificates for the client and server? How do other games usually handle this?


texts: In the game I'm making, I'll sometimes need to play videos of the .mp4 format. Does Irrlicht support .mp4 playback? And if so, can anyone recommend a good tutorial on doing so?


texts:
I'm working on an app which is a Word Puzzle. Player has to arrange about 10 words in correct order to solve it.
I have two options to build it:

Give user feedback (right or wrong) when he has put each word
Give user feedback (right or wrong) when he has put all words

In first option, the player gets quick feedback (as early as putting first word). But it is easy to brute-force the puzzle and hence the difficult of the game is low.
In second option, the player has to wait for long time (until he/she puts all words). But the puzzle is difficult to brute-force and the difficulty of the game is high.
I'm not sure which option should I choose?


texts:
I have two car in game one of them is cop that chase player, i put a NavMesh on cop with these values:

when the cop get close to player (player speed is 10 ) , movement will go jittery and not smooth.
Note: cop will not collide with player because i have changed stopping distance in script instead of editor.
Note 2: this jittery movement is not only in camera its also on scene view.
now how i must make movement smoother? where is the problem?


texts: I have been looking at the development of MMO games for a while and have got stuck up on one thing. Player Movement. If we have an area with 10 players, each player needs to be able to see the orientation and position of other players. But when players start moving I need to update the ten players locations simultaneously. If I were to use an MYSQL database it would be slow and laggy to send coordinates and get coordinates from the database everytime a player moved. What would be the professional and proper (more efficient) way of doing this?


texts:
I'm trying to get a sprite sheet clipped in the right order but I'm a bit stumped, every iteration I've tried has tended to be in the wrong order. This is my current implementation.

    Frames = (TempSurface->h / ClipHeight) * (TempSurface->w / ClipWidth);
    SDL_Rect Clips[Frames];
    for (i = 0; i < Frames; i++) {
            if (i != 0 && i % (TempSurface->h / ClipHeight) == 0)
                    ColumnIndex++;
            Clips[i].x = ColumnIndex * ClipWidth;
            Clips[i].y = i % (TempSurface->h / ClipHeight) * ClipHeight;
            Clips[i].w = ClipWidth;
            Clips[i].h = ClipHeight;
    }

Where TempSurface is the entire sheet loaded to a SDL_Surface and Clips[] is an array of SDL_Rects. What results from this is a sprite sheet set to SDL_Rects in the wrong order.

For example I need a sheet of dimensions 4x4 to look like this:

| 0 | 1 | 2 | 3 |
| 4 | 5 | 6 | 7 |
| 8 | 9 | 10| 11|
| 12| 13| 14| 15|

But instead I get this order:

| 0 | 4 | 8 | 12|
| 1 | 5 | 9 | 13|
| 2 | 6 | 10| 14|
| 3 | 7 | 11| 15|

Columns and rows order does not match. What should I do to fix the order?


texts: database design help for game / user levels / progress

texts:
Sorry this got long and all prose-y. I'm creating my first truly gamified web app and could use some help thinking about how to structure the data.

The Set-up

Users need to accomplish tasks in each of several categories before they can move up a level. I've got my Users, Tasks, and Categories tables, and a UserTasks table which joins the three. ("User 3 has added Task 42 in Category 8. Now they've completed it.") That's all fine and working wonderfully.

The Challenge

I'm not sure of the best way to track the progress in the individual categories toward each level. The "business" rules are:

You have to achieve a certain number of points in each category to move up.
If you get the number of points needed in Cat 8, but still have other work to do to complete the level, any new Cat 8 points count toward your overall score, but don't "roll over" into the next level.
The number of Categories is small (five currently) and unlikely to change often, but by no means absolutely fixed.
The number of points needed to level-up will vary per level, probably by a formula, or perhaps a lookup table.

So the challenge is to track each user's progress toward the next level in each category. I've thought of a few potential approaches:

Possible Solutions

Add a column to the users table for each category and reset them all to zero each time a user levels-up.
Have a separate UserProgress table with a row for each category for each user and the number of points they have. (Basically a Many-to-Many version of #1.)
Add a userLevel column to the UserTasks table and use that to derive their progress with some kind of SUM statement.

Their current level will be a simple int in the User table.

Pros & Cons

(1) seems like by far the most straightforward, but it's also the least flexible. Perhaps I could use a naming convention based on the category ids to help overcome some of that. (With code like "select cats; for each cat, get the value from Users.progress_{cat.id}.") It's also the one where I lose the most data -- I won't know which points counted toward leveling up. I don't have a need in mind for that, so maybe I don't care about that.

(2) seems complicated: every time I add or subtract a user or a category, I have to maintain the other table. I foresee synchronization challenges.

(3) Is somewhere in between -- cleaner than #2, but less intuitive than #1. In order to find out where a user is, I'd have mildly complex SQL like:

SELECT categoryId, SUM(points) from UserTasks WHERE userId={user.id} & countsTowardLevel={user.level} groupBy categoryId

Hmm... that doesn't seem so bad. I think I'm talking myself into #3 here, but would love any input, advice or other ideas.

P.S. Sorry for the cross-post. I wrote this up on SO and then remembered that there was a game dev-focused one. Curious to see if I get different answers one place than the other....


texts: I'm looking for a basic example of rotating camera using the mouse. the only problem is I'm not sure of how to rotating the camera around it target. should i do this by an algorithm or is there a method of doing this? I am also only using managed dirextx and no wrappers


texts: Is attribution sufficient for CC BY-SA 3.0-licenced music in a commercial mobile game?

texts:
I am in the process of developing a mobile game that I intend to sell on Google Play. I want to include a music licensed as:

  Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0)

If I attribute the author/contributor of the music, am I allowed to sell my game without the same license?

I would like to get opinions from people who have had experience in this situation.


texts: RenderTexture is not cleared after it was released

texts:
I want to create some image effect. I've written a script that draws a cube mesh at the render target and then copies the render texture at the screen. I don't want to render anything except Mesh(M) in my RenderTexture(rt):

    void OnRenderImage(RenderTexture src, RenderTexture dest)
    {
        RenderTexture rt = RenderTexture.GetTemporary(Screen.width / 1, Screen.height / 1 );

        Graphics.SetRenderTarget(rt);
        Graphics.DrawMeshNow(M, new Vector3(0.0f, 0.0f, -8.0f), Quaternion.identity);
        Graphics.Blit(rt, dest);

        Graphics.SetRenderTarget(null);
        RenderTexture.ReleaseTemporary(rt);
    }

Where M is GameObject.CreatePrimitive(PrimitiveType.Cube).GetComponent<MeshFilter>().sharedMesh;

When I moved my camera, I see this:

It seems like the RenderTexture didn't cleared itself when released. Or maybe I did something wrong? Please explain why this happened and how can I fix this.


texts: Which are the most complete DirectX game or technical demo with source available

texts:
I have found plenty of games with source for OpenGl, but so far I haven't found anything like that for DirectX. There are plenty of examples in the SDK, but they are very basic and usually they just expose one very specific aspect of the API at a time.
So I am wondering which are the best or most complete DirectX games with source available these days.

EDIT

I am making a small study about the differences in the final output across different GPUs. I want to have games in DirectX and OpenGL. To remove any differences caused by non-determinism, like thread scheduling and timing information. I already have done it for Doom 3 which is a great example for OpenGL. I would like to have something in DirectX to perform similar tests with, and I was hoping I could find something better than the simple demos included in the SDK.


texts:
I've been working on a fish system in a compute shader but bugs have been drowning me. The latest bug had me strip almost all the functionality to track down:

Fish keep turning in circles. It starts slowly, the fish gains velocity in the proper direction, then it reverses. The fish slowly loses velocity until it does a 180 and then the forward wander then applies acceleration behind it repeating the process. However the reverse isn't exactly 180 degrees behind it. It goes from doing roughly 180 degree instant turns to tracing smooth circles over a period of roughly 10 seconds.

float desiredSpeed = 0.2f;
// Wander Behavior substitute
float3 acceleration = (fish.mat._21_22_23 * desiredSpeed  - fish.velocity) * velocityMultiplier;

// Acceleration
float accelMag = length(acceleration);
float3 steerDirection = fish.mat._21_22_23;
if (accelMag > 0)
    steerDirection = acceleration / accelMag;
if (accelMag > desiredAccel)
{
    acceleration = steerDirection * desiredAccel;
    accelMag = desiredAccel;
}

// Direction
if (accelMag > 0)
{
    // Removed rotation smoothing
    fish.mat._21_22_23= normalize(acceleration); // forward
    fish.mat._11_12_13 = normalize(cross(fish.mat._21_22_23, float3(0, 0, 1))); // right
    fish.mat._31_32_33 = normalize(cross(fish.mat._11_12_13, forward)); // up
}

// Velocity
fish.velocity += fish.mat._21_22_23 * accelMag * fishDeltaTime;

speed = length(fish.velocity);
if (speed > desiredSpeed)
{
    fish.velocity = fish.velocity / speed * desiredSpeed;
    speed = desiredSpeed;
}
fish.mat._41_42_43 += fish.velocity * fishDeltaTime;

Once the fish is going in circles I understand what is happening. The fish has a velocity off to one side and it calculates the desired velocity as (forward * speed - velocity). That translates to an acceleration added at an angle pointing inwards away from the velocity so the fish continues to turn. You can sort of see it in this picture:

The light gray line is the current velocity, dark blue the desired wander velocity (forward), light blue the wander acceleration that is causes the fish to turn to the left.

My questions are:

Why does the fish slow and start to turn if acceleration is only added in the forward direction?

How do I rewrite the code so that the this sort of situation doesn't happen? Ideally the current velocity would become more forward and the corrective acceleration would lower until it went back to a normal straight line.


texts:
I have done some reading into this subject but haven't been able to come to a conclusion that I'm really satisfied with so far, so here is the situation. I have a game set in space, its top down and essentially 2D as far as physics is concerned and it revolves around the gravitational interaction between planets and black holes. I'm using Unity, so I have the ability apply forces to bodies. However, I have to do all the gravity calculations myself... This is where I get stuck.

Now it's not the maths that I'm having trouble with, maths I can do, its general game "feel" that is the sticking point. Originally I tried Newtons standard gravitational equations but I found that to a general user they produce unexpected behaviour. If you place two different mass planets on either side of a central black hole, both the same distance away, they will reach the central black hole at the same time (which "feels" odd). I also played around with more primitive implementations that just manipulate distance and mass in different ways but I always ended up with the same issue; as the planets im using undergo dramatic shifts in mass over the course of the game, the effect of the black holes always starts off being overly erratic (at low body masses) and then moves to being overly sluggish (at high masses) giving the game a very inconsistent feel at the moment.

Has anyone run into the same issue here and come out with a good way of simulating gravity in space? Does anyone know of examples of where this has been done before? What are some things that I may have overlooked or may want to take into consideration in the calculations?  Remember that realism isn't the main concern here, its game "feel".

I'm open to any and all suggestions here so don't hesitate to put forward any sort of crazy answers!


texts: Unity3D Hex Grid neighbor search with radius

texts:
I am trying to develop a small Game with a Hex Grid. I need to find the Neighbors of one Hex Tile in a specific radius.

Here is a screenshot of my Problem: Screenshot

I followed this awesome tutorial along and implemented some of the systems presented here: https://www.redblobgames.com/grids/hexagons/

public GameObject[] GetNeighbarsInRange(Vector2 pos, int range) {

    List<GameObject> tiles = new List<GameObject>();

    int min = -range, max = range;

    for (int x = min; x <= max; x++) {

        for(int y = min; y <= max; y++) {

            for(int z = min; z <= max; z++) {

                if (x + y + z == 0) {

                    Vector2 newPos = getVector2Coord(new Vector3(x, y, z)), newTilePos = new Vector2(pos.x + newPos.x, pos.y + newPos.y);
                    tiles.Add(getTile(newTilePos));

                }

            }

        }

    }

    return tiles.ToArray();

}

public Vector2 getVector2Coord(Vector3 pos) {

    int x = (int) pos.x, z = (int) pos.z;
    int newX = x, newZ = z + (x - (x&1)) / 2;
    return new Vector2(newX, newZ);

}

public Vector3 getVector3Coord(Vector2 pos) {

    int x = (int) pos.x, y = (int) pos.y;
    int tileX = x, tileZ = y - (x - (x&1)) / 2, tileY = -tileX - tileZ;
    return new Vector3(tileX, tileY, tileZ);

}

Here you can see my Neighbor calculation and my Cube to Offset Coords and my Offset Coords to Cube Functions. My Grid is based on the Offset Coord System, I am saving my Grid in a 2D Array and when I search for neighbors I convert them into the Cube Format. My Problem is for the even cols its working fine but for the odd cols, it is not. My Question is how can I fix this?

It is btw. the same if I increase the radius to 2 instead of 1.

Kind regards,

Alex

(Sorry for my bad English I am from Germany:D)


texts: Transform coordinates from 3d to 2d without matrix or built in methods

texts:
Not to long ago i started to create a small 3D engine in javascript to combine this with an html5 canvas.

One of the issues I run into is how can you transform 3d to 2d coords.
Since I cannot use matrices or built in transformation methods I need another way.

I've tried implementing the next explanation + pseudo code:
http://freespace.virgin.net/hugo.elias/routines/3d_to_2d.htm

Unfortunately no luck there. I've replace all the input variables with data from my own camera and object classes.

I have the following data:
An object with a rotation, position vector and an array of 4 3d coords (its just a plane)
a camera with a position and rotation vector
the viewport -> a square 600 x 600 surface.
The example uses a zoom factor which I've set as 1

Most hits on google use either matrix calculations or don't implement camera rotation.
Basic transformation should  be like this:
screen.x = x / z * zoom
screen.y = y / z * zoom

Can anyone point me in the right direction or explain to me howto achieve this?

edit:
Thanks for all your posts, I haven't been able to apply all this to my project yet but I hope to do this soon.

Ok after playing around a while some issues still remain.
I've created a new projection matrix:

    var w = (2 * nearPlane) / viewportWidth;
    var h = (2 * nearPlane) / viewportHeight;
    var q = farPlane / (farPlane - nearPlane);

    this.ProjectionMatrix = $M([
      [w, 0, 0, 0],
      [0, h, 0, 0],
      [0, 0, q, 1],
      [0, 0, (nearPlane * farPlane) / (nearPlane - farPlane), 0]
    ]);

where viewport = 600 * 450

and near plane = 0.5 and far plane = 500

the original code for drawing the vertices is this:

 var comboMatrix = world.WorldMatrix.x(camera.ViewMatrix);
    for (i = 0; i != this.NumberOfPolygons; i++) {
        var transformedVertices = new Array(verticesPerPolygon);
        var valid = new Boolean(1);
        for (j = 0; j != verticesPerPolygon; j++) {

            currentVertex = this.Mesh[i][j].x(comboMatrix);

            currentVertex.elements[0][0] = currentVertex.elements[0][0] / currentVertex.elements[0][2];
            currentVertex.elements[0][1] = currentVertex.elements[0][1] / currentVertex.elements[0][2];

            if (currentVertex.elements[0][0] < -1 || currentVertex.elements[0][0] > 1 || currentVertex.elements[0][1] < -1 || currentVertex.elements[0][1] > 1) {
                valid = new Boolean(0);
                break;
            }

            // Process Viewport Mapping Transformation
            currentVertex.elements[0][0] = currentVertex.elements[0][0] * 300 + 300;
            currentVertex.elements[0][1] = -currentVertex.elements[0][1] * 300 + 300;

            transformedVertices[j] = currentVertex;
        }

        // Draw the polygon
        if (valid == true) {
            this.DrawQuad(context, transformedVertices, true, new Boolean(0), new Boolean(1));
        }
    }

which kinda works since the letter H is drawn on my screen. Moving the camera however makes parts of the letter stop being drawn whenever one of the vertices is outside a 300 * 300 region.
I'm assuming this has something to do with a very basic implementation of a projection in these lines:

            currentVertex.elements[0][0] = currentVertex.elements[0][0] * 300 + 300;
            currentVertex.elements[0][1] = -currentVertex.elements[0][1] * 300 + 300;

Can anybody help me out howto change this piece of code so it works with my projection matrix?

I've tried removing the last 2 lines and changing transformedVertices[j] = currentVertex; into transformedVertices[j] = currentVertex.x(projection);
with no result.


texts:
How to improve image clarity in Unity 3d. If we use same images for game developing in Adobe Flash and in Unity , flash game have more clarity , but in unity image will blur . Text Mesh also blur

How to get good clarity in unity games

I made a 2d game using quad,cube , sprite and Text Mesh . Platforms Android ,iPhone , Mac ,PC . Every platform have poor clarity

Image size is 44X44 pixels to 1024x1024 pixels


texts: Collision detection with heightmap based terrain

texts:
I am developing a 2D tank game. The terrain is generated by Midpoint Displacement Algorithm, so the terrain is represented by an array:

index --->  height of terrain
[0]   --->  5
[1]   --->  8
[2]   --->  4
[3]   --->  6
[4]   --->  8
[5]   --->  9
...         ...

The rendered mountain looks like this:

        *
  *     * *
  *     * *
  *   * * *
* *   * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
0 1 2 3 4 5 ...

I want tanks to be able to move smoothly on the terrain (I mean tanks can rotate according to the height when they move), but the surface of the terrain is not flat, it is polygonal. Can anyone give me some help with collision detection in this situation?

Thanks in advance.


texts: When to carry on with a buggy game state versus terminate the process?

texts:
Imagine a situation where a level/game designer has missed assigning a prefab in one of the game objects' inspector configurations. (I am coming from Unity, but what I basically mean a reference to some object prototype).
In this case we are getting a NullReferenceException which could crash the game.
If we know that this could happen, we can prevent this exception and print something useful to the console.
How should we choose between these two methods?

throw an exception and crash the process
or just print something useful to the console for the developer to know.

The problem is when player would be playing the game, in case of an exception they would be thrown out of the game and it would stop working showing them what has gone wrong and to send info to the developer, but in case of console log they would be able to continue playing the incomplete version of the game.
It may seem like this question requires an opinionated answer, but to me it seems like there is a best practice for these situations and there are vivid pros and cons to each one.
My thoughts:
If player continues to play an incomplete game this will result in an incomplete experience which may lead to bad reviews or something like that. But when game is terminated at some point - player may be even angrier that game is not working at all.
My own conclusion is that you would rather continue with the game, but in case of any error logs you would display player that something has gone wrong in the UI.
Unity specific:
Unity usually runs fine after unhandled exception has been thrown, so there could be no point to this.
But the problem is that I have a choice between:
Debug.LogError("Something useful for the designer.");
return new ADummyObjectThatWillPreventFutherExceptions();

or
throw new NullReferenceException("Something useful for the designer.");

The second one seems more appealing since it's really hard or impossible to predict most situations when this could happen.


texts: Combine skin material to two elements without a visible seam

texts:
Software used: 3ds max 2015 and Photoshop CC 2014.

I have two elements of the head, the "FaceHead" and "UpperHead". I used unwrap UVW for both elements and used Photoshop to add a skin color (eye and lips for "FaceHead") and the same skin color for "UpperHead". I created an image for both elements in Photoshop and added the image to the elements using the Material Editor (with Bitmap option). The problem is, that there is a visible seam between the 2 elements, although I used the same color for both. Is there a solution to solve this?

What I tried:

Used of MaterialByElement
Used of different color
Extend to 2 pixel from the border using Photoshop when applying Paint.


texts: What's the equivalent of wglShareLists for Mac OS?

texts:
I'm trying to share lists between two contexts on Mac OS but despite my research I couldn't come up with an answer so far. I've found that NSOpenGLContext was able to initialize a context with a shared context but not to set it afterward.

What's the equivalent of wglShareLists on Mac OS?


texts:
I make my money in C# Generally in that language I like to decouple everything to the high heavens using interfaces. This has served me well in enterprise code but in writing games in C# I find myself tending towards inheritance due to being able to define some default behaviors for base classes. I feel dirty doing this though, like I'm disobeying some architecture god who once said "favor composition over inheritance". I know its not black and white but I also feel like i could use interfaces with a bit more work and achieve roughly the same thing.

What do other people do? Is inheritance the right approach for games or should I refactor in some interfaces?


texts: One pass rendering with GL_TEXTURE_CUBE_MAP_ARRAY

texts:
I try to rework rendering of point light shadows from "pass per cube face" to "one pass using geometry shader".

initialization:

glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, texId);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexImage3D(GL_TEXTURE_CUBE_MAP_ARRAY, 0, GL_DEPTH_COMPONENT, getWidth(), getHeight(), 6 * lightsNumber, 0, GL_DEPTH_COMPONENT, GL_FLOAT, (ByteBuffer) null);
glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, 0);

glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, texId, 0);

int status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
   throw new IllegalStateException("Could not create FrameBuffer: " + status);
}

glBindFramebuffer(GL_FRAMEBUFFER, 0);

using:

glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, shadowBuffer.getTexture().getId(), lightNumber);

glClear(GL_DEPTH_BUFFER_BIT);

renderMeshes(scene, transformation);

depthShaderProgram.unbind();
glBindFramebuffer(GL_FRAMEBUFFER, 0);

GS:

#version 430

layout (triangles) in;
layout (triangle_strip, max_vertices=18) out;

uniform mat4 projLightViewMatrix[12]; // just two light
uniform int lightNumber;

void main() {
  for (int lIdx = 0; lIdx < lightNumber; lIdx++) {
    for(int face = 0; face < 6; face++) {
      gl_Layer = lIdx * 6 + face;
      for(int i = 0; i < 3; i++) {
        gl_Position = projLightViewMatrix[gl_Layer] * gl_in[i].gl_Position;
        EmitVertex();
      }
      EndPrimitive();
    }
  }
}

It casts shadows only for 1st light.
Could you notice something wrong?


texts:
I'm trying to save a slider value and load it when I run again the game. but here is not working. yes, I can change the value and save it but not load it.

    public Slider Brightness;
    public float bri,briv; // only briv value I saving it.

    // Use this for initialization
    void Start () {
        PlayerPrefs.GetFloat("briv");
        Brightness.value = briv;
        }

    void Update() {
            briv = bri;
            bri = Brightness.value;

    if (Input.GetKeyDown(KeyCode.S)) {
        PlayerPrefs.SetFloat("briv",briv);
        Debug.Log ("save");
    }

        } // end update


texts: Resolution problems with global illumination in Unity

texts:
I am pretty new to Unity and after hours of searching I have finally figured out how to set everything up for (baked) global illumination to work for my model.

However the model is an export from a CAD program and so the mesh is rather bad quality (it seems it is optimized by the CAD program for minimum number of triangles). At least I am implicitely assuming that this is a bad quality mesh because it would by standard of finite element meshes, which of course doesn't directly apply here.

So what I am observing is three resolution problems (see images):

1) the lighting in the scene is somewhat "cloudy" although the faces are evenly colored and there are no lights that could explain the patterns (see eg. area inside drawn red rectangle)

2) there are slight jumps in brightness visible at the edges of the triangles of the mesh (see red arrows and, for comparison image of mesh)

3) the shadows are pixelated (see red ellipse, yes I have already tried to change shadow quality to high in the project settings, but to no avail)

Because there are so many settings that affect lighting, I assume it will take me hours if not days with trial and error to figure that out.

Which settings are likely to be responsible for these three problems?

I found a display mode of the scene view, called: Baked Global Illumination->UV Charts that probably explains the first problem, but I don't know how to interpret it, see third image below:


texts: What framework do you reference for external dll's to work with Unity/Mono?

texts:
So I want to compile an extensions dll for a unity game because I feel I'll end up reusing these extensions in other games/projects too - and I want to learn about external dependencies with Unity. :)

Anyway. I've found some posts that say to reference .NET 2.0, however, when selecting a framework in project settings, I get a list of Unity frameworks that I think were added to VS by either UnityVS(VSUnity?) or Unity 5.

I'm unsure which to select for an external DLL. :/

edit: I also thought the current Unity (v5) supported Mono up to the equivalent of .NET 3.5?

A related question. Whichever framework I end up selecting, will I be able to reference "UnityEngine" in said project?


texts: How do I correctly import an animation from blender into UE4?

texts:
I have animated a conveyor belt in blender. When I import the animation to UE4, the conveyor belt does not move correctly. What am I doing wrong?
Here is a link to my blender file: Blender File


texts:
What processes, tools, methods are used by game artists to prepare materials for the programmers?

I am interested in tools (ie: photoshop, pixelmator, etc for drawing) and also how they are used together to produce texture atlases or individual images for the programmers.

Methods or way of working (tool-chains maybe), which can be used by the artist to

Present ideas (sketches)
Mesh up game images (photosop: front menu, in-game)
Cut up images/layers into (ie: copy paste?)

smaller individual pieces
texture atlases (some other tool)

Generate coordinates ie: (xywh) for button "Options" on the main screen which is stored as main_options.png or (uvhw, xywh) for in-game HUD which is in a texture_atlas.png.
Any way to automate some of the steps above?

============ before edit ============

The artist(s) might use hand drawings-scanner/sketch pad for illustration.
These are then imported and further improved in some other image manipulation tools.
The result then can be used to produce both preview of the game (menu, in-game meshups) and final elements which will be used by the programmer(s): individual images or texture atlases.

Which tools are artists using out there and how for game development to produce the material used by game programmers?

I am particularly interested if there are automated tools where a small change at the illustration part can be propagated to produce final production images/textures without the need for the artist to cut/merge them.


texts: How to correctly reference a texture bound using SetTexture in Direct3D 9

texts:
In Direct3D 9, after assigning a few textures to samplers using SetTexture, what is the correct way to access/create the samplers in the relevant pixel shader? Previously I was creating samplers like this:

texture tex : register(r0);
sampler2D sam = sampler_state {
    texture = <tex>;
    minfilter = none;
    magfilter = none;
    mipfilter = none;
};

Which seemed to work fine, however, now that I'm binding multiple textures this doesn't work consistently. However, the following appears to work:

sampler2D sam : register(s0);
sampler2D sam1 : register(s1);

The documentation for SetTexture says:

  Programmable shaders reference textures using the sampler number.

But I'm not sure whether or not this means that the sampler registers should be used to sample textures set with SetTexture, or whether the sampler requires any further initialisation aside from the call to SetTexture.


texts: Game navigation disabled after changing Quality settings

texts:
Just installed Unity 2019.11.f1(Personal)[Window10/64bit-Dx11 on Dx10] and ran the sample "Lightweight rendering pipeline" Construction Project.

At the start,the game navigation keys [W-A-S-D] worked but the navigation was slow.
So on changing the Quality settings[Edit-ProjectSettings-Quality] from  default "High" to "Low", the game navigation keys have got disabled and the console throws the following error-

Converting invalid MinMaxAABB

On reverting back to the working "High" quality settings , the navigation controls no longer work.
How to resolve this issue?


texts: Unity2D Multiplayer - Spawning player at user's end

texts:
I am currently into a 2d mobile multiplayer project. Its going to be a 2 player game for now. So the host and the client are the only players.

I am using Unity 5.4 and the default multiplayer platform by the way. I am able to spawn the character both on client and server. The syncing also works pretty well.

But for the game to be user friendly, obviously I have to spawn the player on his end of the screen and the opponent on the other end. I am unable to achieve this on the client screen. In the client screen, the client starts from the upper end of the screen making it difficult to play with.

So, my question. How would I go about spawning a player in his device on his end of the screen and the opponent on the other side? The only idea I came up with was switching the spawn points in the client version of the game. Is it possible accessing client's version of the game during runtime? And would it be the right way to go about it? If not please share an alternate solution.

Thanks


texts: Entity/Component System - Unique Behaviour

texts:
So, I decided to see what the Entity/Component system of game development was all about. I really liked it. So, I decided to implement my current game with it.

My problem: Unique Behaviour with the system. From what I have seen, the way to implement Unique Behaviour for a entity is to Create a unique Component, and a Unique System that only accepts Entities with that Component. This seems to be a lot of code, for what could be a very small feature.

My Solution: Have entities with "hooks" in them, so that they can define their own unique behaviour in them. They would still have the major things done for them by systems, such as Health, Rendering, and Movement.

e.g.:

public abstract class EntityLiving extends Entity{

    /**
     * Called when a entity is spawned in
     * @param map
     */
    public void onSpawn(Map map) {this.map = map;}

    /**
     * Called when an entity is killed
     * @param map
     */
    public void onDeath(Map map) {}

My Question: Is this bad programming practice? Could this be done in a 'better' way? I realize that this question is extremely subjective, but I would like some professional opinions.

EDIT: By better I mean, in order of priority:

Less Code for this scenario
Code Reusability
Code Efficency


texts: Does a 2D Vector or 2x2 Matrix play any role in 2D Transformations?

texts:
I'm having trouble trying to figure out if a vec2 or mat2 class are used at all in transformations for 2D rendering. Vec2, apart from representing UVs, AFAIK, is relatively pointless in regards to homogeneity.

What about 2x2 Matrix? I guess if we're hanging on to temp variables for shear, scale, and/or rotation it could make sense, but I'm feeling like I'll never use it.

It isn't much effort to implement, but I'd like to know if I'm missing something, or if Vec2 and Mat2 are largely useful for representing objects in 2D space.

I do know that a 3x2 or 2x3 matrix is a more data efficient* way to store the data for affine transformations-- does vec2 have any utility in these sort of cases?

Or is this even true? Do alignment optimizations negate this advantage? Or is it only true for the data that we transfer into OpenGL?


texts: What are the steps to get sound from reality into a game?

texts:
As we all know, the game is not only about gameplay, sound effects add a lot to the production value. The more unique, the better the result.

What are the steps to get a decent quality sound from reality into a game environment?

And some tips probably, as whether I should cover multiple cases of the "sound": normal, echo and other. Or this can/should be done within the engine itself, or post-processed after normal sound?


texts: GlViewport-code doesn't work in one specific screen?

texts:
I am currently working on a small game using LibGDX and Java.

However, I have found one oddly specific problem. I want the game to resize so that it never has to be cropped and so it never has to cut anything off - basically just setting the viewport so everything still fits onto the screen on resize. Sounds simple.

Now, I have the code for that in place. All of my screens extend one BaseScreen in which I defined the following code:

@Override
public void resize (int width, int height) {
    Vector2 size = Scaling.fit.apply(Constants.GAME_WIDTH, Constants.GAME_HEIGHT, width, height);
    int viewportX = (int)(width - size.x) / 2;
    int viewportY = (int)(height - size.y) / 2;
    int viewportWidth = (int)size.x;
    int viewportHeight = (int)size.y;
    Gdx.gl.glViewport(viewportX, viewportY, viewportWidth, viewportHeight);
}

(Note, I have not written this code by myself, it is one of the few pieces of code I searched online for as I had no previous experience with LibGDX)

Now, this code works absolutely fine in almost every screen - just not in the RoomScreen, which is the screen where the main gameplay is happening. Which is quite a bummer, as it basically makes the game look really shitty except for multiples of my game size (the constants are set as 480 and 272).

Now, I have absolutely no idea why this is the case. I read that this might be because transforms are pushed, but not pulled afterwards, but I did not find any instance of this in my code.

I also tested wether the code is executed, and it indeed is. All variables are correctly set, it simply doesn't work.

If any of you is able to help me, I would be unbelievably thankful!

The full code is currently only available in my Dropbox, as my own Git server recently crashed. Here is the link: https://www.dropbox.com/sh/evvw5kiqcfos7fu/AADwogpkwl1RWj2QcI6eePyda?dl=0
(I am terribly sorry that I am only able to share it this way, but I am afraid that sharing every relevant class in this post itself would in the end result in pasting all my code here, making it almost unreadable. If any of you has a better idea than this, please tell me, I'll gladly share it otherwise!)

If you are wondering, the screen classes are in the folder "screen".


texts: How to achieve an aesthetic which looks like hand-made pencil and paper drawings?

texts:
I am a programmer in the process of making a stick figure game and I draw the figures myself. The thing is that they look like they are made of black pixels, but I want them to look photorealistic as if they were drawn on paper. They are also animated with short 4 frame loops, each frame drawn individually.

I want my game art style to look somewhat like the following drawings,

but imagine this is actually a game where everything is animated. Is this possible with proper art style alone or shading techniques should be involded in the process? If so, can you point me in the right direction?


texts: LibGDX Box2DLights shadow offset problem on bodies

texts:
Hello I just started to use LibGDX, and it's awesome.
I looked at the Box2DLights library, and started to learn how the lighting work here.

I got something up:

(source: gyazo.com)

As you can see, it works, but the shadow of the sprite goes over itself, and doesn't start in the right place.

Why is it doing this? is it possible to set offsets?

This is how I initialize them:

    this.texture = new Texture("sprites/water.png");
    this.camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    this.camera.setToOrtho(false);
    this.renderer = new SpriteBatch();

    this.map = new TileMap(20, 20);
    this.map.generateAllSame(new Texture("sprites/sprite.png"));

    this.world = new World(new Vector2(), true);

    this.createBodies();

    RayHandler.setGammaCorrection(true);
    RayHandler.useDiffuseLight(true);
    this.ray = new RayHandler(this.world);
    this.ray.setAmbientLight(0.2f, 0.2f, 0.2f, 0.1f);
    this.ray.setCulling(true);
    this.ray.pointAtLight(50, 0);
    this.ray.setBlurNum(1);
    camera.update(true);
    this.spriteLight = new PointLight(ray, 128);
    this.spriteLight.setDistance(500f);
    this.spriteLight.setPosition(150, 150);

    this.spriteLight.setColor(new Color(0.5f, 0.8f, 0.7f, 1f));
    this.spriteLight.setSoftnessLength(0);
    this.spriteLight.setSoft(true);

public void createBodies() {
    CircleShape chain = new CircleShape();
    chain.setRadius(10);

    FixtureDef def = new FixtureDef();
    def.restitution = 0.8f;
    def.friction = 0.01f;
    def.shape = chain;
    def.density = 1f;

    BodyDef body = new BodyDef();
    body.type = BodyType.DynamicBody;

    for (int i = 0; i < 3; i++) {
        body.position.x = 40 + MathUtils.random(500);
        body.position.y = 40 + MathUtils.random(500);

        Body box = this.world.createBody(body);
        box.createFixture(def);
        this.bodies.add(box);
    }
    chain.dispose();
}

And my rendering:

public void render() {
    handleInput();
    camera.update();
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    renderer.setProjectionMatrix(camera.combined);

    renderer.disableBlending();
    renderer.begin();
    this.map.render(renderer);
    renderer.draw(texture, 50, 50);

    renderer.enableBlending();

    for (Body body : this.bodies) {
        Vector2 pos = body.getPosition();
        renderer.draw(texture, pos.x + amount, pos.y);
    }
    renderer.end();

    ray.setCombinedMatrix(camera.combined, camera.position.x, camera.position.y,
            camera.viewportWidth * camera.zoom, camera.viewportHeight * camera.zoom);

    ray.update();
    ray.render();

}

What did I do wrong?


texts: Generate 4 vectors rotated in cardinal directions from a central vector

texts:
There is some unit vector, which is a coordinate in a spherical space. It is necessary to obtain from it 4 vectors diverted in different directions (right, left, forward, backward) by a certain number of degrees. For these actions I use the following code:

Vector3 center = point;
Vector3 left = Quaternion.Euler(-30, 0, 0) * center;
Vector3 right = Quaternion.Euler(30, 0, 0) * center;
Vector3 back = Quaternion.Euler(0, 0, -30) * center;
Vector3 front = Quaternion.Euler(0, 0, 30) * center;

The problem is that this works when point is equal or close to Vector3.up. When deviating from the vertical position, the lateral vectors begin to "stick together".

Here is a visualization of what I need:

Test code is attached:

using System.Collections;
using UnityEngine;

public class Test : MonoBehaviour
{
    public GameObject centerGO;
    public GameObject leftGO;
    public GameObject rightGO;
    public GameObject backGO;
    public GameObject frontGO;

    ArrayList list = new ArrayList();

    void Start()
    {
        SetCenterPoint(Vector3.up);
    }

    void Update()
    {
        DrawDebugRays();

        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit))
        {
            SetCenterPoint(hit.point);
        }
    }

    void SetCenterPoint(Vector3 point)
    {
        Vector3 center = point;
        Vector3 left = Quaternion.Euler(-30, 0, 0) * center;
        Vector3 right = Quaternion.Euler(30, 0, 0) * center;
        Vector3 back = Quaternion.Euler(0, 0, -30) * center;
        Vector3 front = Quaternion.Euler(0, 0, 30) * center;

        centerGO.transform.position = center;
        leftGO.transform.position = left;
        rightGO.transform.position = right;
        backGO.transform.position = back;
        frontGO.transform.position = front;

        list.Clear();
        list.Add(center);
        list.Add(left);
        list.Add(right);
        list.Add(front);
        list.Add(back);
    }

    void DrawDebugRays()
    {
        for (int i = 0; i < list.Count; i++)
        {
            Color color = Color.red;
            switch (i)
            {
                case 0:
                    color = Color.green;
                    break;
                case 1:
                case 2:
                    color = Color.blue;
                    break;
            }
            Debug.DrawRay(Vector3.zero, (Vector3)list[i], color);
        }
    }
}


texts: How to run a method after a scene2d being rendered in libGDX

texts:
I want to make a screenshot with

ScreenUtils.getFrameBufferPixmap(x, y, w, h);

I call this function in Actions.run(new Runnable{...}) in scene2d.ui, and the problem is that actions are called at very beginning of a new frame, so nothing is rendered yet.

How to call this method properly, e.g.

Scene.inTheEnd(run(ScreenUtils.getFrameBufferPixmap(x, y, w, h);));

?


texts:
I need to set up a monetary system for my game however I am unsure how to craft an internal economy for that money. I want to make an rpg with a economy system that keeps the player for a time from just selling numerous of the same item to grind for money. So when the player sells to much of a certain item the buy price for that item will go down temporarily. Also, I would like to add a system where certain items go up in terms of what they can be sold for temporarily as well.

For example, in "Story of Seasons" I can sell items to vendors in order to get money, however if I sell to much of that type of item the price I get for it goes down. Also, there is a system where for a certain vendor or more the price I can get for the items actually increases.


texts: Unreal Engine Physics creation is slower in Editor

texts: I just figured out that when UPrimitiveComponent::CreatePhysicsState() is called, it calculates the mass, but only in editor, also when i build for non-editor it is faster (standalone) this is not because the editor is eating up resources, because time is measured in code. Why is the mass only calculated in editor?


texts:
I've recently been trying to blend multiple textures based on the height at different points in a heightmap. However i've been getting poor results. I decided to backtrack and just attempt to recreate one single texture from an SDL_Surface (i'm using SDL) and just send that into opengl. I'll put my code for creating the texture and reading the colour values. It is a 24bit TGA i'm loading, and i've confirmed that the rest of my code works because i was able to send the surfaces pixels directly to my createTextureFromData function and it drew fine.

struct RGBColour
{
    RGBColour() : r(0), g(0), b(0) {}
    RGBColour(unsigned char red, unsigned char green, unsigned char blue) : r(red), g(green), b(blue) {}

    unsigned char r;
    unsigned char g;
    unsigned char b;
};

    // main loading code
SDLSurfaceReader* reader = new SDLSurfaceReader(m_renderer);
reader->readSurface("images/grass.tga");

// new texture
unsigned char* newTexture = new unsigned char[reader->m_surface->w * reader->m_surface->h * 3 * reader->m_surface->w];

for (int y = 0; y < reader->m_surface->h; y++)
{
    for (int x = 0; x < reader->m_surface->w; x += 3)
    {
        int index = (y * reader->m_surface->w) + x;

        RGBColour colour = reader->getColourAt(x, y);

        newTexture[index] = colour.r;
        newTexture[index + 1] = colour.g;
        newTexture[index + 2] = colour.b;
    }
}

unsigned int id = m_renderer->createTextureFromData(newTexture, reader->m_surface->w, reader->m_surface->h, RGB);

    // functions for reading pixels
RGBColour SDLSurfaceReader::getColourAt(int x, int y)
{
    Uint32 pixel;
    Uint8 red, green, blue;
    RGBColour rgb;

    pixel = getPixel(m_surface, x, y);

    SDL_LockSurface(m_surface);

    SDL_GetRGB(pixel, m_surface->format, &red, &green, &blue);

    SDL_UnlockSurface(m_surface);

    rgb.r = red;
    rgb.b = blue;
    rgb.g = green;

    return rgb;
}

    // this function taken from SDL documentation
// http://www.libsdl.org/cgi/docwiki.cgi/Introduction_to_SDL_Video#getpixel
Uint32 SDLSurfaceReader::getPixel(SDL_Surface* surface, int x, int y)
{
    int bpp = m_surface->format->BytesPerPixel;

    Uint8 *p = (Uint8*)m_surface->pixels + y * m_surface->pitch + x * bpp;

    switch (bpp)
    {
    case 1:
        return *p;
    case 2:
        return *(Uint16*)p;
    case 3:
        if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
            return p[0] << 16 | p[1] << 8 | p[2];
        else
            return p[0] | p[1] << 8 | p[2] << 16;
    case 4:
        return *(Uint32*)p;
    default:
        return 0;
    }
}

I've been stumped at this, and I need help badly! Thanks so much for any advice.


texts: Static constants set to default value in HLSL

texts:
I'm using dx11 and I'm working on SSAO. I am having wierd results, so I tried debugging it using RenderDoc and stepping through the pixel shader log, all the values of the static array seems to default to 0-vector. For example, look at r3-register in the following screenshot.

Here's the pixel shader I'm using. The global static variable that seems to be all null despite my initialization is the gSSAOKernel. Why is this? Isn't this correct?

#ifndef SSAO_PIXEL_HLSL
#define SSAO_PIXEL_HLSL

#include "Constants.h"
#include "Common.hlsl"

static const float gKernelSize = 16.0;
static const float gRadius = 1.5;
static const float gSSAOPower = 2.0;
static const float3 gSSAOKernel[gKernelSize] =
{
    float3(-0.0780436, 0.0558389, 0.0281286),
    float3(0.034318, -0.0635879, 0.0741237),
    float3(0.00230821, 0.0807279, 0.0805477),
    float3(0.0124638, 0.117585, 0.0578601),
    float3(0.093943, -0.0944602, 0.0816459),
    float3(0.139348, -0.109816, 0.0618508),
    float3(-0.181872, -0.129649, 0.0380075),
    float3(0.240066, -0.0494057, 0.118559),
    float3(0.115965, -0.0374714, 0.301286),
    float3(-0.294819, -0.100726, 0.225789),
    float3(-0.149652, 0.37459, 0.202967),
    float3(0.261695, -0.292813, 0.349015),
    float3(-0.37944, -0.425145, 0.206921),
    float3(0.628994, -0.189387, 0.224343),
    float3(-0.331257, -0.646864, 0.307335),
    float3(-0.467004, 0.439687, 0.618459),
};

cbuffer SSAOCBuffer : register(CBUFFER_REGISTER_PIXEL)
{
    float4x4 gViewProjMatrix;
    float4x4 gProjMatrix;
    float2 gScreenSize;
};

Texture2D gPositionTexture : register(TEXTURE_REGISTER_POSITION);
Texture2D gNormalTexture : register(TEXTURE_REGISTER_NORMAL);
Texture2D gNoiseTexture : register(TEXTURE_REGISTER_DIFFUSE);
Texture2D gDepthTexture : register(TEXTURE_REGISTER_DEPTH);
SamplerState gPointSampler : register(SAMPLER_REGISTER_POINT);

float linearizeDepth(in float depth, in float4x4 projMatrix) {
    return projMatrix[3][2] / (depth - projMatrix[2][2]);
}

float4 ssao(in float3x3 kernelBasis, in float3 originPos)
{
    float occlusion = 0.0;
    for (int i = 0; i < gKernelSize; i++)
    {
        float3 samplePos = mul(kernelBasis, gSSAOKernel[i]);   <---------------------- this line
        samplePos *= gRadius * originPos;

        float4 offset = mul(gViewProjMatrix, float4(samplePos, 1.0));
        offset.xy /= offset.w;
        offset.xy = offset.xy * 0.5 + 0.5;

        float depth = gDepthTexture.Sample(gPointSampler, offset.xy).r;
        depth = linearizeDepth(depth, gProjMatrix);

        float rangeCheck = abs(originPos.z - depth) < gRadius ? 1.0 : 0.0;
        occlusion += (depth <= samplePos.z ? 1.0 : 0.0) * rangeCheck;

    }
    occlusion = 1.0 - (occlusion / float(gKernelSize));

    return pow(occlusion, gSSAOPower);
}

float4 ps_main(float4 position : SV_Position) : SV_Target0
{
    float2 coords = float2(1920.0, 1080.0) / float2(4.0, 4.0);
    coords *= float2(position.x / gScreenSize.x, position.y / gScreenSize.y);

    float3 originPos = gPositionTexture[uint2(position.xy)].xyz;
    float3 normal = gNormalTexture[uint2(position.xy)].xyz;

    float3 rvec = gNoiseTexture.Sample(gPointSampler, coords).xyz; //texture(uNoiseTex, noiseTexCoords).rgb * 2.0 - 1.0;
    float3 tangent = normalize(rvec - normal * dot(rvec, normal));
    float3 bitangent = cross(tangent, normal);
    float3x3 kernelBasis = CreateMatrixFromCols(tangent, bitangent, normal);

    return ssao(kernelBasis, originPos);// gFinalTexture.Sample(gPointSampler, coords);//float4(1.0, 0.0, 1.0, 1.0);
}

#endif

Also - offtopic, but this pixelshader murders my framerate, all the way from solid 450+ to 80-90. I guess with all the texture lookups the technique is simply expensive, but still, I must be doing something wrong in regard to performance.


texts: What to consider legally when cloning an old game?

texts:
Possible Duplicate:
  How closely can a game resemble another game without legal problems

I'm going to make a game in the form of a 100% free Android phone app that will be basically a clone of an old arcade style NES game, but with a few modifications to make it better. Now the game I am inspired by was released in 1985, so I'm not exactly shitting bricks about being sued, but I just thought I'd ask on here first about what kind of legal considerations developers go through when copying others' games.


texts: How can I efficiently represent territories and their borders on a map like if it was a Risk board game?

texts:
I am exploring the idea of programming a territory control based RTS. These territories would be in 3D and I would like their colors to change when captured to represent the faction's color. I would also like if my borders be embossed to separate them more easily. Which brings me to my question. Is there a way to efficiently represent these territories to make them easy to modify and where I could track the borders efficiently and with precision?

For instance, lets say I have a map divided like the classic Risk map (ignore the continental colors):

How can I represent each territory in a way where I could easily modify its properties (color, shape and possibly borders)? Should I engrave the borders in lists of coordinates and draw my territories according to these lists? Should I draw the map in an editor like Photoshop and analyse it pixel by pixel through a code execution to create the actual 3D map? Should I design each piece in a 3D modeling program (which seems insanely time consuming) and import the models when I load my map? Or is there a simpler answer right under my nose that I haven't explored yet?

I'm not sure yet if I'll be using Java or C++ to code, but I know it will be one of these two with OpenGL as my graphics library.

I understand that my question might be confusing, so please do ask for me to explain if it is the case and I'll try to clear any question you might have the best I can.


texts:
I'm creating an online-canvas-game with a tank as player object.

Now I have several structures in my canvas, that shouldn't be able to be overdriven by the tank...
My solution is to detect the collision like that:

if(hero.x > reactor[i]['x'] - 32 && hero.x <= reactor[i]['x'] + 32
   && hero.y > reactor[i]['y'] - 32 && hero.y <= reactor[i]['y']){
    collidetop = true;
}

if(hero.x > reactor[i]['x'] - 32 && hero.x <= reactor[i]['x'] + 32
   && hero.y >= reactor[i]['y'] && hero.y < reactor[i]['y'] + 32){
    collidebottom = true;
}

if(hero.x > reactor[i]['x'] - 32 && hero.x <= reactor[i]['x']
   && hero.y > reactor[i]['y'] - 32 && hero.y <= reactor[i]['y'] + 32){
    collideleft = true;
}

if(hero.x > reactor[i]['x'] && hero.x <= reactor[i]['x'] + 32
   && hero.y > reactor[i]['y'] - 32 && hero.y <= reactor[i]['y'] + 32){
    collideright = true;
}

The hero object is the tank, hero.x the x-coordinate, and so on...
Now I'd like to deactivate the keyboard input for the direction key, if the objects collide...
For this reason I have the variables wok, aok, sok and dok - they all contain booleans.
If wok = false, then the key "w" is deactivated...
I've connected the collide variables to the keyboard inputs:

if(collidetop == true){
    sok = false;
}
if(collidetop == false){
    sok = true;
}
if(collidebottom == true){
    wok = false;
}
if(collidebottom == false){
    wok = true;
}
if(collideright == true){
    aok = false;
}
if(collideright == false){
    aok = true;
}
if(collideleft == true){
    dok = false;
}
if(collideleft == false){
    dok = true;
}

My problem is: if the tank doesn't collide the other object any more, the keys stay blocked... Could you help me with that?


texts: How does Unity load asset bundle dependencies and how can they be accessed?

texts:
Loading assets from an asset bundle is done explicitly. You give the bundle the name of the asset to load, then it returns it( either now or later. ) However, loading dependencies is done completely automatically.

How is this done? Is the asset bundle completely removed from memory after the required objects are loaded? Are all the bundle's assets loaded, or just the necessary ones? How can these assets be accessed outside of the reference that caused the dependency in the first place?

I ask this because I am trying to collect some type information about the assets loaded in asset bundles. I need to be aware of all assets of a certain type that are loaded into the game.


texts:
I'm in process of developing simple android puzzle game. I decided to choose andEngine as an engine for my game.

In my game I have a gameField [][] array, which represents a game field, where each element is a cell of game level and consists of a type of the cell (for ex. FLOOR of WALL). During the game, state of cell can be changed (for ex. DOOR_CLOSED changed to DOOR_OPENED), but it happens rarely, almost all the elements of gameField don't change.

I tried to implement that by adding repaint method to updateHandler, which would paint sprites for each cell every tick. But I wonder wouldn't be that approach a wasting of memory and processor time? What is the best practise for doing that?


texts: Best Way To Make Responsive UI Buttons in Unity

texts:
I've been stuck on this for quite some time. I'm trying to make a platformer game for android so I need some touch buttons. I made some buttons in Photoshop but I can't figure out how to make them move the player right. I've tried implementing the IPointerDownHandler interface but once I get the player moving I can't stop it, even if I call a function in OnPointerUp to set the players velocity to a new vector3 where all values are zero. I've also tried attaching event triggers to the  buttons I made, but it's the opposite the player only moves for one frame and then I have to press the button again. I don't want to import any assets from the asset store and I don't want to use gui system. I want to learn how to do it myself. Thanks in advance. Here is the script in which I call functions from my PlayerController.

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;

public class LeftButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    public Image leftButton;

    private PlayerController player;

    private void Start()
    {
        leftButton = GetComponent<Image> ();
        player = FindObjectOfType<PlayerController> ();
    }

    public virtual void OnPointerDown(PointerEventData ped)
    {
        Debug.Log("LeftButton Pressed!!");
        player.moveLeft (-2);
    }

    public virtual void OnPointerUp(PointerEventData ped)
    {
        player.stopMoving ();
        Debug.Log ("Button Lifted!!");
    }
}

Here is my PlayerController script.

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

    private Rigidbody2D myrb;

    // Use this for initialization
    void Start ()
    {
        myrb = GetComponent<Rigidbody2D> ();
    }

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

    }

    public void moveLeft(float moveSpeed)
    {
        myrb.velocity = new Vector3 (moveSpeed, myrb.velocity.y, 0f);
    }

    public void moveRight(float moveSpeed)
    {
        myrb.velocity = new Vector3 (moveSpeed, myrb.velocity.y, 0f);
    }

    public void stopMoving()
    {
        myrb.velocity = new Vector3 (0f, 0f, 0f);
    }
}


texts: Which size do I need to use in Blender to import to Unity

texts: I want to create a cube with different textures in Blender. But if I import the model to Unity 2017 the cube has not the same size as a cube with scale x,y and z = 1 from Unity's default components. Which size do I need for my cube in Blender so it has the same size as a default cube in Unity?


texts: NullReferenceException in my inventory system

texts:
I'm making a simplified inventory system for a 3d game.

When I try to pick up an object, I get the following error:

  NullReferenceException: Object reference not set to an instance of an object

Here are the scripts I'm using:

Pick Up goes on the item - the error fires inside the Update method

public class PickUp : MonoBehaviour {
    private playerInventory inventory;
    public Transform woodIcon;
    public Transform slot1;
    public void Start()
    {
        inventory = GameObject.FindGameObjectWithTag("Player").GetComponent<playerInventory>();
    }

    public void Update()
    {
        if (inventory.slot1 == true) // <-- error fires on this line.
        {
            Destroy(gameObject);
            Instantiate(woodIcon, slot1.position, woodIcon.rotation);
        }
    }
}

Player Inventory

public class playerInventory : MonoBehaviour {

    public bool slot1;

    public void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.name == "wood")
        {

        }
        if (slot1 == false)
        {
            slot1 = true;
        }
    }
}

Here is a screen shot showing my setup and the error:


texts: most flexible way to implement a buff /debuff system for a RPG game

texts:
I'm making an RGP board game where I have different heros, each one of them belongs to some types

for example ("Aatrox" is a Dragon and a Ninja hence he belong to these two types),and each player has a

list of champion with fixed attirubtes like basicAttackDamage,criticalstrike/chance/ability..etc

and i have what are called as buffs, a buff gets activated to player when his some of his heros

belong to certain types

eg: if a player gets two Dragons or more , then every hero whose type is Dragon gets double Damage

Attack, TrueDamage(Ignore magic resist and armor), Attack..etc

so i was wondering what would be the most flexible way to implement these sort of buffs considering the

fact that each champion could only use his attack/ability once in each round and there are buffs that

gets added with a certain chance "this buffs gives the hero 40% chance to stun the enemy with basic

attack, and buffs which add health to heros ("this buffs give the hero 250 extra health") etc..

my current approach is to add tags on buffs and apply these buffs when attacking or defending an attack

so this would look something like

enum BuffsType{
OnHit,OnAttack
}

but this approach kinda fails at complex buffs like "a chance to hit extra

attack/extra enemy/". I have seen some discussions about this but none of the answers seemed to be REALLY flexible, most of them failed at complex buffs

design-patterns software-design


texts: I wanted to add a light source for a project I'm working on, and luckily I had some code based on this article: http://ncase.me/sight-and-light/, but when I ran the code after carefully transplanting it I realized my implementation of lighting was really slow. In the previous project I only ever had to worry about a few polygons at a time, but in my new project there are a metric ton of different polygons that the ray caster is checking against. I can avoid testing every ray against every polygon side.


texts: why is it faster to draw lots of small arrays than one big array?

texts:
This application on-line here has interesting performance characteristics:

Sorting the rectangles to be drawn so it keeps having to change colour is faster than sorting the rectangles by their colour and drawing all of each colour at once...

(Timings are printed to Javascript console.  Javascript profiling and understanding what is happening between the emitting of draw ops and the actual rendering of frames is, well, guesswork and disappointment.  But the result is still surprising (to me).)

I'm very interested in the fps logged to the javascript console when run in your browser, and how it differs when sorted by colour vs sorted by z

Now naturally I assume GPU batches are expensive and in my normal apps I get that impression, but I cannot distill a simple test case to show this; quite the opposite, in fact!

Deep in my code, it places all the vertex data interleaved into a single big VBO array.  It then calls glDrawArrays as often as needed.  So drawing a rectangle (6 vertices, each 4 floats) in three colours can be:

Red*1,Blue*1,Red*1 = 3 glDrawArrays calls
Red*2,Blue*1 = 2 glDrawArrays calls, but is slower

I am not sorting, creating, uploading the vertices each frame.  I compute the buffers to draw once.  Each frame, I simply call glDrawArrays as often as needed.

Because I've built this vertex attribute VBO once, and keep reusing it, I have a tight little draw-loop for rendering each frame.  So the Javascript code is doing more work when I have lots of little calls, and less work when I'm emitting concatenated rectangles.

So why is it faster to call glDrawArrays multiple times with small sub-sequences of the array, instead of calling it only a few times and telling it draw long sequences from the array?

Related: there's +500 pts up for grabs over on StackOverflow for the best general discussion about optimising the drawing of a 2D scene.


texts: XNA Calling Variables from separate Classes

texts:
I'm having some issues in XNA. I have a Player class and I would like to call a foreach function from a list which has been declared in the Game1 main class, which is below:

public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    // Player
    Player player;
    // Landscape
    public List<Tile> tiles = new List<Tile>();

The following is the code I'm using and within it is the foreach:

if (isJumping == true)
        {
            foreach (Tile tile in tiles)
            {
                if (recTopBot.Intersects(tile.rectangle))
                {
                    position.Y += velocity.Y * curTime;
                    velocity.Y += gravity * curTime;
                }

                else
                {
                    position.Y = 320 - texture.Height;
                    velocity.Y = 0;
                    isJumping = false;
                }
            }
        }

It says that the name "tiles" does not exist in the current context. Now, I understand why it doesn't work, but what's the best way to fix it without modifying the classes and ruining my algorithms?

That chunk is used for detecting bottom collision for the tiles that are added in my world to make jumping + gravity work as intended.

Thank you very much!


texts: How can I convert a 3ds Max .max to a Cinema 4D .c4d and maintain the animation?

texts:
I have recently purchased this asset from the3dstudio.com:

http://www.the3dstudio.com/product_details.aspx?id_product=193089

It has a corrupt .3ds file available, and a .max (as well as what appears to be a broken .dfx and a textureless and animation-less .obj).

I wrote the site administrator, who attempted to make me a new .3ds file from his master copy (I'm assuming the working .max file) but said:

"The .3ds export doesn't seem to be completed so normally we would just re-export it but I can't get a good export on this model. Only the low-poly control mesh wants to export so I emailed the author to see if they can get us a better file and will let you know as soon as they reply.

"With any non-max format you will not have any rigging in the model as common formats (3ds, dxf, obj, etc) do not support things like rigging (which are program specific) so any export to 3DS (and thus C4D) would just be the geometry, textures, and basic materials."

So it was my understanding based on my very limited knowledge and this e-mail I got that none of the formats that I'd be able to get into Cinema 4D would be able to carry animation data. Then I saw this Elance job posting:

http://www.elance.com/j/convert-3d-studio-max-animation-cinema-4d/19612175/

Now obviously that's not, like, internet canon: I realize just because there was a listing on some site somewhere that made it seem like it was possible doesn't make it true. But it looks like that team in India was willing to do it for sixty bucks, which makes it hard to believe it could be that in-depth of a process. But maybe that's my naïveté about either 3D or American to Indian currency conversion rates or both.

So, is this possible?


texts:
I'm trying to draw some cubes with Hardware Instancing.

However they don't get displayed. So I debugged my code, and found the source of the problem:

In my VertexShader, the var that has the per instance world matrix has a value of:

{ 0.0f, 0.0f, 0.0f, 0.0f,
  0.0f, 0.0f, 0.0f, 0.0f,
  0.0f, 0.0f, 0.0f, 0.0f,
  0.0f, NaN, NaN, NaN }

The weirdest thing is that it outpus NaN (Not a Number). Here's how I create my instanced buffer:

XMMATRIX trans[4];

trans[0] = XMMatrixTranslation(0.0f, 0.0f, 0.0f);
trans[1] = XMMatrixTranslation(0.5f, 0.5f, 0.5f);
trans[2] = XMMatrixTranslation(-0.5, -0.5, 0.5);
trans[3] = XMMatrixTranslation(0.5, -0.5f, 0.5);

//Store world matrices
for (int i = 0; i < 4; i++)
    XMStoreFloat4x4(&mIV[i].world, trans[i]);

D3D11_BUFFER_DESC instDesc;
ZeroMemory(&instDesc, sizeof(D3D11_BUFFER_DESC));
instDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
instDesc.Usage = D3D11_USAGE_DYNAMIC;
instDesc.ByteWidth = sizeof(XMFLOAT4X4) * 4;
instDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;

//Create instanced buffer
HR(mDevice->CreateBuffer(&instDesc, NULL, &mBoxInstB));

Here's how I map the instanced data to my buffer:

D3D11_MAPPED_SUBRESOURCE mapSub;
mContext->Map(mBoxInstB, 0, D3D11_MAP_WRITE_DISCARD, NULL, &mapSub);

VertexI* idata = reinterpret_cast<VertexI*>(mapSub.pData);

idata = mIV;

mContext->Unmap(mBoxInstB, 0);

Thanks for the help!
If you need some more info, write it in the comments!


texts:
I am looking for a library which would easily allow me to render shapes (cubes, spheres, lines, circles, etc.) in 3D3 and OpenGL if possible. I want to be able to rapidly design visual debugging tools and I am not proefficient enough in graphics rendering to do it myself (writing the low level stuff that is). The library would have to be for C/C++.

I've already taken a look at the open-source 3d engine, but I feel those are too big for what I really need.

Do any of you know if such library exist? If so, links would be appreciated!


texts: How to confirm an actor location in a realtime multiplayer game at the exact same time on two devices?

texts:
I am trying to figure out how to make a game like Pong in multiplayer. I have two devices that run the same simulation. Now I want to make sure that each of them start at the exact same time and send packets from the host to the client that confirm the position of the ball.

I am not sure if this would be the right approach, but how do I make sure that both devices are running the same game?


texts: (Unity)How to make the BGM not stop between scenes

texts: I want my BGM to keep playing on loop, but whenever I transition into another scene, the loop starts over. Is there any way to have the scene record the last point of the music it plays, and in the next scene starts playing at that moment?


texts: How do I know when the app is launched, loses focus and gets focus again on mobile?

texts:
I searched in Unity Documentation but there are no information. I'd like to know which methods is called and what it returns in the following scenarios on Android:

App initially starts
App goes in the background
App is brought forward after being in the background

As for IOs I know that the scenarios should be the following:

App initially starts:

OnApplicationFocus(true) is called
App goes in the background:

OnApplicationFocus(false) is called

OnApplicationPause(true) is called
App is brought forward after being in the background:

OnApplicationPause(false) is called

OnApplicationFocus(true) is called


texts:
I have simple blur shader which I calculate offsets in:

Piece of vertex shader:

output.texCoord1 = input.tex + float2( texelSize * -4.0f, 0.0f );
output.texCoord12 = input.tex + float2( texelSize * -3.0f, 0.0f );
output.texCoord13 = input.tex + float2( texelSize * -2.0f, 0.0f );
output.texCoord14 = input.tex + float2( -texelSize, 0.0f );
output.texCoord15 = input.tex + float2( 0.0f, 0.0f );
output.texCoord16 = input.tex + float2( texelSize, 0.0f );
output.texCoord17 = input.tex + float2( texelSize *  2.0f, 0.0f );
output.texCoord18 = input.tex + float2( texelSize *  3.0f, 0.0f );
output.texCoord19 = input.tex + float2( texelSize *  4.0f, 0.0f );

However with this manner I have artifacts on the sides of the screen:

I know that it occurs because when the offset goes out from the right it takes pixels from the left appropriately.

So my question is: how is the "standard" way to deal with this? I was trying to saturate() all of the values assigned to output.texCoordX, it removes the artifacts in 95%, but it makes my blur much weaker and with strange sharper edges ("roll my log and I will roll yours"?).


texts: In Unity3D, what ways can I improve the batching with a single texture atlas and four-point material?

texts:
I'm building a randomized city terrain with a set of planes, custom 4 vertice square made in Blender. I've got a texture atlas working so that it draws on a single material and texture, but it's still hitting 97 batch calls when I render the layout. 4 of those are other things, leaving the ground resulting in 93 calls. Are there any other ways I can increase the efficiency? For the moment, the planes are created with a standard instantiate call:

    for (int y = 0; y < NumberOfTilesX; y++) {
        for (int x = 0; x < NumberOfTilesY; x++) {
            CityGround[i] = Instantiate(GroundTile, new Vector3(x, 0, y) * 6, GroundTile.transform.rotation) as GameObject;
            CityGround[i].transform.parent = City.transform;
        }
    }

After being created, they set their own texture within the atlas using a random choice selector.


texts:
I am working on connecting a client to a server using socket connection. I have a button, when I click on the button, it's giving the below exception in Unity.

"SocketException: No connection could be made because the target machine actively refused it.".

What will be the issue? Can anyboady help me out? Below is the code I have written for connecting to the server:

internal Boolean socketReady = false;
NetworkStream theStream;
StreamWriter writer;
StreamReader reader;
try{
        connect = new TcpClient (host, port);
        theStream = connect.GetStream ();
        writer = new StreamWriter (theStream);
        reader = new StreamReader (theStream);
        return true;
        //socketReady = true;
    }
    catch(ObjectDisposedException) {
        return false;
    }


texts: Calculating the output of two armies fighting

texts:
I am programming a strategic game using Flash. The game works very similar to the famous game "Travian".

My problem is as follows: I am trying to make the calculation of the troops lost as a result of a fight between two armies. The two armies have different types of units. Some of them are stronger against some other units and weaker against other types.

How can I put that effect of this differences in the equation of the fight?

It seems to be easy if they only have att and def points only, but when it comse to the units type dependency, I am lost.


texts:
Is there any way to have the texture of a model loaded from a Png ?

I have a simple prism to test it on, but i just want to be able to edit an image and have the model's texture change.

Thanks!


texts: How can I create a lighting effect like this?

texts:
This is the most beautiful 2d lighting I have ever seen, and I'd like to perform lighting like this too. How do I do it?

I don't care about the physics or how the particles are simulated - I only want to know about the lighting.

Here are some videos for reference:

http://www.youtube.com/watch?v=BIQRhOFkvQY
http://www.youtube.com/watch?v=tnTYXPuecMs
http://www.youtube.com/watch?v=rhC_jVM8IYU
http://www.youtube.com/watch?v=_Aw5BdjWqqU

Or you could download Polluted Planet 2 here.


texts: LibGDX Scene2D event handling and bounding box relative to the center of a TextureRegion

texts:
I'm experimenting with Scene2D to see if it fits fot the game I want to develop.
Say I have an Actor with the origin in the center of its TextureRegion.

My setup method contains this code:

float width = WorldUtils.pixelsToMeters(Assets.bullet.getRegionWidth());
float height = WorldUtils.pixelsToMeters(Assets.bullet.getRegionHeight());

setPosition(x, y);
setOrigin(width / 2, height / 2);
setSize(width, height);
setRotation(angle);

Where WorldUtils.pixelsToMeters(float) is just a method to convert pixels to world units (basically 64px = 1 meter).

My draw() method is like this:

@Override
public void draw(SpriteBatch batch, float parentAlpha) {
    batch.setColor(getColor().r, getColor().g, getColor().b, getColor().a);
    batch.draw(Assets.bullet, getX()-getOriginX(), getY()-getOriginY(), getOriginX(), getOriginY(),
               getWidth(), getHeight(), 1, 1, getRotation());
}

This way the actor's position is equal to its center position. This simplifies a lot of stuff like moving the actor to a specific (x, y) in the game world. Otherwise everytime I have to use this actor's position I have to take in account for its screen representation's size... and it doesn't make much sense.

But the way I setup things come at the cost of messing up with event handling. From what I understand Scene2D event handling assumes I'm using (0, 0) as origin of the actor's bounding box.
So when I touch/click on my actor during execution it can handle only the ones slightly up-right it real position (obviously).

Is there a way to fix this without touching the library code? I would like to handle certain objects with origin in the center and others with origin in the bottom-left corner.

Maybe I misunderstood how to setup my actor?


texts:
In my current script responsible for camera movement, I use Mathf.Lerp to smoothly move the camera to the desired position (with WASD movement, panning with MMB, and zooming with the scrollwheel).
However, due to the nature of the Lerp method, I have performance concerns. Does it ever stop calculating the distance and slightly moving the camera towards the location, or do I have to have an if statement that checks if a distance is < 0.0005f, then stop lerping? If so, which is more performant / better practice?
As a bonus question, I've seen there are other smoothing functions such as MoveTowards, Slerp, SmoothDamp... is there any benefit to using any of those over lerp? My main priority is the camera movement being as performant as possible, and I don't understand how these functions work behind the scenes, despite doing much research.
The entire code to my CameraController is here (the lerping is done in LateUpdate): https://pastebin.com/URZhq3MA


texts: I love creating games, and I've always made games using OpenGL and not with game engines such as Unity or Unreal. Can I legally sell the games I made with OpenGL?


texts: How to build TileMaps dynamically from a database?

texts: The game I'm building allows users to create their own tile maps essentially, so I want the server to respond with tilemap coordinates if / when a user enters their custom world.


texts: How to handle pixel-perfect collision detection with rotation?

texts: Does anyone have any ideas how to go about achieving rotational pixel-perfect collision detection with Bitmaps in Android? Or in general for that matter? I have pixel arrays currently but I don't know how to manipulate them based on an arbitrary number of degrees.


texts:
Imagine the following scene: The height one player can reach on jumping depends on how much time the button for jumping is pressed. When the player jumps, the input is sent to the server and physics are updated.

Now, imagine that for some reason, one input packet is lost or due to lag it begins to arrive late. From the point of view of server, the player is not jumping anymore, and its character will start its fall. Every other client will receive this information and let the character fall.
Then, a new packet arrives that corrects this problem. From the perspective of the player, the character is still jumping. Maybe, thanks to this extra input the character can reach a higher slope. But from the point of view of the server and rest of clients, it wont make it.

This could happen, but online games that i have played (except for long jumps and high lag) it doesnt happen. My question then is: How does the server handle this situation? It cannot wait forever for input, it must update physics and acknowledge other clients on what's going on.


texts: Are very long floating point numbers a problem?

texts:
Very simple question, but important: I was using a floating point number ('float') in C++ to handle movement speed, and it suddenly ran crazy. It turns out the speed increased very fast to 259614846795304004193338175520768.0. That's 33 digits, on a typical (non-double) floating point number. How is that even possible, and can it cause the rest of my program to derail? Or will this number simply be cut down to the 23 bits of significant digits that floating point numbers usually have?

(edit: This is not a bug hunt. I am simply trying to understand how a float can hold such a large number with perfect precision (it's not an exponent, because that would just leave a trail of zeroes after a few significant digits). I am not looking for flaws in my code, just a better understanding of how floating point numbers work, and how this can happen)

EDIT: The solution seems to be a mix of bits from several answers, so I don't know whom to assign as the correct answer. Floating point values are apparently assigned by exponent, which means that some numbers can be amazingly huge without losing precision, as long as they are precise exponents of 2 somehow. Mine was. I thought the size was limited to 23 bits, flat out. As soon as I started using variations of the number that were NOT precise exponents of 2, everything went crazy. Sorry for the radio silence, I had to figure this whole thing out experimentally, once I learned that about floating point numbers from various answers.

I seem unable to close the question. Could someone with proper clearance close it down? And thanks to everyone for the help, I am now far more enlightened regarding floating point numbers!


texts: Is it possible to overlay EditText box on a GLSurfaceView on Android?

texts:
I am trying to add a "PlayerName" box on top of a opengl menu background, is this possible?  I've tried various layouts, but they don't seem to allow an EditText box to appear on top

What is the typical way of doing something like this?  Do I need to manually render the text and handle input or is there a better way?  It seems like it should be possible to show the EditText on top of the GLSurfaceView somehow.


texts: SDL2 linux fullscreen issue at lower-than-desktop resolution

texts:
Having a problem trying to get proper fullscreen in linux.

I'm using 1440x900 on desktop. When i set SDL to use 1280x720 as fullscreen, it does change screen resolution. But if i drag the mouse cursor to the bottom or right edge of the game screen, it "scrolls" the screen beyond the game surface and makes part of the desktop visible.

Here's how I set the window/screen:

gameWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, screenWidth, screenHeight,
SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS ); }

Am i missing some flag(s) perhaps?
Is this a common problem? I'm on Linux Mint MATE (Rosa).
This problem also occurs when trying to run the same build in an Openbox session.
Using nVidia drivers (x64, v340.96) from nvidia.com, on 9600 GT card(s). No twin/dual screen or second Workspaces.

Any good tips on how to avoid or workaround this issue?


texts:
I would like to find out what Y is if X is a certain number from a cubic bezier curve to make a custom easing function, like it's done on this site: http://cubic-bezier.com/
Does anyone know a formula or a function to find Y if X is something of a cubic-bezier? (Coding in C#/XNA)


texts: Bandwidth cost / hour for one MMORPG player

texts:
I am trying to calculate / guesstimate the costs of running an MMORPG for a client. And now I need a pretty accurate estimate for the monthly bandwidth cost so I can calculate the possible revenue of the investor / client. So what is a pretty reasonable bandwidth cost for each player per hour?
The MMORPG I'm trying to make is a virtual conference with gamification. We can go to booths, see other people, make a transaction in the booths. And we will also have a quest and mini-game system for the gamification.
We will be making it using Unity + Forge. We were thinking of using Photon before, but when I reached out to them, they said I need to subscribe for Photon Industries since it's not a game, per se, which is like 2.5x the cost of PUN.
We will split the server into two: the game server and the REST API server. I'm in charge of the game side of the project so the REST API and backend is not my jurisdiction. I this is the specs of the game that I had in mind:

The event will be held for 10 days, possibly running 24 hours straight.
Max customer that we have anticipated is around 1000-2000 CCU
There will be multiple scenes / rooms that the customer can go to (e.g. Commerce area, Lobby area, Mini-Game area, etc)
The quest system, booth transactions, and other features that doesn't need real time update will be handled by the backend.

So that leaves these data that needed to be synced:
Player:

position : 4 bytes * 3 (X, Y , Z) = 12 bytes
currentScene: 1 byte
avatarModel: 4 bytes (will use bitmasking to handle the current type of clothing and accessories of the player model)
playerAction: 4 bytes (player's enumerated action type)
playerActionTarget: 4 bytes (player's action's target)

Scene:

sceneStatus: 16 bytes (any status of the current scene e.g. the current quest. Still unsure how many bytes I need to sync)

So, this is what I have calculated so far using AWS EC2 (possibly wrong):


texts:
Can anyone explain the responsibilities of the Technical managerand the Lead programmer, in team ?

Suppose a medium-size team with about 10-15 persons .


texts:
I'm trying to pick a random texture from a fodler placed in assets and use it but it's giving me errors. I'm doing so in the main game screen class

    final  File dir = new File("img");
    Random rand = new Random();
    File[] files = dir.listFiles();
    File file = files[rand.nextInt(files.length)];
    Image = new Texture(Gdx.files.internal(file.getPath()));

The error is

java.lang.NullPointerException: Attempt to get length of null array

to my knowledge this error should only be there if File[] files = dir.listFiles(); is null, and it isn't, currently two pictures are there. So what's happening?

I tried supplying the full path in the first line to img folder but to no avail. Plus I don't want to supply the full path anyway, it will change  from device to another.


texts:
So I have a video stream of known resolution and I have a VR headset via HDMI at a known resolution.

Is there an existing library to create the slight fisheye and side-by-side layout for these single screen headsets? (It's a custom build, so no hardware locked API please)

Target: Win 7/8/10


texts: How do I create a circular progress bar in Unity3D 5?

texts: I am new to programming and Unity3D. I want to show a circular progress bar starting invisible and growing in 3 seconds to a circular line when reloading is done. How can I do that?