texts: Problems implementing a Sign Sprite in Libgdx

texts:
I am making a tile based game in LibGdx. I am using the TiledMap in .tmx format. I want when my player reaches a tile whose property is set (tileType -> sign), he should see a Sign sprite and on colliding which, he should see the signScreen (small) in the Parent screen game screen.
Here is my code

//calling this method at the beginning ...in create()

    TiledMapTileLayer layer = (TiledMapTileLayer) map.getLayers().get(1);
    //test ="layer selected :-> "+layer;
    TiledMapTile tile;

        for(int y=0; y< mapHeight;y++){
            for(int x=0;x<mapWidth;x++){

        //Step-1: Search within the level map where should we construct a Sign
        //*
                try{
        tile = layer.getCell(x,y).getTile();

        if("sign".equals(tile.getProperties().get("tileType").toString())){
        layer.setCell(x, y, null);

//creating my sign sprite deleting that tile .. at the same position
            signs.add(new Sign(x , y , signCount++));

        }

    }
        catch(NullPointerException e){
            System.out.println("While Searching Tile for Sign ->"+e);
        }
            }
        }
}

But this code is not working. I checked ...things look Ok. But if I am placing this code in the collision detection code, where I am checking collision of player with the Layer of map. It works. But I do not want to put the code there.Because, if I am searching and replacing for the tile there..it outputs as if...........

"when the player reaches there and touchs the sign, then my Sign sprite becomes visible and at the same time, the child screen appears"....But I want all the tiles that I have marked as (tileType -> sign) should be checked at the beginning and replaced with my Sign Sprite.

Please suggest

Is there any problem with the above code or the loop
Is there is any other way to implement such a sprite that can communicate to player through a small screen .. i.e. illusion of telling something.


texts: Social Network Gaming on Windows, Linux and OS X

texts:
I'm working on mobile platforms as Android, IOS... Many users of Moblox ask us a windows and an OS X version.
There is no difficulties to provide these versions, because we are developing on OS X C++ code but we miss global scores and social network part (facebook, twitter). Is there any library to implement these functions on Desktops plaforms ?

On mobile platforms, we have many SDK to provide theses functions as OpenFeint, ScoreLoop, Plus+. We have used cocoslive and uploaded scores with libcurl but it's very limited.


texts: If I disable depth and stencil buffering, do I have to create and set the depth stencil buffer?


texts: Couldn't all games avoid post-start loading?

texts:
Just as giant open world games load massive maps dynamically, couldn't we load separate maps, menus, and virtually any interface or 3D setting via that same dynamic loading method? Without changing the environment, it seem like interfaces and various locations within the game could all be loaded dynamically the same way massive open world maps are loaded as you walk through them.
Why isn't this done? I see so many modern games where you have to wait a minute or more while the match / map / level is loading. I know there's a latency involved with connecting peers, but that doesn't take more than a few moments in my experience. What issues exists with this concept to stop it from being used to eliminate loading time involved with loading map / level / interface data?


texts: What is the best practice to move sprites using mouse order in Tile games?

texts:
I am trying to make my first Tile-game using XNA. I have no problem drawing the map layers using TiledLib from codeplex, but, now I want to give sprite an (order) to move to a specific position on map, by selecting the sprite (left mouse click) and then right mouse click somewhere on the map to specify the target position. I don’t know what is the best practice to move sprite this way, considering that there may be collision objects in the direct path.

What is the best practice to do this? Is there any demo covering this issue?

