texts: 2D Tiled Map - Small tiles or big tiles with pixel-precise movement

texts: I am using Java - LWJGL - Slick2D . I have tried to do a proper collision detection with 32 x 32 tile size but failed three times. I just cant get it to work! I found a youtube video that was using ligbdx (but the code was understandable) that used small tiles and achieved something like pixel-precise movement , so here is the question , NOT opinion based. Keep trying to make a legit collision system or use small tiles? Also , please give me some info related to your answer like "tiles need to have X times Y size" or "a good resource is X Site for pixel-precise movement".


texts: Best practise for representing large spaces in a scene graph

texts:
I'm attempting to represent a procedurally generated world in a scene graph, specifically in the Jmonkey engine (Jme3). To make this managable I have broken up the world into smaller chunks. Each chunk consists of a triangle mesh of the relevant piece of terrain. (A Geometry object holding the mesh and the relevant texture.)

I can't find any information however on which way is best to represent these within a scene graph, specifically how to deal with the coordinates of the map & camera.

One way of doing it would be to simply add these pieces on their world coordinate (which could get extremely large) detaching any nodes that are not within range of the camera and moving the camera trough this theoretically-infinite space. This would be very convenient but can the scene graph deal with the currently rendered scene having very large coordinates? The translations on each piece could easily go into the millions or more "distance units" on the graph's axis.

Another method that comes to mind is converting the world coordinates to a smaller local space and move the terrain that is being rendered to stay close to the origin of the scene graph. Essentially moving the world around the camera.Possibly moving the whole structure along with the camera 1 chunk in the opposite direction to keep it centred whenever a chunk border is crossed. However this seems like it could also have a large impact on performance.

Which of these options, or possibly a completely different one, would be preferable to represent the world in terms of CPU/GPU usage?


texts: Problem when using two different shaders

texts:
I have created a simple shader for drawing my scene in OpenGL. When another shader was introduced, a problem appeared.

I use the first shader and draw few objects in the scene. Then I use the second shader and draw something else. Every draw call has it's glUseProgram() before the drawing starts. Problem is that all my objects drawn with the first shader disappear, but if I call glUseProgram(firstShader) right after the second drawing is finished everything is fine. I can't figure out why this is happening even if I'm calling glUseProgram(firstShader) right before the drawing starts.

Is there something I'm missing about OpenGL drawing process? Is it possible that OpenGL actually draws everything using the second shader?

Most simplified version of my program looks something like this:

glClear(...);

glUseProgam(simpleStandardShader); // just transforming vertices and doing some directional lighting and texturing
foreach (GameObject)
    glDrawArray(...); // draw all 3D objects

glUseProgram(spriteShader); // transforming quads in screen space and texturing
foreach(Sprite)
    glDrawArray(...); // draw all quads

glSwapBuffers(); // i hope i wrote it right, don't remember exact name


texts: Why is my mesh generation algorithm not working properly?

texts:
I am trying to generate a grid in OpenGL ES, using known methods for triangle strips and stitching as shown in:
this post and this post

The code below, generates the vertices for a 4x4 grid with a spacing of 1 unit and then indices for a triangle strip to render the mesh as is commonly done. The coordinates as shown look fine and the indices look fine too. I am just not able to figure out what is wrong. The output is as shown in the attached image.

I hope its something silly that I am overlooking.

int total_verts = width * height;
int verts_first_plus_last = width *2;
int verts_between = total_verts - verts_first_plus_last;
int rows_between = height - 2;
int total_indices = verts_first_plus_last + (2*verts_between) + (2*rows_between);
float vertices[] = new float[total_verts*3];
short indices [] = new short[ total_indices  ];

float xCoord = 0f;
float yCoord = height - 1f;
float zCoord = 0f;

for(int x=0;x<total_verts;x++)
{
    vertices[x]   = xCoord;
    vertices[x+1] = yCoord;
    vertices[x+2] = zCoord;

    System.out.print("(" + xCoord + "," + yCoord + "," + zCoord + "),");

    xCoord= (xCoord + xDelta) % width;
    if(xCoord == 0 )
    {
        yCoord = (yCoord - yDelta) % height;
        System.out.println();
    }
}

System.out.println("\n\nIndices:");

int vert_no = 0;
int ctr =0;
int vert_ctr = 1;

boolean fwd = true;
//0,4,1,5
while(ctr < total_indices)
{
     if(fwd)
     {
         indices[ctr] = (short) vert_no;
         ctr++;
         fwd = false;
     }
     else
     {
         indices[ctr] = (short) (vert_no + width);

         if( vert_ctr % width == 0 && vert_ctr < total_verts - width)
         {
             indices[ctr+1] =  (short) (vert_no + width);
             indices[ctr+2] =  (short) (vert_no + 1);
             ctr+=3;
         }
         else
         {
             ctr++;
         }

         vert_no++;
         vert_ctr++;
         fwd = true;
     }

}

for(int x=0;x<indices.length;x++)
{
    System.out.print(indices[x]+",");
}

Vertices Generated:

(0.0,3.0,0.0),(1.0,3.0,0.0),(2.0,3.0,0.0),(3.0,3.0,0.0),
(0.0,2.0,0.0),(1.0,2.0,0.0),(2.0,2.0,0.0),(3.0,2.0,0.0),
(0.0,1.0,0.0),(1.0,1.0,0.0),(2.0,1.0,0.0),(3.0,1.0,0.0),
(0.0,0.0,0.0),(1.0,0.0,0.0),(2.0,0.0,0.0),(3.0,0.0,0.0),

Indices:

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


texts:
I ran into an access violation reading error and when I debugged it, I saw that the insert function of std::map is inserting a NULL pointer into the map.

Though I've fixed the error by first inserting a NULL value into the map and then changing that value to the corresponding object I wanted to insert in the map. But I want to know the reason the error occurs and why it got fixed.
My code looks like this:

void CTextureBank::AddTexture(int ID)
{
    // Create a CTexture object, load texture into it and insert it into the Texture List
    CTexture* texture = new CTexture();
    texture->LoadTextureFromFile(mRenderer, ID);
    mTextureList.insert(std::make_pair<int, CTexture*>(ID, texture));
}

In the AddTexture function, I'm first creating a texture object, loading a texture into it and putting that texture into the map.
But, this one gives me an access violation reading error.

And doing this doesn't:

void CTextureBank::AddTexture(int ID)
{
    // Create a CTexture object, load texture into it and insert it into the Texture List
    CTexture* texture = new CTexture();
    texture->LoadTextureFromFile(mRenderer, ID);
    mTextureList.insert(std::make_pair<int, CTexture*>(ID, NULL));
    mTextureList[ID] = texture;
}

So it would be great if someone can tell me why this occurs.
Thanks :)


texts:
I'm using SharpDX Toolkit and load a png file with SharpDX.Toolkit.Graphics.Texture.Load(GraphicsDevice, Stream)
If I apply the texture to another texture it's drawn upside down.
The texture is:
and is drawn as this:
Loading is:

Texture image;
FileInfo file = new FileInfo(layer.Id.ToString() + ".png");
if (!file.Exists)
    return;
image = Texture.Load(GraphicsDevice, file.OpenRead());
layer.SetData(image.GetData<byte>());

the SetData Method:

private Texture2D map;
public void SetData(byte[] data) {
    map.SetData(data);
}

VertexBuffer declaration:

vertexBuffer = SharpDX.Toolkit.Graphics.Buffer.Vertex.New<VertexPositionTexture>(GraphicsDevice, new[] {
    new VertexPositionTexture(new Vector3(0, 0, 0), new Vector2(0, 0)),
    new VertexPositionTexture(new Vector3(0, Size.Height, 0), new Vector2(0, 1)),
    new VertexPositionTexture(new Vector3(Size.Width, Size.Height, 0), new Vector2(1, 1)),
    new VertexPositionTexture(new Vector3(Size.Width, 0, 0), new Vector2(1, 0))
});

and the WVP:

wvp = Matrix.Scaling(zoom) *
    Matrix.LookAtLH(new Vector3(camPosition, 0), new Vector3(camPosition, 1), Vector3.Up) *
    Matrix.OrthoLH(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 1);

Any idea why SharpDX draws the image upside down and how I can fix it?


texts: I don't seem to be able to visualize tensors. I am reading The Morgan Kauffman Game Physics Engine Development and he uses tensors to represent aerodynamics but he doesn't explain them so I am not really able to visualize them.


texts:
I'm working through a game in Slick2D and am now focusing on a lot of the graphical end. It's going pretty well other than a couple of issues with alignment. An image illustrating both of these issues here:

Firstly, the background. I have 2 Entity objects containing coordinates, velocity, and an image for the background. Both contain the same image (1600x600). For the first, x=0 and for the second, x=1600. They both move to the left at a speed of 1 pixel per frame. No matter if I make the offset smaller (like 1580), I am still left with a gap showing the background colour. I've put the two images together in photoshop and they blend together, so it's not an issue with the image. Here is some relevant code:

//in init block
Entity bg1 = new Entity("background",1600,600);
        bg1.setXVelocity(BACKGROUND_VELOCITY);
        Entity bg2 = new Entity("background",1600,600); //a second one is needed for endless background
        bg2.setXVelocity(BACKGROUND_VELOCITY);
        bg2.setX(1600);
        backgroundList = new ArrayList<Entity>();
        backgroundList.add(bg1);
        backgroundList.add(bg2);
...
//in update loop, running every frame
for (Entity bg : backgroundList){
    bg.update();
    if (bg.getX() < -1*bg.getSpriteWidth()){
        bg.setX(1600);
    }
}

In other words, what I expect my code to do is have both images move left one pixel each until the left image reaches -1600 (-1*bg.getSpriteWidth()), at which point the right image will be at 0, and with a width of 1600 the first image would be moved to 1600. This is, at least, how I expect my code to work. bg.update() calls a method which adjusts the position based on the velocity given, so it will move x backward by 1 each time for both backgrounds.

Secondly, the misaligned walls. As you can see in the image, the walls on the right are perfectly aligned. They move left together at the same velocity in the same way as above. For some reason, however, as the walls pass the mid-way mark (where the fish is), the upper wall's velocity slows for a slight second which misaligns it with the lower wall (though the velocity returns after and they stay that constant distance apart). I actually have found the code causing this (when commented out it stops), but I cannot see why it would do such a thing. The values still remain correct, but the graphical output is distorted.

for (int i = 0; i < wallList.size(); i++) {
    Wall wall = wallList.get(i);
    wall.update();
    if (wall.getX() < -1 * wall.getImageWidth()) {
        wallList.remove(i);
    }
}
...
if (wallList.get(wallList.size() - 1).getX() < WIDTH - DISTANCE_BETWEEN_WALLS) {
    createWalls();
}

