texts: How to change Vectors due to change in it's dependent Base Vector?

texts:
PLOT :

I have been developing a game where the player falls down on Y axis and the camera is a Top-Down view camera. The camera, player (main character in the game) movements etc. have all been implemented based off the idea/notion that the player is falling down Y axis. Hence I used to feed in the vectors based of it. The player is always acted upon gravity.

DESIGN CHANGE :

Now after all these months of developing it, I am changing the design. Now the player who was falling down, upon reaching the ground is going to take off and fly parallel to the ground

PROBLEM :

As I am changing the entire scenario, it creates a complication with vectors I used to feed in for the camera and player. Also due the constraint that the experience should be exactly similar to that off the "falling towards the ground" I have to change the gravity accordingly. Now how do I accomplish this when I have vectors all over the place based off the top down view. Please forgive if I am confusing you here. Give me a min.

To break it into the most primitive segment - I input Vector A, B etc to the camera and the player when the gravity is (0,-1,0). Now if I change the gravity to (1,0,0), how should I change the Vector A, B etc. Is there a way to formulate the Vectors A, B etc when I know the gravity has been shifted from (0,-1, 0) to (1,0,0). All the vectors are normalized. If you ask me the relationship of Vector A, B etc with the gravity (0,-1,0) - I have to say there is no relationship. As it was a game, I supplied the Vectors on how I need the Player and Camera's to work.

CODE :

    // The required Force applied in Flap mode
    void ForceToBeApplied()
    {
            //HORIZONTAL FORCE
            if(!HNEXT)
            {
                    rigidbody.AddRelativeForce((Vector3.right) * DeltaTime * LeftDrag * 3);
                    if(LeftDrag < 400)
                            LeftDrag += ToTarget(DefaultDrag,TurnSine);
                    rigidbody.AddForce(2,(-LeftDrag/50),0);
            }

            if(HNEXT)
            {
                    rigidbody.AddRelativeForce((-Vector3.right) * DeltaTime * RightDrag * 3);
                    if(RightDrag < 400)
                            RightDrag += ToTarget(DefaultDrag, TurnSine);
                    rigidbody.AddForce(-2,(-RightDrag/50),0);
            }

            //VERTICAL FORCE
            if(!VNEXT)
            {
                    rigidbody.AddRelativeForce((Vector3.forward) * DeltaTime * UpDrag * 3);
                    if(UpDrag < 400)
                            UpDrag += ToTarget(DefaultDrag,TurnSine);
                    rigidbody.AddForce(0, (-UpDrag/50),-2);
            }
            if(VNEXT)
            {
                    rigidbody.AddRelativeForce((-Vector3.forward) * DeltaTime * DownDrag * 3);
                    if(DownDrag < 400)
                            DownDrag += ToTarget(DefaultDrag, TurnSine);
                    rigidbody.AddForce(0,(-DownDrag/50),2);
            }
    }

IF you happen to look into the above module, I add force to the rigidbody. Those forces were added when the gravity was (0,-1,0). Now if I change my gravity to (say) (1,0,0), how should I change the forces applied to the rigidbody.

TYPE OF APPROACH I THINK :
What if I could create a static class which could take those vectors and convert them to equivalent vectors for the current gravitational force.

Simple Diagrammatic Expression of The Problem :

I hope I am clear in the problem I am facing.

Thank you..


texts: Cannot implicitly convert type object[] to UnityEngine.GameObject[]

texts:
So, I cannot implicitly convert type object[] to UnityEngine.GameObject[]. But why? As far I know, are all types a inheritanced types of object. So, for my logic, I could put a GameObject array in a object array. That's why, this should work:

spawnedObjects = FindObjectOfType<Tools> ().AddObjectToArray (spawnedObjects, go);

//

public object[] AddObjectToArray(object[] _array, object _toAdd){
    if (_array.GetType() == _toAdd.GetType()) {
        object[] a = new object[_array.Length + 1];
        a = _array;
        a [a.Length] = _toAdd;
        return a;
    } else {
        Debug.LogWarning ("The object that should be added to the array have to be the same type as the arrays type. Initially array was retuned!");
        return _array;
    }
}

But yeah, it won't do


texts:
I'm trying to implement a GLSL shader which helps understanding special relativity Lorentz Transformation.

Let's take two axis-aligned inertial observer  O and O' . The observer O' is in motion w.r.t observer O with velocity v=(v_x,0,0).

When described in terms of O' coordinates, an event P' = (x',y',z',ct') has transformed coordinates (x,y,z,ct)= L (x',y',z',ct')

where L is a 4x4 matrix called Lorentz transformation which helps us writing the coordinates of event P' in O coordinates.