BTW: I couldn’t upload snapshot because of my low score :(


texts: Trying to draw lines using LineRenderer from tower to spawners

texts:
So I have a tower surrounded by 4 spawner gameobjects. I want to draw lines to all of them using LineRenderer. I wrote the following code to achieve this but for some reason I am getting NullReferenceException: Object reference not set to an instance of an object at the line myLines[i].transform.position = startPos;

public Transform towerPos;
GameObject[] myLines;

void DrawLines()
        {
            myLines = new GameObject[spawnpoints.Count];
            Vector3 startPos = towerPos.transform.position;
            for (int i = 0; i < spawnpoints.Count; i++)
            {

                myLines[i].transform.position = startPos;
                myLines[i].AddComponent<LineRenderer>();
                LineRenderer lr = myLines[i].GetComponent<LineRenderer>();
                lr.material = new Material(Shader.Find("Particles/Alpha Blended Premultiply"));
                lr.SetColors(Color.red, Color.red);
                lr.SetWidth(0.3f, 0.3f);
                lr.SetPosition(0, startPos);
                lr.SetPosition(1, spawnpoints[i].spawnPoint.transform.position);
                //GameObject.Destroy(myLine, duration);
            }
        }

The above function is called at Start(). The tower GameObject is dragged into the towerPos variable in the editor so dont know why its a null.


texts: Trouble with a modified parallax scrolling concept

texts:
I have a set of layers (each of them being a list of items) moving with different speeds as I mentioned here: https://stackoverflow.com/a/18962019/270197. Layers back in the scene move with slower speed than those in the front. The position of items in the front layer is calculated from VelocityTracker.getYVelocity() (we are not doing infinite scrolling but responding to the user's gestures) by using standard Euler integration with friction applied to decrease the velocity by a fixed number of percent each frame.

I would need a similar dynamics class for the background layers that act as a satellite, that is, movement should gracefully finish at the same time so instead of an abrupt pause, the velocity of the slower layers should dynamically adjust to the top layer's velocity on each frame (reaching 0 together) to create a realistic but synchronized fling movement on each layer. Any ideas about the algorithm to achieve that?

Update: it is implemented now on github.


texts: how to make a ball move in opposite direction when hitter to ball or paddle

texts:
I had set angle but it's not correct and I'm not getting exactly what I needed. The ball should bounce when hit to paddle or border and move in opposite direction. I'm writing the code in c++.

I had presently written this code when the ball and paddle intersects and I couldn't get how the code is working.

auto paddleY=paddleSpr->getPositionY();
auto intersectY=ballSpr->getPositionY();

auto paddleheight=65;
auto maxBounceAngle=45;
auto speed =1550;

auto relativeIntersectY=(paddleY+(paddleheight/2))-intersectY;

auto normalizedRelativeIntersectY=(relativeIntersectY/(paddleheight/2));

auto  bounceAngle=normalizedRelativeIntersectY*maxBounceAngle;

float vx = cos(bounceAngle * M_PI / 180) * speed;
float vy = sin(bounceAngle * M_PI / 180) * speed;

pbody11->setVelocity(Vect(vx,vy));


texts: OpenGL, GLSL, Modify Background Fill via Fragment Shader

texts:
I have noticed that fragments rendered by the glClearColor() method do not pass through shaders. However, I'd like to modify these fragments using my fragment shader. Is there any way of forcing them through?

To clarify, I'd like to fill the background with a solid colour in such a way that causes each pixel to be treated as a fragment (and passed through the fragment shader).

One way of doing this is creating and loading an image into memory that is as large as the background. However, this seems like a horrible waste of memory.

I have tried making a VAO with a source size of one pixel and destination size of the screen dimensions but this gets treated as a single fragment.


texts: How does one do unit testing in a game engine?

texts:
Much to my shame, I have never written a proper unit test, only small unorganized test programs that I would then dispose of after the test succeeded. I don't really have a clear idea of how unit testing should be performed in a game project. (My language is C++.)

Should I have a separate project for each subsystem in my engine and an associated test with it, and then have a bigger project/ solution that builds the actual engine? Say for example I have the event module in my engine; how should I handle that?


texts: How do I identify a collision with a specific body?

texts: How can I identify when the ground body collides with another b2Body? I can use b2ContactListener to be notified of collision events, but how do I tell which bodies collided?


texts: How to make player seem bigger / world smaller, without changing world coordinates

texts:
I am making a voxel game with OpenGl, I've got the major parts working, except the camera seems small compared to the the blocks.
How do I make the camera bigger?
Do I do a scaling on the model matrix for each chunk? Or do I do something with the view matrix of the camera? When i tried these things, it messed up the coordinate system of my game, the blocks were not where they really were. I just want the player to be visually 2x bigger.
// the view matrix
glm::mat4 Camera::GetViewMatrix()
{
    glm::mat4 view = glm::lookAt(position, position + target, up);
    return view;
}

    // Where i do the chunk rendering
void WorldRenderer::RenderChunck(Chunk *c)
{
    glActiveTexture(GL_TEXTURE0);
    worldTexture->BindTexture();
    worldShader->Bind();
    worldVertexBuffer->BindVertexArrayBuffer();
    worldVertexBuffer->PutVertexData(c->meshData.verts, c->meshData.indices, c->meshData.textureCoords);

    glm::mat4 model = glm::mat4(1.0f); // model = local space to world space
    model = glm::translate(model, vec3(c->pos.x * Chunk::CHUNCK_SIZE, c->pos.y * Chunk::CHUNCK_SIZE, c->pos.z * Chunk::CHUNCK_SIZE));

    worldShader->setMat4f("model", model);
    glDrawElements(GL_TRIANGLES, c->meshData.indices.size(), GL_UNSIGNED_INT, 0);
}
void WorldRenderer::Render(glm::mat4 projectionMatrix, glm::mat4 viewMatrix)
{
    worldShader->setMat4f("view", viewMatrix);
    worldShader->setMat4f("projection", projectionMatrix);

    for (Chunk *c : renderedChunks)
    {
        this->RenderChunck(c);
    }
}


texts:
I am making a recreation of the 2D voxel game Terraria in JavaScript. Like most sandbox games, Terraria has lighting, but because I am using JavaScript, performance is going to be an issue.
I have thought of a few ways I might do this:
One idea I have is to create a brightness map that stores a brightness value between 0 and 1 for each corner of a block, then draws a gradient on top of each block based on those values. But you already know this will take too long to render.
Another idea I have, is to draw the whole thing black, then draw partially transparent circles of colors over that. This would allow me to have colored lights. But I don't want to code an entire lighting system that may also take too long to render.
What are some of the concepts used by most games to create 2D lighting effects, and which are the fastest?
I have seen this question but it doesn't actually describe how to make the lightmap.


texts:
Generically speaking, how would you handle a huge 2D Map of which only a part is displayed? Imagine the old top-down racing games like Micro Machines.

I would know how to do something with a tile-based map, but I want to create completely custom Maps.

Target Devices are iOS, Windows Phone 7, Android, Mac and PC.

Assume the Map is too big to fit to fit into a single Texture. Would I have multiple textures, 4096x4096 each and load them all into RAM? Seems wasteful, and if textures are uncompressed I might actually run out of graphics memory.

Would I only load the max. 4 Textures that I need at any given point (when I'm at the intersection)?

Or would I have one huge image file and load parts of it? In that case, are there any image formats that make it easy (O(1)) to find the file offset and length which I would have to load?

Or is there a completely different algorhithm? Are textures the wrong idea?

How would you implement a game like Micro Machines?


texts:
I'm working on a script to battle against nested prefabs. The script finds and replaces certain prefabs with a new version of that prefab. Now finding the prefabs is easy:

prefabList.AddRange(GameObject.FindObjectsOfType(typeof(GameObject)).Where(x => x.name == "PrefabName"));

But how can you instantiate a prefab in an editor script when the prefab is not in a resources folder? From what I read the PrefabUtility.InstantiatePrefab is used to do that, but I need a reference to the object which is instantiated.


texts: Android: Synchronizing timers across multiple devices

texts:
Im writing a turn-based multiplayer game that implements a chess timer. When the current players turn starts, all devices start timing for the current player, however, as his turn proceeds, the timers fall out of sync, and at the end of his turn(say for example he took 1 minute to make a move) his time on the other players devices are sometimes up to 10 seconds ahead or behind. I understand theoretically its impossible to time-sync devices down to the millisecond, but if i can get it atleast within a second, that will work just fine. I tried the following the try overcome this:

-Sync time across devices at the beginning and end of current players turn.

-Sync time whilst it is current players turn.

-Combination of the two.

The problem with these attempts is that they cause a lot of flickering on the clock, and, at the end of the turn, when other players see the current players time increasing by 5-10 secs, they feel cheated, and it just doesnt look good. Newbie here so be gentle with your responses :)


texts: Games that mix emulated old machine code with modern languages

texts:
Is there any example of game development in a "modern" multi-purpose language (C++, Python, Java, Go) that loads game binaries of an old platform (e.g. 8-bit, 16-bit or 20-bit DOS) and emulates it partially until a given condition and then mixes it with code that runs natively on the host platform?

I am looking for games or extensions of games that use a hybrid approach of emulation and native programming to build newer versions of old games.
I am also not looking for software disassembled and ported to a new system, like SDLPoP.


texts: How to determine whether a line intersects any other?

texts:
I have a collection of lines:

List<Line> _lines;

Each has the properties: X1, X2, Y1, Y2

How can I determine whether any given line in the list (Line[n]) intercepts, at any point, any other line in the list?


texts: Why does this whirlpool simulation not work?

texts:
I am trying to create a simple whirlpool simulation, where particles are constantly compelled to move towards a point in a whirlpool like fashion.

To do this I do the following (in sudo code)

variable speed = 1.0 //This can vary to speed things up
Rotate by (70 * speed) degrees
Move Forward (4 * speed) Steps
Point Towards center

And this works quite nicely, however as the particles get nearer to the center it breaks down causing there to be an area where they just circle around never getting closer to the center. The larger the speed variable is the larger the radius is that they begin to not move closer to the center.

If one decreases the rotate by to a value of like 50 degrees the anomaly is much smaller, however the points rotate around the center many less times.

Why is this happening? How can I fix this?

I am open to completely changing the method I use even if it means physics, however polar coordinates will not work because of the way the center moves among other simulation reasons.


texts: custom SetInterval function in javascript

texts: i am trying to make an custom set interval function for my game but everytime i tried, i end up with a infinite loop. I can't use the default javascript's set interval because it can not take the random number. any idea?


texts: Huge procedurally generated 'wilderness' worlds

texts:
I'm sure you all know of games like Dwarf Fortress -  massive, procedural generated wilderness and land. Something like this, taken from this very useful article.

However, I was wondering how I could apply this to a much larger scale; the scale of Minecraft comes to mind (isn't that something like 8x the size of the Earth's surface?). Pseudo-infinite, I think the best term would be.

The article talks about fractal perlin noise. I am no way an expert on it, but I get the general idea (it's some kind of randomly generated noise which is semi-coherent, so not just random pixel values).

I could just define regions X by X in size, add some region loading type stuff, and have one bit of noise generating a region. But this would result in just huge amounts of islands.

On the other extreme, I don't think I can really generate a supermassive sheet of perlin noise. And it would just be one big island, I think.

I am pretty sure Perlin noise, or some noise, would be the answer in some way. I mean, the map is really nice looking. And you could replace the ascii with tiles, and get something very nice looking.


texts: How to add isometric (rts-alike) perspective and scolling in unity?

texts:
I want to develop some RTS/simulation game. Therefore I need a camera perspective like one knows it from Anno 1602 - 1404, as well as the camera scrolling.
I think this is called isometric perspective (and scrolling).

But I honestly have no clue how to manage this. I tried some things I found on google, but they were not satisfying.

Can you give me some good tutorials or advice for managing this?

Thanks in advance


texts: Picking cells which form a completed line between to 2d grid cells

texts:
I'm using Bresenham's line algorithm to calculate a "line" of cells between a start and end point on a 2D tile grid.

However, I'm using this during terrain generation to create a visible pathway, which means I need every cell to have at least one shared border with a neighbor.

This shows how the line algorithm is picking cells:

Yet if you imagine this as a road, there's no way to drive from one "segment" to the next.

How can I calculate a line that doesn't "jump" like this?

I've thought about using pathfinding or raycasting but they both feel like overkill because they worry about things I don't need here. I won't have obstacles to route around and I don't care about calculating ray intersections.


texts:
Currently I am trying to reflect a sky sphere into a flat piece of geometry which is acting as water. The sphere is very small, it follows the camera on all 3 axis and the z-buffer is turned off so it appears behind everything else.

Can someone please tell me how I can reflect the world matrix on a xz plane. And should I the plane be the water height or the camera height.

Thank you.


texts:
I'm new to game development and development in general, I want to make a Connect 4 game. I have made a few simple game tutorials and I decided I wanted to make my own game now. I figured a connect 4 game should be a simple start for me, can anyone help me out how to go about with this please?

Should I use Cocos2d or write it in ObjC?

Thanks
David H.


texts:
How would you code a simple "8 bit fire torch" (just one, nothing else to worry about on screen), without using any sprites?

For instance, how would you "animate" a torch that looks like this one:


texts: Why do people like `realistic' physics and graphics in games?

texts:
If games are all about fun, then why do people tend to like realistic physics and graphics are good for games?

Can you cite your source?


texts:
I use Physics.Raycast and transform.forward to shoot a ray in front of my gameobject, but the ray gets cast downwards instead.

if (Physics.Raycast(transform.position, transform.forward, out var hit, range))
{
   Debug.Log(hit.transform.name);
}

Debug.DrawRay(transform.position, transform.forward * 50, Color.green);

What's wrong with my code?


texts: Why am I getting this "tag not defined" error?

texts:
In the log, it says

UnityException: Tag: car is not defined.
  at PlayerController.OnTriggerEnter (UnityEngine.Collider other) [0x00000] in <filename unknown>:0

I'm checking against the tag car when colliding, why does this happen? I have tagged the object, see picture below

heres some code

void OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("car"))//error here
    {
        //more code
    }
}


texts:
I'm trying to imitate the damage indicator in Ragnarok online (moving in an arc): sample here.
But I can only do this

I have this code below. I'm not sure how to make it go faster. If I do pos.y += 2 * yOffset;, it will just go higher.

public void update(float delta) {
    if(xOffset < Math.PI) {
        xOffset += delta;
        pos.x += xOffset;
    }
    if(xOffset >= Math.PI) {
        xOffset = Math.PI;
    }
    yOffset = (float)(3 * -Math.sin(2*xOffset));
    if(xOffset < Math.PI) {
        pos.y += yOffset;
    }
}


texts: How can i write automated tests for some SDL2 objects?

texts:
For eg having a class that is rendering something on the screen, could be even a point or a line if not an image or whatever.

How is possible to write some tests for that class only?

or just a small program rendering a line, would it be possible to write an automated test for it?


texts: Marching squares: Finding multiple contours within one source field?

texts:
Principally, this is a follow-up-question to a problem from a few weeks ago, even though this is about the algorithm in general without application to my actual problem.

The algorithm basically searches through all lines in the picture, starting from the top left of it, until it finds a pixel that is a border. In pseudo-C++:

int start = 0;
for(int i=0; i<amount_of_pixels; ++i)
{
   if(pixels[i] == border)
   {
      start = i;
      break;
   }
}

When it finds one, it starts the marching squares algorithm and finds the contour to whatever object the pixel belongs to.

Let's say I have something like this:

Where everything except the color white is a border.

And have found the contour points of the first blob:

For the general algorithm it's over. It found a contour and has done its job. How can I move on to the other two blobs to find their contours as well?


texts: Adding a small slide when player releases left/right key

texts:
The aim is for the player object to slow down and stop instead of just stopping dead. The following codes works ok when the player is not jumping, but gets stuck in an object if the player is in the air when they do it.

Left key released event:

if hsp = 0 exit;

hspeed = -3;
friction = 0.20;

if obj_Player.hspeed = 0
{
hspeed = 0;
}

Right key released event:

if hsp = 0 exit;

hspeed = +3;
friction = 0.20;

if obj_Player.hspeed = 0
{
hspeed = 0;
}

Horizontal collision code for interest:

if (place_meeting(x+hsp,y,obj_bound))
{
while(!place_meeting(x+sign(hsp),y,obj_bound))
{
    x += sign(hsp);
}
hsp = 0;
}

x += hsp;


texts:
I have 2 CCSprites and I want to tell if their x and y are equal I tried this:

if(sam.position.x == tom.position.x && sam.position.y == tom.position.y){
NSLog(@"Hooray!");
}

Although I do not think this is the right way to do this. Could anyone help me?

Thanks.

ALSO The CCSprites are named sam and tom.


texts: What are the advantages of a sprite sheet over an image sequence/flash timeline?

texts:
I've noticed sprite sheets are used more and more in Flash games and I don't fully understand what are the advantages over an image sequence/flash timeline - MovieClip.

I've read this related question:
2D graphics - why use spritesheets?
and that makes sense for hardware accelerated games, but that's not the case for
flash yet.

Any Flash Player specific insights ?


texts: Slope handling in a tile-based platformer

texts:
I'm trying to implement slopes in my 2D tile-based platformer made in GameMaker Studio 1.4.

I'm done with the normal solid block tiles, they work like charm, but slopes are even harder than I expected.

There are many problems with what I already tried. At some point, I was somewhat OK with it, but somewhat OK is not enough, it must be perfect.

So let's talk about uphill and let's assume our slope is going right.

So I need to check if we are in a slope. When we are, I need to calculate how much we are in the slope. Since it's a 45 degree slope for now, we should move the character upwards the same amount of pixels as we are in the slope. That looks and works fine for most of the cases.

But let's face some of the issues: If there are not wall tiles (black
ones in the picture) then the player may fall down between two slope
tiles.
Going down doesn't work in my current implementation, it works    if
I ignore, how much I am in the tile (but then, it snaps to the
slope even if I don't touch it, but I'm really in the slope tile),
really visible, when I am at the left-most part of the slope (snaps
to the bottom). Also sometimes it just positions kinda badly... Look
at the Grounded variable state.

If I ignore the intrusion amount (so it snaps into the tile), then
I'm still not good yet, as reaching the bottom of the slope may move me out
sideways. Applying the x velocity may make me leave the slope tile
before applying the y position and since I left the tile, there won't be y position applying. My character will be above ground
for a while depends on x velocity and gravity. At higher x velocity,
the player may left the slope tile more than one pixels above the
ground.

In overall, all the solutions I tried were imperfect. Most of the times, it work, but there are those situations where it becomes unreliable, especially at higher speeds. I think I will go until 8 pixels / frames speed with a very few of the objects. I wonder how specific games did it? I tried to learn from games like Castlevania - Dawn of Sorrow, since I got an editor for it and I experimented with slopes. To make the slopes work perfectly, there must be an solid block below the slopes at the intersections, or the player will fall between them. I wouldn't mind this that much. Worst case scenario, I would mark some tiles with some special flag below the slopes.

Screenshots from Symphony of the Night's hidden debug mode room:

This is how Dawn of Sorrow (not) handles slopes:

So I'm a bit confused / puzzled about the situation.


texts: How to erase the small gaps in tilemap in Unity?

texts:
I want to erase small gaps in my tilemap. The gaps look like this:

The texture I used has no gaps:

I tried by disabling anti aliasing.It didn't worked so what can I do in this case?


texts: XNA - How to move skinned model and merge animations

texts:
After you helped me to resolve my loadContent problem I've wrote some code and made 3D model with animation. Because XNA 4.0 doesn't support .fbx with multiple animations I've generated 3 models with different animations:
1. Start animation ( when you press arrow for the first time)
2. walk animation ( when you still hold it)
3. stop animation ( when button is up)

And here comes my question. How to apply those 3 models to work with arrows.
Now I'm using to render animations (http://xbox.create.msdn.com/en-us/education/catalog/sample/skinned_model )

 protected override void LoadContent()
    {
        // Load the model.
        currentModel = Content.Load<Model>("end_R");

        // Look up our custom skinning information.
        SkinningData skinningData = currentModel.Tag as SkinningData;

        if (skinningData == null)
            throw new InvalidOperationException
                ("This model does not contain a SkinningData tag.");

        // Create an animation player, and start decoding an animation clip.
        animationPlayer = new AnimationPlayer(skinningData);

        AnimationClip clip = skinningData.AnimationClips["end_R"];

        animationPlayer.StartClip(clip);
    }

file with model and animation's name is identical.

I have also second question :) How to get model position from or how to move this model? Now it's connected with camera coordinates but I'd rather prefer the model to have it's own coordinates and transform it independently from camera.


texts: Matrix transforms with SpriteBatch overloading - how do you rotate/zoom around a point?

texts:
I have a transform matrix which works as intended for game objects I want to be completely controlled by my camera:

_transform = Matrix.Identity *
    Matrix.CreateTranslation(-_position.X, -_position.Y, 0) *
    Matrix.CreateRotationZ(_rotation) *
    Matrix.CreateTranslation(origin.X, origin.Y, 0) *
    Matrix.CreateScale(new Vector3(_zoom, _zoom, _zoom));

I expose this to my drawing and use the following SpriteBatch.Begin() overload:

sb.Begin(SpriteSortMode.Deferred,
    BlendState.AlphaBlend,
    SamplerState.PointClamp,
    DepthStencilState.None,
    RasterizerState.CullCounterClockwise,
    null,
    view.Transform);

This works as expected. No problems.

However, I have an object which controls it's own translation as it's a fake star field. I didn't want to have to generate potentially millions of stars to be drawn in order for it to be translated about, so the star field just loops them back to the opposite side if they past the edge of the screen. Zoom just acts really bizarrely. It's not being zoomed into the middle of the screen like it should. At some high zoom value it just swipes off the screen. I initially was having an issue with the rotation but after reordering via trial and error I was able to use the correct sequence of transforms. Here's what I'm currently doing:

_transformNoTranslation = Matrix.Identity *
    Matrix.CreateTranslation(origin.X, origin.Y, 0) *
    Matrix.CreateRotationZ(_rotation) *
    Matrix.CreateScale(new Vector3(_zoom, _zoom, _zoom)) *
    Matrix.CreateTranslation(-Origin.X, -Origin.Y, 0);

And here's what it looks like:

http://www.youtube.com/watch?v=0lg-V36M7og

How do I get the zoom to work correctly?

As a side question, any ideas as to why the ship jutters at high speeds? I don't plan to ever be at those high speeds during game play so it's not a huge cause for concern. Some kind of precision error with the high translation values?


texts: Add a random number to an existing number to produce output in Unity

texts:
I am trying to add a random number to an existing number. I am able to get the output in Unity console, but in the inspector, I can see that the public variable is on a non stop loop.

I intend to produce the result when I press the enter key. Is this an efficient way, or can I improve on the code? I am a beginner, and passionate to learn.

Here's the code:

using UnityEngine;
using System.Collections;

public class LearningScript : MonoBehaviour
{
    public int number1 = 5;
    public int number2 = 10;
    public int number3=20;
    public int finalResult;
    public string statement = "NO KEY PRESSED";

    void Update()
    {
        input ();
        if (Input.GetKeyDown (KeyCode.Return))
            Debug.Log (finalResult);
    }

    void Start(){}

    int addnumbers(int num1,int num2)
    {
        int additionResult = num1 + num2;
        return additionResult;
    }

    void input()
    {
        int randomNumber = Random.Range (1, 10);
        finalResult=    addnumbers (number1, randomNumber);
    }
}


texts:
What are some of the preferred methods or libraries for creating video from an OpenGL graphics simulation?

For example, I want to create a visualization(video) of an N-Body gravity simulation by rendering non-real-time OpenGL frames.

The simulation is already coded, I just don't know how to convert it to video.

EDIT:
I am also interested in providing the described functionality: The user can adjust parameters including the time step between captured frames and then initiate the simulation.  The user waits for the simulation to complete, and then can watch the results.  The user is able to increase or decrease the playback speed of the simulation whereas in slow motion, more frames are used i.e., you see higher resolution time steps, and when the speed is increased, you see lower resolution time steps at a higher rate, but the frames per second flashing on the screen is constant.


texts: Balancing Attack to Defense in a text based RPG

texts:
I understand that there is no correct or incorrect way of doing this, and its all down to a matter of trial and error in terms of perfecting the system.

What I am after is some advice or even get thoughts on how others have tackled a situation like this.

Right now I have a very basic attack formula

$attackPower = $baseAttack * 4;
$percent = $attackPower / 100;
$percent1 = $percent * 10; // Gets 10% of the users attack power

Using the above code I then use rand to work out a users attack power, so it varies rather than a single number

$power = rand($attackPower - $percent1, $attackPower + $percent1)

So that's the users attack power calculated.

However if I used the same formula to calculate the opponents defense, and then calculated the Attack minus Defense equals the damage

$totalDamage = $power - $defense;

This may sometimes result in a negative value (especially if the opponent has a considerably higher defense stat to the users attack)

Above I have used

$attackPower = $baseAttack * 4;

For calculating the defense would this be efficient?

$defensePower = $baseDefense * 2; // Could have this set to rand? 1 - 3??

Is there anything that could be changed to balance the stats out a bit more?
Could there be a much simpler formula?


texts: Data structure fo a ship like in Faster Than Light

texts:
I am wonder me, whats the best data structure for a ship like in FTL.
At first I thought its easy and I need only to make a array with the rooms(Tiles).
But than I noted, that I must put somewhere the doors, walls, weapons, crew and systems.
And with this Aspect I don't know a clean data structure.
Have someone a idea ?

If there is something unclear write it and I try to explain.


texts:
I've been trying to learn some Windows programming using the Win32 API. Now, i'm used to working with the OS layer being abstracted away, mostly thanks to libraries like SFML or Allegro. Could you guys help me out and tell me if i'm thinking right here.

The place for my gameloop is where i'm reading the messages?

while (TRUE)
{
     if (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
     {
          if (msg.message == WM_QUIT)
               break ;

          TranslateMessage (&msg) ;
          DispatchMessage (&msg) ;
     }
     else
     {
          //my game loop goes here
     }
}

Now the slightly bigger issue, that is, drawing. Do i run my drawing where i normaly do it, inside the game loop after the game logic? Or do i do it when WM_PAIN is being called and just call InvalidateRect (hwnd, NULL, TRUE); when i want to draw? This does feel weird, the WM_PAINT is a queued message, so i don't know for sure when it'll be called. So if i wanted to avoid this, do i just get the device handle inside the game loop and only ValidateRect (hwnd, NULL); in the WM_PAINT case (beside the ValidateRect (hwnd, NULL); called after drawing in the game loop)? Actually, now that i think about it, do i even need WM_PAINT in this situation or can i skip it and let DefWindowProc handle it (does it validate the screen if WM_PAINT isn't processed)?

If this is any important, i'm setting up my code for OpenGL.


texts:
I'm trying to implement ads on Unity for my program with Vungle, I followed the implementation guide at
https://support.vungle.com/hc/en-us/articles/360003455452#reference-sample-app-0-3
But the ads aren't displaying at all. I get a debug.log that seems to indicate the ad was called, but no ad displays, even if I build and run the program. I contacted support, but they haven't been super helpful. They told me to wait a little longer before calling the ad, I put it on a coroutine with a 10 second delay and still no ad. Here's my script for reference,
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class VungleAds : MonoBehaviour
{
    string appID;
    string iosAppID = "ios_app_id";
    string androidAppID = "android_app_id";
    string windowsAppID = "5fbfc6bc1136b9069f63f0bf";

void Awake()
    {
        appID = windowsAppID;
        Vungle.init(appID);
    }

    private void Start()
    {
        StartCoroutine(ShowBanner());
        Vungle.loadBanner(appID, Vungle.VungleBannerSize.VungleAdSizeBanner, Vungle.VungleBannerPosition.BottomCenter);
    }

    IEnumerator ShowBanner()
    {

        yield return new WaitForSeconds(3);
        if (Vungle.isAdvertAvailable(appID))
        {
            Vungle.showBanner(appID);
        }
        else
        {
            print("No ad");
            StartCoroutine(ShowBanner());
        }
    }

}

It's just printing "No ad." repeatedly.
Does anyone have any experience with Vungle ads? I have been trying to figure this out for like a week haha.
Thanks


texts: How to have qt5 work on desktop like on mobile devices (es2, correct glsl version)?

texts:
I am looking for help/information concerning this issue :

My work: I have an opengl es2 render engine that works on an iOS app. I almost managed to make it work by calling the same openGL rendering engine from a Qt(4.8 first, then 5.0 since today) app with a QGLWidget. To support es2 function set my widget also inherits QGLFunctions (QtOpenGLFunctions with qt 5.0.0).

However I still have issues with shaders : I could not compile them on qt with glCompileShader because of almost every keywords (lowp, vec4, vec2 …) were returning compilations errors. So I compiled it with QOpenGLShader program, but I had to specify “#version 120”, the closest to es2. But still, my sprites don’t show up the right size and the only potentially influencing different pieces of code with iOS are in shader compilation / version. I think the issue in the shader is that gl_PointSize is not taken into account.

Is there any better way for me to have shaders compiled on qt like they are on iOS ? ( I know glsl es2 version is coming from version 120 but I don’t know to what extent they differ ).
The hello-gl-es2 example did not help me because glsl version also returns 1.20.

I’ll happily receive any hints, thank you !

My shaders, working well on iOS but not on Qt:

const GLchar vShaderStr[] =
#ifdef  __BUILD_DESKTOP__
"#version 120\n" // necessary for Qt to compile shaders
#endif //__BUILD_DESKTOP__
"attribute lowp vec4 Position;\n"
"attribute mediump vec2 TextureCoord;\n"
"attribute lowp float Weight;\n"
"uniform mat4 MVP;\n"
"varying mediump vec2 TextureCoordOut;\n"
"void main(void)\n"
"{\n"
"  gl_Position = MVP * Position;\n"
"  TextureCoordOut = TextureCoord;\n"
"  gl_PointSize = Weight;\n"
"}\n";

const GLchar fShaderStr[] =
#ifdef  __BUILD_DESKTOP__
"#version 120\n" // necessary for Qt to compile shaders
#endif //__BUILD_DESKTOP__
"varying mediump vec2 TextureCoordOut;\n"
"uniform sampler2D Sampler;\n"
"uniform bool IsSprite;\n"
"uniform lowp vec3 TextureColor;\n"
"uniform lowp float Opacity;\n"
"void main(void)\n"
"{\n"
"   lowp vec4 textureColorResult;\n"
"   textureColorResult = texture2D(Sampler,  IsSprite ? gl_PointCoord : TextureCoordOut);\n"
"   gl_FragColor = IsSprite ? vec4(mix(textureColorResult.rgb,TextureColor, 1.0),\n"
"                    textureColorResult.a * Opacity) : textureColorResult;\n"
"}\n";

Edit : replaced preprocessor QT_OPENGL_LIB with custom BUILD_DESKTOP as the first is no more declared in qt5.


texts: GetMouseButtonUp/TouchPhase.Ended doesn't work properly

texts:
I'm trying to make a game where your tap doesn't count until you've released your click, or stop tapping.

The weird thing is, it doesn't work in game, but it works for animation.

public class Swipe : MonoBehaviour {

    public Animator anim;
    public bool tap, swipeUp, swipeDown, swipeLeft, swipeRight, hold;
    public bool isDragging = false;
    public Vector2 startTouch, swipeDelta;
    public float animTime;
    public Life life;

    private void Update()
    {
        tap = swipeUp = swipeDown = swipeLeft = swipeRight = false;

        anim.SetBool("Hold", isDragging);

        #region Standalone Input
        if (Input.GetMouseButtonDown(0))
        {

            isDragging = true;
            startTouch = Input.mousePosition;
            //Debug.Log("Tapped");
        }
        else if (Input.GetMouseButtonUp(0))
        {
            tap = true;
            isDragging = false;
            Reset();
        }

        #endregion

        #region Mobile Inputs
        if (Input.touches.Length >= 1)
        {
            if (Input.touches[0].phase == TouchPhase.Began)
            {
                // tap = true;
                isDragging = true;
                startTouch = Input.touches[0].position;
            }
            else if (Input.touches[0].phase == TouchPhase.Ended || Input.touches[0].phase == TouchPhase.Canceled)
            {
                tap = true;
                isDragging = false;
                Reset();
            }
        }

        #endregion

        //calculating the distance
        swipeDelta = Vector2.zero;
        if (startTouch != Vector2.zero)
        {
            if (isDragging)
            {
                if (Input.touches.Length > 0)
                    swipeDelta = Input.touches[0].position - startTouch;
                else if (Input.GetMouseButton(0))
                    swipeDelta = (Vector2)Input.mousePosition - startTouch;
            }
        }

        //did we cross the deadzone?
        if (swipeDelta.magnitude > 125)
        {
            //which direction?
            float x = swipeDelta.x;
            float y = swipeDelta.y;
            if (Mathf.Abs(x) > Mathf.Abs(y))
            {
                //left or right
                if (x < 0)
                {
                    swipeLeft = true;

                }
                else
                {
                    swipeRight = true;
                }
            }
            else
            {
                // Up or down?
                if (y < 0)
                {
                    swipeDown = true;
                }
                else
                {
                    swipeUp = true;
                }
            }
        }

        #region Animation
        if (Tap)
        {
            anim.SetTrigger("Tap");
        }

        if (SwipeDown)
        {
            anim.SetTrigger("Down");

        }

        if (SwipeUp)
        {
            anim.SetTrigger("Up");
        }

        if (SwipeLeft)
        {
            anim.SetTrigger("Left");
        }

        if (SwipeRight)
        {
            anim.SetTrigger("Right");
        }

        #endregion
    }

    public void Reset()
    {
        startTouch = swipeDelta = Vector2.zero;
        isDragging = false;
    }

    public Vector2 SwipeDelta { get { return swipeDelta; } }
    public bool Tap { get { return tap; } }
    public bool SwipeUp { get { return swipeUp; } }
    public bool SwipeDown { get { return swipeDown; } }
    public bool SwipeLeft { get { return swipeLeft; } }
    public bool SwipeRight { get { return swipeRight; } }
}


texts: How to do a genetic algorithm's chromosome which controls movements

texts:
First I would like to inform you that I'm french and 15 so my english is not very good.

I've read some articles about genetic algorithms (GA) and since I discovered the HTML5's canvas element, I can create an AI with animations, so I've created two little experiments to enjoy seeing robots moving on their own but first I'll present you the second one because it's easier :

The aim of this experiment for the white circles is to touch the red square and instead of using coordinate calculations, like I said, I would like to create an autonomous algorithm which evolves in the time.

I give to the circles their relative coordinates to the red square like so they know exactly where they are and their speed that they will be able to change.

So to do it I need a solution to create a chromosome that contains moving informations but since the x and y positions are randomly assigned to circles and the square, if a member of the population has the good solution, it's only for this particular configuration.

I'm searching how to make them know that if the x coordinate is inferior to 0, they have to go left without creating a function like this if(firstGeneInfo == 2){bot[i].x += redSquare.x - bot[i].x;}.

This is a screenshot of the canvas :

And the jsfiddle link but movements are random for the moment.

http://jsfiddle.net/KLn8r/1/

The other experiment is a sort of "survival game" where the red square has to last,
first I created it as a human-AI experience but I prefer to do an AI vs AI game,
and so implement a genetic algorithm but in this case it is a lot more complicated because they are multiple enemies, I thought that with informations like enemies's coordinates and speed once again, the red square would developp kind of a strategy. The enemies are controlled by an algorithm and there is no need to do a GA for them.

A screenshot :

and the jsfiddle link : http://jsfiddle.net/f6ghk/

If you've read all this, I already thank you ! I'm not asking for the full working code but just the principle of a chromosome that works in theses cases.

I hope that my english wasn't to horrible to read and that for my problems I don't need a simulated neural network because it seems a bit complicated to me.

Thank you for your answers !


texts: What is a good university for computer science and game development?

texts:
I am starting my computer science degree at a local community college in programming using C++. However, I will be transferring to a 4-year university. Does anyone have any insight on university programs?

I know Cal State Fullerton has a degree with a minor in Game Development. however, is that as important as getting a degree from a really great school? If I could shoot for something like Cal Poly would that be better? Or even Stanford or SF State being so close to so many gaming companies up there in the Bay area?


texts: JavaScript - 2D Top-down Collision Detection issue

texts:
I'm developing a 2D Top-down Game using HTML5 Canvas and a custom Game Engine. I'm implementing the Quad-intersection detection (Function below, if it helps) on different areas of the Sprites (As they're larger than Tiles in some cases), and have thought of an issue with this. I want to check these areas before moving, using the amount of pixels I will move if allowed to (Nothing blocking the character). Below if the code I use to move the Player:

move: function(delta) {
    var distance = Math.floor(this.getSpeed() * Math.floor(delta / 10));

    this.setMoving(false);

    if(Engine.input().isPressed(Engine.keys.LEFT_ARROW)) {
        this._config.x -= distance;

        this.setMoving(true);
        this.setDir(0);
    }
    if(Engine.input().isPressed(Engine.keys.RIGHT_ARROW)) {
        this._config.x += distance;

        this.setMoving(true);
        this.setDir(1);
    }
    if(Engine.input().isPressed(Engine.keys.UP_ARROW)) {
        this._config.y -= distance;

        this.setMoving(true);
        this.setDir(2);
    }
    if(Engine.input().isPressed(Engine.keys.DOWN_ARROW)) {
        this._config.y += distance;

        this.setMoving(true);
        this.setDir(3);
    }

    this.boundaries();
}

As the distance is not 1 pixel, it will be checking a few pixels ahead of the Player for solid tiles, and if there is one X many pixels in front of them, they can't move the distance and stop.

Problem

So - let's say the distance is 3. If they're 2 pixels from a Solid Tile, they will not move those 2 pixels because of the collision detection, meaning there will be a 2 pixel gap between the Player and the tile, which will only increase the larger the Player, or Entities, speed.

Is there any way to get around this, other than having to check pixel-by-pixel for each anchor point I want to check collision on?

Collision Detection

collided: function(box1, box2) { // Basic Quad-intersection Collision
    return (
        ( (box1.x >= box2.x && box1.x <= (box2.x + box2.width) ) ||
        ( (box1.x + box1.width) >= box2.x && (box1.x + box1.width) <= (box2.x + box2.width) ) ) &&
        ( (box1.y >= box2.y && box1.y <= (box2.y + box2.height) ) ||
        ( (box1.y + h1) >= box2.y && (box1.y + h1) <= (box2.y + box2.height) ) )
    ) ? true : false;
},


texts: How to implement 2d explosions that will cause damage taking into account covers and distance?

texts:
How can I implement a 2D explosion in a way that it will cause less damage to characters that hide behind crates or other cover? Ideally damage will depend on the strength of the cover (e.g. metal wall will protect better then wooden crate). Ideally damage will decrease with distance as well.

I am going to use a port of Box2D physics engine - Farseer.

Thank you.


texts:
I'm making a 2D, oblique-styled sprite based RPG. My game does not live in a 2D matrix (like Tetris), rather it's sprites animating over a tilemap. I am trying to set pathing rules for NPCs. I've considered a few methods to do this but am not sure on the path I should take (no pun intended).

The NPC's trajectory is set by calculating the angle between origin coordinates and next coordinates and moves at that angle. I'm sure this will lead to blocky movements as they move along an array of coordinates along their path.

So, to set pathing rules, I was considering the following approaches and would like some direction given my style of game:

Manually define coordinates: For each NPC, define a set of coordinates for a given destination (a destination location set in my game). This issue with this is it will get tedious to set all the coordinates along the path.
Pathing algorithm: I'd rather simply set the destination coordinates once, and perhaps use a pathing algorithm, such as Dijkstra's Algorithm, that the NPC can use to navigate the map. I am not sure if this will have any ability/effect on smoothing out the movement.

It was also suggested using the Rapidly Exploring Random Tree algorithm, but again... not sure if this is overkill for my game... and what the performance hit would be.

Here is a snapshot of my map. The red arrow is a sample path. The blue lines are collision rules defined around map objects.

I would love some guidance on this. I am not sure if something like a pathing algorithm is a) overkill my game, b) doesn't fit with my game style


texts: How can I detect a long press then activate an animation?

texts: How can I detect a long press on a touch screen then activate an animation? And when the finger is released, play another animation smoothly? Let's take for example the main character in Crossy Road: when the user presses down, the chicken "squats" and when the user releases their finger, the chicken jumps. Same concept. C#.


texts: LibGDX - how to close game and dispose objects properly

texts:
can someone tell me how to close game and dispose objects properly? I tried several methods but always have problems. I have ImageButton with ClickListener.

Here's code of listener:

exitListener = new ClickListener(){
            @Override
            public void clicked(InputEvent event, float x, float y) {
                getGame().dispose(); // reference to GameClass
                Gdx.app.exit();
                super.clicked(event, x, y);
            }
        };

but something causes problems because I have error:

  buffer not allocated with newUnsafeByteBuffer or already disposed

and logs show that stage.dispose() causes problems.


texts: How do I rotate a sprite with ccbezierTo in cocos2d-x?

texts:
In cocos2d-x, I move a sprite with ccbezierTo like this:

// use for ccbezierTo
bezier.controlPoint_1 = ccp(m_fish->getPositionX() + 200, visibleSize.height/2 + 300);
bezier.controlPoint_2 = ccp(m_fish->getPositionX() + 400, visibleSize.height/2 - 300);
bezier.endPosition = ccp(m_fish->getPositionX() + 600,visibleSize.height/2);

bezier1.controlPoint_1 = ccp(m_fish->getPositionX() + 800, visibleSize.height/2 + 300);
bezier1.controlPoint_2 = ccp(m_fish->getPositionX() + 1000, visibleSize.height/2 - 300);
bezier1.endPosition = ccp(m_fish->getPositionX() + 1200,visibleSize.height/2);

bezierForward = CCBezierTo::create(6, bezier);
nextBezier = CCBezierTo::create (6,bezier1);

m_fish->runAction(CCSequence::create( bezierForward, nextBezier, NULL));

How can I make my sprite rotate while moving it with CCBezierTo?


texts: How to enable antialiasing for SVG Images?

texts:
My game has vector icons and sprites, like this one:

Its quality disappoints me. I guess that antialiasing is disabled here for some reason, but have no idea how to turn it on.

The problem is only with UI component SVG Image. Sprite Renderer seems to not have this issue:

Regular Image does not support vector icons. I tried this approach.

MSAA is enabled on Camera and in Quality settings. When it's disabled, second sprite becomes exactly the same as first.

Unity version: 2018.2.7.f1 for Linux
Vector graphics package version: 1.0.0-preview.23

I will accept a solution or an optimal workaround of any complexity. But please don't suggest using raster images.

Why?

I have to compress them because the game is for WebGL and I already had problems with memory because of textures. Vector sprites take less memory.
Without mipmaps icons are pixelated. With mipmaps, they look blurry. They are all power of two, but at different scales. They are even blurred different, some more, some less. I can't use fixed-sized sprites because there's an animation that changes zoom, and canvas will rescale in fullscreen.

Vector guns are to the left, raster ones with mipmaps - to the right. Thin black border lines are gone.


texts: What is the purpose of bitdepth for the several components of the framebuffer in glfwWindowHint function of GLFW3?

texts:
I would like to know what are the following "framebuffer related hints" of GLFW3 function glfwWindowHint :

GLFW_RED_BITS
GLFW_GREEN_BITS
GLFW_BLUE_BITS
GLFW_ALPHA_BITS
GLFW_DEPTH_BITS
GLFW_STENCIL_BITS

What is the purpose of this?
Usually their default values are enough?
Where are those bits stored? In a buffer in the GPU?
What do they affect? And by that I mean in what way

Thank you in advance!


texts:
Possible Duplicate:
  OpenGL 2D Depth Perception

I have a 2D RPG game written in Java using LWJGL. All works fine, but at the moment I'm having trouble deciding what the best way to do depth perception is. So, for example, if the player goes in front of the tree/enemy (lower than the objects y-coordinate) then show the player in front), if the player goes behind the tree/enemy (higher than the objects specific y-coordinate), then show the player behind the object.

I have tried writing a block of code to deal with this, and it works quite well for the trees, but not for the enemies yet. Is there a simpler way of doing this in LWJGL that I'm missing?


texts:
I'm trying to create an arbitrary sized(but not infinite) 2d tilebased world. My question is, how do i save a world like this?

My idea was to split up the tiles into bigger chunks and then save those seperately. Let's say you have a world of 5000x5000 tiles, each chunk would be 50x50 and saved in a seperate file. This leaves me with 10000 seperate files, which does not seem optimal. Is there a better way?


texts: How do I determine the player's grid position?

texts:
My original method for doing this involved taking the player's position, dividing it by the grid cell size, and rounding the result. This works for most cases except when I move my player up above y-axis zero or to the left of x-axis 0. I use the grids to load chunks of procedurally generated tiles into my scene.
it keeps resulting in -0 being a component of the position vectors, which throws my system off. I fixed that by converting each component to integers, but that doesn't solve the greater problem.
There must be a more effective method for this available.
EDIT:
I am using Godot Engine and GDscript for the game I am creating.
This is my code:
    func calculate_grid_position():
    var grid_position = Vector2(int(round(position.x/ 1600)),
                                int(round(position.y/ 1600)))
    return grid_position


texts:
How to change the gravity of a ball upward with a click
Then change it again downward with another click
And so on
In unity


texts: How to make the main menu screen fade out when the game starts in libGDX?

texts:
I am creating the main menu of my game, and I want the main menu screen to disappears with a fade out. I thought that if I used a Stage to make the menu and added buttons as actors, the menu would work...

But I get the following problem: If I add the fadeOut(1) in the click event of the button used to start the game, instead of having the whole screen fade out, only the buttons of the menu disappear. Probably using Stage is the wrong way to make menus, and I do not know the right way ...

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.phillips.mrbulb.MrBulb;

public class MenuState extends Estado {
    private Stage menu;
    private Texture fondo;
    private Drawable empz, instr, acrc, slir;
    private ImageButton empezar, instrucciones, acerca, salir;
    public MenuState(GameStateManager gsm) {
        super(gsm);
        fondo = new Texture("fondo_temp.png");
        empz = new TextureRegionDrawable(new TextureRegion(new Texture("Empezar.png")));
        instr = new TextureRegionDrawable(new TextureRegion(new Texture("Instrucciones.png")));
        acrc = new TextureRegionDrawable(new TextureRegion(new Texture("Acerca.png")));
        slir = new TextureRegionDrawable(new TextureRegion(new Texture("Salir.png")));
        empezar = new ImageButton(empz);
        empezar.addCaptureListener(new ClickListener(){
            public void clicked(InputEvent event, float x, float y){
                menu.addAction(Actions.fadeOut(1));
            }
        });
        empezar.setPosition(MrBulb.ANCHO/2 - 90,MrBulb.ALTO/2);
        instrucciones = new ImageButton(instr);
        instrucciones.setPosition(MrBulb.ANCHO/2 - 80,MrBulb.ALTO/2 - 90);
        acerca = new ImageButton(acrc);
        acerca.setPosition(MrBulb.ANCHO/2 - 62,MrBulb.ALTO/2 - 180);
        salir = new ImageButton(slir);
        salir.setPosition(MrBulb.ANCHO/2 - 33,MrBulb.ALTO/2 - 267);
        menu = new Stage();
        menu.addActor(empezar);
        menu.addActor(instrucciones);
        menu.addActor(acerca);
        menu.addActor(salir);
    }

    @Override
    public void update(float dt) {
        Gdx.input.setInputProcessor(menu);
        handleInput();
    }

    @Override
    public void handleInput() {

    }

    @Override
    public void render(SpriteBatch batch) {
        batch.begin();
        batch.draw(fondo,0,0,MrBulb.ANCHO, MrBulb.ALTO);
        batch.end();
        menu.act(Gdx.graphics.getDeltaTime());
        menu.draw();
    }

    @Override
    public void dispose() {
        fondo.dispose();
    }
}

What would be the correct way to make a menu for the game? Or, if using Stage, what would be the right way of coding it?


texts:
I'm not sure if the title is correct (please comment if it is not). I have a sprite (rectangle body), and I'm applying force on it to make it move from left to right and then go backward. The platform consists of a few rectangle blocks of same size, lined up, with no distance between them . What they form is a perfectly straight line. The platform can be flat or sloped.

What I want

The sprite moves smoothly forward and backward on the platform.

What actually happens

The sprite is sometimes clogged at the point it moves from one block to another, even there is no space between blocks at all. Also sometimes at that point a collision is registered.

I have tried to search and found something called "internal corners", but have no clue how to fix this problem. Is there a way to get around? Thanks!


texts:
Since updating to 2019.1, I have noticed that my custom editors are not drawing properly. It is kinda like they were being cropped, for some reason.

Here is an example:

public override void OnInspectorGUI()
{
    serializedObject.Update();

    EditorGUILayout.PropertyField(scale);
    EditorGUILayout.PropertyField(threshold);
    EditorGUILayout.PropertyField(index);
    EditorGUILayout.PropertyField(seed);

    Rect r = new Rect(50, 50, 100, 100);
    EditorGUI.DrawRect(r, Color.red);
    serializedObject.ApplyModifiedProperties();
}

As you can see, the objects rendered with EditorGUILayout seem to be rendering fine, but when I draw the Rect with EditorGUI, the inspector crops part of the Rect.

What is going on??


texts: How can I achieve this "stroked lines" effect?

texts:
I have a collection of arbitrary vertices and edges that are connected, but which do not necessarily form triangles. These vertices and edges mostly fall along a flat plane, but have some height variation. They represent points on terrain with paths between them. You could think of them as overlapping roads, rivers, or a navigation mesh.
I would like to draw them like this:

In this sketch, we see vertices (black) and edges(red) on the left. On the right, we see blue blobs corresponding to the pixels that are within some radius "r" of any vertex or edge. When viewed from the side, the blue areas basically correspond to the "floor" near edges and vertexes.
So far, I have tried to do this just by drawing quads at along every edge with thickness "r", but this doesn't look great because the vertices are all (slightly different) heights (they are positioned on terrain), so the individual quads are visible as overlapping ribbons in 3d space. I also haven't yet looked into how to make smooth miters where the vertices join multiple edges together.
I should mention I'm using glsl for this project, and modern opengl on android.
One thing I've though of doing was "painting" a 2d raster image as viewed from above, and then projecting that down onto the terrain as a texture or light of some kind.


texts:
I seem to find only examples to use the raycaster with the camera, but none that just have a raycaster from Point A to Point B.

I have a working raycaster, it retrieves my Helpers, Lines etc. but it seems it does not recognize my sphere.

My first thought was my points are off, so i decided to create a line from my pointA to my pointB with a direction like so:

var pointA = new Vector3( 50, 0, 0 );
var direction = new Vector3( 0, 1, 0 );
direction.normalize();
var distance = 100;

var pointB = new Vector3();
pointB.addVectors ( pointA, direction.multiplyScalar( distance ) );

var geometry = new Geometry();
geometry.vertices.push( pointA );
geometry.vertices.push( pointB );
var material = new LineBasicMaterial( { color : 0xff0000 } );

var line = new Line( geometry, material );

This will show a line from my point (50 0 0) to (50 100 0) right trough my sphere which is at point (50, 50, 0) so my pointA and direction values are correct.

Next i add a raycaster:
To avoid conflicts with any side effects i recreated my points here:

var raycaster = new Raycaster(new Vector3( 50, 0, 0 ), new Vector3( 0, 1, 0 ).normalize());
var intersects = raycaster.intersectObject(target);
console.log(intersects);

Seems pretty straight forward to me, i also tried to use raycaster.intersectObjects(scene.children) but it gives Lines, helpers etc. but not my sphere.

What am i doing wrong? I am surely missing something here.

IMG of the line and the sphere:


texts: Unity GUITexture or GUIText not showing up

texts:
Currently I've got a little 2.5D platformer with the camera tracking the player. Now when I go to insert a GUITexture or GUIText game object into the scene, it comes up absolutely fine in the Editor view, but when I go to play it there's absolutely nothing to be seen!

At first I thought it may have been a script I was using on the GUI, but I've tried it out with a completely bland GUITexture object that has no interaction with the rest of the game and I still get the same effect. I'm wondering if my camera is messing it up somehow, but I assumed that all GUI objects are drawn to screen space and just stay with the camera.

I've been really stuck for the past few hours so if any one could offer some insight, I'd be very, very grateful!

~Ray


texts: Why do my variables reset when calling Destroy() in Unity?

texts:
I need to Collect and Destroy the money but when I add Destroy or an equivalent function, it resets and always says 5 instead of 5-10-15...

I watched videos on YouTube and the only difference we're having is that they do something like this:

Class object = new Class();

I don't think this can cause the problem because when I remove the destroy() function, the problem is solved! But I can't not have this call.

How can I fix this?

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

public class moneysystem : MonoBehaviour {

    bool intrigger;
    variables asd = new variables();
    private void OnTriggerEnter(Collider other)
    {
        intrigger = true;
    }
    private void OnTriggerExit(Collider other)
    {
        intrigger = false;
    }

    public void FixedUpdate()
    {
        if (intrigger)
        {
            if (Input.GetKeyDown(KeyCode.G))
            {
                asd.summoney =  asd.money += asd.moneyonpaper;

                Debug.Log(asd.summoney);
                asd.summoney = asd.lastmoney;
                Debug.Log(asd.lastmoney);
                Destroy(this.gameObject); // when I remove This then there is no problem remains
                // I also tried Destroy(gaemobject) and gameobject.setactive(false) and same problem
                Debug.Log(asd.lastmoney);
            }
        }
    }
}

Variables.cs

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

public class variables : MonoBehaviour {

    public int moneyonpaper = 5;
    public int money;
    public int summoney;
    public int lastmoney;
}


texts:
I am very new to programming, and trying to get my player to walk to the mouse click position. I currently have this script, which "teleports" my character to the clicked position:

private void getInput() {
    xMove = 0;
    yMove = 0;

    float tempX = handler.getMouseManager().getMouseX();
    float tempY = handler.getMouseManager().getMouseY();
    float diffX = tempX - x;
    float diffY = tempY - y;

    if (handler.getMouseManager().leftPressed) {
        x = tempX;
        y = tempY;
    }
}

The first thing that came to my mind was to use the following script, for moving to a click which is to the right:

if (handler.getMouseManager().leftPressed) {
    if(diffX>0) {
        for(float counter = 0; counter = diffX; counter++)
            xMove = speed;
    }
}

However, this doesn't work. How would I go about making my player walk to the mouse click position?


texts:
I've been working on a water shader for a project I'm currently working on and have been trying to work on the intersections between objects in the water to create a foam effect that radiates outwards. I'm very new to shaders so my code is probably horribly inefficient! But here it is:

Shader "Unlit/WaterShader"
{
    Properties
    {
        _Color("Color", Color) = (1,1,1,1)
        _IntersectColor("Intersection Color", Color) = (0,0,0,0)
        _MinIntensity("Minimum intensity", Float) = 0.04
        _MaxIntensity("Max Intensity", Float) = 0.4

    }
    SubShader
    {
       Tags { "Queue"="Transparent" "RenderType"="Transparent" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            sampler2D cameraDepthTexture;

            struct appdata
            {
                float4 vertex : POSITION;
                float4 uv : TEXCOORD0;
            };

            struct v2f
            {
                float4 screenPos : TEXCOORD2;
                float4 vertex  : SV_POSITION;

            };

            float4 _Color;
            float4 _IntersectColor;
            float _MinIntensity;
            float _MaxIntensity;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.screenPos = ComputeScreenPos(o.vertex);
                return o;
            }

            sampler2D _CameraDepthTexture;

            fixed4 frag (v2f i) : SV_Target
            {
                float currentDepth = tex2Dproj(_CameraDepthTexture, UNITY_PROJ_COORD(i.screenPos)).r;
                float linearDepth = LinearEyeDepth(currentDepth);
                float depthDifference = linearDepth - i.screenPos.w;
                if(depthDifference < _MinIntensity)
                    _Color = _IntersectColor;
                return  _Color;
            }
            ENDCG
        }
    }
}

It works well enough :

But now Id like to maybe try increase the intensity of the intersection. I know increasing _MinIntensity doesn't really do what I want it to do, as it only shows more and more of the image submerged in water, which removes the effect of shoreline foam. I'd also like the outline of the objects in the water to spread out and fade out over time, I've tried using a sin wave for this but haven't been able to achieve the desired look.


texts: PBR Graph option not showing up in Unity

texts:
I downloaded the URP render pipeline into an existing project of mine (created using the 3D template) to try out shader graphs. All of the guides and tutorials I'm following use an option called the "PBR Graph". However, I can not find that option in Unity. Did they change the name of the graph? How can I get access to it?
When I open up a new project using the URP template, I have the option to choose the PBR graph, but not in my original project, so do I have to create the project with the URP template to begin with?
The version I am using is 2020.2.3.


texts:
I'm a programmer and would like to get some perspective on the art / content creation part of game development.

Comparing a 2D platformer like Super Meat Boy and a high-end game like Crysis 2, what do you think:

What is harder to do / more likely to cause the project to fail: Art or programming?
Which will consume more time and take more people to work on?


texts:
Can't seem to find a definitive way to import text to C# in Unity3d. I'm looking to import either a lot of different text files or one large json file to represent all the text in the game.

Thanks for your help


texts: Simulating a real camera's perspective projection

texts:
I'm trying to simulate a real camera's perspective projection of straight, parallel lines running along the ground (one-point perspective) by mapping the real-world 3D coordinates of the lines to 2D screen coordinates. Suppose the camera's tilt angle is known, is there a way to calculate the slopes/coordinates/expression of these lines projected on to the 2D plane? Which parameters of the camera are needed?

My understanding is that when the camera is tilted, the vanishing point is effectively shifted. But does tilting the camera cause the same changes in the perspective of the lines as moving the camera lower to the ground (closer to the lines)?


texts: What are the alternatives to OpenGL arrays for deferred rendering?

texts:
I'm trying to build a deferred rendering technique in an OpenGL engine, but I can't figure how I could get more than the limit of 32 lights.

I use an array in my shader, feed light properties into this array then loop through it and compute lightning, but I can't get more than 32 items into my array.

What is a better alternative to this?


texts: How do I keep user input and rendering independent of the implementation environment?

texts:
I'm writing a Tetris clone in JavaScript. I have a fair amount of experience in programming in general, but am rather new to game development.

I want to separate the core game code from the code that would tie it to one environment, such as the browser.

My quick thoughts led me to having the rendering and input functions external to my main game object. I could pass the current game state to the rendering method, which could render using canvas, elements, text, etc. I could also map input to certain game input events, such as move piece left, rotate piece clockwise, etc.

I am having trouble designing how this should be implemented in my object.

Should I pass references to functions that the main object will use to render and process user input? For example...

var TetrisClone = function(renderer, inputUpdate) {
    this.renderer = renderer || function() {};
    this.inputUpdate = input || function() {};
    this.state = {};
};

TetrisClone.prototype = {
    update: function() {

       // Get user input via function passed to constructor.
       var inputEvents = this.inputUpdate();

       // Update game state.

       // Render the current game state via function passed to constructor.
       this.renderer(this.state);

    }
};

var renderer = function(state) {
    // Render blocks to browser page.
}

var inputEvents = {};

var charCodesToEvents = {
    37: "move-piece-left"
    /* ... */
};

document.addEventListener("keypress", function(event) {
    inputEvents[event.which] = true;
});

var inputUpdate = function() {
   var translatedEvents = [],
       event,
       translatedEvent;

   for (event in inputEvents) {
       if (inputEvents.hasOwnProperty(event)) {
           translatedEvent = charCodesToEvents[event];
           translatedEvents.push(translatedEvent);
       }
   }

   inputEvents = {};

   return translatedEvents;

}

var game = new TetrisClone(renderer, inputUpdate);

Is this a good game design? How would you modify this to suit best practice in regard to making a game as platform/input independent as possible?


texts: Most efficient way of brighten and darken sprites with OpenGL > 2.0

texts:
So I have been shading (brighten/darken +adding color) my sprites by using glTexEnvf with GL_MODULATE and GL_ADD and a vertex color.
I only had to rebind the batch every time I needed to change from modulate to add and vice versa.
it was not perfect but worked well enough.

However libGDX 1.0 dropped support for OpenGL1.1 and the only way I see is to use shaders. I want to stay up to date and therefore want to update.
I am new to shaders but I found some code that works to brighten a sprite. However as far as I understood I need to rebind the batch every time I want another value for my brightness => batch binding on every sprite I render. That is not very performant.

Is there a way to change values between the bindings? (I don't think it's possible because shaders get compiled afaik).
Or do you have another idea how to archive this effect with openGL2.0 (like I did before)?
Or is rebinding every sprite the most efficient way with OpenGL2.0?


texts: Cocos2d-x v3.1 for WinPhone 8 auto change texture after resumed from background

texts:
I have some sprites in my game (for Windows Phone 8). These are my steps to reproduce the problem:

Open game
Play (this is an optional step)
Press Windows button to send game to background
Press Back button to resume game

The problem is: After the game has resumed, some sprites exchange textures, some sprites go black (like there is no texture being bound).

I'm using cocos2dx version 3.1. Can someone help me to solve this problem?


texts:
trying to create simple 360 rotation animation on 2d object but can't understand delay between animation cycles, please check youtube video with issue:
https://www.youtube.com/watch?v=JlLJLHvnkgo


texts: How to Use/Initialize UDP (Unity Distribution Portal)

texts:
I would like to use UDP (which stands for Unity Distribution Portal) in my game, but I have a problem with the Initializing. What i´ve already done is: Downloading/Importing UDP from Unity Assets Store and setting up the connection between UDP and my game (with the Client ID)
Now i would like if anyone can give me a detailed description what to do next, The description on the official Unity Website just confuses me...


texts: Making a night scene without being dark on the monitor

texts:
What would be a good way to make a 3D scene look "like" a dark night, without being so dark on the monitor that it's hard to see stuff (especially when playing in a brightly lit room).

I've been experimenting with making the light bluish in nature, and having a fairly dark ambient component with a brighter diffuse component, but I find the result either a bit lack-luster or still too dark, depending on the exact parameters.

Are there any good examples to study?


texts:
Obviously in a first person view point the player sees only what's in front of them (with the exception of radars and rearview mirrors, etc).  My game has a top down perspective, but I still want to limit what the character sees based on their facing.

I've already worked out having objects obstruct vision, but there are two other factors that I worry would be disorienting and want to do right.

I want the player to have reduced peripheral vision and very little view behind them.  The assumption is he can turn his head and so see fairly well out to the sides, but hardly at all behind without turning the whole body.  How do I make it clear you are not seeing behind you?
I want the map to turn so the player is always facing up.  Part of the game is to experience kind of a maze and the player should be able to lose track of North.  How can I turn the map rather than the player avatar without causing confusion?


texts: Problem disposing content from a screen's content manager

texts:
I have a problem with my game. I am using multiple classes for different screens, for exemple: Main Menu is one screen, When playing is another, and so on...

I decided to use multiple ContentManagers, different content for each screen, so the game won't consume very much RAM, and to load the screen's content when the user will navigate on that screen, and unload/dispose the content when user navigates away.

I have created different content managers for each screen that I had to, but for exemple if I navigate from main menu, to the playing screen, then back to the main menu (when the content from playing screen gets disposed), and then back to the playing screen, I get this error:

An exception of type 'System.ObjectDisposedException' occurred in MonoGame.Framework.DLL but was not handled in user code

Additional information: Cannot access a disposed object.

I googled this problem, and the only answer that I found was not to dispose the Content Manager, but each texture on that screen.

Is this the only way that I can handle this? To dispose each texture from the screen, when user navigates away?

Thanks.


texts: apply non-hierarchial transforms to hierarchial skeleton?

texts:
I use Blender3D, but the answer might not API-exclusive.

I have some matrices I need to assign to PoseBones. The resulting pose looks fine when there is no bone hierarchy (parenting) and messed up when there is.

I've uploaded an archive with sample blend of the rigged models, text animation importer and a test animation file here:
http://www.2shared.com/file/5qUjmnIs/sample_files.html
Import the animation by selecting an Armature and running the importer on "sba" file.
Do this for both Armatures.

This is how I assign the poses in the real (complex) importer:

matrix_bases = ... # matrix from file
animation_matrix = matrix_basis * pose.bones['mybone'].matrix.copy()
pose.bones[bonename].matrix = animation_matrix

If I go to edit mode, select all bones and press Alt+P to undo parenting, the Pose looks fine again.

The API documentation says the PoseBone.matrix is in "object space", but it seems clear to me from these tests that they are relative to parent bones.

  Final 4x4 matrix after constraints and drivers are applied (object
  space)

I tried doing something like this:

matrix_basis = ... # matrix from file
animation_matrix = matrix_basis * (pose.bones['mybone'].matrix.copy()  * pose.bones[bonename].bone.parent.matrix_local.copy().inverted())
pose.bones[bonename].matrix = animation_matrix

But it looks worse. Experimented with order of operations, no luck with all.

For the record, in the old 2.4 API this worked like a charm:

matrix_basis = ... # matrix from file
animation_matrix = armature.bones['mybone'].matrix['ARMATURESPACE'].copy() * matrix_basis
pose.bones[bonename].poseMatrix = animation_matrix

pose.update()

Link to Blender API ref:

http://www.blender.org/documentation/blender_python_api_2_63_17/bpy.types.BlendData.html#bpy.types.BlendData

http://www.blender.org/documentation/blender_python_api_2_63_17/bpy.types.PoseBone.html#bpy.types.PoseBone


texts:
I keep getting some strange errors in my Geometry shader and when I search for the cause of the errors, it returns nothing substantial. Here is the code.

Shader

#version 450 core

layout(triangles) in;
layout(points, max_vertices = 3)out;

void main(void) {
    int i;
    for (i = 0; i < gl_in.length(); i++) {
        gl_Position = gl_in[i].gl_Position;
        EmitVertex();
    }
}

Log.

0(4) : error C3008: unknown layout specifier 'max_vertices = 3'
0(4) : error C3008: unknown layout specifier 'points'
0(10) : error C3004: function "void EmitVertex();" not supported in this profile

I'm using OpenGL 4.5 (My pc supports it before anyone asks :p) and and glfw 3.2

EDIT:
Here is the steps I'm using to load up my shader.

Creating a shader instance:

shader = new StaticShader("VertexShader.shader", "TesselationControl.shader",
"TessilationEvaluation.shader", "Geometry.shader", "FragmentShader.shader");

StaticShader Constructor

ShaderProgram::ShaderProgram(const char * vertex_file_path, const char * tesselation_controll_shader_path,
    const char * tesselation_evaluation_shader_path, const char * geometry_shader_path, const char * fragment_file_path) {
    vertexShaderID = loadShader(vertex_file_path, GL_VERTEX_SHADER);
    tessControllShaderID = loadShader(tesselation_controll_shader_path, GL_TESS_CONTROL_SHADER);
    tessEvaluationShaderID = loadShader(tesselation_evaluation_shader_path, GL_TESS_EVALUATION_SHADER);
    geometryShaderID = loadShader(geometry_shader_path, GL_GEOMETRY_SHADER);
    fragmentShaderID = loadShader(fragment_file_path, GL_FRAGMENT_SHADER);
    Status("ShaderProgram", "Initilizing shader program");
    programID = glCreateProgram();
    glAttachShader(programID, vertexShaderID);
    glAttachShader(programID, tessControllShaderID);
    glAttachShader(programID, tessEvaluationShaderID);
    glAttachShader(programID, geometryShaderID);
    glAttachShader(programID, fragmentShaderID);
    bindAttributes();
    glLinkProgram(programID);

    GLint isLinked = 0;
    glGetProgramiv(programID, GL_LINK_STATUS, (int *)&isLinked);
    if (isLinked == GL_FALSE) {

        GLint maxLength = 0;
        glGetProgramiv(programID, GL_INFO_LOG_LENGTH, &maxLength);

        if (maxLength > 1) {
            GLchar* infoLog = (GLchar*)malloc(maxLength);
            glGetProgramInfoLog(programID, maxLength, &maxLength, &infoLog[0]);
            std::cout << infoLog;
        }

        StatusError();
        exit(0);
    }
    StatusOkay();

    //Clean Up
    glDetachShader(programID, vertexShaderID);
    glDetachShader(programID, tessControllShaderID);
    glDetachShader(programID, tessEvaluationShaderID);
    glDetachShader(programID, geometryShaderID);
    glDetachShader(programID, fragmentShaderID);

    glDeleteShader(vertexShaderID);
    glDeleteShader(tessControllShaderID);
    glDeleteShader(tessEvaluationShaderID);
    glDeleteShader(geometryShaderID);
    glDeleteShader(fragmentShaderID);
}

Load shader function:

GLuint ShaderProgram::loadShader(const char * file_path, int type) {
    GLuint shaderID = glCreateShader(type);
    std::string shaderCode = FileManager::readFile(file_path);
    char const * sourcePointer = shaderCode.c_str();
    Status("ShaderObject", "Compiling Shader " + std::string(file_path));
    glShaderSource(shaderID, 1, &sourcePointer, NULL);
    glCompileShader(shaderID);
    GLint isCompiled = 0;
    glGetShaderiv(shaderID, GL_COMPILE_STATUS, &isCompiled);
    if (isCompiled == GL_FALSE){

        GLint maxLength = 0;
        glGetShaderiv(shaderID, GL_INFO_LOG_LENGTH, &maxLength);

        if (maxLength > 1) {
            GLchar* infoLog = (GLchar*)malloc(maxLength);
            glGetShaderInfoLog(shaderID, maxLength, &maxLength, &infoLog[0]);
            std::cout << infoLog;
        }

        StatusError();
        exit(0);
    }
    StatusOkay();
    return shaderID;
}


texts: Custom VertexDeclaration for Color, Texture, Normal

texts:
What is the best way to create a VertexDeclaration, that makes it able to render a Shape consisting of vertices and also be able to store a color for the shape (in case the texture can't be rendered - or in case we want color instead of a texture) - instead of having both a VertexPositionNormalTexture and a VertexPositionColor struct in the same class/struct.

I'm trying this approach:

public interface IShape : IVertexType { }

public struct ShapeFace
{
    public int Count { get; set; }
    public Color Color { get; set; }
    public Vector3 Position { get; set; }
    public Vector2 TextureCoordinates { get; set; }
    public Vector3 Normal { get; set; }
    public Vector3[] Vertices { get; set; }

    // Perhaps I need this?
    // public int[] Indexs { get; set; }
}

public struct Shape : IShape
{
    public ShapeFace[] Faces { get; set; }

    /* Need to implement VertexDeclaration here */
}

How do I implement the VertexDeclaration to understand what I want to do?

A shape contains faces, each face can have it's own texture OR color, normal mapping, texture coordinates, etc.

Example A cube has 6 faces, each face needs 2 triangles, each triangle has 3 points. 6 * 2 * 3 = 36 vertices. This way I can create a cube with 6 faces instead of 36 vertices, and render it in color or with a texture.

I really want to simplify it so that I can create some kind of struct that works this way.


texts: Hardware for iPhone 2d games development

texts:
Do I need the cutting edge MacBook Pro or iMac for 2D games development?

Would a iPod touch (with Wi-Fi support) do instead of a full-fledge iPhone?


texts: Unity: cg fragment shader processing array of points

texts: I need to write a fragment shader which would somehow be aware of N points that are in the scene and darken pixels based on their world coord distance to the points. I'm looking for a method that would be still suitable for mobile devices. I image I could pass the points as a texture but i'm stuck in figuring out how to effectively evaluate if a pixel is close enough to any of the N points (I know how to do this for 1 point, but for N without a loop?). Any ideas if this is doable in a performance efficient manner? All ideas are welcome. Thanks!


texts: compiler optimixation interfering with threaded function

texts:
I'm making a block game in c++ that stores voxels in a octree and because, at least in my implementation, editing the octree is slow, I'm generating the chunks of land in a separate thread.

I manage the thread with my ThreadManager class. Every frame I loop through the threads and see if they have finished and remove them. When the ThreadManager object goes out of scope(it is the first game object to go out of scope) it waits for every thread to finish in the destructor. My problem is that when O2 or O3 compiler optimizations are turned on(O and O1 are fine) the threads never finish and I have to force quit the program.

I know that making variables volatile can stop the compiler from optimizing away variables used as conditions that are changed in another thread, but that doesn't seem to be the problem here. What fixes it is printing something in the loop of the generateChunk function or making the height value a constant instead of using Worldgenerator::getTerrainHeight() (see below) Could anyone think of a way to make sure that I can keep the loops from getting the call to Worldgenerator::getTerrainHeight() from being "optimized" this way without using O or O1? (without at least O2 the chunk generation is quite slow and I'd not like to remove possibility of further increasing speed everywhere else for the sake of this one part)

ThreadManager:

class ThreadManager{
public:

    ~ThreadManager(){
        std::cout << "destroying threads\n";
        for(int i = 0;i < threads.size();i++){
            std::cout << i << "\n"; //never makes it past index 0 with O2 or O3 flags
            threads[i].get();
        }
        std::cout << "threads destroyed\n";
    };

    void addThread(std::future<void> newThread){
        threads.push_back(std::move(newThread));
    }

    void pollThreads(){//called every frame
        for(int i = 0;i < threads.size();i++){
            if(threads[i].wait_for(std::chrono::milliseconds(0)) != std::future_status::timeout){
                threads[i].get();
                threads.erase(threads.begin()+i);
                i--;
            }
        }
    }

    int getNumThreads(){
        return threads.size();
    }

private:
    std::vector< std::future<void> > threads;

};

This is the function executed in a another thread:

void Game::generateChunk(Chunk& chunk){
    //std::cout << "generate\n";
    Octree& tree = chunk.getTree();

    for(double x = tree.getX();x < tree.getX()+CHUNK_WIDTH;x+=1.0){

        for(double z = tree.getZ();z < tree.getZ()+CHUNK_WIDTH;z+=1.0){
            //std::cout << "height\n"; when this is uncommented the threads end when .get() is called on it
            double height = worldGenerator.getTerrainHeight(x*100000,z*100000)*40;
            //double height = 40; if this line replaces the preceding line it works as well

            for(double y = tree.getY()+CHUNK_WIDTH-1.0;y >= tree.getY() && y > height;y-= 1.0){
                tree.setBlock(tree.coordsToLoc(x,y,z,1.0), Voxel{BLOCK_TYPE_AIR});
            }

        }
    }

    chunk.generated = true;//std::atomic<bool>

    voxelInstanceDataMutex.lock();

    quickMesh(chunk.getPos(), vulkanApp);

    needsVoxelInstanceBufferUpdate = true;//std::atomic<bool>
    voxelInstanceDataMutex.unlock();
    return;
}

How the threads are created:

//future objects are std::move()ed to put them into the ThreadManager
for(auto newPos : newChunkPos){
    chunks.emplace(newPos, Chunk{newPos,CHUNK_WIDTH});
    Chunk& c = chunks.find(newPos)->second;
    threadManager.addThread(std::async(std::launch::async,&Game::generateChunk, this, std::ref(c)));
}


texts:
I need to render certain scenes and read the whole image back in main memory for further processing which is not suitable for rewriting into shaders of CUDA, and saving to disk. I've search for this and it seems that most video cards will accelerate the rendering but the read-back will be very slow. After a bit of research i only found this card mentioning "Hardware-Accelerated Pixel Read-Back"

The other approach would do software rendering and the read-back problem doesn't exist, but then the rendering performance will be bad.

Likely, i will have to implement both in order to be able to find the optimal trade-off, but my question is about what other alternative can i have hardware-wise; i understand Quadro is for modelling and designer market segment, which is precisely the client target of this application, Does this means that i'm not likely to find better pixel read-back performance in other video card lines? i.e: Tesla or Fermi, which don't even have video outputs btw


texts: How to efficiently (no pointers) store hex grid with shared edges and vertices?

texts:
I have a hex grid stored in a 2d array; now I want to add some properties to the edges of the grid (e.g. rivers between hexes) and also potentially to the vertices.
How can I store edges and vertices

Without duplication, i.e. I don't want to store a river between
two hexes in both, or check neighboring hexes - I want to store it
once in the edge.
With a fast way to find mapping between things,
i.e. from a given edge to two hexes it's dividing, or from a given
vertex to its 3 edges, etc.
Efficiently i.e. without tons of
pointers in every object to every neighboring object?

I was thinking there should be 3 2d arrays (hexes, vertices, edges) with arithmetic formulas to map things to things. However for the only schemes I can come up with to store vertices and edges (since they don't map naturally onto a 2d array), the mapping formulas between array coordinates are very convoluted.
I wonder if there's some simple scheme that I'm missing?


texts: How to handle Multiple-accounts creation and cheating?

texts:
I am developing a game that is running as a web application. The fact is that the game lose sense if one player creates several accounts. Imagine that is a turn-based strategy game, and if you play against yourself (with another account) you can earn tons of points easily.

At first, I thought about logging every single user action, and then comparing the users IP to detect if there is any clue of cheating. But then I noticed that different users could be running under the same IP, for example if they are in the school and all them share the same IP using a proxy. Using this way innocent people could result banned.

Is there any better approach that I'm missing?


texts:
I'm thinking of and RPG, FPS or a turn based game (does not really matter), where the player does not know his character(s) exact stats. Of course they exist as random variables of normal distribution inside the game engine. So no visible HP bar, Level, ATK or DEF. You can only determine it's status by it's signs of life (good mood, fatigued, dying, dead, etc...). With regard to casting spells, when your mana is running low, your chance of failing to cast a spell increases (so there is no "zero" point when you need to find the next gas station for refill). To measure your skill you can battle with monsters which has always have fixed (but yet unknown) stats.

The stats would improve as you use them, but each character would have a random talent set so some skills can be improved easier than others.

So my question for the game devs and gamers, is making the true self of your character a mystery a good idea?

UPDATE:

From the answers it seems it depends on heavily the genre of the game.

For RPGs, I thought finding out what's good for your character is fun.  From the responses, it seems it's not so fun because the players usually have an established play style and will try force it from their character for all costs.

The actual game idea I dreamed about is manager like game somewhat similar to the Pokemon game series. The main character has several champions and wanders around the virtual world and battles with others in an arena in a HOMM like fashion. And those champions would have the hidden stats. I didn't mentioned this in the original question because I don't wanted to bias the answers around this particular game concept.

For the feedback to the player (in both cases): There would be ratings similar to the elo ratings that a chess player has. One for the melee hitting, melee blocking, ranged hitting, ranged blocking abilities, and one for the magic abilities.
Hitting the opponent with a sword will increase the melee hitting rating, if the enemy blocks the hit melee hitting decreases. If the opponent hit us with a sword, our melee blocking rating decrease, for successful block it increases, same for the ranged attacks. For the magic skill it's a bit tricky. High magic ability means: easier to cast spells successfully, harder to be affected by cursing spells, and easier to be affected by enchanting spells.

The standard abilities like hit points, toughness, strength, magic power, are estimated from the performance of the champion. These determine the actual damage dealt on successful hit. There would be "standard champions" that has a fixed and known stats, and the other champions' stats can be measured against them to bootstrap the system.

So if the player tries out all aspects of his champions he can find out the skillset his champions have, if the player don't like the skillset he can trade his champions to get the ones with skillset he likes.

UPDATE 2:

So to get straight to point: Would it be fun if I center my game around the concept of getting to know your characters/champions, instead of serving all stats readily to the player?

It would be similar to the football players. The coach will need to see how their players perform in various positions to assign them to position that's the best for them. So he will need to try each one as a goalkeeper, defender or forward. After several matches it will be clear which position is good for them.


texts: Determine when a PIXI texture is loaded to clone it

texts:
I'm in the latest PIXI v5, where my texture is made like let texture = PIXI.Texture.from(TEXTURE_URL).

The texture isn't loaded synchronously- Pixi just covers this up. That would be fine but when I try to apply a frame, the following error is thrown because the texture has no dimensions because it isn't loaded yet. I have no way of determining whether it's loaded or not!

Error: Texture Error: frame does not fit inside the base Texture dimensions: X: 8 + 8 = 16 > 0 and Y: 0 + 8 = 8 > 0

How can I get a promise for when a Pixi texture is loaded or clone it anyway?


texts: Finding new position after collision with multiple colliders

texts:
What is the most accurate way to find the correct position to where a moving character should be re-positioned as a collision-resolution, after it has collided with multiple colliders?

The figure below illustrates the situation. The rectangles in black are the walls, the rectangle/circle in blue is the moving character and the arrow in read shows the direction of movement, i.e. in this case from right to left. My set up is in 2D and I am using C# in Unity.