...
private void createWalls() {
    Wall w1 = new Wall();
    Wall w2 = new Wall();
    int yPos = rand.nextInt(400) + 50 - w1.getImageHeight();
    w1.setLocation(WIDTH, yPos);
    w1.setXVelocity(WALL_VELOCITY);
    w1.setVisible(true);
    w2.setLocation(WIDTH, yPos + 11 * player.getImageHeight() / 3 + w2.getImageHeight());
    w2.setXVelocity(WALL_VELOCITY);
    w2.setVisible(true);
    wallList.add(w1);
    wallList.add(w2);
}

It's the wallList.remove(i); line that is causing this offset to happen. When I remove the line, the walls stay aligned as intended. Any ideas? Are these just imperfections of Slick2D? Perhaps there is a better way for me to do these things?


texts: Determining Rectangle-Circle Collision Point

texts:
I'm developing a 2D game engine currently. I stuck on determining position of a rectangle that collides with a circle when its speed is added to its position. Rectangles have only x axis speed.

On picture rectangles are same. Left sided rectangles x,y,width and height values are known. Second rectangle should be next position. Circles radius, x and y values are known also. (x and y values are top left position of an object). I need to find second position of rectangle.

Edit: I can detect collision perfectly. But I need its new position.


texts:
I want to shoot a piece of tnt from the players face and then let it explode when it hits the target block.

        if (cmd.getName().equalsIgnoreCase("cannon")) {
        if(!perrmissionCheck(sender, "Needs.cannon", "cannon")){
            return true;
        }
        if (!(sender instanceof Player)){
            sender.sendMessage(nameC+"You must be a player to preform this command.");
            return true;
        }
        Block block = ((Player) sender).getTargetBlock(null, 50);
        Location location = ((Player) sender).getLocation();
        //float power = 4;
        //if (args.length == 1){
            //power = Float.parseFloat(args[0]);
        //}
        sender.sendMessage(name+"BOOM!");
        double x = block.getX();
        double y = block.getY();
        double z = block.getZ();
        TNTPrimed tnt = (TNTPrimed) ((Player)sender).getWorld().spawn(location, TNTPrimed.class);
        Vector v = new Vector(x, y, z);
        tnt.setVelocity(v);
        //block.getWorld().createExplosion(location, power);
        //block.getWorld().spawn(tntLoc, TNTPrimed.class);
        return true;
    }

This kinda just ramdomly throws the tnt and then exploads i want to get where the player is looking and then shoot it that way if someone could also describe how the args work for new Vector(arg0, arg1, arg2) i would appreciate it...

Thanks any help is great

EDIT
I relize this is really old but i wanted to share how I did it,

    int v = 2;

    if (args.length > 1){
        v = Integer.parseInt(args[0]);
    }

    final Vector direction = user.getEyeLocation().getDirection().multiply(v);

    TNTPrimed tnt = user.getWorld().spawn(user.getEyeLocation().add(direction.getX(), direction.getY(), direction.getZ()), TNTPrimed.class);

    tnt.setVelocity(direction);

    user.sendMessage(name + "Boom!");
    plugin.inGameMsg.msgAdmins(plugin.chatDark_AQUA + user.getName() + plugin.chatGray + " used cannon command!");
    return true;

this sends the tnt right where the player is looking


texts:
I am creating a 2D platformer using Unity3D, I want to have the player destroy enemies when it jumps/falls over them (just from the top). But I have been having problems trying to implement this. I stripped everything and used two simple box colliders in order to make it easy. So, when onCollisionEnter2D is called I get the bounds of the objects colliding like this:

    Bounds playerBounds = new Bounds(transform.position, collider2D.bounds);
    Bounds collisionBounds = new Bounds(collision.transform.position, collision.collider.bounds);

Then I check if the object colliding is below by comparing it's bounds:

    //If the player's lowest point is greater than the
    //colliding object's highest, then it is above it
    bool isAbove = playerBounds.min.y >= collisionBounds.max.y;

Then I check if the object is actually an enemy, and if so, I destroy it:

    if(isAbove)
    {
        if(collision.gameObject.tag == "Enemy")
        {
            collsion.gameObject.getComponent<EnemyController>().die();
        }
    }

Now the thing is this never happens, isAbove is never true, so I tried checking the heights of each object so I use

    Debug.Log("player : "  + playerBounds.min.y + " enemy : " + collisionBounds.max.y)

It says the player bottom-most is below the enemy top-most. Since I use this same method to detect if the player is grounded in order to enable jumping I noticed it works beautifully with other things like platforms but not with enemies. Also y used Debug.break to stop the game and noticed that when colliding with platforms the player's collider was always above the platform's, but when it collided with enemies they overlap: so the player's bottom-most part is below the enemy's top-most part. I read somewhere that this is due to the minPenetrationPenalty property, I didn't like the results of messing with it so I just left it the same (If I lower it doesn't even work with platforms, and I increase it they don't even touch and the collision is detected). I tried to compensate for this penetration when checking the bounds so I said:

    bool isAbove = playerBounds.min.y >= collisionBounds.max.y - 0.01;

It sometimes fails and sometimes not depending on the angle and other stuff, I still don't get it because if this was the problem It shouldn't work with the platforms either but it does, it only fails with enemy. I even tried to check for the overlap and said:

    float overlap = playerBounds.min.y - collisionBounds.max.y;

    bool isAbove = overlap > -0.01;

this still works beautifully with platforms only reporting positive values (which means they are not overlapping), but with enemies it actually reports negative values (which confirms the previous: they do overlap), even more strange it actually reports overlaps greater than what should be allowed, the usually report a -0.09 which means a 0.09 overlap which is greater than the 0.01 that the physics engine is supposed to allow.

If I apply this code in OnCollisionStay2D instead it works, I guess by this time the overlap  is fixed, but this looks unnatural and I still don't understand why this works perfectly with platforms (they never even overlap!) and not my enemies.


texts: Colliding without physics in Unity: is it possible to put OnTriggerEnter in the moving character?

texts:
My main question is: is it possible to put OnTriggerEnter in a script that goes attached to the moving character instead of to trigger area/object? Let me explain my exact need.

I want to detect the collision between an object called MyCube and another called MyOther, but without MyOther stopping MyCube to go on. It is, MyCube should not be stopped or bounced. It should actually just move on, without any physics reaction. Yes, I know that it can be achieved by using Triggers.

More specifically, I should define MyOther's bounding box as a Trigger and then define MyCube as a kinematic rigidbody. Then, I should add a script to MyOther with a function like, for instance, OnTriggerEnter. However, in my scene I will have thousands of objects like MyOther, i.e. working as triggers, and also all the action to be performed when colliding would be performed on the movign character itself. So I would like to retrieve the collision not trough MyOther, but trough MyCube.

1) I thought that I could put OnTriggerEnter in a script attached to the moving character, but when I do that no collision is recognized. No trigging occurs. Is such a thing possible?

2) Otherwise, is there another way trough which I could achieve what I have described?


texts: 2D Rendering in DX11. Texture Storage and Reference

texts:
I'm trying to think of the best way to manage textures in my 2D game.

First, I am using DX11, so right now my "textures" are just pointers to a ID3D11ShaderResourceView created by D3DX11CreateShaderResourceViewFromFile. Is this how I should be loading content?

Right now my basic idea is to create a hashmap of textures with string references.

When an object is created that uses a texture it passes the reference of the texture to the hashmap and gets back a pointer to the texture. If the texture isn't loaded it will use the string to find the correct texture to load, add it to the map and pass back the pointer, so it automatically loads new textures as required (my game is turn based, and many small pauses would have no real effect).

But here are my issues:

Is the above method the best method I could be using (without it becoming overly complex)
ID3D11ShaderResourceView. Is this how I should be storing texture data in DX11?
Ideally I want to have all my texture data compressed in a file. Right now I am simply loading jpgs and so on. But I have no idea how to compress these images and selectively re-load them as required. Ideally I would want to compress them to be locatable in the file using the reference string used when searching the hashmap too.


texts:
I used to extend my Player/Entity class with Sprite, that way I could create a walking animation using SetRegion and super(stilldown.getKeyFrame(0));

I've recently started porting everything over to Scene2D and I use Actors now. I do not know how to use this way of animation anymore, does anybody have a guess how I could do this?

        animationtime += delta;
    if(dir == Direction.DOWN){
        setRegion(velocity.y == 0 ? stilldown.getKeyFrame(animationtime) : walking.getKeyFrame(animationtime));
    }else if (dir == Direction.UP){
        setRegion(velocity.y == 0 ? stillup.getKeyFrame(animationtime) : walkingup.getKeyFrame(animationtime));
    }else if (dir == Direction.RIGHT){
        setRegion(velocity.x == 0 ? stillright.getKeyFrame(animationtime) : walkingright.getKeyFrame(animationtime));
    }else if (dir == Direction.LEFT){
        setRegion(velocity.x == 0 ? stillleft.getKeyFrame(animationtime) : walkingleft.getKeyFrame(animationtime));
    }

This is how I'd initialise the animation

    playeratlas = new TextureAtlas("overworld/player/playersheet.pack");

    Animation walking;
    Animation walkingup;
    Animation walkingright;
    Animation walkingleft;

    Animation stilldown;
    Animation stillup;
    Animation stillright;
    Animation stillleft;

    walking = new Animation(1 / 4f, playeratlas.findRegions("walkingdown"));
    walkingup = new Animation(1 / 4f, playeratlas.findRegions("walkingup"));
    walkingright = new Animation(1 / 4f, playeratlas.findRegions("walkingright"));
    walkingleft = new Animation(1 / 4f, playeratlas.findRegions("walkingleft"));

    stilldown = new Animation(1 / 4f, playeratlas.findRegions("stilldown"));
    stillup = new Animation(1 / 4f, playeratlas.findRegions("stillup"));
    stillright = new Animation(1 / 4f, playeratlas.findRegions("stillright"));
    stillleft = new Animation(1 / 4f, playeratlas.findRegions("stillleft"));

    walking.setPlayMode(Animation.PlayMode.LOOP);
    walkingup.setPlayMode(Animation.PlayMode.LOOP);
    walkingright.setPlayMode(Animation.PlayMode.LOOP);
    walkingleft.setPlayMode(Animation.PlayMode.LOOP);

    stilldown.setPlayMode(Animation.PlayMode.LOOP);
    stillup.setPlayMode(Animation.PlayMode.LOOP);
    stillright.setPlayMode(Animation.PlayMode.LOOP);
    stillleft.setPlayMode(Animation.PlayMode.LOOP);