(for details look http://en.wikipedia.org/wiki/Lorentz_transformation#Boost_in_the_x-direction)

I've wrote down a first preliminary vertex shader that apply the Lorentz transformation given the velocity to every vertex, but I can't get the transformation to work correctly.

vec3 beta= vec3(0.5,0.0,0.0);
float b2 = (beta.x*beta.x + beta.y*beta.y + beta.z*beta.z )+1E-12;
float g=1.0/(sqrt(abs(1.0-b2))+1E-12); // Lorentz factor (boost)
float q=(g-1.0)/b2;

//http://en.wikipedia.org/wiki/Lorentz_transformation#Matrix_forms
vec3 tmpVertex = (gl_ModelViewMatrix*gl_Vertex).xyz;
float w = gl_Vertex.w;

mat4  lorentzTransformation =
        mat4(
            1.0+beta.x*beta.x*q ,   beta.x*beta.y*q ,   beta.x*beta.z*q , beta.x*g ,
            beta.y*beta.x*q , 1.0+beta.y*beta.y*q ,   beta.y*beta.z*q , beta.y*g ,
            beta.z*beta.x*q ,   beta.z*beta.y*q , 1.0+beta.z*beta.z*q , beta.z*g ,
            beta.x*g , beta.y*g , beta.z*g , g
            );
vec4 vertex2 = (lorentzTransformation)*vec4(tmpVertex,1.0);

gl_Position = gl_ProjectionMatrix*(vec4(vertex2.xyz,1.0) );

This shader should apply to every vertex and perform the non-linear Lorentz transformation, but the transformation it performs is clearly different from what I'd expect (in this case a length-contraction on x-axis).

Has somebody already worked on special relativity shader for 3D videogame?


texts:
I would like to have more higher poly sphere than in Unity standard sphere.

I have made sphere in Blender, set smooth and imported in Unity as fbx.

Now, I have problem that for every face there is a black border showed. It doesn't look very nice. How to fix that ?


texts: Changing one prefab changes all other instances of that prefab too

texts:
I have made two prefabs of my enemies for my 2D game: normal and damaged. The I put several of these prefabs on scene. When enemies health <=0 I need to destroy its GameObject and then instantiate a damaged prefab on its position. But when I am doing this, all other prefabs are destroying too and damaged prefabs are instantiated on their positions. After searching this site I found out that any changes with one prefab are applying to all other prefabs on scene? Is this right?

P.S. I have edited the script where I am destroying prefab and added to it a simple check, if the prefabs renderer is visible on scene, then I need to destroy it, because all other prefabs are not visible at this moment. Do I need to check to make sure that this is the instance of the prefab is that I need every time when I want to apply to it some change?


texts: Will this method of hashing player positions be effective in defeating FPS wall-hacks?

texts:
For example using a class like below to Hold the player positions and only show the players to each other when their Distance is less than something, So the calculations are also used by the client's PC.

public struct SafeFloat {
private float offset;
private float value;

public SafeFloat (float value = 0) {
    offset = Random.Range(-1000, +1000);
    this.value = value + offset;
}

public float GetValue ()
{
    return value - offset;
}

public void Dispose ()
{
    offset = 0;
    value = 0;
}

public override string ToString()
{
    return GetValue().ToString();
}

public static SafeFloat operator +(SafeFloat f1, SafeFloat f2) {
    return new SafeFloat(f1.GetValue() + f2.GetValue());
}
// ...the same for the other operators
}


texts: Networking gampeplay - Sending controller inputs vs. sending game actions

texts:
I'm reading about techniques for implementing game networking.

Some of the resources i've read state that it is a common practice (at least for some games) to send the actual controller input across the network, to be fed into the remote game's loop for processing.

This seems a bit odd to me and i'd like to know what are the benefits of using such a method?

To me, it seems that controller input is merely a way to gather data to be fed into the game, which in turn determines how to translate these into specific game actions.

Why would i want to send the control data and not the game actions themselves?


texts:
I developed a small xna games.
For some time I have a problem with the saturation of RAM. In fact everything works perfectly, the game runs with a "Frame" of 60fps. But strangely I do not know for what reason my games every 4 seconds freeze half a second.

Yet my average call time of the "Update" function is approximately 7 ms (which is supposed to be good ..)

Here is a screen capture of the Task Manager. I can see the ram flush periodically.

Have you any idea why the ram saturates at only 50%?


texts: Blurring point light variance shadow map

texts: I've been working on implementing variance shadow mapping for my game.  I was able to get a spot light working with variance shadow mapping with a gaussian blur applied to the shadow map to reduce the aliasing.  Now I'm trying to implement point lights but I'm not sure how to adapt the gaussian blur to work with the the shadow map when its stored in a cube map.  I've searched around for a while but I can't seem to find any examples that use point lights.  Can anyone help me out here?


texts:
I have implemented a collision and response system based on the famous "Improved Collision detection and Response" paper. However I'm having an issue with objects sliding backwards on slopes. I believe I could circumvent this issue if I understood how to find the angle of the plane of which my object is colliding with. Take the below screenshot as an example of the situation:

I know the following data:

Position of player object (the ellipsoid at the bottom of the ramp)
Vertices of the collision triangle
Normal of the collision triangle
Intersection point between player object and collision triangle
Penetration distance between player object and collision triangle

How can I use this information to determine the angle of the collision triangle?


texts: Does anyone know of a pseudo 3D track editor ? I now need one to design my stages, as manually trying to create segments, and position static and movable objects would be too time consuming.


texts:
I am trying to understand how to implement and combine steering vectors for autonomous agents as described by Craig Reynolds.

My understanding is that each steering force should be calculated separately and then all of the steering forces should be added together and then applied.

I understand that each steering force is equal to the desired velocity for a particular behavior, minus the agent's current velocity.

I am trying to combine two basic behaviors: Seek and Flee. Below are two diagrams to illustrate my issue.

I have an agent that is Seeking a target directly ahead of it, and fleeing from a target below it. When the target is at rest (current velocity = 0), the steering forces for each behavior are equal to their respective desired velocities:

vSteer = vDesired - currentVelocity = vDesired - 0 = vDesired

And the combined steering force points up and to the right, in blue. This is roughly what I would expect.

However, if the agent is moving, we get a completely different result. For the sake of simplicity, say the agent is already moving at top speed in the direction of the target. So the agent's current velocity is equal to its desired seek velocity.

When the agent's current velocity is equal to the desired seek velocity, then the seek steering force is 0 (vSteer = current - desired = desired - desired = 0). The flee steering force then is equal to the desired flee velocity minus the current velocity, which produces a vector that points BACKWARD! And since the seek steering force is zero, the total steering force equals the flee steering force.

I noticed this issue while trying to implement a separation force, which is essentially the situation illustrated in the diagrams but with the red X representing a neighboring agent. The net effect is that agents maintain separation, but move at about half speed, with a seek steering force pointing forward, a flee steering force pointing backward and away from the neighbor, that largely end up cancelling each other out.

It really doesn't seem like any component of the flee force should be pointing backwards here. What am I misunderstanding?


texts: Updating entities in response to collisions - should this be in the collision-detection class or in the entity-updater class?

texts:
In a game I'm working on, there's a class responsible for collision detection. It's method detectCollisions(List<Entity> entities) is called from the main gameloop.

The code to update the entities (i.e. where the entities 'act': update their positions, invoke AI, etc) is in a different class, in the method updateEntities(List<Entity> entities). Also called from the gameloop, after the collision detection.

When there's a collision between two entities, usually something needs to be done. For example, zero the velocity of both entities in the collision, or kill one of the entities.

It would be easy to have this code in the CollisionDetector class. E.g. in psuedocode:

for(Entity entityA in entities){
    for(Entity entityB in entities){
        if(collision(entityA, entityB)){
            if(entityA instanceof Robot && entityB instanceof Robot){
                entityA.setVelocity(0,0);
                entityB.setVelocity(0,0);
            }
            if(entityA instanceof Missile || entityB instanceof Missile){
                entityA.die();
                entityB.die();
            }
        }
    }
}

However, I'm not sure if updating the state of entities in response to collision should be the job of CollisionDetector. Maybe it should be the job of EntityUpdater, which runs after the collision detection in the gameloop.

Is it okay to have the code responding to collisions in the collision detection system? Or should the collision detection class only detect collisions, report them to some other class and have that class affect the state of the entities?


texts: Using logic gates for Sprite Collision Detection - humor an old fart please

texts:
Im an old coder who came back so to speak, learning Java I know what I want but I cannot find anyone asking it anywhere so here goes...

Im writing a basic tank game to code for practice but as is always the case my personal ambitions out pace my abilities.

Ive been reading up on the various methods used for collision detection using rectangles and point testing around the sprite for collisions but it all seems a little hap hazard and processor heavy to me.

I was thinking maybe a method would work by which I could logically compare two sprites -

So maybe I have a tank(me) and I come to a tile which is meant to be wall. OK so I can compare the square from an array and look up what type of tile is there and prevent movement in that direction, but again Im not happy with this because its not accurate enough. I mean what happens if I want that wall shootable, where it goes through several stages of destruction before its turned into a fully traversable square, it may have a few bits un-destroyed and I want to be able to detect even this.

So how about if I created a tank mask, black and white and grab the square the tank is entering and logically AND it with the tank sprite, creating zero unless a pixel appears in both locations, in which case it hit something.

Is this clear enough?

Do you think this would work and which coding direction do you recommend, Im still new to the syntax but as you can see I know what I want....I think!


texts: Performance problems with quadtree for dynamic objects

texts:
I´ve implemented a quadtree spatial partitioning to my game engine as I wanted to try it and see how it affects the performance checks. The results were great (instead of hundreds collision checks only for cursor I was suddenly having just about 10%), however I faced performance problems (not caused by the number of collision checks but by the spatial structure itself [or my implementation]) :

1. At first I was inserting items every frame and at the end of the frame the quadtree was cleared and so on. I realised this slowed down the performance more than 2-3 times.

2. Of cource the next step was to try to make the quadtree dynamic by not clearing it but by checking the moving objects from the quadtree. However this process is also not trivial as I can have a multiple nodes containing the same object (if it doesnt fit to any of the children I "broadcast" and check neighbour nodes so it can be visible in more than 1 node) and I ended up by digging through the entire quadtree again.

How did you solve these problems with the quadtrees? I´ve read that some of the engines use multiple spatial structures to divide work for static/dynamic objects, I would use quadtree for static structure but what would be suitable for dynamic? Also I think I "hurt" myself when I want to make as generic solution as possible so I dont have to change the spatial structures of my game engine no matter what type of game I´m creating with it at the time.


texts:
Unity3d: I know exist OnApplicationQuit called before the application is ended.

But, does exists an event that is called before a new scene is loaded ?

Thanks


texts: Best practice to define fields scope in C# script of Unity in regard to serialization?

texts:
I know from Object Oriented Design perspective that in order to provide encapsulation, we should avoid defining public variables in a class as much as we can and instead access them through public methods.

Currently, I working on a Unity project code base which defines most of the fields as public because It needs having to access them in Inspector tab of Unity. Was it better to defined fields as private and just added [SerializableField] attribute? Is there any drawback with doing so? I was wondering if there are any best practices for defining the scope of fields in the driven Unity classes?

private fields:

public class SampleClass: MonoBehaviour
{

    [SerializeField]
    private Field sampleField;
}

public fields:

public class SampleClass: MonoBehaviour
{

    public Field sampleField;
}


texts: Thread per connection or thread-pool in a MMO server?

texts:
So I'm writing this MMO server, and I'm really struggling in this topic. I'm writing a fast paced MMO, and the server max players would be 800.

I have read that one thread per connection is not a good idea, and also that thread-pooling is not ideal in some cases.

I think 800 threads listing for client message is bit to much. In my case, which approach is better?


texts:
Game Engine: Gamemaker Studio

Situation: I want 6 rows of 6 objects, each housed in a cell of a 6x6 matrix. However, this presents the problem of the matrix knowing what's in the cell, but the object in the cell doesn't know where in the matrix it is.

Reason why this is a problem is because I want to have events in the housed object's events that check adjacency to other objects in the matrix.

Question: How do I let the an object know where in a matrix it is?

Do I just need to have 2 variables in the object, which is set to the object's position in the matrix, or is there an easier way to do this? Or a better way, I guess.

Or perhaps the question is, is there a better way than the way I am doing?

How I'm using it Right Now:

//check if the last link in the chain is adjacent to the target link

     //includes diagonals
     if(obj_Handle_Links.Last_Link.Matrix_Location_y = (Matrix_Location_y-1)
     || obj_Handle_Links.Last_Link.Matrix_Location_y = (Matrix_Location_y+1)
     || obj_Handle_Links.Last_Link.Matrix_Location_x = (Matrix_Location_x-1)
     || obj_Handle_Links.Last_Link.Matrix_Location_x = (Matrix_Location_x+1))
    {
        obj_Handle_Links.Match_Length +=1; //because we're increasing the length
        image_index = 1; //this should highlight
        //add to link - implement later
        obj_Handle_Links.Last_Link = id; //makes it so this is what's seen as last link
    }


texts: What is the view perspective angle of most 2.5D isometric games

texts:
I examined several quite popular games to determine what perspective angle they are using. For the purpose I created a grid that is 45 and 60 degrees isometric viewed and put it onto a screenshot (of Diablo II in this case). None of these grids fit to the game's perspective. So I tried to find the angle that fits best to the perspective and it is close to 53.5 degrees. However, this number seems like coming from nowhere and I believe there is a strong logic behind the number that defines the perspective angle. I tried 9/16 * 90 degrees and 3/4 * 90 degrees (coming from ratios of screens resolution 16:9 and 4:3) but none of my assumptions seem to be correct. Here are screenshots of what I mean:

60 degrees

45 degrees

Something between the two - 53.5 degrees - quite near to the real number

I really need to know what the real degrees are and where it derives from. Any help is quite appreciated! Thank you!


texts: How would I setup the Environment Variables for BulletPhysics?

texts:
I am using Bullet Physics v2.78. And Im trying to build this library to be used for ogrebullet. The main problem is that Im getting errors trying to find the Bullet Directory.

Im wondering if maybe my environment variables are setup wrong.

I am using Windows Vista 32 bit, and here are my Environment variables:

BULLET_ROOT: C:\BulletPhys

BULLET_INCLUDE_DIR: C:\BulletPhys\src

as other information I am trying to build these libraries in cMake. Bullet physics builds perfectly, but ogrebullet cant find the libraries needed to configure(Dynamics, Collision, LinearMath, etc.)

So my question is: How would I setup the environment variables so ogrebullet can find them?

If any other information is needed i will provide upon request.

Thanks

-Molma


texts:
So, I've heard of the delete keyword, which clears variables that use the new or new[] keywords.

I have a class called Box, which I made a object of in my main.cpp.

What if I want to clear a variables memory in my Box object, from my main.cpp?

I've tried adding the new keyword to the variables, but the variable types has no default constructor so I can't use it on them :

b2Body* body = new b2Body;

Is there any way to clear the memory of a variable that looks like this :

b2Body* body = nullptr;

(note that when I want to clear it, it has assigned a value to it.)

Example :
In minecraft when an item is dropped on the ground, and it disappears after some time, I'm guessing it's texture variables, animations, stats etc is not saved?

This is what I want to do.

I want to remove the memory of a variable I no longer need to use.


texts: p2.js physics engine behavior on Heightfield

texts:
I am writing a small game consisting of a 'ragdoll' character riding a skateboard.

I have created a 'skateboard park' with some ramps and a jump.

I am using a 'heightfield' object as the ground.  What I notice is that the behavior of the wheels rolling up and down slopes on one side are entirely different that slopes on the other side.. even though the slopes are symmetrical.

Does anyone know why it behaves like this?

Here is a codepen to illustrate the problem. http://codepen.io/smatthews1999/pen/uGmaE

and here is an image to explain clearly what the issue is.


texts:
I have firmly decided to be in the games industry. However, I have really hard time choosing a bachelor program because I can't understand what's the difference between games technology and games development. I've checked the unis prospectus and I find the two programs pretty much similar.

What is the difference between games technology and games development?


texts: Love2D : Problem rotating image in a SpriteBatch

texts:
I'm working on a falling blocks type of game with triangular pieces. I'm using a SpriteBatch to accumulate and remember the pieces and their locations.

The problem is that when I rotate a scaled Image of the triangle, I get unexpected results, that is the origin of the sprite rotation is wrong -- but if I rotate a full-size image (no scaling) it works fine. The sprite should rotate from the center of the image (x + xScale * imgWidth / 2) and (y + yScale * imgWidth / 2). When xScale and yScale == 1, everything is fine. But as soon as it scales down to a fraction of the original size, the origin seemingly freaks out to weird sizes. Here's some code to inspect:

function love.load()
    img = love.graphics.newImage("triangle.png")
    sb = love.graphics.newSpriteBatch(img, 1024)
    imgWidth = img:getWidth()
    imgHeight = img:getHeight()
    x = 250
    y = 250
    xScale = 0.4
    yScale = 0.4
    xOrig = (xScale * imgWidth / 2)
    yOrig = (yScale * imgHeight / 2)
    angleDirection = 0
    id = sb:add(x, y, math.rad(angleDirection), xScale, yScale, xOrig, yOrig, 0, 0)
end

function love.update(dt)
    if love.keyboard.isDown(" ") then
        angleDirection = angleDirection + 180
        if angleDirection >= 360 then
            angleDirection = 0
        end
    end
    sb:set(id, x, y, math.rad(angleDirection), xScale, yScale, xOrig, yOrig, 0, 0)
end

function love.draw()
    love.graphics.draw(sb)
end

Now, to see the problem in action, run the preceding code. Change the xScale and yScale to a 1 to see the rotation work properly. Thanks in advance for any suggestions you have.


texts: Back face as pure black with LWRP - Unity

texts:
I need to use LWRP in my current project, and I was looking for a way to render the back face as pure black, no lights, no shadows, nothing, just pure black while the normal face would should the textures and the maps.

I know how to do it using the regular shaders, but it is possible to do using the LWRP shaders?


texts: What is the standard technique for shifting the frames of a sprite according to user input?

texts:
From my own experience, I developed two techniques for changing the sprites of a character that's reacting to user input -- this in the context of a classic 2D platformer.

The first one is to store all character's pixmaps in a list, putting the index of the currently used pixmap in an ordinary variable. This way, every time the player presses a key -- say the right arrow for moving the character forward -- the graphics engine sees what's the next pixmap to draw, draws it, and increments the index counter. That's a pretty common approach I believe, the problem is that in this case the animation's quality depends not only on the number of sprites available but also on how often your engine listens to user input.

The second technique is to actually play an animation every key press event. For this you can use any sort of animation framework you want. It's only necessary to set the timer, the animation steps and to call the animation's play() method on your key press event handler. The problem with that approach is that is lacks responsiveness, since the character won't react to any input while the current animation is still being played.

What I want to know is whether you are using one of these techniques -- or something similar -- in your games, or whether there's a standard method for animating sprites out there that's widely known by everybody but me.


texts: Using multiple bone rigged objects for character animations (Unity2D 8 directions isometric movement)

texts: my partner made the animations for our character in a 2d isometric game built with unity. He made 5 bone rigged bodies (each made of several sprites) and each has its own animator. He then made 1 animation for each body (N, NE, E, SE, S) and mirrored 3 of them (NE, E, SE) to make the missing ones. We have 8 animations for Idle and 8 for moving, one for each direction. How can i link animations from different animators on player movement input (checking for vertical/horizontal input)? Any help would be really appreciated. The bodies have been rigged on unity but im thinking of getting Spine2D, would it be more helpfull to make an 8 way isometric 2d character animation to implement in unity? Making this with spritesheets was really easy but with the different rigged bodies im kinda in the blue here... cheers!


texts: Directx D3D9 fails to render a primitive on a RenderTarget surface

texts:
So for some reason DrawPrimitive() doesn't seem to work with my render target surface.

// The current target, we must set it back as target afterwards
IDirect3DSurface9* temp_target;
device->GetRenderTarget( 0, &temp_target );

// Craete the surface
IDirect3DSurface9* surf;
surf = NULL;
device->CreateRenderTarget( group->width, group->height, group->format, D3DMULTISAMPLE_NONE, 1, false, &surf, NULL );
device->SetRenderTarget( 0, surf );

device->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_ARGB( 255, 0, 255, 0 ), 1.0f, 0 );