For now I only use a static image for my Actor

Sprite text = new Sprite(new Texture(Gdx.files.internal("overworld/player/placeholder.png")));

Now I draw it like this

public void draw(Batch batch, float ParentAlpha){
    text.draw(batch);
}

I would greatly appreciate help, I'm new to Scene2D and I can't find much on it.


texts:
A few weeks ago i watched a video and found a really cool 2d push forward/sprinting effect which looks like the following :

How this is made ? Is this effect included into the animation or just spawned as randomly sized dust clouds ? And how this would work ? Is there any pseudo code ?


texts: How to make 4 way walking animation in game maker studio 2?

texts: So I am trying to make a 4 way movement for my character, and I cant seem to get the walking animations to work for it. The character moves fine, but whenever he moves, the walking animation doesn't play. I figured it was because I made it so when the button was held down, it put it as the sprite for that direction constantly, so it could never get to the next frame. does anyone know how to bypass this? (btw I am using D&D)


texts: HTML5 games: play() failed because the user didn't interact with the document first

texts:
I'm creating an HTML5 game using MelonJS game engine. Before I load the game, I have a simple pre-login page with a Splash and background music. This page has no need to load the game engine or game scripts.

The game will most likely be played on Chrome, but with the latest Chrome 66 update, you cannot autoplay music until someone "interacts" with the page:

  login.html:72 Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.

With code

<audio id="soundtrack" src="data/bgm/Music_Login_Splash_v1.ogg" type="audio/ogg"></audio>

and

$(document).ready(function() {
    $('#soundtrack').get(0).play();
});

Google states: Autoplay with sound is allowed if:

User has interacted with the domain (click, tap, etc.).
On desktop, the user's Media Engagement Index threshold has been crossed, meaning the user has previously play video with sound.
On mobile, the user has added the site to his or her home screen.

Mousemove no longer counts as "an event" or "interaction".

Wondering if there's a solid workaround for this as not autoplaying the login splash soundtrack will be odd and ruin the user gaming experience. Workarounds I've tried are to have an autoclick event happen, or autoreloading the page if it's their first time. Otherwise, I can try loading the game engine for the login page and playing thru canvas audio.


texts: SlimDX 11: Setting Multiple Render Targets

texts:
I'm using SlimDX 11 in my managed Direct3D application. I would like to implement deferred shading. I'm having trouble when I try to set a depth stencil surface and multiple render targets at the same time. Here is my code:

// depth stencil view
DepthStencilView dsv = GetD3D11DepthStencilView();

// array of 3 render target views
RenderTargetView[] rtv = GetPositionDiffuseEmissiveRenderTargetViewArray();

// device context
DeviceContext context = GetD3D11DeviceContext();

context.OutputMerger.SetTargets(dsv, rtv);

EDIT:
// create depth stencil state
context.OutputMerger.DepthStencilState = DepthStencilState.FromDescription(GetDevice(), new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                DepthComparison = Comparison.Less,
                DepthWriteMask = DepthWriteMask.All,
                IsStencilEnabled = false,
                //StencilReadMask = 0xff,
                //StencilWriteMask = 0xff,
                //BackFace = new DepthStencilOperationDescription()
                //{
                //    Comparison = Comparison.Always,
                //    DepthFailOperation = StencilOperation.IncrementAndClamp,
                //    FailOperation = StencilOperation.DecrementAndClamp,
                //    PassOperation = StencilOperation.Keep
                //},
                //FrontFace = new DepthStencilOperationDescription()
                //{
                //    Comparison = Comparison.Always,
                //    PassOperation = StencilOperation.Keep,
                //    DepthFailOperation = StencilOperation.IncrementAndClamp,
                //    FailOperation = StencilOperation.Keep
                //}
            });

// clear depth stencil
context.ClearDepthStencilView(dsv, DepthStencilClearFlags.Depth, 1.0f, 0);
// draw as usual
...

When I set the depth stencil and render targets all at one time then nothing is rendered to the screen. When I set only the render targets everything renders normally...Why might this occur?


texts: How do I create user-friendly, unique game IDs?

texts:
How do I create unique game IDs which are also user friendly -- so that one user can easily give that game ID to someone else for joining the game.

I am creating my game in Silverlight with C#.


texts: Separating Axis Theorem - Calculate Normals from Points in 3D

texts:
So while researching for a method to detect collisions in a 3D space between (arbitrary rotated) boxes, I stumbled upon this excellent question with great resources for my further research and great answers: How many and which axes to use for 3D OBB collision with SAT

I now managed to implement nearly everything in C++, and I understand why I have to check all 15 axis and why they are important. Yet I don't understand, how to calculate a0, a1, a2, b0, b1 and b2 (the normals of A and B). Since I only have cuboids for collision detection, I would rather use normals instead of the edges. It does seem to be easier.

To be more precise: First of all, my data structure to save a OBB is a loose collection of 8 vertices of the cuboid 1]. I understand, how to calculate a normal mathematically. I just calculate the cross product of two edges... But I don't know which two edges to choose. If I look at a face of the cubiod, I have 4 edges I could use to calculate the normal for that face. Another problem is, that using the above mentioned data structure, I can't tell whether two vertices belong to one face.

So what can I do to get the 3 normals of a cuboid programmatically?

Do I have to expand my data structure, or can the missing information be derived somehow in a easy way?

1] Example for a cuboid in my data structure (represented in JSON, with (x,y,z) being a point in double^3):

[(0,0,0), (0,1,0), (1,0,1), (1,1,1), (0,1,1), (1,1,0), (1,0,0), (0,0,1)]


texts: Why Unity3D 2018 UI looks bad and very sharpy?

texts:
I update my project from Unity 2017.1.1 to 2018.3.9 and almost everything is OK except UIs.
All of UIs like Images,Buttons,texts,text mesh pro, sprites and others looks very sharpy and pixel pixel ...

please see the attached image :

Unity3D 2017 before update :

Unity3D 2018 after update :

why this happens ? and how can I solve this problem ?


texts:
I am currently designing a game for small kids that have not yet learned to read and would like to get some opinions, and views, on scoring?

Given that these (hopefully) will be small children that cannot yet read or children that have just learned to read, between 2 - 5 maybe what about scoring, do you think that is needed?

My idea was to avoid both any character at all and only use pictures. However, if scoring is implemented there re always other ways to do that i guess with colors, bars etc.

Would someone nice just elaborate a bit on general design criteria's for this type of games and applications with this target audience?


texts: Why is professional game development harder in Europe?

texts:
In comparison to the U.S.A., there seem to be far less leading or successful game companies in Europe.

The recent salary survey of GameCareerGuide shows that the average salary of a games programmer in Europe is only 46k versus 80k in the U.S.A.
While only 378 European developers replied to the survey, 1014 developers from the States provided usable feedback, which might also indicate that there are less people employed in game development in Europe.

What makes it so much harder to develop games professionally, both AAA, indie and casual in European countries?

Note: the total number of game companies in both continents seems to be rather equal (see wikipedia for a complete list, around 117 companies are U.S based versus 106 European). But we have to take into account that, although North America is 2.5 times larger than Europe, there are many more people living in Europe than in the States (731,000,000 versus 309,944,000).


texts: Most efficient way to implement walls and shadows in 2d

texts:
I am making a 2d top-down programming game similar to robocode. There will be up to 1000 walls (lines) in the arena, and up to 50 robots. Each robot can see in a 90 degree arc, and cannot see through walls. I need an efficient way to calculate what each robot can see (other robots and walls). I already have a grid of bins implemented. I was wondering what is the most efficient way to tackle this problem.

It would be nice if the method also includes a way to draw the shadows for visualization, but this is not necessary.

I am using C++ and the Qt framework.

Summary: The main question is how to generate a list of robots and walls that each robot can see. For example:

Robot 1 can see:
    Robot 6
    Robot 15
    A wall from (50,60) to (70,80)

Robot 2 can see:
...


texts: How can i start rotating object slowly smooth and then stop the rotation also slowly smooth?

texts:
In the top of the script:

public FirstPersonController fpc;
public float speed;

In the Update

void Update()
{
  fpc.transform.localRotation = Quaternion.Slerp(fpc.transform.rotation,
  Quaternion.Euler(0, 0, 0), speed * Time.deltaTime);
}

The problem is that the rotation start immediately. And i want it to start slowly smooth then it will get some speed and then near the end to slowly smooth again until stop.

Update:

This is the complete script for now:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;

public class FadeScript : MonoBehaviour
{
    public UnityStandardAssets.ImageEffects.Blur blur;
    public UnityStandardAssets.ImageEffects.BlurOptimized blurOptimized;
    public FirstPersonController fpc;
    public float fadeDuration = 5;
    public float startAcceleration = 0.6f;
    public float endAcceleration = 0.6f;
    public float maxSpeed = 1.0f;

    private Material material;
    private float targetAlpha = 0;
    private float lerpParam;
    private float startAlpha = 1;
    private bool rotated = false;
    private float rotationSpeed;
    private Quaternion clampedTargetRotation;
    private bool start;

    void Start()
    {
        material = GetComponent<Renderer>().material;
        SetMaterialAlpha(1);

        fpc.enabled = false;
    }

    void Update()
    {
        lerpParam += Time.deltaTime;

        float alpha = Mathf.Lerp(startAlpha, targetAlpha, lerpParam / fadeDuration);
        SetMaterialAlpha(alpha);

        if (alpha == 0)
        {
            fpc.enabled = true;

            if (rotated == false)
            {
                fpc.GetComponent<FirstPersonController>().enabled = false;
                rotationSpeed = Mathf.Clamp(rotationSpeed + startAcceleration * Time.deltaTime, 0, maxSpeed);
                rotationSpeed = Mathf.Clamp(rotationSpeed - endAcceleration * Time.deltaTime, 0, maxSpeed);
                clampedTargetRotation = Quaternion.RotateTowards(fpc.transform.localRotation, whateverRotationTokeepGoing, rotationSpeed * Time.deltaTime);
                fpc.transform.localRotation = clampedTargetRotation;
            }

            if (fpc.transform.localRotation == Quaternion.Euler(0,0,0))
            {
                fpc.GetComponent<FirstPersonController>().enabled = true;

                blur.enabled = false;
                blurOptimized.enabled = false;

                rotated = true;
            }
        }
    }

    public void FadeTo(float alpha, float duration)
    {
        startAlpha = material.color.a;
        targetAlpha = alpha;
        fadeDuration = duration;
        lerpParam = 0;
    }

    private void SetMaterialAlpha(float alpha)
    {
        Color color = material.color;
        color.a = alpha;
        material.color = color;
    }
}

My problem is in the rotation part:

if (rotated == false)
            {
                fpc.GetComponent<FirstPersonController>().enabled = false;
                rotationSpeed = Mathf.Clamp(rotationSpeed + startAcceleration * Time.deltaTime, 0, maxSpeed);
                rotationSpeed = Mathf.Clamp(rotationSpeed - endAcceleration * Time.deltaTime, 0, maxSpeed);
                clampedTargetRotation = Quaternion.RotateTowards(fpc.transform.localRotation, whateverRotationTokeepGoing, rotationSpeed * Time.deltaTime);
                fpc.transform.localRotation = clampedTargetRotation;
            }

The rotation should start from the current fpc rotation state and end at 0,0,0
This is where the rotation should be end when fpc is 0,0,0

if (fpc.transform.localRotation == Quaternion.Euler(0,0,0))

If fpc rotation is at 0,0,0 then stop. Between the start and stop make the whole rotation operation.


texts: How can I stop transform.position from being modified when adding a child object?

texts:
I suspect there is a well-known and easy to explain reason for the behavior I'm seeing, but I am having difficulty explaining it (and likely not able to Google for the answer).

When adding a child GameObject to a translated parent, the child's localPosition is modified so that the child's position stays the same after  the parent's transformation is applied. Is there a way to not have this be the case?

In the following example, I create a parent object and move it to (1,1,1), and then attach the child. I would like the child's position to be (1,1,1), that is (0,0,0) relative to the parent. However, the child's position is modified to be (-1,-1,-1) so that it is (0,0,0) relative to the world.

Here is a repro:

// Create parent.
GameObject parent = new GameObject();
parent.name = "Parent GameObject";
parent.transform.parent = foregroundObject.transform;

// Move the parent.
parent.transform.Translate(1, 1, 1);

// Add a child under the parent GameObject.
GameObject child = (GameObject) GameObject.Instantiate(guildiePrefab);
child.name = "Child GameObject";

child.transform.parent = parent.transform;

// PROBLEM: localPosition is set so that the "global" position is (0,0,0).
// How can I add the child object and have its position be (1,1,1)?
this.Assert(child.transform.localPosition.ToString() == "(-1.0, -1.0, -1.0)");
this.Assert(child.transform.position.ToString() == "(0.0, 0.0, 0.0)");

Is there a different way I should be adding child as a child of parent? Or, should I always zero-out the position of parent before adding a child? If that is the case, any reason why I need to do this? What is the rational for this design choice?


texts: How do I create an Ubuntu snap for a MonoGame application?

texts:
I've been going through the snapcraft documentation and examples and I'm still really confused about how to go about creating my snapcraft.yaml file.

Basically I have a folder with my game in it.  The folder contains all the files that are needed to run it.

I just want it to copy the files onto the end user's computer and have the shell script that launches the game targeted.

Here is my yaml file:
https://gist.github.com/c349bc23febbe73a6976b83b7757f887

Here are the contents of my directory:
https://github.com/SoundGoddess/OpenSolitaire/releases/download/0.9.2/OpenSolitaire.Classic.0.9.2.Linux.tgz

When I execute "snapcraft snap" I get the following error:
'NoneType' object has no attribute 'lstrip'

It looks like the parts folder gets generated ok, but then it fails on the build:

kati@linux:~/Development/OpenSolitaire.Classic$ snapcraft snap
Skipping pull opensolitaire-classic (already ran)
Preparing to build opensolitaire-classic
Building opensolitaire-classic
'NoneType' object has no attribute 'lstrip'

Any help would be greatly appreciated :)


texts: Unity Collision Doesn't Work when Two Players Instantiated

texts:
I am using Unity3D and I have a problem. I have a script which instantiates the player gameobject once you are connected to the server. I also have an attack script. When there is only 1 player on, everything works fine. When the second player comes on, the attack doesn't work! I did Debug.Log and I found out that when you clicked the other player to attack instead of attacking him, you are attacking the terrain below it.

Here is my code. Instantiate Code:

GameObject myPlayer = PhotonNetwork.Instantiate (
  character,
  mySpawn.transform.position,
  mySpawn.transform.rotation, 0) as GameObject;

Attack code:

using UnityEngine;
using System.Collections;

public class SendAttackInfo : Photon.MonoBehaviour
{
  public float damage = 100;

  // Use this for initialization
  void Start()
  {
  }

  void Update()
  {
    bool RMB = Input.GetMouseButtonDown(0);
    if (RMB)
    {
      RaycastHit hit;
      Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
      if (Physics.Raycast(ray, out hit, 100))
      {
        Debug.Log("We arm-hit: " + hit.collider.name);

        hit.collider.transform.gameObject.GetComponent<PhotonView>().RPC(
          "ApplyDamage",
          PhotonTargets.AllBuffered,
          damage);
        hit.collider.transform.FindChild("Cube").GetComponent<PhotonView>().RPC(
          "ApplyDamage",
          PhotonTargets.AllBuffered,
          damage);
      }
    }
  }
}


texts: What is the `AssetBundle` dropdown in the inspector for?

texts:
I know what an AssetBundle is alright. But what is the dropdown at the bottom right for?

Apparently you can choose an asset bundle for this asset to belong to. So what? What happens when you choose one? Does Unity build an AssetBundle for you? Where?


texts:
I've been looking into adding 'sloping' tiles into my platform game and my first attempt at collision detection with these tiles has produced some promising results (considering it's a first attempt), however, there is something that I just can't work out.

First, some background.

My tiles (on my dev device which is a Google Nexus 10 tablet) are 102 pixels wide by 100 pixels tall (this was done on purpose so they fit better to the screen).

So, my 'slope tile' looks something like this:

Not being a perfect square, the slope isn't quite 45 degrees but that shouldn't really matter I don't think.

Now, in order to find out the vertical 'centre' for collision purposes, I'm doing the following:

Find out where the sprite is in relation to the X Coordinate of the tile. (So, if the tile is at 100 and the sprite is at 110, then I am 10 in from the X of the tile.
I then multiply that by my slope (slope being height/width or 100/102 in my case)
I then divide by 2 to get the centre
Finally, I subtract that result from the height of the tile (to invert it)

This gives me the vertical center which I can compare with the centre of my sprite to check for collision.

So, my code looks like this:

VertTileCentre=Math.round(tileYCoord]+tile.quadHeight-((slope*(spriteX-tileX))/2));

Results

When I run this, although my sprite can slide up and down the slope it doesn't follow the (visible) path of my tile so I get something like this:

So when moving down the slope it moves in a jagged line and when trying to move up, it moves up the slope until it hits the next tile along, then gets stuck

Would appreciate if someone could point out why my sprite path is not following the slope correctly or anything else I may be doing incorrectly.

Edit 1 - results from further experimenting

I've noticed that the sprite when at the top-left of a slope tile sinks into the tile slightly, this is why the sprite was 'getting stuck' when moving up - because it was hitting solid blocks behind (which have their own collision detection)

Strangely, I've also noticed that if I remove the 'divide by 2' from my above calculations the path of the sprite is pretty much OK although the sprite itself still sinks into the tile slightly (But now throughout the whole slope) - therefore if I remove the solid blocks, it works OK.

So I have no idea why not dividing by 2 makes sense and also why my sprite is not correctly sitting on the slope!!


texts:
I want to add MoPub native ads in one of my unity project.So,is there any way to achieve this.Cause I found that it works with web and Android or iOS native apps.
Is there any way around to make it possible to add native


texts: How do I show a small sprite being dragged by touch?

texts:
In my mobile game, users drag shapes across the screen. Think of it as a classic Lines game, where you drag a dot on the field, or a chess game where you drag and drop pieces.

The problem is that the player's finger totally covers the sprite, making dragging confusing.

Is there a common practice to solve this?

My best try so far was to move the sprite to be offset from the finger when the dragging starts, then move along with the finger in the offset position until dropped.

The problem with this approach is that users might be left- or right-handed. If I offset the sprite to the top-left of the finger, dragging with the left hand covers the sprite again.


texts:
I have a collision system (in 3D but for the purpose of the question assume 2D) where I want to calculate the new velocity (stored as a vector) after a collision.

What I have is the velocity of the object colliding against a plane and I want the object to then slide down that plane.

I know the angle of impact with the plane and I know the normal of the plane.  I can create a Rotation Matrix for the rotation that the velocity needs to be changed by, I just am not sure how I rotate the velocity vector by that matrix.

I'm sure it's an easy answer but I haven't quite been able to get it.

I added a picture as requested

Any help would be appreciated.


texts: I am baking animation to draw a huge amount of crowd in unity3d. I am storing mesh of each frame of skinned mesh in the list and just iterating over it. I can't use the compute shader as I want to target low-end devices too. But now I am facing memory issues as mesh consumes over 1.5gb of memory. Is there any way I can free memory consumes by mesh?


texts: Need ideas on how to give my levels structure

texts:
I am making an iOS game for a project at school. It is going to be a tiny bit like Fruit Ninja, as in it will have different things on the screen, and when you hit them, they die, and you get points. The trouble is that unlike Fruit Ninja, my game will have different types of sprites, all doing different things (moving different places, doing different things, etc).
The one thing that is bad about having all of these sprites that do different things is that it is hard for them to look neat on the screen all together. I was planning on having a couple of different gamemodes:

Time Trial
You have 120 seconds to kill as many sprites as possible.

Survival
You have three lives, every time you try to hit a sprite and miss, you lose a life.

????
Whatever I think of.

I am a rookie to game design in general, and I don't know the best way to make my game look good, and play well. I could have all of these sprites on the screen at the same time, or I could have them come in waves, for example 10 of sprite_a come on, and once they are killed, 10 of sprite_b come on, etc...

Please give me your opinion about which one I should code. If you have any other suggestions for either a third gamemode, or a completely different way to make the levels, feel free to tell me.


texts: How can I make a flapper game that scales to multiple aspect ratios?

texts:
So I've never made a game before besides a basic 4:3 aspect ratio flapper, so bare with me. Recently I had this wild idea that I wanted to make this complected (for a 2d) game in cca. Unfortunately I'm stumped. At first I decided it's smart to program my game in a 16:9 aspect ratio, but then I thought about it... The iPad and Nexus 9 work in a 4:3 aspect ratio. How would one make a game (like a flapper) scale to both aspect ratios?

Edit: If it helps at all, I will be using JS... Primarily the Pixi.js library.


texts: Add sprite flickering to a LibGDX object

texts:
How can I make a LibGDX Actor object flicker over a set duration?