sprite->Draw( device, 0, 0, 0 );

// Save the current surface
IDirect3DSurface9* tex_surf = NULL;
texpage->GetSurfaceLevel( 0, &tex_surf );

device->StretchRect( surf, NULL, tex_surf, NULL, D3DTEXF_NONE );

group->texpages->push_back( texpage );

// Set the render target back to what it was previously

device->SetRenderTarget( 0, temp_target );

And the sprite draw:

void StreamSprite::Draw( LPDIRECT3DDEVICE9 device, float x, float y, int subimg) {
    D3DCOLOR colour = D3DCOLOR_ARGB( 255, 255, 255, 255 );
    VERT* vertices;
    RECT rect;
    rect.left = ( long ) x;
    rect.right = ( long ) x + width;
    rect.top = ( long ) y;
    rect.bottom = ( long ) y + height;

    float u1 = ( subimg / img_count );
    float u2 = ( ( subimg + 1 ) / img_count );

    device->SetFVF( D3DFVF_TLVERTEX );

    device->SetStreamSource( 0, buf, 0, sizeof( VERT ) );

    //Lock the vertex buffer
    buf->Lock( 0, 0, ( void** ) &vertices, NULL );

    //Setup vertices
    //A -0.5f modifier is applied to vertex coordinates to match texture
    //and screen coords. Some drivers may compensate for this
    //automatically, but on others texture alignment errors are introduced
    //More information on this can be found in the Direct3D 9 documentation

    vertices[ 0 ].color = colour;
    vertices[ 0 ].x = ( float ) rect.left - 0.5f;
    vertices[ 0 ].y = ( float ) rect.top - 0.5f;
    vertices[ 0 ].z = 0.0f;
    vertices[ 0 ].u = u1;
    vertices[ 0 ].v = 0.0f;

    vertices[ 1 ].color = colour;
    vertices[ 1 ].x = ( float ) rect.right - 0.5f;
    vertices[ 1 ].y = ( float ) rect.top - 0.5f;
    vertices[ 1 ].z = 0.0f;
    vertices[ 1 ].u = u2;
    vertices[ 1 ].v = 0.0f;

    vertices[ 2 ].color = colour;
    vertices[ 2 ].x = ( float ) rect.right - 0.5f;
    vertices[ 2 ].y = ( float ) rect.bottom - 0.5f;
    vertices[ 2 ].z = 0.0f;
    vertices[ 2 ].u = u2;
    vertices[ 2 ].v = 1.0f;

    vertices[ 3 ].color = colour;
    vertices[ 3 ].x = ( float ) rect.left - 0.5f;
    vertices[ 3 ].y = ( float ) rect.bottom - 0.5f;
    vertices[ 3 ].z = 0.0f;
    vertices[ 3 ].u = u1;
    vertices[ 3 ].v = 1.0f;

    //Unlock the vertex buffer
    buf->Unlock();

    //Set texture
    FAILED( device->SetTexture( 0, texture ) );

    //Draw image
    device->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, 2 );
}

I cut out a few pieces that shouldn't be necessary.

I've also made sure that all functions work properly (don't return an error), I've debugged them all. no errors. It's probably me having some option not set properly somewhere.


texts: How do I lerp between values that loop (such as hue or rotation)?

texts:
View Demo

I'm trying to make the joint rotate smoothly around the center of the canvas, toward the angle of mouse pointer. What I have works, but I want it to animate the shortest distance possible to get to the mouse angle. The problem occurs when the value loops around at the horizontal line (3.14 and -3.14). Mouseover that area to see how the direction switches and it takes the long way back around.

Relevant Code

// ease the current angle to the target angle
joint.angle += ( joint.targetAngle - joint.angle ) * 0.1;

// get angle from joint to mouse
var dx = e.clientX - joint.x,
    dy = e.clientY - joint.y;
joint.targetAngle = Math.atan2( dy, dx );

How can I make it rotate the shortest distance, even "across the gap"?


texts:
I'm currently learning Unity and working my way through a video game maths primer text book.

My goal is to create a racing game for WebGL (using Three.js and maybe Physic.js).

I'm well aware that the Unity program shields you from a lot of what's going on and a lot of the grunt work attached to developing even a simple video game, but if I power through a bunch of Unity tutorials, will a lot of the skills I learn translate over to other frameworks/engines?

I'm pretty proficient at level design with WebGL, and I'm a good 3D modeller. My weaknesses are definitely AI and Physics.

While I am rapidly shoring up my math, and while
Physics is undeniably interesting there's only so many hours in the day and there's a wealth of engines out there to take care of this sort of thing.

AI does appeal to me a lot more, and is a lot more necessary. AI changes drastically from game to game, is tweaked heavily during development, and the physics is a lot more constant.

Will leaning AI concepts in Unity allow me to transfer this knowledge pretty much anywhere? Or will I just be paddling up Unity creek with these skills?


texts: How do I create inertia when my character turns around?

texts:
I've been trying to give my character some inertia when it turns in the opposite direction, but for some reason my acceleration variable only seems to apply itself when my horizontal velocity is 0. For example, if my character is standing still, and my horizontal acceleration is set to 0.5 seconds, it takes my character 0.5s to reach its maximum velocity. However if I reach this velocity and then begin to turn around, the transition is much faster. This doesn’t make sense to me because it should take less time to go from 0 to 10 than it does to go from 10 to -10.

It is very easy to see this difference in my game, as even if I change my acceleration to 3s, once I reach my maximum velocity I can turn around almost instantly. I'm using the smoothdamp function, and have tried a few other methods than the one in the code below, one of which distinguished between two distinct velocity smoothing variables. I felt that this created a better feeling of drag, but could result in jerky movement depending on input.

Should I be using smoothdamp for this kind of movement, or is there a more effective solution? Ideally I'd like to have this drag increase or decrease according to my current velocity.

private void FixedUpdate ()
{
    HandleInput();
}

private void SetHorizontalForce(float x)
{
    if (directionalInput.x != 0)
    {
        velocity.x = Mathf.SmoothDamp(velocity.x, x, ref velocityXSmoothing,
                (State.IsCollidingBelow) ? Parameters.accelerationTimeGrounded : Parameters.accelerationTimeAirborne);
    }

    else if (directionalInput.x == 0) //Prevents the character from 'sliding' if suddenly moving left and right at low velocities
    {
            velocity.x = Mathf.SmoothDamp(velocity.x, 0, ref velocityXSmoothing, Parameters.stopTime);
    }
}

private void HandleInput()
{
    directionalInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));

    if (!Controller2D.State.IsClimbingLadder && !Controller2D.State.ClampLadderMovement)
    {
        SetHorizontalForce(directionalInput.x * stats.movementSpeed);
    }
}


texts: Should I link GLFW and GLEW into my engine directly?

texts:
I want to write my own (simple) game engine with OpenGL.
I use GLEW and GLFW and so far linked it successfully.

Should the engine or the respective game (which depends on the engine) include GLFW and GLEW?