Many 2D platformers have the player character 'flicker' after taking damage to indicate temporary invincibility, (ie: invincibility frames). For an example, see the below gif from Shovel Knight.

It's fairly simple to make an object fade in or out over time using LibGDX's Actions library.

Actor player = new Actor();
// fade out in 0.25 seconds
player.addAction(Actions.fadeOut(0.25));

But searching through the documentation, I couldn't find any method for Actions.flicker(). How can I implement sprite flickering in LibGDX?


texts: How to calculate the ideal hit of arrow?

texts:
I am trying to make the AI shoot an arrow and always hit the target. Assuming that the target is within his range I am stuck what the correct way is to do this. I search and found some solutions but they do not seem to work 100% perfectly in my code
(How can I shoot an arrow if I know the shot power and target?).

My code is (target is the prefab I want the AI to hit):

arrow.GetComponent<Rigidbody>().AddForce (Aim()*speed, ForceMode.VelocityChange);

private Vector3 Aim()
{
    float xAim = target.transform.position.x - transform.position.x;

    float yAim = Mathf.Rad2Deg * Mathf.Atan((speed*speed + Mathf.Sqrt(speed*speed*speed*speed) - (-Physics.gravity.y) * (-Physics.gravity.y * HorizontalDistance()*HorizontalDistance()) + 2 * VerticalDistance() * speed*speed / -Physics.gravity.y * HorizontalDistance()));
    float zAim = target.transform.position.z - transform.position.z;
    Vector3 aim = new Vector3(xAim, yAim, zAim).normalized;
    return aim;
}
private float HorizontalDistance()
{
    float xDistance = target.transform.position.x - transform.position.x;

   // float zDistance = target.transform.position.z - transform.position.z;
    float distance = Mathf.Sqrt(xDistance*xDistance);// + (zDistance*zDistance));

    return distance;
}
private float VerticalDistance()
{
    return Mathf.Abs(target.transform.position.y - transform.position.y);
}


texts: Collision detection across multiple components

texts:
I have been reading this article: http://gameprogrammingpatterns.com/component.html which describes how a game object should be constructed out of components. It also encourages the decoupling of components, which brings up a problem with input, collision detection, and things that cause events to be triggered.

If I have a game object, which is a player and this player has 3 components; PlayerSoundManager, PlayerCollisionDetection, and PlayerStateManager, how would I go about making sure they have no references to each other? If PlayerCollisionDetection detects that a player should die, messages should be sent to the other two components telling the player to play a death sound, and change it's state.

Would it be wrong to put collision detection methods throughout all components and perform each reaction separately?


texts: How to prevent unwanted scaling of textures in world space

texts:
I allow players to select buildings of different sizes in my game, in the image below is a building that is 30x30 units and one that is 10x10 units.

To indicate that the building is selected, I added a child called Selection indicator, this child is simply a texture dragged into the scene, which creates a plane. I activate/deactivate this on select/deselect.

So far so good, but as you can see in the image, in order to match the different sizes, I need to scale the Selection indicator, which distorts its edges. Simply using sprite editor here does not seem to change anything since it's in world space.

How could I approach this in a way that the frame for my Selection indicator does not stretch like in the image?


texts:
I'm using Dijkstra algorithm to find shortest path and I'm drawing this path on the screen. As the character object moves on, path updates itself(shortens as the object approaches the target and gets longer as the object moves away from it.) I tried to visualize my problem.

This is the beginning state. 'A' node is the target, path is the blue and the object is the green one.

I draw this path, from object to the closest node. In this case my problem occurs. Because 'D' node is more closer to the object than 'C' node, something like this happens:

So, how can i decide that the object passed the 'D' node? Path should be look like this:

One thing comes to my mind is that I use some distance variables between the two closest nodes in the route path. (In this example these are 'C' and 'D' nodes.) As the object approaches 'C' and moves away from the 'D' node at the same time, this means character passed the 'D'.

However, I think there are some standardized and easy ways to solve this. What approach should I take?


texts: What should deliverables for a school game project be?

texts:
I am planning on making a 3D hack-n-slash RPG with Unity for a school project. I have to come up with a project proposal. I am suppose to identify project deliverables.

I cannot think of what "deliverables" would be for this kind of game. I am hoping someone can give me some examples to get me started?

Would they be art work or characters? Content? Story? Core features? Technical requirements? What technology I am using? I am not sure.


texts:
This is the view from my spaceship. It can move around in 3d space and turn up, down, left and right.

The planet Earth on the top right is selected.
Now I want to create the red arrow to always point to the direction of Earth even if my ship is facing away from it.

this is my code so far

//These are euler angles
Vector3 wantedheading = SelectedObject.transform.position - Statics.Player.transform.position;
Vector3 curentheading = Statics.Player.transform.localRotation.eulerAngles;

Quaternion qwanted = Quaternion.Euler(wantedheading);
Quaternion qcurent = Quaternion.Euler(curentheading);
Quaternion qMove = Quaternion.FromToRotation(curentheading, wantedheading);

but now I have a 3d rotation... what do I do to make it into a 2d rotation always pointing to the shortest direction to the planet?


texts: Why is the texture all wrong on my model?

texts:
Why is this happening? If possible I'd like to know what this particular problem is called. The model is a simple cube made in blender and exported with normals and MTL. Texture is the cube unwrapped with crate image on each side.

Are the UV coordinates wrong?


texts: Developing an ELO like point system for a multiplayer gaming site

texts:
I'm currently working on a gaming site where users will submit virtual players for different games, like Chess, Nash, Backgammon, Go, etc. The idea is that users don't compete themselves, but through their virtual players. There will be leagues, tournaments, and other competition formats.

The question is which would be a good rating system for users in this environment. Take into account that every user may have many different virtual players playing in many different games. As a general guideline I would like to guarantee the following properties:

Users who have a lot of mediocre players should not score higher than users with a few very good players.
A user with a high rating should not be penalized if he adds a new bad player, until he has had enough time to improve his player.
Users who don't play often should not score higher than users who play every day.

Thanks in advance.


texts: What is the purpose of integration in physics engines?

texts:
All online resources seem to assume that you know what this means and/or state that this is related to object movement in some way.

How does this differ than just position.x++ and position.y++ and how does integration allow us to simulate movement? (calculus integration?)

I understand there are a few different methods, namely Euler explicit, RK4, and Verlet. These methods I read are meant to solve ODE's, what are we solving for when we solve these equations?


texts:
I want to make a 3d editor in DX9/XNA for a project I'm working on. I'm just thinking through how I would go about certain tasks and I'm stuck on one particular thing, which is crucial to making the editor working.

The editor will allow 3d objects to be added to the scene. For example I would add a cube to the scene. Now I want to be able to select one edge of the cube. When this edge is selected it should change colour. The remaining edges should not change colour.

If my description is not clear enough then it would basically be the same as the edge tool in blender. If you look at the following image you will see the first double cube has its centre edge highlighted

http://wiki.blender.org/index.php/File:Manual-Part-II-EdgeSpecials-EdgeSlide.png

I can't recall coming across anything in DX9 or XNA that allows edges to highlighted in this way. Would this be done in a shader perhaps?

Thanks