Ultimately I would like to create a library out off my engine and include it into my game, but I'm not quite sure if that is possible, if its the case, that the engine should depend on GLFW and GLEW. Would I have to link all the libraries that are neccessary for GLEW and GLFW into the game plus the engine-lib itself?


texts:
I have a unity web browser game. Since I'm working on a small company with limited machines which are all of either 2GB RAM or 4 GB RAM with decent processors. I'd like to know if there are any web based or software 'solutions' to test the game with low configuration both hardware and network bandwidth.

And, I have tried cross-browser testing solutions, But I didn't see any solution with the option of testing a browser game made for the unity web player .


texts: I was looking at game engines and found Unreal Engine. I want to make a game where the player has to create a camera by crafting it and can customize how many pixels the camera detects and what the camera detects (Ex: Sound, light, energy, etc). How could I do this?


texts: Astar heuristics closing in on an answer before searching around to find nodes with lower movement costs

texts:
I am having some trouble with my A* path finding. everything works fine and the path is always found. However, my game is a open map space strategy game. There are no walls etc to navigate around. Now, the movement cost along the navgrid is the same unless the agent chooses to navigate thro a 'jump gate' (in which case the cost is 100 times cheaper. almost always the better option).

I have a problem where the heuristics will narrow in directly towards the answer rather than searching around for a better solution. If my heuristics function always returns 0, then I always get the correct route, however with no heuristics I need to search the entire map and this makes it far too slow.

As you can see, the top agent ignores the jump gate and flies directly towards the destination, completely ignoring the gate way. The bottom agent opts to use the gate way (only because its heuristics was causing it to search in a north-west pattern anyway.

What are some possible solutions?


texts:
I have a simple camera class which works for following my character around, and has an adjustable zoom.  However, I cannot figure out how to keep the camera within the bounds of the world.  As far as I know, I can't just pull the X and Y coordinates of the Transform, so I don't know how to check if it is out of bounds.  Help greatly appreciated.

using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Game10
{
class Camera
{
    protected float _zoom;
    public Matrix Transform { get; private set; }

    public Camera()
    {
        _zoom = 1f;
    }

    public void DecreaseZoom()
    {
        if (Input.IsZoomDecrease())
           {
                _zoom -= 0.25f;
                if (_zoom < 0.25f
                {
                    _zoom = 0.25f;
                }
           }
    }

    public void IncreaseZoom()
    {
        if (Input.IsZoomIncrease())
           {
                _zoom += 0.25f;
           }
                if (_zoom > 4f
                {
                    _zoom = 4f;
                }
    }

    public void Follow(Player target)
    {
        var position = Matrix.CreateTranslation(
            -target.Position.X - (target.Bounds.Width / 2),
            -target.Position.Y - (target.Bounds.Height / 2),
            0);

        var offset = Matrix.CreateTranslation(
            Platformer.ScreenWidth / _zoom / 2,
            Platformer.ScreenHeight / _zoom / 2,
            0);

        var zoom = Matrix.CreateScale(_zoom, _zoom, 1);

        Transform = position * offset * zoom;

    }

}
}


texts: The tolareable lag range in a multiplayer game

texts:
I am programming a multiplayer game. I calculate the ping in ms as :

ping = the_time_i_recieved_pong - the_time_i_sent_ping

I implemented client-side prediction and interpolation algorithms. When I test the game with my friends, it works quite fine for those who have a ping under 100ms, but after 120ms it becomes unplayable as they have told me. So my question is wheter I should try to improve the client's game experience under a latency more than 120 ms or not ( is a lag >120ms considered tolerable ? )

Thank you all !

NOTE : My game is a fast-paced game so the lag compensation matters.


texts: Should I use select() for networking in my gameloop?

texts:
I'm writing a simple networked game in C/C++. To keep things simple I'm using TCP.

In my server's game loop I'm using a POSIX select() with a zero second timeout for two things:

Discover incoming data from connected clients
Discover new incoming connections

Is this a reasonable way to do it? Instead of using select() I could just loop through all connected socket descriptors and call recv() (or something like it) for each, to see if there is any new data. Would that be better?

The same question goes for the client. Note that on the client there's only one socket descriptor. Should I here use select() and a zero second timeout to find out if there's any new data incoming, or should I just call recv() on each game tick?

Or perhaps it would be even better if I pushed networking to a separate thread?


texts: Make Unity Text Area to act like a logger

texts:
I'm trying to create a text area in Unity using UI.Text that contains multi-line text which should act like a log view, i.e the text area Vertical Overflow is set to Truncate and a new line of text is added to the text property every now and then but instead of the text being eventually cut of at the bottom when the text area is full I want the text to 'scroll' up so that the newest added line is always the last displayed at the bottom of the text area, e.g.

  Line 1
  Line 2
+------------------------------------------+
| Line 3                                   |
| Line 4                                   |
| Line 5                                   |
| Line 6                                   |
| Line 7                                   |
| Line 8                                   |
+------------------------------------------+

... When Line 7 is logged Line 1 goes out of the text area at the top, when Line 8 is logged, Line 2 goes out, etc. Can this be done with UI.Text?


texts: How do I render light propagation volume without aliasing?

texts:
I have two major problems in my LPV implementation:

The "blockyness" of my LPV light rendering (yes am using trilinear interpolation when sampling for the coefficients)
The flickering that happens as I rotate the camera (see this question )

Is see on the internet people do manage to get very smooth lighting and almost zero flickering across a surface, don't see how that's possible given how coarse the LPV (32x32x32 in my case) is..

Here is one with trilinear sampling, you can see it aliasing, specially in the slanted wall in the background:

Here is one with GL_NEAREST, this I use to tell me which pixels are falling on which LPV boxes.  The coarseness of the LPV is obvious, I can't comprehend how you reconstruct smooth lighting from this.


texts: How to achieve light that changes color mid-way?

texts:
I thought of creating light sources, and some colored windows. Now, the windows are semi-transparent. How could I make it so that when the light (say, pure white) hits the glass and continues through it, but changes the color to the same color as the glass it passed?

I know the effect described here can be faked by using area lights on the "colored" side of the window, but what if I just wanted to have one white point light?


texts:
Basically i am trying to render a model yet it seems to draw polygons that should be behind something, in front of it. So i end up seeing some faces that should be behind something, totally covering it. Bah, i suck at explaining so here's the pic:

See the Railing? It should be at the front, but it's covered by the top of the platform. Also, on the side, the shadowed area should be practically hidden from that front wall... Other bits are around the place too if you just look at it... :(

I tried the 3 different cull modes, none of them fixed it, so i don't think its the culling (in fact Clockwise made it worse... :P). Thanks for any help.


texts:
I am currently working on a game in XNA 4.0, where I want to implement 2.5D, like in "Paper Mario". I feel like it has something to do with z-buffering a Texture2D, and drawing that, but I really have no idea where to start.

How do I render a 2D sprite in 3D space?


texts: How to differentiate between instantiated objects in Unity?

texts:
I'm currently trying to solve a way to go about the following problem before I start writing any code (the old fashioned pen and paper way) but I'm not sure how I could achieve the following.

I'm going to have an object with a Collider attached to it in my scene. As my instantiated enemies pass through this Collider they will be added to an ArrayList which lets the object in question keep track of the enemies. The problem I can't figure out is how to determine which object is which.

I will have a script attached to my main camera which will be responsible for spawning the enemy units, I'll be using a while loop in sudo code it would look something like this.

public Transform; (Attach the prefab in the inspector)

Somefunction() {

int i = 0;
arraylist goes here;

while (i < 10) {
arraylist[i] = Newly instantiated object.

}
}

My object with the collider will then have something like the following:

OnTriggerEnter() {
get specific object somehow
add to arraylist
}

I can't use the tag function because all the objects will have the same tag, the only thing I assume will be different is the position of the object in the spawn array (ie: arraylist[1] arraylist[2] etc.)

If I created a public accessor method on the trigger object could I call this method to return a string name or something special that identifies the object uniquely compared to the rest of the objects in the scene or does Unity already do this somehow natively?


texts:
I'm considering purchasing courses from Game Institute, specifically, the Foundation Studies Package. Has anyone here taken their courses? If so, do you feel they are a good value? If you can, please be specific as to what you benefited from them, and their strengths and weaknesses.

Though I am most interested in reinforcing computer science fundamentals with respect to game development, I would also like to know if the material is relevant to today's technologies.

I'm especially interested in responses from working professionals who have taken their courses or reviewed their materials.

Background: My work week is spent mostly with SQL Server ETL and some C# web forms development. I have ideas for 2D and 3D platformers, but I don't have the skills to build them to completion yet.

TIA!


texts: Pick a color and then Chop image with that color into 7 easy pieces

texts:
I have an image with 8 colors - (ROYGBIV and white) - I want to create 7 images - each has only one of the colors in the resulting image. I can do that fairly easily in GIMP.

Next I need to chop each of the 7 images into 7 layers - 7 pieces across with identical widths - with full height.

Finally I need to overlay the 7 layers on top of each other and see the resulting locations of the selected color.

Any ideas how to automate this image processing?


texts: OnPointerDown / OnPointerUp aren't working in world-space canvases

texts:
I'm working on a project where I have a main UI (Screen Space - Overlay canvas) and various game objects that have little popups above them (World Space canvas) that the player should be able to click on.  Everything on the main UI works fine, but the OnPointerDown and OnPointerUp methods on the World Space canvases aren't firing when I click on them.

Things I've made sure to check:

The canvases have a Graphic Raycaster
The canvases have their Event Camera set to the scene's camera
The Image on the canvas that's supposed to get clicked on has Raycast Target set to true

This was all working fine in Unity 2018, but in 2019 it's not.  Is this a bug, or has something changed that I just don't know about?  Either way, is there any way to fix this?


texts:
I'm writing planet generator, using pico8. I got surface generation done:

And the last thing to do is to map the texture onto a sphere.
Pico8 has no triangle function. So my question is, how do I make a sphere in my 2d space, and how do I apply a texture on it?

Looking for an effect like this (with no lighting, of course!):

I have really bad knowledge of 3d space manipulations.
The full list of available API functions can be found here.

Update 4:

Solved!

Try it live here.


texts: What heuristic should I use for A* pathfinding?

texts:
So, I've successfully implemented A* pathfinding (java) (http://www.cokeandcode.com/main/tutorials/path-finding/) in my game, but that pathfinding doesn't work as I wanted it to work. I don't know where should I look to change this behavior.

S - Start
E - End

I want it to work like on the left side. Now it works like on the right side.

I am using a Manhattan heuristic.


texts: How can I position objects in a circular motion from the inspector

texts: From the image below, I would like to position copies of my original circle (which is at the center) that are 1 unit away from the center and 30 degrees from each other in a circular motion. I would like to do this in the inspector. How can this be done?


texts: How to play a video on a TV model inside a game?

texts: I am new to Unity3D. I need to know how can I play news when I switch on a TV using any scripting language in Unity3D ?


texts: Should I create thread for both UDP and TCP?

texts:
So I have TCP connection for stuff like leveing, player info, etc..And I have UDP datagram for stuff like player position, rotation, etc..Should I create new thread for both TCP and UDP on both client and server side?That won't be resource heavy on client side but on server side with up to 15 players that will be 30 new threads.
I don't know if that amount if threads are not much or is there a better way of solving this issue.


texts: How to move a body from one world to another?

texts: I have a Box2D world for each level in my game. When a level is completed, I want the player to be removed from the completed level's world and added to the next level's world. How do I do this?


texts: How to render transparent meshes without sorting?

texts:
Let's assume we have some arbitrary triangle manifold meshes which are transparent.

How real guys effectively render it?

Is it possible todo it without sorting faces back to front (e.g. via bsp) and then render it with blending?


texts: How can I more efficiently write my Math-Code in AS3

texts:
So this might be an odd question to ask. But I'm not really the biggest mathematician out there, and I have a weird habit of writing code. So I'm going to post what I'm working on. I'm doing a self-game jam this weekend which will be 48 hours long, and I've kind of cheated by already starting. The question is -- well what I'm trying to do is create a ease-in / bouncing effect without using a Tween library.

I feel that what I have is suffice, but I don't think it is very efficient and that I'm overcomplicating my code with clutter.

Below is code from my Engine class with comments that should help decipher what I am doing.

package {
    import flash.display.MovieClip;
    import flash.ui.Mouse;
    import flash.display.Stage;
    import flash.events.Event;

    public class Engine extends MovieClip {

        public var spaceShip:Ship = new Ship(stage);
        private var logo:IcarusLogo = new IcarusLogo();

        //Math, Velocities , Numbers
        private var vF : Number = 0.5; // Velocity Forward
        private var vX : Number = 0; // Velocity X
        private var vY : Number = 0; // Velocity Y
        private var iV : Number = 0.2; // Initial Velocity
        private var fV : Number = .90; //Friction
        private static var pI:Number = 3.14; // pI

        public function Engine() {
            initGraphics();
            runGame();
            Mouse.hide();
        }
        //INIT EVERYTHING
        private function initGraphics():void {
            initShip();
            initLogo();
        }
        private function initShip():void {
            spaceShip.x = stage.stageWidth/2;
            spaceShip.y = stage.stageHeight/2;
            stage.addChild(spaceShip);
        }
        private function initLogo():void {
            stage.addChild(logo);
            logo.x = stage.stageWidth - 1200;
            logo.y = 200;
        }
        //RUN THE GAME
        private function runLogoStyles():void {
            logo.x += vX;
            iV = .025;
            vX *= fV + iV;
            if (logo.x <= 450) {
                logo.x += vX;
                vX += fV + iV;
                iV = -.2;
            }
        }
        public function runGame():void {
            stage.addEventListener(Event.ENTER_FRAME, update);
        }
        public function update(e:Event):void {
            runGame();
            runLogoStyles();
        }
        //TRASH EVERYTHING THATS NOT NEEDED.
        //AS3 HAS NO NARC RULE SO JUST REMOVE.CHILD
        public function trashCan():void {
            //TrashCan is similar to init. Create Sub-Functions // and init everything in here.
        }
    }
}

Here's a screenshot to give a better understanding : http://f.cl.ly/items/3X3j0L052v0M2b0v2p1b/screen.png


texts: Storing game state at exit on the iPhone with Objective-C

texts: How would you store your game state at exit for an iPhone game written in Objective-C?


texts: Replace PolygonCollider2D with MeshCollider at runtime

texts:
I am using a PolygonCollider2D to load in points for a MeshCollider at runtime, but am having issues switching between the two at runtime using good coding practices.

This is a simplified version of the current code:

Awake(){
    PolygonCollider2D polyCollider = this.gameObject.GetComponent<PolygonCollider2D>();
    //save vectors
    Vector3[] v3 = new Vector3[polyCollider.points.Length];
    for (int i = 0; i < polyCollider.points.Length; i++)
    {
        v3[i] = new Vector3(polyCollider .points[i].x, polyCollider .points[i].y, 0);
    }
    //destroy collider
    DestroyImmediate(collider);
    meshCollider = this.gameObject.AddComponent<MeshCollider>();
    meshCollider.sharedMesh.vertices = v3;
}

Other than the bad naming, how can I substitute DestroyImmediate(collider) with Destory(collider) while still having it behave correctly. I would be willing to move the mesh collider declaration to a different function to delay its assignment.


texts:
On Button click at editor mode I am trying to make a scene of selected Hierarchy game-object but the problem is as i click the button new scene
     become upon and I lost the scene where i were selected the Game-object. My code given below:

 if (GUILayout.Button("Generate Scene"))
        {
            Scene newScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects);;
            SceneManager.MoveGameObjectToScene(Selection.activeGameObject, newScene);
            EditorApplication.SaveScene("Assets/RegionScene/" + gameObjectSelected[gameObjectSelected.Count - 1].name + ".unity"); //newScene

        }


texts: How to store the configuration of Unity prefab components during map generation?

texts:
I managed to have a basic map generation algorhytm, but now it needs some content.

I generate abstract map data, which then will be used to build the map itself.

When I want to generate monsters, chests, entrances, etc, I have a prefab, and I will determine it's placement, then register it in the mapdata.

The problem is that I want to configure them as well, like affixes, stats, or where those entrances lead, etc.
But the component is only available after the map is built.
At generation I have only the prefab, so I have to transfer the generated configuration to the map builder somehow.

If I could clone the prefab, modify the clone's values and store that prefab.. . that would be great. But I can only instantiate prefabs, and I can't clone them without making a new asset.


texts:
I would like to show weapons and health items in an inventory grid.

The item can be rotated in the grid, and it occupies a certain region in the grid.

Currently I store this information (where the item is located, if it is rotated, etc.) in an additional array. However, this is not elegant and error prone.

I would therefore like to ask if it is possible to somehow store this additional information directly in the weapon or health GameObject.

Ideally I would like to be able to do something like this:

Pistol.GridProps.Rotation = 90
Pistol.GridProps.Row = 5
Pistol.GridProps.Col = 3

Is it possible to add something like "GridProps" to all my game objects?

Thank you!


texts: Unable to create suitable graphics device?

texts:
I've been following the Eye of the Dragon tutorial, which is basicly a guide to making a 2D RPG game, obviously.

I recently finished the tutorial about making pop up screens in the menu and changed the screen to load as a full screen.

Whenever I try and load the game it just goes black and my mouse sits there. I cannot change out of it other then with CtrlAltDel. Once i do that it says No suitable graphics card found, unable to create graphics device.

I read somewhere about XNA not allowing more then one screen when any one of them is full screen. but it wasnt very informative. Anyone have any ideas whats going on and/or how to fix this?

Just incase if this helps this is the code for the graphics device:

public Game1()
{
    graphics = new GraphicsDeviceManager(this);
    graphics.PreferredBackBufferWidth = 900;
    graphics.PreferredBackBufferHeight = 768;
    graphics.IsFullScreen = true;
    this.Window.Title = "Eyes of the Dragon";
    Content.RootDirectory = "Content";
}


texts:
So I want to make it possible for players to jump on objects (meshes) that are somewhat lower than the players camera.

I have set the checkCollisions to true but i can't seem to jump on any objects

(I'm using Babylon.js)

Here is my jump function

//Object i wanna jump on
var cube = BABYLON.Mesh.CreateBox("box", 10, scene);
cube.checkCollisions = true;
cube.position.y = - 4.5 ;

//Jump function
_playerJump : function(){
        $this = this;

        if($this.isJumping == false && $this.energy - 30 >= 0){
            var
                camera = $this.camera,
                jumpAnim = new BABYLON.Animation("jumpAnim", "position.y", 20, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE),
                keys = [],
                jumpStep;

            camera.animations = [];

            for(jumpStep = 0; jumpStep < 23; jumpStep ++)
                keys.push({frame: jumpStep, value: camera.position.y + jumpStep / 5});

            for(jumpStep = 24; jumpStep < 46; jumpStep ++)
                keys.push({frame: jumpStep, value: camera.position.y + 4.8 - (jumpStep - 24) / 5});

            jumpAnim.setKeys(keys);

            var easingFunction = new BABYLON.BezierCurveEase(.13,.01,.63,1.41);
            easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEIN);
            jumpAnim.setEasingFunction(easingFunction);

            camera.animations.push(jumpAnim);

            $this.isJumping = true;

            $this._setEnergy(-30);

            $this.scene.beginAnimation(camera, 0, 46, false, 4, function(){
                $this.isJumping = false;
                $this.isCrouching = false;
            });
        }
    }


texts: Light bounding geometry for deferred rendering

texts:
What is the best bounding geometry to use in a deferred renderer for each one of the following light types?

Sphere area light (obviously a sphere)
Disk area light (obviously a cone)
Rectangular area light (a frustum?)
Tube area light (a frustum as well?)

And how can I create those geometries? For the sphere and the disk it's quite simple given the attenuation radius and the attenuation angle, but for the other ones?


texts: How do open world game engines allocate memory?

texts:
My troubles
I've been trying to create a game engine but since I am not well experienced in C++ I am having trouble deciding on how to load new scenes efficiently level by level or just an open world.
Example
Recent games are heavy, Most populat games are about 40 to 100 gigabytes but neither RAM nor GPU have that much memory at least Normal PC or Consoles.
So obviously most game engines pre-allocate enough memory to fit the scene and sometimes just tolerate some wasted memory but how would you decide how much is enough?
Possible solution
I was planning to create separate game loops, before entering the game loop I would load each level, then start the loop, thus I would be able to deallocate preceding level and then reallocate new memory for a next level.
Since I am new to the world of games and memory management my solution may sound rather stupid, But I need to know how to handle such situations efficiently.


texts: To what extent are video game bots & NPCs “artificial intelligence”?

texts:
Wikipedia says:

  In video games, this usually means a character controlled by the computer through artificial intelligence.
  ~https://en.wikipedia.org/wiki/Non-player_character

  In video games, a bot is a type of weak AI expert system software which for each instance of the program controls a player [...]
  ~https://en.wikipedia.org/wiki/Video_game_bot

However as far as I know such bots & NPCs are way too hard-coded or explicitly coded to be accurately called "artificial intelligence".

Mainly most often they lack the ability to learn dynamically from the player. Arthur Samuel calls "artificial intelligence" The "field of study that gives computers the ability to learn without being explicitly programmed" (1959).

So to what extend can bots and/or NPCs be called "artificial intelligence" if they (or a subset of them) can be designated as such?


texts:
I'm making a 2d tile based game. In pygame I could create a map like this:
screen = pygame.display(resolution)
map = pygame.Surface(width, height)
for tile in all_tiles:
    map.blit(tile)
screen.blit(map)

The strength of this is that I can scroll the map by changing the map surface x and y. Also all the in-game coordinates are conveniently set in relation to the map rather than the screen. However I can no longer use pygame, and I'm trying to switch to pyglet instead. As far as I can tell pyglet doesn't have an equivalent surface class built in, and therefore I need to build my own, this is what I need help with.
I've used pygame.Surface extensively without really understanding how it works (python programmers these days huh). So I'm hoping you can offer some insight on how to get started. I know it needs a width and height, as well as some kind of list of the sprites which have been 'blitted' to it, and that moving the surface itself moves all the contained sprites, so surfaces blitted to it are somehow anchored to the surface rather than the screen.
How is this stuff done in pygame, and how do we create a pyglet friendly version?


texts: Fragment shader code for simple shading is making the app crash

texts:
My fragment shader compilers fine but the my app crashes when i use it.

My bug hunting deducted that the shader is linking fine.
Also it's curious that striping down the core and removing everything and outputting just a colour is showing the model in one colour off course.

What is wrong?

Fragment shader:

#version 330 core
const float PI = 3.14159265359;
out vec4 coloroutfinal;

in vec3 fragpos;
uniform vec3 lightpos;
uniform vec3 camerapos;

vec3 wi;
vec3 normal;
float cosT;
uniform vec3 lightcolor;
vec3 incidentlight;

uniform float metallic;
uniform float roughness;
uniform vec3 albedo;
uniform float ao;

vec3 fresnel(float cosT,vec3 Fo);
float ND(vec3 H,vec3 N,float roughness);
float G(vec3 L,vec3 N,vec3 V,float roughness);

void main()
{
  wi=normalize(lightpos-fragpos);
  normal=normalize(fragpos);
  cosT=max(dot(normal,wi),0.0);
  float attenuation=1.0/pow(length(lightpos-fragpos),2);
  incidentlight=attenuation*cosT*lightcolor;
  vec3 V=normalize(camerapos-fragpos);
  vec3 H=normalize(V+wi);

  vec3 Fo=vec3(0.04);
  Fo=mix(Fo,albedo,metallic);
  vec3 F=fresnel(max(dot(H,V),0.0),Fo);

  float ND=ND(H,normal,roughness);
  float G=G(wi,normal,V,roughness);

  vec3 BRDFn=F*ND*G;
  float BRDFd=4*max(dot(normal,wi),0.0)*max(dot(normal,V),0.0)+0.001;
  vec3 specular=BRDFn/BRDFd;

  vec3 KS=F;
  vec3 KD=1.0-KS;
  KD*=(1.0-metallic);

  vec3 lo=(KD*albedo/PI+specular)*incidentlight;
  vec3 colorout=lo+(ao*albedo*vec3(0.05));

  colorout=colorout/(colorout+1.0);
  colorout=pow(colorout,vec3(1/2.2));
  coloroutfinal=vec4(colorout,0.0);

}

vec3 fresnel(float cosT,vec3 Fo)
{
  return Fo+(1.0-Fo)*pow((1-cosT),5);
}

float ND(vec3 H,vec3 N,float roughness)
{
   float roughness4=pow(roughness,4);
   float cosT=max(dot(N,H),0.0);
   float cosT2=cosT*cosT;
   float num=roughness4;
   float denom=cosT2*(1.0-roughness4)+1.0;
   return num/denom;
}

float GP(float cosT,float roughness)
{
roughness-=1.0;
   float r2=roughness*roughness;
   float k=r2/8;

float num=cosT;
float denom=cosT*(1.0-k)+k;
 return num/denom;

}

float G(vec3 L,vec3 N,vec3 V,float roughness)
{
  float cosTL=max(dot(N,L),0.0);
  float cosTV=max(dot(N,V),0.0);

  float GL=GP(cosTL,roughness);
  float GV=GP(cosTV,roughness);
  return GL*GV;
}


texts: Creating A Bounding Box around each item in a list XNA 4.0

texts:
I have asked a similar question before except i am more experienced and have more understanding of XNA. I have bullets that shoot whenever you press RightTrigger. I am having trouble though creating bounding boxes around each bullet in the list though. I want to have this so you can shoot the man and when he is hit he will die, except for some reason no bounding boxes are being drawn.
I have updated this now because im trying the same method in a platformer after i gave up on the shooter game because i gave up on it because i couldnt get the collision detection right. Now im trying this method again and am having trouble. The thing is, it does work but only on the last ground piece added to the list. Here is the code for the collision detection in the Game1 class:

OLD CODE (DISREGARD)

public bool hitBullet()
    {

        foreach (Bullets bullet in bullets.bulletAmm)
        {
            bulletRect = new Rectangle(
                (int)bullet.position.X,
                (int)bullet.position.Y,
                bullet.size.X,
                bullet.size.Y);

            manRectangle = new Rectangle(
                (int)man.position.X,
                (int)man.position.Y,
                man.pistolTexture.Width,
                man.pistolTexture.Height);
        }

        return bulletRect.Intersects(manRectangle);
    }

NEW CODE (PAY ATTENTION)

 public bool HitGround()
    {
        foreach (Ground newGround in ground.groundAmmount)
        {
            groundRectangle = new Rectangle(
                (int)newGround.position.X,
                (int)newGround.position.Y,
                newGround.shortTexture.Width,
                newGround.shortTexture.Height);

            iceBoyRectangel = new Rectangle(
                (int)iceBoy.position.X,
                (int)iceBoy.position.Y,
                iceBoy.texture.Width,
                iceBoy.texture.Height);
        }

        return groundRectangle.Intersects(iceBoyRectangel);
    }

now the same method of

    foreach (Bullets bullet in bullets.bulletAmm)

or
        foreach(Ground newGround in ground.groundAmmount);

works for updating and drawing each bullet which works. but not for the bounding boxes. Any suggestions?

EDIT 1:

i noticed now that this method works sometimes, but only for about 1 in every 20 bullets which makes this even stranger.

EDIT 2:

i thought that i had solved this issue but it turns out i havent. I have updated the code to what it is now.


texts: I'm developing an iOS game and was considering putting level info and monster info in a Lua script for ease of use. However, since I'm using Game Center for multiplayer I'm concerned users will attempt to change these scripts to cheat. What measures can I take to protect my Lua scripts?


texts: Can you help me find resources for developing a top-down 2D game in Java?

texts:
I just started reading about games, and I'm going to develop a game where a person is moving around on a 2D map. My preferred language is Java. Is that suitable to develop games?

I'm going to develop a desktop app and need some help to get started. Can someone please give me some good resources for newbies?


texts:
Irrlicht uses namespaces, a C++ feature not available in Objective-C:

/*
In the Irrlicht Engine, everything can be found in the namespace 'irr'. So if
you want to use a class of the engine, you have to write irr:: before the name
of the class. For example to use the IrrlichtDevice write: irr::IrrlichtDevice.
To get rid of the irr:: in front of the name of every class, we tell the
compiler that we use that namespace from now on, and we will not have to write
irr:: anymore.
*/
using namespace irr;

How can I still use Objecive-C with Irrlicht? Thanks.


texts: How to render top-down perspective in a tile-based RPG?

texts:
My question is specifically about the type of perspective that GBA Pokemon games like Fire Red/Leaf Green have:

I'm not sure of the correct terms for what I'm trying to achieve.

I am using SDL2 and can render a tilemap and sprites on top of it, with basic collision detection, but since everything is constrained inside a tile, it looks like the player collides with a wall when their head touches it, rather than the feet.

The above screenshot has a tiny bit of perspective (is that considered 2.5d?), so the head of the player hides a portion of the tile above.

There are definitely ways to make this work, e.g. being a bit more lenient on collision (i.e. not the whole bounding box of the player but the middle of it collides with a wall), but my question is mostly about efficient rendering.

Is rendering from the bottom up the best thing to do so that I respect the perspective? If it is then I guess I need to know at which tile to render the player, so I need to compare every coordinate with the player coordinates to see if it's time to render the player?


texts:
I've recently attempted to develop a simple client prediction for an FPS based on Gaffer on Games famous blog (http://gafferongames.com/game-physics/networked-physics/).

Now I've gotten to the point that everything works (more or less), my main problem is crossing the message sent from the server and finding the appropriate snapshot on the client. I can use the last/average ping time to find a very near state, but it will never be exactly timed/placed as on the server.

So my question is - how exactly can I sync and find the time stamp sent from the server to the client and find which snapshot is the correct one on the client?


texts: Which Box2D-like physics engine parameters need pixel conversion?

texts:
The official guide does not have any useful details on the matter:

http://www.box2d.org/manual.html

Position is an obvious one. What about velocity? Density? Anything else?

Update: the context is wrapping/interfacing a physics engine to make it more usable. E.g. units of measure in the game editor should be consistent.


texts: HLSL compiler specification (optimizations)

texts:
Can I read somewhere about optimizations that HLSL compiler performs?

For example, in some codes I have different variables that get a constant value (just to let myself adjust the shader with other values) and I use them later in some mathematical expressions, but actually it can be precalculated earlier. Does the compiler do such thing?

It's just an example, I would like to know most of these things.


texts: How to make a scrolling background in Delphi with FireMonkey?

texts:
I'm making a scrolling background game alike classic Mario 2D games.

How do I make a scrolling background in Delphi XE7 using FireMonkey?


texts:
I'm writing a tower defense game in Unity, inspired by Desktop Tower Defense.

Creeps spawn on one side of the screen, and if they make it to the opposite side, the player takes damage.  The board starts out unobstructed, and the player builds towers that shoot at creeps while also blocking their path.  They can funnel creeps along a path by strategic placement of towers.

I have a terrain GameObject with a NavMesh, each creep has a NavMeshAgent, and each tower has a NavMeshObstacle.  This works fine, the creeps go toward the goal and avoid the towers.

The problem is that the player is not allowed to block off all of the paths to the goal.  If placing a tower would leave no routes open to the goal, it is not valid to place a tower there.  I can detect this after the tower is placed, but I want to warn the player and prevent the placement from happening at all.

I also don't want to even briefly block the path to the goal by temporarily placing a NavMeshObstacle in an invalid position, because it might be exploitable by players by repeatedly attempting to place a tower there.

How can I predict whether placing a NavMeshObstacle will completely block a route between two paths, while NavMeshAgents are actively traversing the NavMesh?


texts: Why aren't my Unity Ads showing "real" ads?

texts:
I don't have "Enable Test Mode" checked under in the ads setting in Services, but when ads pop up on my published game, it's showing Unity ads as if the test mode is on. How can I fix this? Thanks!
This is the code I use to add the ads:
Advertisement.Initialize(GooglePlay_ID, GameMode);
Advertisement.Show();


texts: Copy a gameObject's collider at runtime (Unity)

texts:
I'm working on a small Unity 2D project in which I need to modify the collider of the player at runtime. I'm using Physics2D.Raycast to find the collider and then what I'd like to be able to do is then copy that exact collider over to the current gameObject and remove the current collider in the process.
Basically when my Ray hits an object, I want my player to turn into that object.

I'm fairly new to Unity and have been digging through the API for some hints but haven't found anything yet. Any help would be appreciated.

So far all I have is as follows:

RaycastHit2D hit = Physics2D.Raycast(transform.position, lookDirection, Mathf.Infinity, 1 << 8);
        if (hit.collider != null)
        {

            //Change the collider somehow
            Collider2D myC = GetComponent<Collider2D>();
            myC = hit.collider; //Haha that doesn't work.

        }


texts: Should I use attack effect collision to detect when damage is dealt?

texts:
I am wondering what a common way for actually dealing damage to different units is. Imagine a game like starcraft for example, should damage be done like this:

  1) zealot attacks zergling, deal damage to zergling

or

  2) zealot attacks zergling, create an attack effect on zergling. When
  this effect collides with the zergling deal damage to said zergling.