Edit From OP:  (Can't seem to post comments so editing the original.)
I had considered drawing lines but wasn't sure if it would trace the exact same path as the edge. I guess I it would be best to try this first before dismissing it. The purpose of the post was to find out if xna or dx9 had something built into it to do this sort of thing. I'm currently just in the design phase so have not implemented anything.

I would accept the answer from Roy T but I can't find the option to do so! Thanks.


texts:
I have an octree that I'm planning to use for 3D pathfinding. My plan was to break down the world such that all the leaf nodes of the tree would be of equal dimensions that would create a nice grid and then adapt A* by adding an extra dimension and just run searches on the grid. The image below shows a sample of my leaf nodes to demonstrate what I'm talking about (ignore the spheres, they are for something else).

What I'm not sure about is how do I perform A* on a tree structure. My thought was to convert the tree structure to a 3D array, which would make it really easy to perform A* on, but I'm not sure how I would go about this. I can recursively work my way down the tree and tell which nodes are the leaf nodes, but I don't know how I could necessarily work my way down in an ordered fashion such that I could index nodes into an array properly. How would I go about this? Is it even the right approach; or it there a better approach to performing A* on the tree?

Note: I am aware the space might not actually be open enough to justify full 3D pathfinding, but this is intended to be a demonstration/test of the concept, so I wanted to keep things relatively simple.


texts:
I've been modifying a pathfinding example from XNA Pathfinding example as described in my previous question Link to question here  I had an issue where the character moved kept moving back and forth in a line. John McD suggestion made the brilliant I alert the way that the Heuristic calculation so that any nodes on the existing path had a lower value.

From what I've debugged in the project the new calculation seems to work fine, despite that the problem still persists. I was wondering if I implemented the Heuristic method wrong.

This is the method which houses the A* algorithm

/// <summary>
/// This Method looks at everything in the open list and chooses the next
/// path to visit based on which search type is currently selected.
/// </summary>
/// <param name="result">The node to be visited</param>
/// <returns>Whether or not SelectNodeToVisit found a node to examine
/// </returns>
private bool SelectNodeToVisit(out SearchNode result)
{
    result = new SearchNode();
    bool success = false;
    float smallestCost = float.PositiveInfinity;
    float currentCost = 0f;

    if (openList.Count > 0)
    {
        foreach (SearchNode node in openList)
        {
            currentCost = Heuristic(node);
            // The heuristic value gives us our optimistic estimate
            // for the path length, while any path with the same
            // heuristic value is equally ‘good’ in this case we’re
            // favoring paths that have the same heuristic value
            // but are longer.
            if (currentCost <= smallestCost)
            {
                if (currentCost < smallestCost)
                {
                    success = true;
                    result = node;
                    smallestCost = currentCost;
                }
                else if (currentCost == smallestCost &&
                    node.DistanceTraveled > result.DistanceTraveled)
                {
                    success = true;
                    result = node;
                    smallestCost = currentCost;
                }
            }
        }
    }
    return success;
}

This is the method which does the new Heuristic calculation

/// <summary>
/// Generates an optimistic estimate of the total path length to the goal
/// from the given position.
/// </summary>
/// <param name="location">Location to examine</param>
/// <returns>Path length estimate</returns>
private float Heuristic(SearchNode location)
{
    int Nodecost = 10;

    foreach (Point point in Currentpath)
    {
        if (location.Position == point)
            Nodecost = 7;
    }
    return location.DistanceTraveled + location.DistanceToGoal + Nodecost;
}

This is the method which adds the point to their respective list once

/// <summary>
/// This method find the next path node to visit, puts that node on the
/// closed list and adds any nodes adjacent to the visited node to the
/// open list.
/// </summary>
private void DoSearchStep(TileMap tileMap)
{
    SearchNode newOpenListNode;

    bool foundNewNode = SelectNodeToVisit(out newOpenListNode);
    if (foundNewNode)
    {
        Point currentPos = newOpenListNode.Position;
        foreach (Point point in level.OpenMapTiles(currentPos, tileMap))
        {
            SearchNode mapTile = new SearchNode(point,
                StepDistanceToEnd(point),
                newOpenListNode.DistanceTraveled + 1);
            if (!InList(openList, point) &&
                !InList(closedList, point))
            {
                openList.Add(mapTile);
                paths[point] = newOpenListNode.Position;
            }
        }
        if (currentPos == endPlace)
        {
            searchStatus = SearchStatus.PathFound;
        }
        openList.Remove(newOpenListNode);
        closedList.Add(newOpenListNode);
    }
    else
    {
        searchStatus = SearchStatus.NoPath;
    }
}


texts: Direct3D and OpenGL Matrix representation

texts: As I read in OpenGL matrices are column major. It means that if I create a 16 element array first four elements are the first column in matrix. Is it the same for Direct3D or any transformation's required.


texts: how to modify multiples BoxCollider on a same game object?

texts: I have an game object with multiples BoxCollider attached to it, is there a way to get all the BoxCollider to an array so that I could modify their value individually ?


texts: How to make blocks like "redstone" working in a minecraft-like game when the chunks are not loaded

texts:
I'm working on a 2D minecraft-like game, I use chunks to save my world and each chunk has 128*128 blocks in it.
And infinite chunks can create an infinite world.

Memory should never be infinite and only several chunks near the character are shown on the screen and loaded into memory. How can I handle logic based blocks like red stone signals when they are in chunks far away and so not loaded in memory?


texts: I recently decided to utilize the C++ library called FreeGLUT to have a window be managed from my program, where I can draw things via OpenGL. But at the same time I saw some people telling that it is an old library, not that much reliable and so on... Should I keep using that or move to another one?


texts: Can I set a texture as the wallpaper of an iOS device?

texts:
I have a game in Unity which creates drawings.

I need to have a button which sets the drawing as the wallpaper (with permission from the user of course).

Is it possible?


texts: Most common resolution used in Android phones as of 2013

texts:
Before making an Android app, I want to know what screen resolutions I should target. I know there are resolutions of 1280x800, 1280x720 and 800x480, but I would like to know which are most common.

Are there any recent stats on the distribution of Android devices' screen resolutions?


texts:
What is the best method to share the projection matrix and view matrix with all graphic entity shaders in a custom game engine? The refer graphic entities have glUseProgram({shader_program_id}); glDrawArrays(GL_XXXX, x);

One of my ideas is to have a camera object that manages the current view and projection matrix. Then, I pass a reference of that camera object to all the entities. However, my issue with that approach is syncing the current camera across all the entities/objects when switching views.

I could make the Camera global, however, that could have many issues.


texts: OpenGL - What steps to take to correctly set up an Uniform Block Array

texts:
I have managed to get uniform blocks to work, but I seem to make something wrong when trying to setup an array of uniform blocks.

Assume this glsl:

layout(std140, binding=1) uniform LightingBlock
{
    vec4 ambient;
    vec4 diffuse;
    vec4 specular;
    vec3 factors;
    float shininess;
} lighting[3];

What's the exact procedure to bind this? What I am doing (and what works for a single block, not an array):

GenBuffer...
BindBuffer...
BindBufferRange(UNIFORM_BUFFER, 1, buffer_id, 0, size_in_bytes)
index = GetProgramResourceIndex(program_id, UNIFORM_BLOCK, "LightingBlock")
UniformBlockBinding(program_id, index, 1);

I read that I should replace the LightningBlock with lighting[0], [1] etc, but this only returns invalid indices. So my current attempt looks like this:

GenBuffer...
BindBuffer...
binding = 1
for(int i = 0; i < 3; ++i)
{
    BindBufferRange(UNIFORM_BUFFER, binding + i, buffer_id, 0, size_in_bytes)
    index = GetProgramResourceIndex(program_id, UNIFORM_BLOCK, "lighting[" + str(i) + "]")
    UniformBlockBinding(program_id, index, binding+i);
}

What am I doing wrong? How to do this correctly?


texts: Just how expensive is it to bind textures in OpenGL? (LibGDX)

texts:
I'm using LibGDX on top of OpenGL and currently my game engine does something along the lines of the following per frame

Bind a terrain texture sprite atlas and a set of transparency masks in another texture atlas
Render terrain tiles using the 2 bound textures to a FBO
Bind a character and item texture sprite atlas
Render characters over the terrain to the same FBO
Bind the same transparency mask atlas and a normal map texture for the terrain
Draw the same terrain tiles' normal map version to a different FBO
Bind the character and item normal map texture atlas
Render character normal maps over the terrain normal map FBO
Bind this normal map FBO as a texture
Render lighting information to a different FBO using the normal map texture information
Bind the diffuse and lighting FBOs as textures
Use these to render the combined final image to the main display

So in summary, each frame I'm binding a total of 9 different textures, one or two at a time.

Should I look into changing my code so all 9 textures are always bound, and the correct one is referenced at the right time? Or is this a reasonable amount of texture binds per frame that isn't going to impact overall performance to a noticable effect? Assume I'm aiming for 60fps and there's a fair amount of other calculations going on per frame.


texts: Need some advice on a java api to use for a 'presentation display board' - based on game 2d/3d tech

texts:
As part of the project i am working on I am looking to produce some software that works on a LCD display (think call center info boards) and displays various graphs (the bars grow etc in realtime, so incoming call stats etc etc) and flicks between various 'plug-ins'.

I asked before, and WPF was suggested, and it looks excellent.. However i really need to keep to Java (work standards).. So the question is what XNA style API is the best for this, I can see that JMonkey etc seem to provide 3d stuff, but I also need sprites etc.

For example: Think, defused 3d planet rotating in the background, while call stats are printed over the top.


texts:
I am using the UI slider from Unity 5 and would like to display a text every time the handle knob is touched/pressed.

My understanding is that my script should extend some Event System interface. From the unity doc either ISelectHandler or IPointDownHandler should be able to 'hear' if my knob is pressed. I am a noobie to the unity event system, so I hope that this question doesn't offend anyone if its pretty basic..

So far this is what I have:

public class SliderControl : MonoBehaviour, ISelectHandler {

    public Slider slider;

    void Start(){
        slider.transform.GetChild (2); // this gets the Handle Slide Area where the knob is
    }

    public void OnSelect (BaseEventData eventData) {
        Debug.Log ("Display some text");
    }
}

My questions are:

What exactly is a base event data in simple English?
How can I convert my slider knob into a BaseEventData type that OnSelect() can work with?


texts: How to figure out hidden fields in an .ini file?

texts:
I'm not sure if this is the right place to ask this, but I can't think of anywhere else that would fit better.

Fallout 4 has just recently released, and I'm wondering what exactly can I edit in the ini. I know you can add certain things that aren't already present in the ini. For example, to change the FOV:

[Display]
fDefaultWorldFOV=100
fDefault1stPersonFOV=100

However, how do I figure out what other 'hidden' fields are? In Skyrim, for example, you can change the camera like this:

[Camera]
fOverShoulderAddY=0.0000
fOverShoulderPosZ=10.0000
fOverShoulderPosX=0.0000
fOverShoulderCombatAddY=0.0000
fOverShoulderCombatPosZ=10.0000
fOverShoulderCombatPosX=0.0000

Surely it's not just trial and error?


texts: Support function of Minkowski Difference

texts: I am watching this and if you stop at 7:25, you will find an implementation of the support function. The goal of the function is to give you the farthest point in a given direction. My question is how do we achieve this without looking at all the points in the Minkowski Difference? How is this not an O(m*n) algorithm ? Is there a way to get just the points that lie on the edges (I am asking because in the slide after that he just shows the edge points and not all the internal ones)? Am I missing something ?


texts: Why when releasing a DirectX Texture it fail

texts:
I have an instance where a class creates a DX9 texture via

UINT usage = D3DUSAGE_RENDERTARGET;
HRESULT hr = D3DXCreateTexture (m_D3DDevice,
                                200,
                                200,
                                0,
                                usage,
                                D3DFMT_X8R8G8B8,
                                D3DPOOL_DEFAULT,
                                &m_texture)

Where m_texture is IDirect3DTexture9*  and hr = S_OK after creation.

But when I come to cleaning it up in the destructor via

if (m_texture != NULL)
{
    hr = m_texture->Release();
}

hr = S_FALSE

Why would it fail to release a texture?


texts: How do I fire a projectile at where an object will be located in the future?

texts:
I'm making a tower defense game where the towers are shooting projectiles at enemies. I do not want to make the projectiles homing, and I want to make sure that when a tower fires a projectile, it will hit where the enemy is going to be, instead of firing at where the enemy is currently located.

My givens are the position and velocity of the enemy, the position of the tower and the speed at which projectiles travel. There is no acceleration.

I was considering taking the distance between the tower and the enemy, calculating how long it would take the projectile to connect with the enemy, and then using that to calculate the future position of the enemy, firing at that instead. However, now the distance between my tower and the enemy in the future might be different, so my calculation isn't going to be precise, and it might miss.

How do I correctly calculate where to fire the projectile so that it will always connect with the moving enemy?


texts: Running OpenGL app on Windows XP x86 produces incorrect texture colors

texts:
I'm working with the Cen64 emulator and I compiled from source a x86 version that operates fine on Windows 10 x64. As soon as I run it on a Windows XP x86 machine the colors are then all incorrect. Here are some screenshots:

Running on Win 10

Running on Win XP SP3

  The color format is set to GL_UNSIGNED_SHORT_5_5_5_1 and the internal format is GL_RGBA:

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, hres + hskip, vres,
    0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, buffer);

I'm pretty new to configuring color packing formats but it appears like some color channels are getting swapped? Maybe some sort of endianness issue going from an x64 to an x86 architecture?

Please let me know if I need to show more of my code to help debug the issue. Thanks for any help! ^_^


texts:
I have object moving from A to B on x-axis and there is no translation of object apart from it. Now, while moving, i want to rotate it around y-axis and the motion should change accordingly, i mean if i rotate it right when moving from -x to +x axis, it should move towards near plane. I have variable in gltranslatef which is modified in the loop after that i have glscalef to scale whole object which is made of hierarchical structure. Now i tried following code to achieve the expected result but its not working properly

   glTranslatef(move, 0, 0);