The advantage of 2 is for projectiles (like a dragoon attack) will deal damage when the attack collides with the target unit.

What are your thoughts about this in general? Are there other ways of doing this?


texts: How to make box2d mouse joint works similar to box2d setposition

texts:
I want to make b2mouse joint working similar to b2setposition, though i know in mouse joint force is applied, so it's not possible to reach the desired point without any delay like setPosition(), but i want to make it works as close as b2setPosition(). So on which mousejoint/body properties should i work on so that it acts as close as b2setposition.

Thanks for your answer.


texts: Is it possible to mute sound in editor in Unity? I mean not in the game, but in the editor, so that when I am debugging there would be no sound whatsoever.


texts: Creating a 2D texture array for depth view

texts:
Following my question here, I decided to create an 2D texture array for all of my depth screen texture so that I can use them for shadows for all my lights.

I'm having an issue setting it up, I'm getting an E_INVALIDARG when I try to create it.

This code is what I use to create the 2D array Texture

D3D11_TEXTURE2D_DESC sTexDesc;
sTexDesc.Width = this->Width;  // 1024
sTexDesc.Height = this->Height;// 1024
sTexDesc.MipLevels = 0;
sTexDesc.ArraySize = arraySize; // The value is 25 here
sTexDesc.Format = DXGI_FORMAT_R24G8_TYPELESS;
sTexDesc.SampleDesc.Count = 1;
sTexDesc.SampleDesc.Quality = 0;
sTexDesc.Usage = D3D11_USAGE_DEFAULT;
sTexDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
sTexDesc.CPUAccessFlags = 0;
sTexDesc.MiscFlags = 0;

HRESULT hr = pd3dDevice->CreateTexture2D(&sTexDesc, NULL, &(this->shadowTexture));
if(FAILED(hr))
    throw std::exception("Failed at creating texture array for shadows");

This is the code that I use to create the depth view

D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc;
ZeroMemory(&dsvDesc, sizeof(dsvDesc));
dsvDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DARRAY;
dsvDesc.Texture2DArray.ArraySize = arraySize; // The value is 25 here
dsvDesc.Texture2DArray.FirstArraySlice = index;
HRESULT hr = pd3dDevice->CreateDepthStencilView(shadowTexture, &dsvDesc, &pDepthMapDSV);
if(FAILED(hr)){ throw std::exception("Error creating 2d texture for shadow"); }

CreateDepthStencilView will return OK for the first texture but it  crashes for the second.

What have I done wrong here?


texts: Make an object follow the mouse pointer with LÖVE2D

texts:
I've been trying to make a picture follow the mouse pointer with LÖVE2D.

I want that the object follow the mouse, and not just be the mouse coordinates, I did that. So I toked the distance between the objects:

distance = dist(object.x, mouseX, object.y, mouseY)

the dist definition is the one from analytic geometry(Distance between two points in the Cartesian plan), well, now I don't know what to do, I tried a timer to update the object's coordinates but didn't work out.

if object.timer >= 2 then
    --object.x = mouseX
    --object.y = mouseY
    object.x = mouseX - distance
    object.y = mouseY - distance
    object.timer = 0
end

It didn't work out either :(. Well, I tried some other stuff, like whale.x - distance, but didn't worked out either, how can I make the object follow the mouse, like, if I let my mouse on (500, 300(Screen coordinates) the image would follow until it reaches the position desired which is the mouse position.

And yea, I really need to learn more math. >.>


texts: How to "reset" velocity.y when entering water?

texts:
I'm using a raycast controller and kinematic ridigbody.

The way I've got my project set up is that I have a set of default values, such as gravity, jump height, etc., and when I enter a certain trigger, such as water, these values change (or, more specifically, I override these values temporarily).

My velocity.y += gravity * time.deltaTime, but there are some bugs if I jump into the water. For example, if I jump in from above then the velocity.y does not change in the water until I collide with the bottom of the water. Essentially it looks like I'm performing a normal jump, and only once I land will the changed gravity in the water trigger affect my movement. Also, if I jump in the water trigger from the side it sometimes propels me very high in the air.

When I print out the gravity value it does change immediately when I enter the water, but it seems the downward force from falling is never changed until I hit the bottom of the ocean floor.

public ControllerParameters2D Parameters { get { return overrideParameters
   ?? defaultParameters; } } //Returns updated parameters, or default
                             //parameters if overrideParameters is null

public void LateUpdate()
{
    JumpInSeconds -= Time.deltaTime; //Calculates how long until the player can jump again

    velocity.y += Parameters.gravity * Time.deltaTime; //Adds the force of gravity to the character's y velocity, scaled per time

    Move(Velocity * Time.deltaTime); //Moves the character per its velocity, scaled by time
}

public void OnTriggerEnter2D(Collider2D other)
{
    var newParameters = other.gameObject.GetComponent<ControllerPhysicsVolume2D>();

    if (newParameters == null)
    {
        return;
    }

    overrideParameters = newParameters.NewParameters;
}

public void OnTriggerExit2D(Collider2D other)
{
    var newParameters = other.gameObject.GetComponent<ControllerPhysicsVolume2D>();

    if (newParameters == null)
    {
        return;
    }

    overrideParameters = null;
}


texts: I'm wondering if anyone can point me in the right direct as to how to take a 2D character/sprite in Unity and have said character turn corners in a 3D style. Solutions or resources welcome.


texts:
im currently writing a simple server for a mobile/web game. In short, players have a number of buildings that will produce several items every x minutes. What i though as a solution its creating a column named "nextProduction" and start a cronjob that will give the items and update that column, then renew the cronjob for the next iteration.

Now i have doubt about it, maybe this solution will be too resource intensive as the number of players increase? Thanks beforehand


texts: Prevent oversteering catastrophe in racing games

texts:
When playing GTA III on Android I noticed something that has been annoying me in almost every racing game I've played (maybe except Mario Kart): Driving straight ahead is easy, but curves are really hard. When I switch lanes or pass somebody, the car starts swiveling back and forth, and any attempt to correct it makes it only worse. The only thing I can do is to hit the brakes. I think this is some kind of oversteering.

What makes it so irritating is that it never happens to me in real life (thank god :-)), so 90% of the games with vehicles inside feel unreal to me (despite probably having really good physics engines). I've talked to a couple of people about this, and it seems either you 'get' racing games, or you don't. With a lot of practice, I did manage to get semi-good at some games (e.g. from the Need for Speed series), by driving very cautiously, braking a lot (and usually getting a cramp in my fingers).