// If I comment these 3 lines, it does not affect the output
     glTranslatef(-move, 0, 0);
glRotatef(rotate,0,1,0);
glTranslatef(move, 0, 0);

glScalef(0.2, 0.2, 1.0);


texts: Create shape from points / lines in editor and mathematically calculate nearest points within shape

texts:
If I want an editor that accepts "points" of a minimum of three (a triangle) and I just add some points first, like this:

how can I mathematically connect these corners (points) into an object of multiple triangles? so amount of triangles looks like something like this, by connecting nearest point:

and then later render this and also being able to define what it is and check for collisions on this ground, so I can create more than Rectangle based "bricks" on a Platformer for example. Also being able to texturize the whole object without it looking ugly.

Any ideas? Or what is this called in game programming?


texts: Unity Shader Graph, set blackboard properties from code

texts:
I have a Shader Graph shader with a blackboard property that I want to change from within my code. The property is called Highlight here are the things I have tried:

Color myColor = new Color(1f,0,0,1f);
material.Color = myColor;                       // throws error (as I expected)
material.SetVector("Highlight", myColor);       // Name in blackboard window
material.SetVector("HighlightColour", myColor); // Name in material property
material.SetVector("Color_8C3A526", myColor);   // Name in the shader inspector

None of these work.

Here's the shader set up:


texts: What is a good alternative to Unified Shader for Shadows?

texts:
Most shadow systems I have seen use a unified shader system for shadowing techniques, resulting in an uber shader for the projects.

What alternatives do you find work well or is the unified shader the best approach?


texts:
I am trying to create an image effect where only a part of the image has the effect applied to.

One way I can think of to do this is to define the portion of the image using the stencil buffer.

Stencil Mask Shader:

Stencil
{
    Ref 1
    Comp always
    Pass replace
}

Image Effect Shader:

Stencil
{
    Ref 1
    Comp equal
    Pass keep
}

OnRenderImage Function

void OnRenderImage(RenderTexture source, RenderTexture destination)
{
    saturationPassMat = CheckShaderAndCreateMaterial(saturationShader, saturationPassMat);

    saturationPassTex = RenderTexture.GetTemporary(source.width, source.height, 24);
    Graphics.SetRenderTarget(saturationPassTex.colorBuffer, source.depthBuffer);

    Desaturate(source, saturationPassTex, saturation);

    Graphics.Blit(saturationPassTex, destination);

}

Applying the stencil portion of the image effect shader to any other object produces a desirable stencil effect (aka: it works).

The Problem:

By the time OnRenderImage is called, it seems that the stencil buffer has already been cleared. Changing Ref to 0 in the Image Effect shader will apply the effect to the entire screen. Any other value will result in a black screen. This can only mean that the stencil buffer has been cleared to 0.

Is there a way to prevent the stencil buffer from clearing? Or is this the right method to use the stencil buffer with image effects? Or perhaps there are other solutions that are still efficient, without the use of Stencils?


texts: Best way to implement a class or interface for a set of UI buttons that only differ in their Draw() function?

texts:
I have three types of UI buttons that go on a cooldown bar:

A traditional cooldown bar button where once the corresponding key is pressed, a timer shows over the button and dims the texture.
A button that shows a cooldown, doesn't dim and adds stacks counting upwards to a max (say 5) in the upper left
A button that acts like a toggle with no timer, but dims depending on if it's on or off

These all inherit from my AbilityButton class. I'd like to put all three Draw() functions in AbilityButton like:

public virtual DrawNormal() {...stuff...}
public virtual DrawStackable() {...stuff...}
public virtual DrawToggle() {...stuff...}

... and tell the children to implement the correct one. The problem is that I don't think it's possible to just tell my children to use one of those. From what I've seen, I'd need to make an instance of the parent in each child and call the corresponding method. This just feels weird and wrong - like I'm designing incorrectly to land in this position in the first place.

Is there a better way to do this? Is this better suited for interfaces? One interface per button type? The problem with interfaces is that I want to actually define the method functionality in the parent which interfaces do not allow.


texts: Examples about how to tie AI actions to animations?

texts:
I wrote a simple test AI for a character; and all that it should do is to be idle while a parameter is below threshold; otherwise it should perform actions based on other parameters.

So for example

if X< 0.5 --> Idle state
else
   if A > 0.3 --> go to point A and perform action A
   else if  0 < A < 0.3 --> go to point B and perform action B

I do have the code for the AI state machine in place; but now I am stuck about how to build the animator that goes with this AI.
I did use the standard AI 3rd person prefab in Unity; and it moves correctly, since the controller script has the logic for moving already integrated; but how do I make the entry for action A and B?

Do I add the animations in the blend tree of the animator, and then from the AI script I call the animator play function for a specific animation? Do I set parameters for such animations so when the variable X and A change; the blend tree read them directly and transition automagically?

All that I can find around is just the usual AI examples for FPS; which use the same patrol-chase-investigate sequence; but they are mostly moving or chasing; not necessarily executing different animations.

Any suggestion would be more than welcome


texts: The LibGDX Actor does not have a dispose method, though it has a texture. Do I need to call dispose on its texture?


texts: Technical Design Document and PNG filesizes

texts:
I am writing a Technical Design Document and starting to list assets and their file sizes.

The formula for calculating the file size of a PNG is easy:
width x height x bit depth.

I am having a problem with the file size windows shows in the file properties for some of my png's.

Background image:

The dimensions are 1280 x 720 32bit and filesize ought to be 3,686,400B.  Windows Properties shows 3.6KB. Shouldn't this be 3600KB?

Now I have a cursor image:

32 x 32 32bit ought to be 4,096B.  Why does the file properties in windows say the file size is 304B?

As you can see the size on disk is correct for the cursor but the size is off.  With the background image the size is correct but the size on disk is bigger.

I am using GIMP to create the images and exporting with none of the tick boxes checked, so no comments or background colour saved etc.

Can anyone explain why windows does this? Thank you.


texts:
I am finding my project is starting to show performance degradation and I need to optimize it. The answer to my previous question and this presentation from NVidia have helped greatly in understanding the performance characteristics of code using the GPU but there are a couple of things that aren't clear that I need to know to optimize my drawing.

Specifically, what calls make the distinction between batches.

I know that any state changes cause a new batch, so that includes:

Render State Changes
Buffer Changes
Shader Changes
Render Target Changes

Correct? What else counts as a 'state change'?

Does each DrawPrimitive() call constitute a new batch?** Even if I were to issue the same call twice, with no state changes, or call it once on on part of the buffer, then again on another?

If I were to update a buffer, but not change the bindings, would that be a new batch?

That presentation and a DX9 page suggest using all of the texture slots available, which I take to mean loading multiple objects in 'parallel' by mapping their buffers/shaders/textures to slots 1-16. But I am not sure how this works - surely to do this you would need to change the buffer binding and that would count as a state change? (or is it a case of you do but it saves 16 calls so its OK?)


texts: Change hero direction in place before movement on a grid based game in Unity

texts:
I've already implemented a grid based movement with all the necessary animations.

Now I would like the make the hero face the direction of the input without moving first and move only if the input direction is the same one he's facing.

E.g.: if the Hero is standing still facing up, and you press left, he will face left without moving. If you then press left again, he will move on that direction cause he's already facing it.

Here's the code:

void Update() {

    movementDirection.x = Input.GetAxisRaw("Horizontal");
    movementDirection.y = Input.GetAxisRaw("Vertical");

    isMoving = Vector2.Distance(transform.position, movePoint.position) > 0.1f;

    SetAnimator();

}

void FixedUpdate() {

    transform.position = Vector2.MoveTowards(transform.position, movePoint.position, movementSpeed * Time.fixedDeltaTime);

    if (!isMoving) {
        if (movementDirection.x != 0) { movePoint.Translate(new Vector2(movementDirection.x, 0f)); }
        else if (movementDirection.y != 0) { movePoint.Translate(new Vector2(0f, movementDirection.y)); }
    }

}

private void SetAnimator() {

    animator.SetBool("Moving", isMoving);

    if (!isMoving && movementDirection != Vector2.zero) {

        animator.SetFloat("Horizontal", movementDirection.x);
        animator.SetFloat("Vertical", movementDirection.y);

    }

}

I tried using global variables to compare Hero's direction with the input, and let the Hero move only if they're the same but due to the Update function called every frame as soon as I update the current direction with the input one the hero will start to move:

void FixedUpdate() {

    Directions latestGivenDirection = GetLatestGivenDirection(movementDirection);

    //this wont work, as the next frame will pass the condition and the hero will move
    if (latestGivenDirection == currentDirection) {

        transform.position = Vector2.MoveTowards(transform.position, movePoint.position, movementSpeed * Time.fixedDeltaTime);

        if (!isMoving) {
            if (movementDirection.x != 0) { movePoint.Translate(new Vector2(movementDirection.x, 0f)); }
            else if (movementDirection.y != 0) { movePoint.Translate(new Vector2(0f, movementDirection.y)); }
        }

    }

    currentDirection = latestGivenDirection;

}

How can I achieve such a behaviour?


texts: How to find a valid point if NavMeshObstacle is blocking path?

texts: Is there any way to find the closest valid point to my target if a NavMeshObstacle is blocking my agent's path? This point can be any point along the red line in the image above.


texts:
I play a lot of "Call of Duty", and can see tracers for gunfire, missiles, care packages falling from helicopters etc. There is a lot of activity. I am curious to know the algorithm one would use, at a high level, to manage all this action when you have 20 people on a map shooting each other to death.

This question touches on the subject, but doesn't ask for a more in-depth answer as to how you the developers go about calculating and transmitting movement and collision detection for projectiles, be it missles, bullets, or any other object that is flying through the air in real-time.

How are trajectories calculated and transmitted to other players, in multiplayer?


texts: Calling Shader Functions Inside Other Shaders

texts:
I'm new to OpenGL and GLSL, and bit confused about calling conventions of shader functions.

I'm trying to implement various procedural noise algorithms in GLSL. I'd like to have separate files for each noise and call these functions inside other fragment shaders.

Let say I have 2 files perlin.glsl and simplex.glsl.

perlin.glsl  consists of pnoise2, pnoise3, pnoise4

simplex.glsl consists of snoise2, snoise3, snoise4

I have another fragment shader marble.frag which calls both snoise2, pnoise2 and has a main()

How do I call fragment shader functions inside other fragment shaders?
Is this considered a good practice?
Can you think of a better alternative?

Thanks


texts: Vertical camera rotation has reduced speed & range when looking at the character from the left or right

texts:
I completed a camera tutorial for Unity. I can rotate a camera around my figure around the Y axis (Vector3.up) and I wanted to extend that for a Fixed-Free 3rd Person camera (What are the types of 3rd-person camera called?) where I can tilt aswell but I am stuck with the wrong rotation.

I expect the camera to go up/down whenever I use the joystick up/down and always go left/right when I use the joystick left/right.

But instead of that I get always left/right movement as I wish but up/down is only working at the center. The further I go left or right (see images) the less I go up/down. This sounds super complicated, please see the images. I want the same behaviour as shown when the camera is behind the object and I want to avoid the behaviour at the right side like in the first image.

Bonus would be if I can limit the up and down movement to say 160° so the player can't look top down.

The Code looks like this (only RotateCamera() and UpdateCameraPosition() are relevant):

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

public class PlayerCamera : MonoBehaviour
{
    [System.Serializable]
    public class InputSettings : System.Object
    {
        public float inputThreshold = 0.1f;
        public string VERTICAL_AXIS = "CameraVertical";
        public string HORIZONTAL_AXIS = "CameraHorizontal";
        public string LOCK_TARGET_PYRAMID = "LockToPyramid";
        public string LOCK_TARGET_AREA = "LockToArea";
    }

    [SerializeField] private Transform target;
    [SerializeField] private float cameraSpeed = 2;
    [SerializeField] private Vector3 lookAtPlayerOffset = new Vector3(0f, 0.6f);

    private PlayerController playerController;
    private float cameraHorizontal, cameraVertical;
    private float lockPyramid, lockArea;
    private InputSettings inputSettings;
    private Vector3 cameraPlayerOffset;

    void Start()
    {
        SetCameraTarget(target);

        inputSettings = new InputSettings();
        cameraPlayerOffset = transform.position - playerController.transform.position;
    }

    private void Update()
    {
        GetInput();
    }

    private void LateUpdate()
    {
        RotateCamera();
        UpdateCameraPosition();
    }

    private void RotateCamera()
    {
        Quaternion cameraRotationXDelta = Quaternion.AngleAxis(cameraHorizontal * cameraSpeed, Vector3.up);
        Quaternion cameraRotationYDelta = Quaternion.AngleAxis(cameraVertical * cameraSpeed, Vector3.right);

        // this does not work how I wish it would after rotating around a bit
        cameraPlayerOffset = cameraRotationYDelta * cameraRotationXDelta * cameraPlayerOffset;

    }

    private void UpdateCameraPosition()
    {
        // prevent camera from clipping through floor
        Vector3 newPos = playerController.transform.position + cameraPlayerOffset;
        newPos.y = newPos.y < 0.2f ? newPos.y = 0.2f : newPos.y;
        transform.position = newPos;
        transform.LookAt(target.transform.position + lookAtPlayerOffset);
    }

    private void GetInput()
    {
        cameraHorizontal = Input.GetAxis(inputSettings.HORIZONTAL_AXIS); // interpolated
        cameraVertical = Input.GetAxis(inputSettings.VERTICAL_AXIS); // interpolated

        lockPyramid = Input.GetAxis(inputSettings.LOCK_TARGET_PYRAMID); // interpolated
        lockArea = Input.GetAxis(inputSettings.LOCK_TARGET_AREA); // interpolated
    }

    private void SetCameraTarget(Transform targetTransform)
    {
        target = targetTransform;

        if (target != null)
        {
            if (target.GetComponent<PlayerController>())
            {
                playerController = target.GetComponent<PlayerController>();
            }
            else
            {
                Debug.LogError("The camera's target needs a player character controller.");
            }
        }
        else
        {
            Debug.LogError("Your camera needs a target");
        }
    }
}


texts: How should I collect user behavior data in an MMO?

texts:
In an MMO, and I'm trying to collect data about user behaviors for the purpose of tweaking the game rules to achieve maximum user satisfaction.

Clearly one way to do it is to hand-roll specific things into an application, much like one might use Console.WriteLine() to view the contents of a variable, or the StopWatch() class to see how long something takes to execute.  But you can use a profiler in lieu of StopWatch, and you can use a debugger in lieu of WriteLine.

How should I collect my data? Are there generalized techniques for instrumenting an application to observe user behavior, or some form of code instrumentation technique?

Also, I'm only interested in collection techniques; you can assume that I already know how to transmit, store and analyze said data.


texts:
I write simple software renderer. In my pipeline I have stage of backface culling.

But looks like it has some error.

I perform culling right after world transformation (is it correct?).

Vector3F view_dir(0.0f, 0.0f, 1.0f);

std::vector<Triangle> to_remove;

for (Triangle &t : m_triangles)
{
    Vector4F e1 = t.v2 - t.v1;
    Vector4F e2 = t.v3 - t.v1;
    Vector3F normal(
        e1.y * e2.z - e1.z * e2.y,
        e1.z * e2.x - e1.x * e2.z,
        e1.x * e2.y - e1.y * e2.x
        );
    normal.Normalize();

    float dot = Dot(view_dir, normal);
    if (dot <= 0)
        to_remove.push_back(t);
}

for (Triangle& t : to_remove)
    m_triangles.erase(std::remove(m_triangles.begin(), m_triangles.end(), t), m_triangles.end());

Camera sits in origin and points in screen (RH).

What is the reason?

UPDATED: The error occurs only when triangle has non-zero offset from origin

UPDATED 2: If i process backface culling in clip space (after transforming all vertices with view and projection matrix), and just check z coordinate of triangle normal - it works perfect... Can i perform culing RIGHT BEFORE view/proj transforms? In this case looks like culling will not depends of projection and it's not right?


texts: Real-time 3D Scene-reconstruction into Physics Engine

texts:
I am trying to create a game where the user scans the room using RGBD camera and reconstructs 3D scene. This scene would be integrated into physics engine, after an object recognition algorithm tells it what objects are there in the scene and of what shape and size. Finally, after being rendered in Physics Engine, user should be able to interact with the environment.
I know how to do 3D scene reconstruction from images, I can figure out how to contruct objects and interact with them in Physics Engine. I know how to do object recognition, shape and size.
However, I am not sure how to integrate the output of 3D scene reconstruction, Object Recognition as input to the physics engine.
Any ideas would be helpful.


texts: How can you represent equip-able items in a 2d game?

texts:
I've been working on an item system for a post-apocalyptic RPG, with diablo as inspiration, and it would be awesome if I could visually represent an item that can be equipped on the player sprite. I was thinking you could have a player sprite with certain animations, then the equipped item would be drawn as if it was on the player with the same animations, so it syncs with the player animations but that couldn't work very smoothly, I imagine there's a better system.

How can you graphically represent an item worn on the player, which moves like he does, and looks as if he's wearing it? I'm not asking you how to do it in framework X or platform X (altho if you REALLY need it, I'm using Allegro 5 with codeblocks on win XP) but instead I'm asking you how to generally program such an idea.


texts: 3D vector graphics - maintaining correct Z 'length'

texts:
So I'm trying to build myself a 3D display 'engine', or whatever it ought to be called. I've been experimenting with PyGame, as it's familiar to me.

In a way this has almost been more an excuse to learn the math than to actually build a 'game engine' or anything like that, though ultimately that's why we're all programmers right? To code the next Super Mario Brothers. :) Anyway, this isn't that, it's a learning project, but unfortunately I seem to have hit a wall and I'm not entirely sure how to proceed or what to look for.

I'm unsure of how to move items smoothly on the Z-axis. 0 is the 'closest' a point gets to the screen, whereas N is the 'furthest' it could go. In the interest of (hopefully) keeping my math similar across calculations, I've set HEIGHT, WIDTH, and DEPTH all to an arbitrary value of 600.

It would appear that moving objects along the Z-axis is not quite the same as moving them along X and Y. Whereas X and Y are just addition and subtraction, Z is apparently only really effective as a percentage. Unfortunately I can't seem to find a method of incrementing Z in any way that doesn't stretch the shapes as if they're going into Warp when I move them closer to the horizon point. Likewise they squash nearly flat as they move closer to the screen.

I believe that the two most likely code candidates for weirdness are the following two snippets; one is the model's "move all the points" method, the other is a view method. Hopefully the code I'm not sharing is self-evident; Zpt is a class that contains x, y, z coordinates, and so on.

def move_pts_to_pt(self, newX=None, newY=None, newZ=None):
##This is how the model moves its points
    oldCtr = self.center
    if newX is not None:
        deltaX = newX - oldCtr.x
    else: deltaX = 0
    if newY is not None:
        deltaY = newY - oldCtr.y
    else: deltaY = 0
    if newZ is not None:
        deltaZ = newZ
    else: deltaZ = 1
    for zpt in self.zpts + [self.center]:
        zpt.x += deltaX
        zpt.y += deltaY
        zpt.z *= deltaZ

def zshape_draw(shapelist, objcolor=(255, 0, 0), objwidth=2):
##This is the view's drawing method for points with a z coordinate
    for shape in shapelist:
        drawnpoints = []
        for zpt in shape:
            z = zpt.z
            horzoff = z / DEPTH
            invhorz = 1.0 - horzoff

            newX = (zpt.x * invhorz) + (WIDTH * HOR_X * horzoff)
            newY = (zpt.y * invhorz) + (HEIGHT * HOR_Y * horzoff)
            drawnpoints.append((newX, newY))

        pygame.draw.polygon(SCREEN, objcolor, drawnpoints, objwidth)

I apologize if I've left any code out; I'm happy to re-edit my post. In any event, I cannot suss out what it is I need to do to prevent the z-values that are closest to the 'back' of the screen from increasing much faster than those closer to the screen, while still maintaining their intended 'shape' -- that is, generally looking like they aren't changing in depth as they move from z=0 to z=600 (or, whatever ends up being 100% 'away' from the screen).


texts: Finding the endpoint of a named bone in Irrlicht

texts:
I'm making a tank game that will have multiple tanks.  I want to be able to define the weapon placements using bones that I can add right inside the modelling program (Blender to be exact).

All tanks will have a bone called Body and a bone called Turret, and then names like Cannon0 and PickupGun for where the shots will be fired from that are attached to the Turret bone.  Is there some way to find the absolute end position of a bone that I choose by name?


texts: Should a system be able to render things? (ECS)

texts:
I'm currently building an entity component system and I just have one question... Should a system be allowed to render things to the screen?

For example, should I make a SpriteComponent that contains a Sprite, and then create a SpriteRenderSystem that renders the sprite to the screen? Or should rendering entities be managed by something else entirely?

The reason I ask is because I've read in many forums that allowing a system to render is a bad idea. But I just don't understand why this is; If game objects in my game are represented using the ECS, how else would I go about rendering objects to the screen?