What can you do as a game developer to prevent the oversteering resonance catastrophe, and make driving feel right? (For a casual racing game, that doesn't strive for 100% realistic physics)

I also wonder what games like Super Mario Kart exactly do differently so that they don't have so much oversteering?

I guess one problem is that if you play with a keyboard or a touchscreen (but not wheels and pedals), you only have digital input: gas pressed or not, steering left/right or not, and it's much harder to steer appropriately for a given speed. The other thing is that you probably don't have a good sense of speed, and drive much faster than you would (safely) in reality. From the top of my head, one solution might be to vary the steering response with speed.


texts:
I'm working on a platformer but I'm stuck at the player movement and collisions.
Right now I'm not including the grid at all in the movement, but it's time I do it. I've read this article on how to do it. But there's no real code examples just theory.
I like the second example and that's the one I'm going for. I want the movement to be smooth, and the player should be able to run in between squares from my map array.
This means I have to get tile information from the array, and according to that allow/forbid my player to move in that direction. And that's where I'm stuck.
My array is a bunch of 1's and 0's right now. I know how to calculate a hitbox around the player, but how do I compare that to the array in an efficiant way?
UPDATE: I've been playing around with this for a while now, and the only thing I came up with is using player X and Y which is in pixels, dividing by tile size, and getting a rough estimate on the map. Then I make it an AABB by adding its width and height to get the corners.
This showed to be very unreliable though, and I would really need some help on how to structure this.


texts: Do the predefined HLSL semantics carry any meaning?

texts:
I'd say there are 3 kinds of HLSL semantics:

SV_* group - these are "system value" semantics which DO carry special meanings (e.g. assign special input/output data to/from shader stages)
predefined semantics - e.g. NORMAL, POSITION and so on... They are mentioned in the docs but I failed to find any special meaning assigned to them
semantics defined be the user - which can be anything (e.g. MY_AWESOME_TEXTURE_SEMANTIC) which apparently have no special meaning either

In addition, the docs say that more than one input/output value can have the same semantic assigned (e.g. 'NORMAL2 and NORMAL2). I guess that it doesn't include the SV_* group, though.

So besides the first group - do semantics carry any meaning at all? Do they even serve any purpose at all? :P


texts: How to calculate the stopping distance of a wheel collider?

texts:
I have an 'AI' bus in my game that needs to pull over occasionally at a bus stop. What I want to do is change the acceleration and brake force based on the stopping distance of the bus. I don't want to simply use the distance between the bus stop and the bus because each time the bus pulls over, it could be traveling at a different speed.

Right now it uses the distance between the bus stop and the bus. It doesn't really work well though because if a bus is traveling faster, it will take a longer distance to stop and will likely go past the bus stop. Same thing if it were going slower.

How do I calculate the stopping distance my bus will take to come to a complete stop?


texts: Why do objects interpenetrate in this simple collision solver?

texts:
The code below is from a Microsoft XNA sample here.
This is quite a simple rigid body simulation that ignores many physical effects (such as angular momentum), but it does try to push objects (spheres) apart so that they are not penetrating one-another.

However, the simulation allows spheres not only to penetrate, but when many spheres are stacked on top of each other, small spheres can be almost completely inside of larger spheres. If I make all spheres have the same radius and mass, then the simulation performs reasonably well (with minimal interpenetration).

Can someone explain why there is any interpenetration at all? Since it moves the positions of the spheres, it seems like interpenetration should be impossible.

For each sphere in the simulation, this method is called on every other sphere.

/// <summary>
// Given 2 spheres with velocity, mass and size, evaluate whether
// a collision occured, and if so, excatly where, and move sphere 2
// at the contact point with sphere 1, and generate new velocities.
/// </summary>
private void SphereCollisionImplicit(Sphere sphere1, Sphere sphere2)
{
    const float K_ELASTIC = 0.75f;

    Vector3 relativepos = sphere2.Position - sphere1.Position;
    float distance = relativepos.Length();
    float radii = sphere1.Radius + sphere2.Radius;
    if (distance >= radii)
    {
        return; // No collision
    }

    // Add epsilon to avoid NaN.
    distance += 0.000001f;

    Vector3 relativeUnit = relativepos * (1.0f / distance);
    Vector3 penetration = relativeUnit * (radii - distance);

    // Adjust the spheres' relative positions
    float mass1 = sphere1.Mass;
    float mass2 = sphere2.Mass;

    float m_inv = 1.0f / (mass1 + mass2);
    float weight1 = mass1 * m_inv; // relative weight of sphere 1
    float weight2 = mass2 * m_inv; // relative weight of sphere 2. w1+w2==1.0

    sphere1.Position -= weight2 * penetration;
    sphere2.Position += weight1 * penetration;

    // Adjust the objects’ relative velocities, if they are
    // moving toward each other.
    //
    // Note that we're assuming no friction, or equivalently, no angular momentum.
    //
    // velocityTotal = velocity of v2 in v1 stationary ref. frame
    // get reference frame of common center of mass
    Vector3 velocity1 = sphere1.Velocity;
    Vector3 velocity2 = sphere2.Velocity;

    Vector3 velocityTotal = velocity1 * weight1 + velocity2 * weight2;
    Vector3 i2 = (velocity2 - velocityTotal) * mass2;
    if (Vector3.Dot(i2, relativeUnit) < 0)
    {
        // i1+i2 == 0, approx
        Vector3 di = Vector3.Dot(i2, relativeUnit) * relativeUnit;
        i2 -= di * (K_ELASTIC + 1);
        sphere1.Velocity = (-i2) / mass1 + velocityTotal;
        sphere2.Velocity = i2 / mass2 + velocityTotal;
    }
}

In particular, I though that this:

sphere1.Position -= weight2 * penetration;
sphere2.Position += weight1 * penetration;

Should completely disallow any interpenetration, why doesn't it?


texts:
Hi I am trying to find the Tile number of a grid of tiles based on the Z and X coordinates.

Where the Z and X axis are potentially infinite in either direction how can i get the number of the tile, based on the Z and X coordinates.

Sorry for the crude drawing


texts: How can i make my program use 2 windows?

texts:
I'm working in Xna 4.0 and iwant to make a program that uses the same code in 2 different windows.
What i want out of this is that one player plays in one window and the other player to play in the second window.

So i have 2 different questions:

Is it possible to use 2 windows for the same program?

Is it possible for 1 window to have focus on one controller and the other window on the other?


texts: ScriptableObject not saving data in PC Build

texts:
I am using ScriptableObject to save state of my game.
Currently Saving:
- Selected object
- Object count

It works fine in editor, but when I make a PC build the data doesn't saves and everything I launch the PC build the game is in default state.

My GameConfig ScriptableObject is located in the Resources folder, can anyone help out exactly what the issue can be? The scriptable object is serialized and so are the fields in it.

Unity version: 2017.3.1p1


texts:
I have stuck in this simple problem but unable to understand that why i am unable to control it.

I have these line of code which is displaying my canvas object in front of my player(camRotationToWatch object name in code) at certain rotation of the player.

if (camRotationToWatch.transform.localEulerAngles.x >= navigationCanvasXMinmumLimit && camRotationToWatch.transform.localEulerAngles.x <= navigationCanvasXMaximumLimit)
        {
            if (!navCanvasHasDisplay)
            {

                navigationCanvas.SetActive(true);
                //Debug.Log(camRotationToWatch.transform.forward);
                Vector3 navCanvas = camRotationToWatch.transform.position + camRotationToWatch.transform.forward * navCanvasDisplayDistanceFromCam;
                navCanvas = new Vector3(navCanvas.x, 2f, navCanvas.z);
                navigationCanvas.transform.position = new Vector3(navCanvas.x, navCanvas.y, navCanvas.z);

                navigationCanvas.transform.rotation = camRotationToWatch.transform.rotation;

                navCanvasHasDisplay = true;

            }
        }

        else
        {
            //navigationCanvas.SetActive(false);
            if (locationPanel.activeSelf == false && infoPanel.activeSelf == false) {
                navigationCanvas.SetActive(false);
                navCanvasHasDisplay = false;
            }
        }

This code is actually work fine when camRotationToWatch object rotate from down to up and Canvas show at correct position but as I try to to rotate camRotationToWatch from up to down it display(active) Canvas at very top position. How can I restrict canvas to show at same position (No matter player rotate from up to down or down to up) but display on front of the player object?


texts: How to draw a string into a polygon? (Libgdx, Java)

texts:
I am working on a 2D grand strategy game (like Hearts of Iron from Paradox but as I said only 2D game) and I would like to render the area names on the map. I made the Polygons for each area. How can I render a String inside that polygon?

Here is the image from my game (I put some area names onto the image to show what I would like to achieve):

Here is the code where the polygon is being made (please check it because this is the first time I use polygons):

private Polygon pol;

    public Polygon polygon(Map m) {
        if (pol == null) {
            float[] vertices = new float[border().size * 2]; // the border() method returns a collection of 2D vectors/points which are the borders.
            for (int i = 0; i < vertices.length; i += 2) {
                Vector2 v = border().get(i / 2);
                vertices[i] = v.x;
                vertices[i + 1] = m.height - v.y - 1; // m.height is the map's height which is 2160; I convert here the coords (not sure if it is neceseray, the top left corner is the 0,0 coord in the map)
            }
            pol = new Polygon(vertices);
            pol.setPosition(0, 0);
            pol.setOrigin(0, 0);
        }
        return pol;
    }

How I checked if the area is on the screen:

private Vector3 ivm = new Vector3();
    public boolean isVisible(Camera cam) {
        for (Vector2 vec : points) {
            ivm.set(vec, 0);
            if (cam.frustum.pointInFrustum(ivm)) {
                return true;
            }
        }
        return false;
    }


texts:
I'm currently working with Phaser, making a game that's procedurally generated. I wanted to use some RPG maker art in my game (for reference, I'm using the RTP). I stumbled across this article, which breaks down how auto tiles work. I also stumbled across this answer which links to another article that explains auto tiling.
Here's the thing, I have no idea how I would implement something like this. I'm sure I would have to keep track of which tile sets can connect to which other tilesets (ie, some tiles have grass on the outside, and sand on the inside, so in this example I'd have to note that "grass" tiles were the outer tiles).
I've made a map generator, and I wanted to make seamless connections between my tile areas. For example, the brown areas would be "dense" areas (forests, caves, etc). The purple areas would be stone floors, and the green area is the grass. There is a tileset that works very well for things like this:

So I would like to use the top left grass, and the third tile set, stone, which connects to the grass.
What sorts of things would I have to consider when implementing auto tiling using these sorts of tilesets, and is there an algorithm I can look at to implement?


texts: What is an acceptable receive rate for a client?

texts:
I've noticed that syncing a transform( in Unity, so a Vector3, and a Quaternion ) ends up being close to 1000 byes per second received on a client( send rate of 20hz ). Multiply this by a generous 20 entities a single match might have and that's about 15k-20k bytes per second.

Is this too much? What should I be aiming for? What data rates do games typically have?


texts: How to implement custom texture formats in Android?

texts:
What I know:
Android can load PNG, BMP, WEBP,... via BitmapFactory.

What I want to achive:
Load my own 2D file format (e.g. 1-bit texture with a 1-bit alpha channel) and output a RGBA8888 texture.

Question:
Is there any interface to achieve this?(or any other way)

The resulting image is used as a texture for a 3D model.

Why would you do that?
Saving phone memory and download bandwidth while expanding the texture at runtime to RAM seems reasonable for very simple textures.


texts: Scene2D viewport affects all other cameras despite having a separate one

texts:
I have two cameras initialized as such:

val mainCamera: OrthographicCamera by lazy { OrthographicCamera(WIDTH * ZOOM, HEIGHT * ZOOM) }
val guiCamera: OrthographicCamera by lazy { OrthographicCamera(WIDTH, HEIGHT) }

override fun initialize() {
    mainCamera.setToOrtho(false, WIDTH * ZOOM, HEIGHT * ZOOM)
    mainCamera.update()

    guiCamera.setToOrtho(false, WIDTH, HEIGHT)
    guiCamera.update()
}

Where WIDTH and HEIGHT values are 960f and 640f respectively and zoom is 0.5f for mainCamera.

mainCamera is used for showing everything game related (following the player mainly) and doesn't use Scene2D, while guiCamera is used for displaying the GUI and is exclusively used within a Scene2D stage and is set in stages constructor like this:

private val stage: Stage by lazy { Stage(StretchViewport(WIDTH, HEIGHT, cameraSystem.guiCamera), batch) }

However when I change the viewport of the stage to FitViewport it seems that everything is shrunk and letterboxed, even the mainCamera.

I expected that using FitViewport with a specific camera would only perform scaling on entities using that camera, not on the whole scene.

Is this how it should work or am I doing something wrong? Sprite and map rendering systems render to the mainCamera and all rendering systems use the same batch, however I've also tried instantiating the stage with it's own dedicated batch so it had both it's own camera and a batch and still everything was shrunk.

P.S: The language used is Kotlin so the syntax is a little different from Java however most of the concepts are the same and straightforward. I'd only like to explain the by lazy syntax to those not familiar with Kotlin. by lazy means that the property won't be initialized until it's accessed for the first time. It allows me to define a final/constant (val) property but delay it's initialization until libgdx context is properly initialized and until artemis-odb system dependencies are injected.