texts: Verify which bubble is connected to top using DFS

texts:
I am working on a bubble shooter game in this game i have implemented searching using DFS as suggested in this link, and this is working fine.

Update

Here is my code for DFS

-(void)callDfs:(int)startR:(int)startC:(int)color{

notVisitedBubblesArr = [[NSMutableArray alloc]init];

//reset visited matrix to false.
for(int i = 0; i < R; i++)
    for(int j = 0; j < C; j++)
        visited[i][j] = FALSE;

//reset count
count = 0;
isFound = NO;
bubbleBlastCount = 0;
[self dfs:startR :startC :color :false];

[self bubbleFalling];

}
-(void)dfs:(int)ro:(int)co:(int)colori:(BOOL)set{
    coundown++;
    for(int dr = -1; dr <= 1; dr++)
        for(int dc = -1; dc <= 1; dc++)
            if([self ok:ro+dr :co+dc]) // 4 neighbors
            {
                int nr = ro+dr;
                int nc = co+dc;

                if ((([[[bubbles_Arr objectAtIndex:nr] objectAtIndex:nc]   integerValue]==colori) && !visited[nr][nc])) {
visited[nr][nc] = true;
count++;
[self dfs:nr :nc :colori :set];
if(count>2)
{
// pass row and colom will start dfs
//  if (nr >= touchClum && nc >= touchROW) {
isFound = YES;
bubbleBlastCount++;
[[bubbles_Arr objectAtIndex:nr] replaceObjectAtIndex:nc withObject:NOCOLOR];
[bubbles[nc+1][nr+1] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"blank.png"]];
}
}
}
}

Now i am trying to implement bubble falling using DFS, i studied this link. i got all unvisited nodes after DFS but i am not able to verify with node is connected to top.

Here is my code for bubble falling

-(void)bubbleFalling{

for(int i = 0; i < R; i++){
    for(int j = 0; j < C; j++){
if (!visited[i][j]) {
    //NSLog(@"Array :  %d %d", i,j);

    NSLog(@"Value : %d",[[[bubbles_Arr objectAtIndex:i] objectAtIndex:j] integerValue]);

    BOOL canReach = [self canreachTop:i :j];
    if(canReach){
        NSLog(@"Yes");

    }
    else{
        NSLog(@"NO");
        [[bubbles_Arr objectAtIndex:i] replaceObjectAtIndex:j withObject:NOCOLOR];
        [bubbles[j+1][i+1] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"blank.png"]];
    }

}

    }
}
}

-(BOOL)canreachTop:(int)ro:(int)co{
   int topNode = [[[bubbles_Arr objectAtIndex:R-1]objectAtIndex:C-1] integerValue];

BOOL success = FALSE;
for(int dr = -1; dr <= 1; dr++)
    for(int dc = -1; dc <= 1; dc++)

        if([self ok:ro+dr :co+dc]) // 4 neighbors
        {
            int nr = ro+dr;
            int nc = co+dc;

            if ((([[[bubbles_Arr objectAtIndex:nr] objectAtIndex:nc] integerValue]== topNode) && !visited[nr][nc])) {
            success = TRUE;
            }
        }

return success;
}

-(BOOL)ok:(int)r:(int)c{
    return r >= 0 && r < R && c >= 0 && c < C;
}

Below is the screenshot of my iPhone simulator in that green bubble should fall because it is not connected with any bubble, i think we have to check whether it is connected with the top bubble or not or i have to follow some other approach?

This is my first game and i am not getting what is wrong with my bubble falling code.

Thanks in advance.


texts:
I am writing a android game using Canvas as the way to draw everything, the problem is that when i run it on different android phones the canvas dosn't change size i tried using canvas.scale() but that didn't make a i difference. The code i use for drawing is ...

public void draw( Canvas c, int score )
{
    Obstical2[] obstmp = Queue.toArray(this.o);
    Coin[] cointmp = QueueC.toArray(this.c);

    for( int i = 0; i < obstmp.length; i++ )
    {
        obstmp[i].draw(c);
    }

    for( int i = 0; i < cointmp.length; i++ )
    {
        cointmp[i].draw(c);
    }
    c.drawText(String.format("%d", score ), 20, 50, textPaint);

    if( isWon && isStarted ) c.drawText("YOU WON", 20, 400, resPaint);
    else if( isLost && isStarted ) c.drawText("YOU LOST", 20, 400, resPaint);
}

The function above calls the draw functions for the entity's on the screen, theses function are as follows

Draw Function For Obstical :

public void draw( Canvas c )
{
    Log.i("D", "COIN");
    coin.draw(c);
}

Draw Function For Coin :

public void draw( Canvas c )
{
     obstical.draw(c);
}

The on create function is :

protected void onCreate(Bundle savedInstanceState)
{
    player = new Player(this);
    //map = new Map(this, );
    WindowManager w = this.getWindowManager();
    Display d = w.getDefaultDisplay();

    float sy = d.getHeight()/800;
    float sx = d.getWidth()/480;

    super.onCreate(savedInstanceState);

    Intent intent = getIntent();
    String type = intent.getStringExtra(CUBEMenuActivity.EXTRA_MESSAGE);

    Log.i("MENU", type);

    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    //mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
    mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

       // Remove the title bar from the window.
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);

        // Make the windows into full screen mode.
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    map = new Map( this, type, sy, sx );

    canvasView = new CanvasSurfaceView(this, map, player, sx, sy );
    setContentView(canvasView);

    Log.i("C", "Canvas View Set");

}

i am using a canvasSurfaceView instead of an XML layout, the canvasSurfaceView constructor method is

public CanvasSurfaceView(Context context, Map map, Player player, float sx, float sy)
{
    super(context);
    holder = getHolder();

    gestures = new GestureDetector(new GestureListener(this));

    this.map = map;
    this.player = player;
    this.background = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.background1), 480, 10000, false);
    this.sx = sx;
    this.sy = sy;
}

when the game is running the run() method is called repeatedly this is where the canvas class is initialized

public void run()
{
    while( run == true )
    {
        if( !holder.getSurface().isValid() )
        {
            continue;
        }

        Canvas c = holder.lockCanvas();

        if( ( map.isWon || map.isLost ) && map.isStarted ) setCompleated();
        //c.scale(sx, sy);

        if( notCompleated == false )
        {

            if( map.map.bottomOfLevel != 800 ) by += player.terminalVelosity / 2;
            update();
        }
        c.drawBitmap(background, 0, by, null);
        map.draw(c, player.score);
        player.draw(c);

        holder.unlockCanvasAndPost(c);
    }
}

How could i make the canvas re-size to it would look the same on any screen ?

Cheers Daniel


texts:
Suppose a basic game with several circles drawn to screen. The user can select and drag any ball and move it around the screen. Should the selected ball overlap with any other ball on screen, the other ball should displace so they are no longer touching.

The example I've seen use the following structure:

for (every ball pair):
   if (collision = true){
   - resolve collision
  }

However, with this method, isn't there a risk that a displacement could cause an overlap in a pair already checked, and therefore the overlap printed to the screen?

Would it not be better to re-check every ball pair's collision, every time a ball is displaced, rather than every time-step?

Maybe something like:

for (every ball pair):
    if (collision = true){
      -resolve collision
         for (every ball pair):
            if (collision = true){
              - resolve collision
              }
       }

EDIT:

Even the method I've listed above shouldn't always provide 100% accurate results. The only way I can think this could work is with some sort of recursive function which only stops when there are no more collisions. Does that seem right?


texts:
Can someone provide some type of example of multiplying a 4x4 matrix without using loops?

typedef struct matrix4
{
    data[16];
} m4;

can someone provide a sample of how you you'd multiply two of these in the opengl column major way?


texts: In Unity C#, how can I change weapon a few frames later?

texts:
I have this Input code to change weapon:

if (d_left)
    {
        if (!p_d_left)
        {
            states.inventoryManager.ChangeWeaponToNextWeapon(true);
            p_d_left = true;
        }
    }
    if (d_right)
    {
        if (!p_d_right)
        {
            states.inventoryManager.ChangeWeaponToNextWeapon(false);
            p_d_right = true;
        }

And in the InventoryManager I have the weapon changed by this:

public void ChangeWeaponToNextWeapon(bool isLeft)
{
    if (isLeft)
    {
        if (l_index < r_l_weapons.Count - 1)
            l_index++;
        else
            l_index = 0;
        EquipWeapon(r_l_weapons[l_index], true);
    }
    else
    {
        if (r_index < r_r_weapons.Count - 1)
            r_index++;
        else
            r_index = 0;

        EquipWeapon(r_r_weapons[r_index]);
    }

    states.actionManager.UpdateActionsOneHanded();
}

Then equip the weapon along with animation and other stuff :

public void EquipWeapon(RuntimeWeapon w, bool isLeft = false)
{
    if (isLeft)
    {
        if (leftHandWeapon != null)
        {
            leftHandWeapon.weaponModel.SetActive(false);
        }

        leftHandWeapon = w;
    }
    else
    {
        if (rightHandWeapon != null)
        {
            rightHandWeapon.weaponModel.SetActive(false);
        }

        rightHandWeapon = w;
    }

    string targetIdle = w.instance.oh_idle;
    targetIdle += (isLeft) ? "_l" : "_r";
    states.anim.SetBool(StaticStrings.mirror, isLeft);
    states.anim.Play(StaticStrings.changeWeapon);
    states.anim.Play(targetIdle);

    UI.Slot uiSlot = UI.Slot.singleton;
    uiSlot.UpdateSlot(
        (isLeft) ?
        UI.QSlotType.lh : UI.QSlotType.rh, w.instance.icon);

    w.weaponModel.SetActive(true);
}

But the problem is the weapon changes immediately after pressing  the button. How can I switch my weapon a few frames later while playing the animation?


texts: Maintain Vuforia tracking during Unity Ad

texts:
My game uses Vuforia pos and ground plane tracking.

During gameplay players are given the option to watch a video to gain additional health.

When 'No' is chosen gameplay resumes fine. However when 'yes' is chosen Vuforia tracking is lost during the video and afterwards all gameobjects are locked in a static position in relation to the AR camera.

Is there anyway to maintain pos tracking during the video?


texts: Why are big files better than small files for consoles?

texts: Why do console game developers use large files to store game data instead of small files like on PC? Less streams in memory? Need to access file tree many times? Other reason?


texts: Is it possible to tilt the canvas and have entities react to it

texts:
I will try and explain this as simple as I can, let me know if you need more details and I'll edit the text.

Imagine a simple gravity-enabled 2D-game with a ball inside a room where the objective is to prevent the ball from hitting the walls of the room while the room itself is tilting from side to side. As a player you can control the ball left or right. The game is over when the ball hits one of the walls.

I have been trying to think of a way to have the ball (entity) react to the tilt of the room (canvas), specifically how to manage the acceleration, velocity and movement of the entity in respect to the tilt, but I haven't been able to find a suitable plugin or solution to this. Has anyone tried implementing this? How do you handle acceleration, velocity and movement, and would you implement the tilt in the canvas, a room entity or something else?


texts: What should I do when a VBO becomes too large in OpenGL?

texts:
Currently I have one buffer for my vertex data and one buffer for normals data. I fill them and then pass them to OpenGL for rendering.

The problem is when I load too large mesh file like "Lucy" from Stanford

The program stops responding or the computer freezes. I allocate my buffers like that:

Vector* vertData = new Vector[numVertices];
// then fill the array with data

where numVertices = 14 027 872 in this case. That allocation doesn't throw bad_alloc exception so I guess there is nothing wrong with the allocation of memory.

I am testing the program on a x64 windows 7 platform with 4GB RAM and GTX 470 which has 1280MB of memory. Windows task managers shows that the program uses about 2GB ram when I run it.

Note that when I choose to render not all the voxels of the mesh - every 2nd for example, then I have no problems.
Maybe the GPU runs out of memory and that's why the program hangs ?

Shoud I split my mesh data into more vertex/normal buffers and then pass them to OpenGL one at a time or there is a better way to do this ?


texts: OpenGL, fetching the names of all uniform blocks in your program

texts:
I want to auto-bind uniform blocks with certain named values to certain binding points when I compile a shader.  For example, I have some basic, default fixed binding points that are always used for certain things like:

0 Camera
1 Model
2 Material
3 Lights

At the moment I'm binding manually by finding the index of a named block with glGetUniformBlockIndex, and then binding it with glUniformBlockBinding.  What I'd like to do is fetch the set of all block names in my shader program.  When I iterate with glGetActiveUniformsiv, I get a list of all uniforms, which excludes block names.

Is there any way to do this without testing and failing each of my above names to see if it's an active block with glGetUniformBlockIndex?  There's no glGetActiveUniformBlocksiv, is there...


texts: Game speed on different devices isn't same

texts:
I have an app, in which I have constant int speed = 5; On each update, the game object (player) is moving 5px ahead. Problem is, that I can't handle that on different devices - older devices is having fx. 20fps (so 20 updates per second), and other one have 60fps. Then, my object is moving faster or slower, than it should.

I tried some screen width divisions, but didn't managed to work it.

I also tried to stick to some FPS (25) and skip frames if necessary. But on my tablet and phone, it just run on its own; it works like there isn't any frame skip code at all.


texts:
I have been trying to build a 2D skeletal animation system for a while, and I believe that I'm fairly close to finishing. Currently, I have the following data structures:

struct Bone {
    Bone *parent;
    int child_count;
    Bone **children;
    double x, y;
};

struct Vertex {
    double x, y;
    int bone_count;
    Bone **bones;
    double *weights;
};

struct Mesh {
    int vertex_count;
    Vertex **vertices;
    Vertex **tex_coords;
}

Bone->x and Bone->y are the coordinates of the end point of the Bone. The starting point is given by (bone->parent->x, bone->parent->y) or (0, 0). Each entity in the game has a Mesh, and Mesh->vertices is used as the bounding area for the entity. Mesh->tex_coords are texture coordinates. In the entity's update function, the position of the Bone is used to change the coordinates of the Vertices that are bound to it. Currently what I have is:

void Mesh_update(Mesh *mesh) {
    int i, j;
    double sx, sy;

    for (i = 0; i < vertex_count; i++) {
        if (mesh->vertices[i]->bone_count == 0) {
            continue;
        }

        sx, sy = 0;
        for (j = 0; j < mesh->vertices[i]->bone_count; j++) {
            sx += (/* ??? */) * mesh->vertices[i]->weights[j];
            sy += (/* ??? */) * mesh->vertices[i]->weights[j];
        }

        mesh->vertices[i]->x = sx;
        mesh->vertices[i]->y = sy;
    }
}

I think I have everything I need, I just don't know how to apply the transformations to the final mesh coordinates. What tranformations do I need here? Or is my approach just completely wrong?


texts: Fixing wave-like movements when rotating an object using mouse input in Unity

texts:
I have encountered a rather odd issue with my program.

The setup:

In my scene, I have a GameObject which I have set as my player/character for this game. The player/character has a child GameObject, which is a cube, which represents the head, and is a child via the hierarchy. It also has a body for the character(both of these are just children of the main children/character).

When I move the mouse, rotation of the head should follow where the mouse is(the mouse is hidden, so it relies on mouse input). If the movement around the y-axis is larger than a set amount, the body of the character should turn as well. I have this all working fine.

The problem occurs with the actual movement. In certain circumstances, it will create a wave-like movement, while still following the mouse

Ie. if I move the mouse vertically, then back to being "flat", then move it horizontally(without any y-movement), it will create a wave movement horizontally. The same occurs with the other rotation, where if I move the mouse horizontally first, then move it up and down, it will create a wave, but only in the up/down movement.

Gyazo for GIF demonstrating issue

In the GIF above, I move the mouse slightly upwards, then left and right. The "wave-like" movement can clearly be seen, as it moves to the left, and to the right.

This is my code:

void moveView()
{
    //This method is called every Update(), after a method that locks the cursor using
    //Cursor.lockState = CursorLockMode.Locked, then sets it to Cursor.visible = false;
    //Raw inputs, ySen and xSen are public floats.
    toRotOnY = Input.GetAxisRaw("Mouse X") * xSen;
    toRotOnX = Input.GetAxisRaw("Mouse Y") * ySen;
    //I think its here, but I'm not sure exactly what the *= operator does to Quaternions. Also, the init values are set in Start()
    targetRotHead *= Quaternion.Euler(-toRotOnX, toRotOnY, 0f);
    //The 0f in the Z feild is to lock rotation to x/y only.
    //Should body rotate to match head?
    if (this.transform.eulerAngles.y >= targetRotHead.eulerAngles.y + 10 || this.transform.eulerAngles.y <= targetRotHead.eulerAngles.y - 10)
    {
    //If the body should rotate, do it here
        this.transform.rotation = Quaternion.Slerp(this.transform.rotation, Quaternion.Euler(0f, targetRotHead.eulerAngles.y, 0f), moveSpeed);

    }
    //Rotate to the wanted rotation
    //moveSpeed is a float which dictates the smoothing.
    headWithCamera.transform.rotation = Quaternion.Lerp(headWithCamera.transform.rotation, Quaternion.Euler(targetRotHead.eulerAngles.x, targetRotHead.eulerAngles.y, 0f), moveSpeed);

}


texts: How to import Blender mesh+rig separately from animations for generic rigs in Unity?

texts:
Currently I'm creating mesh, rig and animations in Blender and export them together as an fbx file.
I know that importing animations separately works for humanoid meshes, but how to do this for  a generic rig?
 Why?
After importing a character, I have to add components to some bone game objects of the characters rig. Adding or changing animations of an already existing character currently requires me to reimport mesh+rig aswell as the animations and then add the components to those game objects again.
Also sometimes the reference of existing prefabs to the reimported mesh is lost and I have to add the mesh to those prefabs again, this might have been me doing somethin wrong though.

 Better solution?
I also thought about naming bones in blender in a certain way and have a script in Unity add these components, I would still prefer to import animations separately though.
Thank you in advance!


texts: Make the player run onto stairs smoothly

texts:
I have a 2D Platform game, where the player Always runs to the right, but the terrain isn't Always horizontal. Example:

I implemented a bounding-box collision system that just checks for intersections with player box and the other blocks, to stop player from running if you encounter a big block, so that you have to jump, but when I put stairs, I want him to run smoothly just like he is on the horizontal ground. With the collision system you have to jump the stairs in order to pass them!

I thought about generating a line between the edges of the stairs, and imposing the player movement on that line... What do you think? Is there something more clever to do?


texts:
I'm trying to make a driving game in Unity, but recently have been having lighting issues.

When I was first building it, the lighting worked fine. However, recently, one side of everything (the indirect lighting side) has turned black.

Here's an image of the issue.

I've tried changing my lighting settings, but can't seem to fix it. Here are my lighting settings.

What can I do to fix this? (I am using Unity 2017.2.0f3)


texts:
I have a sphere with tiles. I need to heck if tile is visible or not. See the image. Tiles are red squares, "screen" is represented by yellow quad.

Currently, I calculate coordinates of tile in spherical coordinates, convert them to Cartesian and project them from world to screen space. This works only partialy (the missing tiles are correctlly removed). However, this process has several false positives. For example tile in blue quad should not be visible, but its screen space bounding box overlap my virtual "yellow screen" => tile is visible.

How to solve this problem correctly?


texts:
I have 100 scenes, each scene has a camera, but I want only the camera from scene 1 to exist in each scene that I appear in.

I use the function DontDestroyOnLoad() to make the camera exist in each scene but I always find my self with another camera that I don't want.

Any ideas? thank you in advance.


texts: Execute code at specific intervals, only once?

texts:
I am having an issue with XNA, where I want to execute some code in my Update method, but only at a given interval, and only once. I would like to avoid booleans to check if I've already called it once, if possible.

My code is here:

    if ((gameTime.TotalGameTime.TotalMilliseconds % 500) == 0)
    {
        Caret.Visible = !Caret.Visible;
    }

As you may have guessed, it's for a TextBox control, to animate the caret between invisible and visible states. I just have reason to believe that it is called twice or maybe even 3 times in a single update-call, which is bad, and makes it look unstable and jumpy.


texts: How does transvoxel algorithm work and how can I implement It?

texts:
After wasting over three days of researching on DuckDuckGo/Google, trying to understand transvoxel paper and existing implementation, I come here to clarify the subject for me and made it easier for the next person who wants to implement it.

Here is the transvoxel's homepage which explains well what the algorithm solves. So now I'm happy to find something that solves my current problem, so I would like to implement it to my code, but the website doesn't explain how to implement it or sharing code (except tables). So I was looking for existing implementation of the transvoxel algorithm:

Transvoxel (XNA): Looks great but this solution all-in-one (octree, caching, voxel, etc.) I really tried to understand the transvoxel class into this one, but no.
Transvoxel (OGRE3D): Looks great too but again, all in one. I tried too to understand, I translated the code from C++ to C#, but no again.

Finding for marching cube was so easy, one class copy&paste, one public function.

So I gave up the idea to use existing implementation. Why not implementing it myself? (Sadly I don't have the skill to fully understand what the paper said, for example the ambiguous case).

The first thing I didn't understand was if transvoxel is a modified marching cube or a seconds layer that modify the work of the marching cube. In the C++ code (second link of the list) the code uses a implementation of marching cube and transvoxelize each border, on the paper they talk about 19x19x19 voxel data on 16x16x16 chunk and about a modified version of marching cube.

So do you guys can explain me how the transvoxel algorithm works and how can I implement it on my existing project?

My existing project is an Unity3D project which uses marching cubes for an infinite world, LOD chunk are ready, the only one thing missing is fixing crack between different LOD level chunk.


texts: I'm having some difficulties with Box2D DistanceJoints, I'm trying to create a rope using DistanceJoints connecting some bodies together but the length of joints between bodies change due to weight of bodies, is there any way to prevent joint lengths from changing?


texts:
I have a question in regards to using quaternions for the rotation of my graphics object.

I have a Transform class which has the following constructor with default parameters:

Transform(const glm::vec3& pos = glm::vec3(0.0), const glm::quat& rot = glm::quat(1.0, 0.0, 0.0, 0.0),
    const glm::vec3& scale = glm::vec3(1.0))
{
    m_pos = pos;
    m_rot = rot;
    m_scale = scale;
}

In my Transform class calculate the MVP as follows:

glm::mat4 Transform::GetModelMatrix() const
{
    glm::mat4 translate = glm::translate(glm::mat4(1.0), m_pos);
    glm::mat4 rotate = glm::mat4_cast(m_rot);
    glm::mat4 scale = glm::scale(glm::mat4(1.0), m_scale);

    return translate * rotate * scale;
}

The issue I'm facing is that when I use const glm::quat& rot = glm::quat(1.0, 0.0, 0.0, 0.0) my object appears normal on screen. The following image shows it:

However if I try to use for example const glm::quat& rot = glm::quat(glm::radians(90.0f), 0.0, 1.0, 0.0) (rotating on y axis by 90 degrees) my object appears as if it has been scaled. The following image shows it:

I can't figure out what is causing it to become like this when I try to rotate it. Am I missing something important?

If it's of any relevance, the following is how I calculate my view matrix:

glm::mat4 Camera::GetView() const
{
    glm::mat4 view = glm::lookAt(m_pos, m_pos + m_forward, m_up);

    return view;
}


texts: How can I do real-time mesh deformation?

texts:
I have a very simple problem: I have a icosphere mesh rendered with OpenGL and I want to deform/stretch it. But it has to be a real-time process because the deformation is generated when user drag'n drop a part of the mesh. The idea is to let the user models the shape like a ball of play dough.
I already tried the biharmonic deformation functionality of libigl. The results are good but the performances are terrible, far from real-time.
I also look into Bullet Physics and its soft bodies but it seems they are just elastic and return to their initial shape when you release them. I need to keep the deformed shape.
How do I  achieve this result? (I just thought of replacing my mesh with a group of rigid spheres stick together and spawning new spheres when user drag'n drop the 'volume' to extend it)
Thank for your help


texts:
I've recently been experimenting with a simple Voxel-based 3d engine (think Minecraft) which uses heightmaps to define terrain in the following format:

http://en.wikipedia.org/wiki/Heightmap

Does anyone know of the best software for producing these kind of maps? Preferably with the ability to define a texturemap also. Are terrogen and picogen the only real alternatives?


texts: What are the main reasons to use scripting in games?

texts:
I'm trying to understand the appeal to scripting in large games.

Is it ease of development by avoiding lower level coding like C++? Thus avoiding the long compile times?

It seems scripting doesn't often have the benefits of rich tools like IDE and debugger and requires an adaptation layer to expose the low level code to the scripting interface.

Is it to keep options for changing story line and game play until later in the process? If so, at some point the scripts must be compiled or encrypted to prevent tampering.


texts:
I've recently implemented shadow maps on my project.  However, I'd like to add a feature that allows the light direction to be dynamically changed, so that the terrain can be viewed using different light angles.  Unfortunately I'm struggling to understand how to do this, as I'm not sure how to 'fake' the position of the light to create a depth texture from.

Essentially, I want to mimic the sun and I'm having trouble getting my head around the fact that directional lights do not have a position, so how can I create a fake position to render the shadows from, while still keeping my scene in view of the orthographic projection.

I'm currently setting up my lights matrices in this way:

    mPosition = XMFLOAT3(-30.0f, 30.0f, -30.0f); //Bottom left corner
    mProjMatrix = XMMatrixOrthographicLH(400.0f, 120.0f, 1.0f, 1200.0f);
    XMFLOAT3 la3 = XMFLOAT3(126.0f, 0.0f, 126.0f); //Look at center
    XMFLOAT3 up3 = XMFLOAT3(0.0f, 1.0f, 0.0f);
    XMVECTOR eye = XMLoadFloat3(&mPosition), la = XMLoadFloat3(&la3), up = XMLoadFloat3(&up3);
    mViewMatrix = XMMatrixLookAtLH(eye, la, up);

    mViewProjMatrix = XMMatrixMultiply(mViewMatrix, mProjMatrix);

And you can find the pixel shader I use here.

Thank you very much for your time


texts: there is a BLOB standard to store images in memory?

texts:
I would like to abstract all the images in memory, to do so i would like to have just 1 format of reference without talking about the usual file formats for the filesystem like JPG, TGA, and so on.

I hear about BLOB in RGBA format but i don't get what is this format, RGBA for me is just a way to abstract color reproduction not a way to serialize image in memory. This also can be the case where one word "RGBA" is used for defining a more general concept and approach.

The possible explanation for me is that a BLOB in RGBA is just a matrix of pixels, but how is formed and what is the order that i'm supposed to use for reading them ? Technology like OpenGL can directly manage this BLOB ?


texts: Can applications using old versions of Opengl still run on newer cards?

texts:
OpenGl 3.0 and up has a quite big difference from the older versions like OpenGl 2.x and opengl 1.x in terms of implementation, does that mean applications which are written with the old versions of opengl won't run on computers having video cards supporting Opengl 3.x and up?

Sorry, if this is not the right place to ask this.

Thanks.


texts: Does anisotropic filtering need a previously generated mipmap?

texts:
I have a GPU which supports anisotropic filtering and a 1024x1024 soil texture. I would like to know, if I even need to create a mipmap when I am using anisotropic filtering or if I can just leave it out and only use anisotropic filtering.

I looked it up in some tuts and posts and each one had mipmapping enabled too, but they did not mention why.

I am not sure, but I think that I need a mipmap because I don't think that anisotropic filtering scales a texture from 1024x1024 to something like 512x512 or 256x256. Am I right?


texts: Most efficient way to detect and act upon collision (Specific for my 2d game)

texts:
Currently, mainly just for fun, I'm working on a 2d game where I have all collide-able blocks (background) assorted into an array when its loading, along with the player put into a different part of the 3d array. The player object gets put in with the AI array. It looks like this -->

    var world_objects = [
  [], //All 'background' collide-able objects. Such as stones and the border ~~ Code name: bg
  [], //All AI ~~ code name: ai
  []  //Projectiles ~~ Code name: ps
];

The map is set up into a bitmap that I've made using another 3d array, that currently is made into a 15x15, but that is subject to change. The brown border is included in the bitmap and world_objects array. And when the blocks/ai/projectiles are inserted, they all will have a basic object properties of:

x, y(2 variations, one with just normal x,y according to the exact pixel in the canvas, and the other is according to which cell its in for the bitmap)

Width, height (Both width and height for ai and projectiles are recorded as percentages according to the size of each cell, because the size is made to change depending on screen size)

Along with other properties not related to collision. What would be the most efficient way of detecting all objects and whether they collide or not? If needed, I could add additional properties to each object if that would make it easier and more efficient.

Click to see all of the code


texts: Webgl: is possible to use one color buffer to unsharp masking the depth buffer?

texts:
I'm noob to webgl. After reading the tutorials at webglfundamentals.org and "Introduction to Computer Graphics", i'm able to succesfully draw some stuff and the depth buffer without thirty-party libraries.

Now, i try to go a step further and apply some visual enhancement to my drawings, by usharp-masking the depth buffer, also called "the cheap SSAO".

What i understand is, that i should:

draw the depth buffer
blur X
blur Y
combine the blurred depth buffer with the diffuse component of the initial image

What i learned so far is, that to apply these four steps, i could use two textures, ping-pong back the textures, apply the effects in sequence to the textures and at the end draw to the screen the final result.

It would be easier with a gl.RGB4 color attachment?

It seems to me, that the final effect is just only to dim the diffuse color of the initial image, so i could draw the depth buffer to the red channel, blur-X the red channel to the green channel, blur-Y the green channel to the blue channel, and then combine this last with the initial drawing.

Isn't this faster or memory-cheaper than swapping two textures, for example by thinking mobile-first?

What are the drawbacks? Anyone already tried this? Thanks in advance


texts: 2D Circular View/Background Wrapping SDL for Game

texts:
In the games such as Defender (1980 arcade) and Defcon, the player can move/scroll in one direction infinitely because the level/terrain simply wraps over and over again(like if it was wrapped around the side of a cylinder).

I am more interested in the wrapping mechanics of Defcon which wrap(on the x-axis) and zoom the entire level. Here is a link to view the game.

To make images(such as a background) wrap is it a per-pixel approach? Is there a function? What methods are there to achieve the circular wrapping of a level?


texts: How to make the button rollover by a keyboardEvent

texts:
I'm designing a game calculator . My problem is how to link between the keyboard event and the button. **When I click no.2 button on my Keyboard the button doesn't roolover .
I want the exact button roolover wen I use the keyboard .

Note

every button have it's instance name
ex:
the button of number one : one_mc

my code is

switch (event.keyCode)
    {
    case 97 :
     res[1].appendText("1");
    break;
    case 98 :
     res[1].appendText("2");
    break;
    case 99 :
     res[1].appendText("3");
    break;
    case 100 :
     res[1].appendText("4");
    break;
    case 101 :
     res[1].appendText("5");
    break;
    case 102 :
     res[1].appendText("6");
    break;
    case 103 :
     res[1].appendText("7");
    break;
    case 104 :
     res[1].appendText("8");
    break;
    case 105 :
     res[1].appendText("9");
    break;
    case 96 :
     res[1].appendText("0");
    break;
    case 8 :
      res[1].replaceText(res[1].text.length-1,res[1].text.length,'');
    break;
    }


texts: Godot C++ NativeScript version not rendering multimesh instance whereas GDScript version does

texts:
I am new to Godot. I am aiming to create a RTS game with 10's of thousands of units and for it to run smoothly. So I'm looking to use GDNative C++ with the Visual Server to handle updating and moving the units and GDScript for everything else.
The following script in GDScript successfully renders a single multi mesh cube at the center of the screen.
extends Spatial

func _ready():

    var meshRid=preload('res://new_cubemesh.tres').get_rid()
    var multimesh = VisualServer.multimesh_create()

    VisualServer.multimesh_allocate(multimesh, 1, VisualServer.MULTIMESH_TRANSFORM_3D,
    VisualServer.MULTIMESH_COLOR_NONE, VisualServer.MULTIMESH_CUSTOM_DATA_FLOAT)
    VisualServer.multimesh_set_mesh(multimesh, meshRid)

    var instance = VisualServer.instance_create()
    var scenario = get_world().scenario

    VisualServer.instance_set_scenario(instance, scenario)
    VisualServer.instance_set_base(instance, multimesh)

I have implemented the alternative In GDNative (C++) and while it doesn't crash and does run the code, it does not render the cube. Camera is in correct position to observe the cube at 0,0. I've just re-purposed the GDNative C++ tutorial for now.
I really like the community here and the engine so far, so hopefully I am just misunderstanding something here and it is possible what I am trying to achieve.
Thank you for your time, c++ scripts below.
gdexample.cpp
#include "gdexample.h"

using namespace godot;

void GDExample::_register_methods() {
    register_method("_process", &GDExample::_process);
    register_method("_ready", &GDExample::_ready);
}

GDExample::GDExample() {
}

GDExample::~GDExample() {
    // add your cleanup here
}

void GDExample::_init() {
    // initialize any variables here
    base=5;
}

void GDExample::_ready(){

    visual = VisualServer::get_singleton();
    loader = ResourceLoader::get_singleton();

    Ref<Resource> meshResource = loader->load("res://new_cubemesh.tres");
    RID meshRid = meshResource->get_rid();

    multimesh = visual->multimesh_create();
    visual->multimesh_allocate(multimesh, 1, visual->MULTIMESH_TRANSFORM_3D, visual->MULTIMESH_COLOR_NONE, visual->MULTIMESH_CUSTOM_DATA_FLOAT);
    visual->multimesh_set_mesh(multimesh, meshRid);

    RID instance = visual->instance_create();

    Ref<World> world = get_world();
    RID scenario = world->get_scenario();

    visual->instance_set_scenario(instance, scenario);
    visual->instance_set_base(instance, multimesh);

}

void GDExample::_process(float delta) {
    return;
}

Let me know if you need gdexample.h or gdlibrary.cpp and I can add, the formatting gets messed up if I include them here for some reason. It's basically just the tutorial stuff though.


texts: OpenGL 2.0 - Texture animation with 'pixelated' effect

texts:
I'm looking for a way to reproduce the effect I've tried to sketch in the image below with OpenGL ES 2.0.

The idea is to let a drop of color fall over a cube which get filled with a kind of 'pixelated' effect.

Could you figure out any feasible solution to achieve it?

Thanks for any hint!

DAN

* EDIT WITH SOLUTION *

Achieving good looking results with a procedural texture generated in real-time is quite hard. Here's a few screenshots taken from an implementation based on Nathan's idea, where the mask has been created by hand.
Cheers!


texts:
So I have searched on google and various other websites but I've not found an answer. The only ones I did find did not work.

So my question is how do I get UV coords from blender (2.63)?

Currently I'm writing my own custom file exporter, and so far have managed to export vertices and their normals. Is there a way to export the UV coords?

N.B. I'm currently try to figure it out using a simple cube that is unwrapped and has a texture applied to it.


texts: Directx11 create Texture2D using subresourceData

texts:
I'm trying to create immutable texture in d3d11 so I want to use subresourceData, every tutorial on textures creates them with 2nd argument being null and after that updates subresource but I want to create it using the 2nd argument.
This code works:

hResult = m_device->CreateTexture2D(&textureDesc, NULL, &m_cubeTexture);
if (FAILED(hResult)) {
    return false;
}

int rowPitch = textureWidth * 4;
m_deviceContext->UpdateSubresource(m_cubeTexture, 0, NULL, &(decodedTexture[0]), rowPitch, rowPitch * textureHeight);

And this does not:

int rowPitch = textureWidth * 4;
D3D11_SUBRESOURCE_DATA tSData;
tSData.pSysMem = &(decodedTexture[0]);
tSData.SysMemPitch = rowPitch;
tSData.SysMemSlicePitch = rowPitch * textureHeight;

hResult = m_device->CreateTexture2D(&textureDesc, &tSData, &m_cubeTexture);
if (FAILED(hResult)) {
    return false;
}

DirectX11 debug layer outputs this:

D3D11 ERROR: ID3D11Device::CreateTexture2D: pInitialData[3].SysMemPitch cannot be 0 [ STATE_CREATION ERROR #100: CREATETEXTURE2D_INVALIDINITIALDATA]
D3D11 ERROR: ID3D11Device::CreateTexture2D: pInitialData[5].pSysMem cannot be NULL. [ STATE_CREATION ERROR #100: CREATETEXTURE2D_INVALIDINITIALDATA]

Which I don't understand since it's not even an array and texture array size is set to 1


texts:
I recently gave a build of my game to some people and asked for any thoughts.  One of the ones I keep getting is, 'I didn't know where to go first, but I guessed.'

The problem is, I'm still getting this after having revised NPC text to be clearer and more helpful to the player. The build in question is here, if you're curious to see what exactly I'm up to.

How can I make sure my NPC dialog is effective at guiding players to the next objective?


texts: Should SIMD be used by people who are new to game development?

texts:
I have been learning game development, using C++ and OpenGL, for about 4-5 months. Before that I used to program in C# and the .NET platform(about a year). So, I consider myself new to game engineering and software development as whole.

Recently I read about SIMD math. I found it interesting and started wondering if it was good to use it in my math library. But, considering that I have so much to learn and I haven't even laid the foundations of my knowledge of game development, should I explore it in depth and start using it? Or should I wait until I really start to need it?


texts: m_BoneMapping is undefined in OpenGL Step By Step Skeletal Animation Tutorial

texts: I am new to this website I was following this specific tutorial on skeletal animation and I have a good idea on what it is, but when I was following his implementation he used a variable called "m_BoneMapping" and which is undefined to me. What am I suppose to do?


texts: OpenGL Texture loaded but wont draw on Bind

texts:
I wrote my entire Texture loader by hand. I'm not using any Libraries. From what I gather the loading part is done correctly and stored in the texture class:

Texture* TGATextureLoader::create(const char *filename) {
        FILE *pFile;            // File pointer
        TGAHEADER tgaHeader;        // TGA file header
        unsigned long lImageSize;       // Size in bytes of image
        short sDepth;           // Pixel depth;
        GLbyte  *pBits = NULL;          // Pointer to bits

        // Default/Failed values
        GLint iWidth = 0;
        GLint iHeight = 0;
        GLenum eFormat = GL_BGR_EXT;
        GLint iComponents = GL_RGB8;

        // Attempt to open the fil
        pFile = fopen(filename, "rb");
        if(pFile == NULL)
            return NULL;

        // Read in header (binary)
        fread(&tgaHeader, 18/* sizeof(TGAHEADER)*/, 1, pFile);

        // Get width, height, and depth of texture
        iWidth = tgaHeader.width;
        iHeight = tgaHeader.height;
        sDepth = tgaHeader.bits / 8;

        // Put some validity checks here. Very simply, I only understand
        // or care about 8, 24, or 32 bit targa's.
        if(tgaHeader.bits != 8 && tgaHeader.bits != 24 && tgaHeader.bits != 32){
            return NULL;
        }

        // Calculate size of image buffer
        lImageSize = tgaHeader.width * tgaHeader.height * sDepth;

        // Allocate memory and check for success
        pBits = (GLbyte*)malloc(lImageSize * sizeof(GLbyte));
        if(pBits == NULL)
            return NULL;

        // Read in the bits
        // Check for read error. This should catch RLE or other
        // weird formats that I don't want to recognize
        if(fread(pBits, lImageSize, 1, pFile) != 1)
        {
            free(pBits);
            return NULL;
        }

        // Set OpenGL format expected
        switch(sDepth)
        {
        case 3:     // Most likely case
            eFormat = GL_BGR_EXT;
            iComponents = GL_RGB8;
            break;
        case 4:
            eFormat = GL_BGRA_EXT;
            iComponents = GL_RGBA8;
            break;
        case 1:
            eFormat = GL_LUMINANCE;
            iComponents = GL_LUMINANCE8;
            break;
        };

        // Done with File
        fclose(pFile);

        Texture* texture = new Texture(pBits);
        texture->setWidth(iWidth);
        texture->setHeight(iHeight);
        texture->setComponents(iComponents);
        texture->setFormat(eFormat);

        // Return pointer to image data
        return texture;
    }

Then when Im done, I call textureName->generateTexture() Method from the texture class:

void Texture::generateTexture(){
        GLuint id;
        glGenTextures(1, &id);
        this->textureID = id;
        std::cout << "Binding Texture\n";
        glBindTexture(GL_TEXTURE_2D, this->textureID);
        glTexImage2D(GL_TEXTURE_2D, 0, 3, this->width, this->height, 0, GL_RGB, GL_UNSIGNED_BYTE, this->data);
        glBindTexture(GL_TEXTURE_2D, 0);
        std::cout << this->textureID;
    }

Then in my initialization of the resources, I call;

textureName = Engine::TGATextureLoader::create("filePath/fileName.tga");
textureName->generateTexture();

lastly in my render method, I bind the texture again before I use it:

glBindTexture(GL_TEXTURE_2D, cubeTexture->getTextureID());
glBegin(GL_TRIANGLES);                      // Drawing Using Triangles
    glTexCoord2f(0.0f, 0.0f);
    //glColor3f(0.0f,0.0f,1.0f);
    glVertex3f( 0.0f, 1.0f, 0.0f);              // Top

    glTexCoord2f(1.0f, 0.0f);
    //glColor3f(1.0f,0.0f,0.0f);
    glVertex3f(-1.0f,-1.0f, 0.0f);              // Bottom Left

    glTexCoord2f(1.0f, 1.0f);
    //glColor3f(0.0f,1.0f,0.0f);
    glVertex3f( 1.0f,-1.0f, 0.0f);              // Bottom Right
glEnd();                            // Finished Drawing The Triangle

The texture doesn't render though. Is there something wrong with this code?


texts: Handling input from an ECS input system into actions in another system/actions on a entity?

texts:
Some background on my engine, each system stores a reference to an entity which has the relevant components for that system. For example movement system has only entities which possess position components, render system takes positions and textures etc.

I'm working on an Entity-Component-System Game Engine for a project and I've hit a bit of a brick-wall in regards to how I'm going to handle input for the entities. I'm unsure of how I would translate say a "W" press input into the movement of a single entity(the player)? I don't want to move the entity inside the input system. I'm unsure of how to go about taking input and getting it to result in a response.

This is my first question, if there's anyway I can improve it or if theres any additional information needed I'd be happy to oblige.


texts: unity Tilt Android Device player Freeze When Die

texts:
I attached tilt script to my Player to move player x and y Axis. Player have Rigidbody2D and also IsKinematic=true. but the problem when the player can Die i want to stop tilting and player goes down to ground.
here is my tilt Code

public float Speed=20f;
 void Update () {
  if (PlayerControll.instance.isAlive) {
   transform.Translate (Input.acceleration.x * Speed * Time.deltaTime, Input.acceleration.y * Speed * Time.deltaTime, 0);
  } else {
   PlayerControll.instance.PlayerRigidbody.isKinematic = false;
  }

I try to do that using disable tilt script when Player die and Iskinematic=false but the problem is player can freeze to his position not goes down to the ground. I do that so many way but not done so what i do don't know then i post the Question. thanks in advance.


texts: How can I generate random levels like in "Square it!" game?

texts:
In this game, you have a 2d field with some free squares and two colored squares which you can move but only together (they'll move only if the spot is still "free"). And you have to fill whole free space.

Here is a video that demos how the game is played.

How can I generate random game levels like in that game?


texts: How to generate texture coordinates for a rectangle?

texts:
I've got a function which generates geometry data for a rectangle. So far I've got the vertex, indices and the normals nailed, but I have no idea how to generate the texture coordinates - so far I've only used textures with imported 3d models, but now I want to generate my own rectangle on the fly and so need to generate the texcoords aswell.

So how do I make the texcoords? I am not sure how the mapping works.

bool CreateRectangleData(const float sizeX, const float sizeY, const float sizeZ, std::vector<float>& vertexData, std::vector<float>& normalData, std::vector<float>& texcoordData, std::vector<uint32_t>& indiceData)
{
    if (sizeX <= 0 || sizeY <= 0 || sizeZ <= 0)
        return false;

    const float X = sizeX / 2.0f;
    const float Y = sizeY / 2.0f;
    const float Z = sizeZ / 2.0f;

    float cubeVertices[] = {-X, -Y, -Z, -X, -Y, Z, X, -Y, Z,
                            X, -Y, -Z, -X, Y, -Z, -X, Y, Z,
                            X, Y, Z, X, Y, -Z, -X, -Y, -Z,
                            -X, Y, -Z, X, Y, -Z, X, -Y, -Z,
                            -X, -Y, Z, -X, Y, Z, X, Y, Z,
                            X, -Y, Z, -X, -Y, -Z, -X, -Y, Z,
                            -X, Y, Z, -X, Y, -Z, X, -Y, -Z,
                            X, -Y, Z, X, Y, Z, X, Y, -Z};

    float cubeNormals[] = {0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f,
                           0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
                           0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f,
                           0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f,
                           0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
                           0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
                           -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
                           1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f};

    float cubeTexCoords[] = {};  // ???

    uint32_t cubeIndices[] = {0, 2, 1, 0, 3, 2, 4, 5, 6,
                              4, 6, 7, 8, 9, 10, 8, 10, 11,
                              12, 15, 14, 12, 14, 13, 16, 17, 18,
                              16, 18, 19, 20, 23, 22, 20, 22, 21};

    vertexData.insert(vertexData.begin(), cubeVertices, cubeVertices + (sizeof(cubeVertices) / sizeof(float)));
    normalData.insert(normalData.begin(), cubeNormals, cubeNormals + (sizeof(cubeNormals) / sizeof(float)));
    texcoordData.insert(texcoordData.begin(), cubeTexCoords, cubeTexCoords + (sizeof(cubeTexCoords) / sizeof(float)));
    indiceData.insert(indiceData.begin(), cubeIndices, cubeIndices + (sizeof(cubeIndices) / sizeof(uint32_t)));

    return true;
}

Thanks


texts: Can I 'emulate' a device by booting its BIOS on my PC?

texts:
So for example let's take a SEGA Genesis (Mega Drive).

Let's say I have a usb Genesis cartridge loader with Sonic 1 plugged in. In that case, could I 'hardware emulate' a Genesis by booting a Genesis BIOS from USB (or any other way to boot a Genesis BIOS) and use that to play or mod Sonic 1, or develop & test home-brew games for the console?


texts: Slick2d font rendering makes all other drawings vanish

texts:
I'm converting a java game to lwjgl and slick-utils. I've followed the slick2d examples for font loading/rendering but I found that the font shows as a solid box of color unless I add the following glBlendFunc code:

GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
head_font.drawString( (float)(x + 20), (float)(y + 80), "Title Here", org.newdawn.slick.Color.green);
GL11.glDisable(GL11.GL_BLEND);

I've tried leaving this code as-is, I've tried leaving the blend function on, but any other drawing methods I have vanish when that blendFunc line is left in.

For example, here's a basic rectangle drawing method. The rect drawn here, only shows when I leave out the blend func. Is there a different blend func I need to constantly switch to?

GL11.glEnable(GL11.GL_BLEND);
GL11.glColor4f( r_f, g_f, b_f, a_f );
GL11.glRecti(x1, y1, x2, y2);
GL11.glEnd();
GL11.glDisable(GL11.GL_BLEND);

Update: Setting the blendFunc back to default values for the drawRect method I have works, but I'm not sure yet if it's the right solution.

GL11.glBlendFunc(GL11.GL_ONE, GL11.GL_ZERO);


texts: Collision Detection Between 3 or More Objects

texts:
Say I have a 2D grid of particles, and I wanted to find out if any of them were colliding. In my head I have come up with a system where you check every possible location for each particle in that 'tick' and see if there is a collision. But, I have found a problem with this system.
If I check each particle against every other particle, (or in a smaller grid, that's radius is the particle's velocity) then how would I check if 3 or more particles have collided? The issue is that the system will see two particles collide, then set their velocities accordingly, but what if there was another particle which was going to collide, but wasn't checked in time, so the system doesn't see any collision, and lets it 'tunnel'.


texts: Lookrotation of a gameObject in just one axis

texts:
So I am trying to orient a gameObject ( house in the picture below) which is nothing but a plane and has a 2d texture on it as you see below. The whole game is made on a hex sphere. I am using Orthographic camera projection for this game. I have oriented the house plane to the normal of the tile and rotated it by 90 degrees in x axis to begin with

cityDummy.transform.rotation = Quaternion.LookRotation(normal);
cityDummy.transform.Rotate(90, 0, 0);

Now I am trying to orient the house to make it look at the center ( blue capsule object in the image is the center point ) but I don't want to rotate it in all angles. Basically that is what LookRotation or LookAt does inside Unity. So after orienting the house with the normal, how do I make the house object look at the center and just rotate it in one axis that would be the y-axis in this case?

The reason why I need to do this is first of all I want to orient the house texture to the normal of the tile it gets placed on as you see in the image above. That works fine.

Now the next thing is we want them to face the south which is the blue capsule in the image above. So they would still be oriented like in the image below but the forward of the city should be facing south or towards the blue capsule. If I do LookAt it messes up the current orientation as it rotates in all axis. I would only want to rotate it on one axis and make it face the capsule


texts: Code reading difficulties with raycasting engine

texts:
I'm trying to teach myself to program some basic engines.  I've been following this tutorial: http://www.playfuljs.com/a-first-person-engine-in-265-lines/ to get a decent idea of a basic way to render objects.

I'm confused, though, about certain items.  I remember that in JavaScript, one must declare and define variables and objects, to me it doesn't seem like this programmer defines objects and methods like "column" and "step".  For example, when he tries to find a ray's angle, he has these three lines of code:

var x = column / this.resolution - 0.5;
var angle = Math.atan2(x, this.focalLength);
var ray = map.cast(player, player.direction + angle, this.range);

The problem is, I'm trying to connect the dots and see how he defines "column", "angle", and "ray" and how they fit into the code at large, but in his tutorial I don't see those definitions everywhere!  So I have no idea how this code seems to fit together.  Is there something I'm missing?  Some library or built-in stuff with Javascript?


texts:
To complete this question about the same color search algorithm, I would like to know if someone knows which is the best implementation for making other bubbles fall when they are no longer attached. More precisely, how can I detect islands of isolated bubbles.

My data structure is a NxM matrix.


texts: How do I create and implement a sprite sheet for my SFML game?

texts:
I have a game I am currently working on, and I have created 6 16 frame animations for my player character. Currently each of these are saved as seperate .jpg files, which are about 1.5x bigger than I want them to be in game. Each animation has a different size for the image, so I have 6 different image sizes. For example, here is the first frame for two different animations:

So I have 6x16 images in a folder, and I want to create a sprite sheet out of them, which I can use in my c++ SFML game. When I create a spritesheet, using a tool like texture packer, I have the sprites in all sorts of positions on a sprite sheet, and I don't know how I can the proceed to implement them in my game. How can implement them such that they
1) Keep in the same position relative to each other in the game
2) Have it so that the game knows the bounding box for the current image that I can use as both a hitbox for collision, as well as the rectangle the game displays the sprite for.

How can I achieve this? My guess is some sort of data file attached to the sprite sheet, but I dont know how to create one.

Additional info: Some images are duplicated, such as my idle frame 2 and idle frame 16. I would like to be able to only put one of those on the sprite sheet.


texts: Cocos2d: Using single timer/scheduler for multiple sprites

texts: want to know if is it possible to use single timer or scheduler method for multiple sprites ? Like I am now working on a game and there could be any number of sprites and i want to perform some actions on all of that sprites, So do I have to use as many timers or schedulers as sprites ? Or How can the job be done using only a single timer or scheduler ? What is I schedule a method and use it for, Say 10 sprites ? Will it affect the performance..?


texts: How can I check if the mouse hits a quad in 3d, and where it hits it?

texts:
I have a sketch that produces the following:

public void settings() {
  size(600, 600, P3D);
  pixelDensity(2);
}

float rot_y;

public void draw() {

  background(30);
  lights();
  float z = (float) ((height/2.0) / Math.tan(PI*30.0 / 180.0));
  translate(width/2, height/2, z);

  if (mouseX > width * 0.9) {
    rot_y += radians(0.5f);
  } else if (mouseX < width * 0.1) {
    rot_y -= radians(0.5f);
  }

  rotateY(rot_y);

  for (int i = 0; i < 8; i++) {
    pushMatrix();
    fill(255);
    rectMode(CENTER);
    rotateY(radians(45) * i);
    translate(0, 0, z);
    rect(0, 0, 400, 400);
    // how can I know it the mouseX, mouseY hits the rect?
    // and if so, also where it hit's the rect?
    popMatrix();
  }
}

Now I would like to know if the mouse is over the rect, and if so where the hit is on the rect is in x and y.

I have seen some topics about rays and quad detection and I found them hard to understand. Since I always have a quad that is basically a AABB but rotated in 3d and the mouse if always a ray coming straight out of the screen; I am hoping this would make a possible solution more easy.

Any help is welcome.


texts:
Is there a way to speed up script compile time when I change something in VS then click on Unity?

It takes 15 seconds. Is this normal?


texts: Start a progress bar when clicking a button

texts:
This is basically what i am trying to do:

Click first scene->Button
Start A Progress Bar
When the Progress Bar finishes, then...
Second Scene->instantiate my Game object

This is my code:

// First Scene
public class LoadingScreen : MonoBehaviour  //first scene script
{
    public GameObject slidercanvas;

    public void NextScene()
    {

        StartCoroutine(LoadNextLevel());
    }
    IEnumerator LoadNextLevel()
    {
        slidercanvas.SetActive(true);
        Slider s = slidercanvas.GetComponentInChildren<Slider>();
        AsyncOperation sceneLoading =SceneManager.LoadSceneAsync("ScrollGrids");

        while (!sceneLoading.isDone)
        {
            float progress = Mathf.Clamp01(sceneLoading.progress / 0.9f);
            s.value = progress;
            yield return null;

        }
   }

  //second scene

  public class ScrollGridScript : MonoBehaviour
  {
    public static ScrollGridScript Instance;
    public GameObject SpawnPrefab;
    GameObject newobj;
    public GameObject parent;
    Vector3 pos;
    string msgSpeech;
    int counter=0,totalVal;
    public List<GameObject> btns;
   //float progress;

    void Start()
    {
        btns = new List<GameObject>();
        StartCoroutine(Populate());
    }
    void Update()
    {
        if (totalVal==counter)
        {
            for (int i = 0; i < btns.Count; i++)
            {
                btns[i].SetActive(true);
            }
        }

    }
    IEnumerator Populate()
    {
        //code here(encoding jsonurl)
        StartCoroutine(Downloadimage(newobj, msgSpeech,tname));
        totalVal =  data["categorylist"].Count;
    }

    public void OnButtonclick(string imgname)
    {
        effector.Instance.setEffector(imgname);
        Debug.Log("ButtonId" + imgname);
    }

   IEnumerator Downloadimage(GameObject newobj, string imgUrl, string catid)
   {
      UnityWebRequest www = UnityWebRequestTexture.GetTexture(msgSpeech);

      DownloadHandler handle = www.downloadHandler;
      yield return www.SendWebRequest();

      Texture2D texture2d = DownloadHandlerTexture.GetContent(www);

      if (www.isHttpError || www.isNetworkError)
      {
            UnityEngine.Debug.Log("Error while Receiving: " + www.error);
      }
      else
      {
       counter++;
       newobj = (GameObject)Instantiate(SpawnPrefab, pos, Quaternion.identity);
       newobj.transform.SetParent(parent.transform);
       newobj.transform.localPosition = pos;
       newobj.GetComponent<Button>().onClick.AddListener(() =>
       OnButtonclick(catid));
       Image sprite = newobj.transform.GetComponent<Image>();
       sprite.sprite = Sprite.Create(texture2d, new Rect(0, 0, texture2d.width,
       texture2d.height), new Vector2(0, 0)); //fetch the images from the serve
       //and convert it
       newobj.SetActive(false);
       btns.Add(newobj);  // instantiate object store in list
    }
}

And here is the output I see when I run this code:


texts: Digital Speedometer wrong update - Unity

texts:
Hi I am making a digital speedometer and I want it to change like a normal meter like: if speed is 10 on meter and the new speed is 50 it does not just show 50 on text instead gradually increase it.

here is what I have done:

    int speed;
    int textSpeed;
    int speedfinal;

    public Text text;

    // Update is called once per frame
    void Update()
    {
        speed = GameObject.Find("gamePlayManager").GetComponent<gamePlayManagerScript>().userSpeed;
        textSpeed = int.Parse(text.text);

        speedfinal = (int)Mathf.Lerp(textSpeed, speed, 0.1f);

        text.text = speedfinal.ToString();
    }

I am not sure if lerp is a good choice here to change text but that is what I know but it is adding 9 less then the orignal speed. Any idea how to do this. thanks.


texts: Should I switch to UDP for a mobile p2p game when considering 3G network?

texts:
I have been making a mobile game that is similar to "Street Fighter" where two players play with each other via Internet.

The game sends out a small packet (controller status) to the other party every 30ms (a lot of packets going on).

I am currently using a server to connect two players and all communications are via TCP through the server. The server load increases a lot even for just 30 concurrent players. I know it sounds not wise to let the communication go through the server, so I think the best design should let these two players to communicate directly via UDP after the server hooks them up.

However, I have some questions when trying to move on to the new design:

Since it's a mobile game, players might be using 3G network a lot. Does UDP hole punching work well in 3G network? Does it matter when a player is actually moving physically (such as inside a car)? Do you think I should change the design or any recommendation of better design concepts?


texts: How to create normal map from bump map in runtime?

texts:
I am using this port of libnoise to generate noise. There are several methods (Noise2D.cs, 462 and 494 line) to output images. Second one, that should give me normal map does not work completely, it outputs this with low intensity (1.0f)

And this with high intensity (>100);

So i decided to use grayscale and default Bumped Diffuse shader works good, but only in Editor.

How should i modify grayscale image for correct normal map? How should i use library in proper way?


texts: Best practices for periodically saving game state to disk

texts:
I'm working on an MMO. All of the player and environment data lives on a server and is kept in memory. There's a "world" object which keeps track of all of the maps, characters, etc. and their relations to each other.

To avoid data loss in case of a crash, I've been periodically serializing the world to disk. The trouble is, this object can be quite large, so when the server starts writing, there's noticeable in-game slowdown for a few seconds, which I'd like to avoid.

Any pointers on how to go about this in a more efficient way?


texts:
I'm currently doing some pathfinding research and my simulation is the following:
I have a 3d scene with a start and end point represented, I'm capable of creating navigational meshes, waypoints and polygons to aid with pathfinding.

I've tried an A* algorithm and some of its variants and they work perfectly.
However, now I'm more interested in 'dynamic' pathfinding.
For example, while finding a path from point A to point B, if a new obstacle suddenly appears, i want my algorithm to immediately be able to re-plan a path and not start searching from scratch again.

I've done some reading on the D* algorithm and wondering if this would be appropriate for what I need or would this seem like an overkill.

So my questions basically are:
What algorithm would be best for Real Time Dynamic Pathfinding?
OR what combination of techniques could I use instead?


texts: How to compress repetitive information when uploading mesh data?

texts:
I want to avoid sending repetitive information when drawing a mesh.

If I use a single point for each face and two vectors as additional attributes that represent the travel of each vertex, I can use that information in a Geometry Shader to produce the normal and the two points followed by any additional attributes for that face.

Is the computation cost worth the saved data needing to be transferred? Or is there a better way to optimize the pipeline for sending over a mesh to draw?

Edit:
In particular this is a case where the mesh has attributes unique to the face and not the vertex, so if it were done the regular way each vertex would be multiplied by the number of faces used by it.


texts:
Update:

I am getting slightly better results by modifying the shader so that it sets a flag on entering a obscured region, and then only sets the fragment to black if the ray casting exits the obscured region. The bordering light is a little less noticeable this way. Additionally objects behind other objects will now be correctly obscured as long as they are not touching.

However as you can see in the image, I have noticed a new problem. The shadow becomes very choppy at the back due to the way I am doing raycasting.

Original:

I am currently trying to render shadows in a 2d game. I use the following shader to do so:

#version 120
varying vec2 vTexCoord;

uniform vec3 u_lightColor;
uniform sampler2D u_texture;

float drawShadow(){
    vec2 loc;
    vec2 norm = normalize(vTexCoord - vec2(.5,.5)); // Pointing from center to point
    vec4 smp;

    float dst = 0.0;

    // For now draw all casters
    if(texture2D(u_texture, vTexCoord - dst * norm).a > 0)
        return 1.0;

    for(int i = 0; i < 256; i++){
        loc = vTexCoord - dst * norm;

        if (length(loc-vec2(.5,.5)) < 1.0/256.0)
            break;

        smp = texture2D(u_texture, loc);

        if(smp.a > 0){
            return 0.0;
        }

        dst += 1.0/256.0;
    }

    return 1.0;
}

void main() {
    float dist = length(vec2(.5,.5) - vTexCoord.xy);

    float shad = drawShadow();

    float intensity = 1-dist*2.0;

    gl_FragColor = vec4(u_lightColor, 1.0)*vec4(shad*vec3(intensity), shad);
}

The light is being rendered at the center of the screen, and the texture being drawn is one where any shadow caster is drawn as a non transparent sprite.

The trouble is because of the way I am sending out the rays I end up with the following:

Where the shadows don't hug the edges of the sprites. Also, I would like to somehow obscure shadow casters if they are in the shadow of another shadow caster, but not if they are the first caster the light hits.


texts: Is there a reason to keep maps in memory?

texts:
I've noticed for a long time that games (mostly FPSes) do not unload the map when the user has finished with it (aka, disconnecting from servers, server changing maps).

The result of this is that the maps are kept in memory, which can lead to colossal memory usage in the region of 5GB for a 2 hour session of CoD:Black Ops 2 or around 8GB for a session of the same time of Crysis Wars.

Games most notable for this behaviour (that I've noticed) are the Crysis series and Call of Duty: Black Ops 2.

I've noticed this for years, but now as I am 'upgrading' Crysis Wars (fixing bugs, adding features, and porting it to my new multiplayer network) I have been able to unload maps when the game is done with them. As a result after two hours of playing the memory usage has dropped from an average of 8GB to just 2GB (I jumped between servers a few times when testing this out).

Is keeping maps in memory when the game doesn't need them anymore a bug, or is it purposeful? This 'memory-leak' exists in other Crysis games and also the Call of Duty series (also on consoles, although I'm not certain of this), so it seems to be purposeful rather than a bug.

I've also had a look at what is actually kept around after disconnecting from a server, and it seems that all entities are left behind but the terrain and hightmaps are removed. A similar thing probably happens with CoD:BO2 where I've also observed this.

Obviously I wouldn't want to purge the map from memory if there was a reason behind it, but however I've noticed no adverse effects so far in Crysis Wars.


texts: UE4 Multiplayer how to replicate Player name in lobby

texts:
I've been working on a little 1V1 snipper project to try and get a better grip on the replication and the game framework of unreal engine.

So after the core gameplay, I'm trying to make a lobby system. I've been able to make the player join together without any issues, but I struggle a little bit with the replication. I'm trying to show the player's name over their pawn in the lobby, and I can't get it to work. In the client, both their name doesn't get replicated, and in the server, only the server name appear:

And I get this error from the server logs

[2020.01.21-00.45.03:318][906]PIE: Error: Only Local Player Controllers can be assigned to widgets. BP_PlayerLobbyController_C_1 is not a Local Player Controller.
[2020.01.21-00.45.03:321][906]LogScript: Warning: Accessed None trying to read property CallFunc_Create_ReturnValue
        BP_PlayerLobbyController_C /Game/Maps/Lobby.Lobby:PersistentLevel.BP_PlayerLobbyController_C_1
        Function /Game/Player/Controller/BP_PlayerLobbyController.BP_PlayerLobbyController_C:ExecuteUbergraph_BP_PlayerLobbyController:0049
[2020.01.21-00.45.03:323][906]LogScript: Warning: Script call stack:
        Function /Game/Player/Controller/BP_PlayerLobbyController.BP_PlayerLobbyController_C:ReceiveBeginPlay
        Function /Game/Player/Controller/BP_PlayerLobbyController.BP_PlayerLobbyController_C:ExecuteUbergraph_BP_PlayerLobbyController

[2020.01.21-00.45.03:325][906]LogOnlineSession: Warning: OSS: No game present to join for session (GameSession)
[2020.01.21-00.45.03:326][906]LogTemp: POST LOGIN FOR
[2020.01.21-00.45.03:331][906]LogScript: Warning: Accessed None trying to read property CallFunc_GetController_ReturnValue
        BP_Character_Lobby_C /Game/Maps/Lobby.Lobby:PersistentLevel.BP_Character_Lobby_C_1
        Function /Game/Player/Character/BP_Character_Lobby.BP_Character_Lobby_C:Display Player Name:00CC
[2020.01.21-00.45.03:333][906]LogScript: Warning: Script call stack:
        Function /Game/Player/Character/BP_Character_Lobby.BP_Character_Lobby_C:ReceiveBeginPlay
        Function /Game/Player/Character/BP_Character_Lobby.BP_Character_Lobby_C:ExecuteUbergraph_BP_Character_Lobby
        Function /Game/Player/Character/BP_Character_Lobby.BP_Character_Lobby_C:Display Player Name

[2020.01.21-00.45.03:335][906]LogScript: Warning: Accessed None
        BP_Character_Lobby_C /Game/Maps/Lobby.Lobby:PersistentLevel.BP_Character_Lobby_C_1
        Function /Game/Player/Character/BP_Character_Lobby.BP_Character_Lobby_C:Display Player Name:00E1
[2020.01.21-00.45.03:337][906]LogScript: Warning: Script call stack:
        Function /Game/Player/Character/BP_Character_Lobby.BP_Character_Lobby_C:ReceiveBeginPlay
        Function /Game/Player/Character/BP_Character_Lobby.BP_Character_Lobby_C:ExecuteUbergraph_BP_Character_Lobby
        Function /Game/Player/Character/BP_Character_Lobby.BP_Character_Lobby_C:Display Player Name

So I get that something is wrong with accessing the 2nd player controller from bluprint like this

But I don't know how to make it work other wise. I've set the PlayerName widget to replicated, but it doesn't seem to work.

Any idea on how I could get this to work?


texts:
i'm trying to limit maximum rotation angle and i do not know how to do that.. i am using this code currently, how can i limit maximum rotation angle of object?

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

public class rotObj : MonoBehaviour {

    void Update () {
        var dir = Camera.main.ScreenToWorldPoint (Input.mousePosition) - transform.position;
        var angle = Mathf.Atan2 (dir.y, dir.x) * Mathf.Rad2Deg;
        var rot = Quaternion.AngleAxis (angle, Vector3.forward);
        transform.rotation = rot;
    }

}


texts:
I'm thinking of writing a MIDI system for my game that would take in an instrument and a note, then play a sound.

Considering so many rhythm games have already been made, I am curious as to how others have tackled this issue, so I might learn what things they considered in making a better system.

To be clear, I am not asking for opinions of 'which way is better', but rather, 'what have others done?'


texts:
I have an enemy attack script that when a raycast hits the player it deals damage to the player, however the enemy attacks at multiple times per second and I wish for the enemy to have to wait 1 second after it attacks the player before it can attack again. The script is here, the main focal point is the void update(). Any help is appreciated, let me know if I've missed out any needed details. :)
public class DamagePlayer : MonoBehaviour
{
    int attackDamage = 10;

    [SerializeField]
    float agroRange;

    [SerializeField]
    Transform castPoint;

    Rigidbody2D rb2d;

    bool isFacingLeft;

    // Start is called before the first frame update
    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();

    }

    bool CanSeePlayer(float distance)
    {
        bool val = false;
        float castDist = distance;

        if (isFacingLeft == true)
        {
            castDist = -distance;
        }

        Vector2 endPos = castPoint.position + Vector3.right * castDist;
        RaycastHit2D hit = Physics2D.Linecast(castPoint.position, endPos, 1 << LayerMask.NameToLayer("Action"));

        if (hit.collider != null)
        {
            if (hit.collider.gameObject.CompareTag("Player"))
            {
                val = true;

            }
            else
            {
                val = false;
            }

            Debug.DrawLine(castPoint.position, endPos, Color.red);
        }
        else
        {
            Debug.DrawLine(castPoint.position, endPos, Color.green);
        }

        return val;
    }

    // Update is called once per frame
    void Update()
    {
        if (CanSeePlayer(agroRange))
        {
            PlayerHealth.currentHealth -= attackDamage;
            //Debug.Log("can see player");
        }
        else
        {

        }
    }
}


texts: How can I show a texture in a separate window in an XNA game?

texts:
I'm playing around with random map generation and what I want to do is:

Input a command to generate a random map.
A texture will be created resembling the generation, each pixel resembling each tile.
A new window will pop-up, without removing the original one, that will contain the texture.

I know how to do this except for the last part. Would someone please tell me how to create a new window and draw a texture to this window?


texts: How do I save and load settings on the Xbox?

texts: I'm using XNA 4.0. How can I load and save settings when on the Xbox? And can I write to and read from files?


texts: In A star, what is the point of recalculating the best path?

texts:
In A* after the finding the next node with the lowest F value, you have to search the adjacent nodes again. When you find a node that was already in the open list, you're supposed to check if the g score for that node would be lower if you went through the current node to get there. My question is, what is the point of this? Won't it always be the same? If you take G = 14 for diagonal and G = 10 for horizontal/vertical wouldn't the G always be more if you went through 2 nodes instead of one?

Say the last node on the closed list's G value was 50. It has an adjacent square to the right with a G value of 60. Your current node has a G value of 64. If you went through the current node to get to the node adjacent to the one with the G value of 50, the G would be 74. You could switch the numbers all you want but the recalculated G would always be higher so what is the point of recalculating it?


texts:
What I've Done

I created a Cube object with Subdivision Surface modifier in order
to model a spehere.
I created a cuboid object looking like a angled, longish baton.

What I Want to Do
I want to merge these two objects. So I want to have got just one object - a (cube locking like a) sphere with a baton sticking out on one side. It should look a bit like a head with a throat attached at the bottom.
How I Want to Do It

I don't want to apply the Subdivision Surface modifier - I want to be
able to edit my object later on nicely.
I don't want to have any space between the baton and the sphere. It should be coherent.
It should be possible without any bad artifices. Everything should be nice.

My Question
How can I merge these two objects nicely? Thanks. - I hope it's clear what I want to describe.


texts: What i'm missing in this multiplayer Unity / photon code?

texts:
i'm having some troubles in my first, simple, multiplayer racing game, using Photon and Unity.
Following classic photon tutorial i've written the code below, but, it won't work properly.
In particular there are any smooth movement and "other" player car continue to appear and disapper... maybe i could post a video.

void Update() {
if (gsAppSettings.gameType == Enumerators.GameType.MultiPlayer) {
            if (pv.isMine) {    //pv is PhotonView
                GetPlayerInput ();
                WeaponsManagement ();
            } else {
                SyncMovement ();
            }
        }
        else if (gsAppSettings.gameType == Enumerators.GameType.SinglePlayer) {
            GetPlayerInput ();
            WeaponsManagement ();
        }
}
void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
    {
        if (stream.isWriting) {
            if (photonView.isMine) {
                stream.SendNext (transform.position);
                stream.SendNext (transform.rotation);
                stream.SendNext (rb.velocity);
            }
        } else {
            correctPlayerPos = (Vector3)stream.ReceiveNext();
            correctPlayerRot = (Quaternion)stream.ReceiveNext();
            currentVelocity = (Vector3)stream.ReceiveNext();
            updateTime = Time.time;
        }
    }

private void SyncMovement() {
        Vector3 projectedPosition = this.correctPlayerPos + currentVelocity * (Time.time - updateTime);
        transform.position = Vector3.Lerp (transform.position, projectedPosition, Time.deltaTime * 4);
        transform.rotation = Quaternion.Lerp (transform.rotation, this.correctPlayerRot, Time.deltaTime * 4);
    }

EDIT: This is video. As you can see, the low car is "flipping" up and down
https://www.youtube.com/watch?v=QKpYl7C5rl0&feature=youtu.be


texts: Handling Latency in Multiplayer Shoot-em-ups

texts:
I had an idea for an architecture, and I was wondering if anyone has implemented something like this or has used AWS or some other service to help?

I thought about using NodeJS + SocketIO to handle a server side for this cooperative shmup (think Raiden or Galaga) we are just starting to work on. We started to think about latency issues.

The solution I came up with was to spin-up/down servers at the mid-point of the 2 users playing with some epsilon value (say 300miles or something). Perhaps the server would allow up to 50 users to play simultaneously and after that it would deny requests, which would then spring up another server. This should cause latency to be about equal for the 2 users playing. Furthermore, if we are matching making users then we always pair the 2 closest users together.

I suppose there are other factors to consider like user skill level, but I think right now we are most concerned about latency since it directly affects gameplay. Actually our game does require fairly precise timing. Also we want users to be able to see each other shoot since cool animations happen when they are in sync with each other.

I suppose this is similar to how a fighting game might operate in terms of timing/precision.

Ideas? Thoughts? How have others approached this problem? Where can I start looking for examples?


texts: XNA 2D - How to switch to a new sprite upon collision and delete itself

texts:
Let's say I have a 2D spaceship that shoots at moving rocks. If a bullet intersects one of the rocks' bounding boxes, that rock will animate according to a new spritesheet and remove itself.

My question is this: How can I load the new animated rock (breaking apart) onto the screen upon colliding with the bullet?


texts: Java single Array best choice for accessing pixels for manipulation?

texts:
I am just watching this tutorial https://www.youtube.com/watch?v=HwUnMy_pR6A and the guy (who seems to be pretty competent) is using a single array to store and access the pixels of his to-be-rendered image.

I was wondering if this really is the best way to do this. The alternative of Multi-Array does have one pointer more, but Arrays do have an O(1) for accessing each index and calculating the index in a single array seems to take one addition and one multiplication operation per pixel.

And if Multi-Arrays really are bad, can't you use something with Hashing to avoid those addition and multiplication operations?

EDIT: here is his code...

public class Screen {
private int width, height;
public int[] pixels;

public Screen(int width, int height) {
    this.width = width;
    this.height = height;

    // creating array the size of one index/int for every pixel
    // single array has better performance than multi-array
    pixels = new int[width * height];
}

public void render() {
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            pixels[x + y * width] = 0xff00ff;
        }
    }
}
}


texts: How should IDs be assigned in an entity component system?

texts: I haven't actually implemented this system yet. I'm trying to work through the major conceptual hurdles before I actually start writing code, and the proper way to generate IDs is a little confusing to me. Should I just give each entity an integer ID in the order that it's created? Use the C# guid? What is the proper way to assign IDs in such a way that there won't be issues later on?


texts: Unity's LODs by distance to the orthographic camera

texts:
I'm trying to do something that I thought was simple, but seemingly it's not that easy.

I understand that Unity's LOD system works by refering to a percentage of screen size that objects occupy. That's not fit for the isometric 3D game I'm trying to make.

I'd like to have my LODs match the distance from the orthographic camera, as perceived from the viewer. Or, to put it otherwise, that the LODs are set according to their distance from the plane of the camera (and not the camera object itself) multiplied by the orthographic factor. Thus, when the ortho camera zooms out, all objects should swap LODs at the same time.

Is there a simple (or less simple) way to do that ?

Thanks


texts: Getting into the details of game engine programming

texts:
I am interested in learning game programming, but I really have an interest in the lower level engineering in games. I have OpenGL experience, and I am really interested in learning more about implementing AI, Physics, etc. I have a computer science degree, so I really like getting into technical stuff.

Many times when I ask about this sort of thing, I get a lot of "Use an engine", "Use Unity3d", "Why waste your time writing code that already exists", etc, etc. My idea was to use simpler libraries such as SFML or XNA so that I could learn how to implement the more complex systems.

The thing is, although I do want to write games, I want to learn things that using something like Unity simply doesn't teach you. My goal is not to make a current generation quality 3D game to sell, I just want to make some cool smaller games and learn all I can about the programming side of game development.

Is this something that people just do not do anymore?

It seems like everywhere I turn people are using Unity or UDK or GameMaker. I fully understand why you would use a tool like these, but I cant see how they would suit my purposes.

So where does someone like myself turn? Am I trying to learn something that people just do not bother doing anymore? Is the innovation in this area gone and just all about gameplay now?

I'm sorry if this question seems silly, but I am genuinely interested in knowing more about this and meeting more people who are interested in this sort of thing.


texts: I am trying to create this in my editor window but not sure how. Basically a drop down arrow, next to a C# icon, next to a toggle, next to a Label with a cog at the end


texts:
I have 2 objects One Having a Transformation Matrix T1 and other Having Transformation Matrix T2. And We are having a View Matrix V and Projection Matrix P.
Basically 2 Object are render using this function

Render(vec3 position,X Rotation , Y Rotation, Z Rotation, Scaling);

So i am having 2 different T1 and T2 transformation matrix.

How should i find the distance between these 2 objects ?
Please Explain ?
I have tried by simple formula using position vector but it is giving me incorrect distance ?


texts: ECS - Stats, damage-types & damage calculation

texts:
Prologue
Im quite new to data oriented programming and my goal is to implement a runescape stats & damage mechanic.

This is quite a pretty complex topic : [Runescape-Mechanics][1] and i havent found any ECS related sources on that topic yet.

In the following example we see a bunch of items which modify the weares stats based on a few conditions.
This happens in two different variants, either for the damage calculation only, or as a buff.
Brine sabre and Brackish blade increase damage against crabs.
or
Silverlight and Darklight increase ability damage by a scaling of 25-124% against most demons. The exact damage bonus is based on your base Attack and Strength, and the monster's base Defence.

The problem
Such a RPG system is very complex. There different damage types, different resistences and other stats.
Having a strong OOP background and no real experience in DOP, i cant find a suitable architecture to fill those needs.
In my current approach every stat is a component. Items and Buffs are structs. A item "buffs" its owner and the buff modifies his stats. This works so far, but i have no idea how i could realise the damage calculation, while still keeping it that flexible as it is in runescape.
This little example would just be able to buff the stats... not deal, receive or modify the damage itself.

// The stats

public struct Health{
  float max;
  float value;
}

public struct MeeleDamage{
  float base;
  float value;
}

public struct MeeleResistence{
  float base;
  float value;
}

// Item & Buffs
public struct Item{
  string name;
  int amount;
  bool equipable;
  List<Buff> buffs;
}

public struct Buff{
  string name;
  float duration;
  Condition applyable;
  ToBuff stat;
  float value;
}

Its also important that an entity can also deal damage to multiple other entities in one frame.
How would you implement such an complex mechanic ? Any examples are appreciated !


texts: How can I efficiently store tilemaps in work memory?

texts:
I've been working on different tile-based projects, but never really bothered with being efficient memory-wise. Each tile was represented by a tile class which would hold the following:

X and Y ID of the tile
Solid boolean
Events for entities when leaving or entering a tile
Graphic data
Size

But especially now, when using a component based system where everything is an entity (which has some base functionality which already takes some memory), I've started to run into memory issues.

I started looking at existing tile engines and noticed that a lot of them don't even have a tile class, but just use an array of integers. I figured you could just use the index of the array for position and the actual integer value for the graphics.

But how would store the other data for this tile? With the events for example, would save them externally from the array or something? This would mean that you would need to have a list for every property you want to save, which sounds like a pain in the ass.

It might be good to know how they would have handled this on a more limited platform, let's say the SNES?


texts: In Socket.IO, should I use JSON for communication between server and client?

texts:
I'm building an MMO with Socket.IO and Node.js. It works quite fast (though I don't have 1000 players yet) but my feeling is that it's not very optimized. JSON is super cool and easy to use within Socket.IO but when I see a broadcast from the server (1 player connected):

   debug - websocket writing 5:::{"name":"snapshot","args":[{"players":[{"id":1,
"tx":-5.62,"y":23.74,"tz":-5.64,"tRotY":0,"tSpeed":0}]}]}

I take it all the variable name are broadcast as well. Isn't that a huge overhead? Wouldn't it be better if I glued all data together using delimiters like this?

1;-5.62;23.74;-5.64;0;0

The disadvantage here would be that I have to split the string each time I receive it. But isn't that much better for latency?


texts: How do I detect and handle collisions using a tile property with Slick2D?

texts:
I am trying to set up collision detection in Slick2D based on a tilemap. I currently have two layers on the maps I'm using, a background layer, and a collision layer. The collision layer has a tile with a 'blocked' property, painted over the areas the player can't walk on. I have looked through the Slick documentation, but do not understand how to read a tile property and use it as a flag for collision detection.

My method of 'moving' the player is somewhat different, and might affect how collisions are handled. Instead of updating the player's location on the window, the player always stays in the same spot, updating the x and y the map is rendered at. I am working on collisions with objects by restricting the player's movement when its hitbox intersects an object's hitbox. The code for the player hitting the right side of an object, for example, would look like this:

if(Player.bounds.intersects(object.bounds)&&(Player.x<=(object.x+object.width+0.5))&&Player.isMovingLeft){
        isInCollision=true;
        level.moveMapRight();
    }
    else if(Player.bounds.intersects(object.bounds)&&(Player.x<=(object.x+object.width+0.5))&&Player.isMovingRight){
        isInCollision=true;
        level.moveMapRight();
    }
    else if(Player.bounds.intersects(object.bounds)&&(Player.x<=(object.x+object.width+0.5))&&Player.isMovingUp){
        isInCollision=true;
        level.moveMapRight();
    }
    else if(Player.bounds.intersects(object.bounds)&&(Player.x<=(object.x+object.width+0.5))&&Player.isMovingDown){
        isInCollision=true;
        level.moveMapRight();
    }

and in the level's update code:

if(!Player.isInCollision)
        Player.manageMovementInput(map, i);

However, this method still has some errors. For example, when hitting the object from the right, the player will move up and to the left, clipping through the object and becoming stuck inside its hitbox. If there is a more effective way of handling this, any advice would be greatly appreciated.


texts: How do I find out where a script is attached to in Unity?

texts:
I'm using Unity 2017.03.0f3 and I have a scripts folder with scripts (C#).

Suppose I forget, or am working on someone else's project:

How do I know exactly which scripts are attached to what GameObjects or PreFabs, without clicking and going through all the Hierarchy objects please, and by first clicking on a script in the Project view?

I hope that's specific enough.


texts:
I have a content size fitter on the content within the scroll view. However the content size fitter is over double the height needed and when scolling there is a large blank space at the bottom on the content that keeps scrolling.

I have tried to change all the settings but nothing has made it shrink and fit the content.


texts:
I cannot understand why the coroutines are not waiting the designated number of seconds before executing the code below it. At the moment, the animation bleeds into the next state. I could get around this by using .time and if statements but I thought the whole point of coroutines is that you can avoid that sort of mess.

         public IEnumerator LoadBow()
     {
         this.gameObject.GetComponent<Animation>().CrossFade("Load_Bow");
         yield return new WaitForSeconds(this.gameObject.GetComponent<Animation>()["Load_Bow"].length);
         aimStates = AimStates.Draw;
     }

     public IEnumerator DrawBow()
     {
         this.gameObject.GetComponent<Animation>().CrossFade("Draw_Bow");
         yield return new WaitForSeconds(this.gameObject.GetComponent<Animation>()["Draw_Bow"].length);
         aimStates = AimStates.Aim;
     }

     public void Aiming()
     {
         moveTarget.SetActive(false);
         switch(aimStates)
         {
             case AimStates.Load:
                 StartCoroutine(LoadBow());
             break;

             case AimStates.Draw:
                 StartCoroutine(DrawBow());
             break;


texts: How should I resolve saved game(cloud saved progress) conflict with local game progress?

texts:
I am using play game services and decided to create a small progress manager which will protect user progress. Now consider this, Player launches the game and sign in to cloud service (play game services or whatever) and sign out by mistake or intentionally. Then make some good progress as a guest player and then later choses to sign in to loud again. Should I overwrite local progress (with more coins and scores) with cloud or do vice versa? I am confused. What should I do?

The solution I came up with to ask user if they want to overwrite the data or save the current local progress to cloud but this seems more ui work and user might find it less like a game and more like a boring software.(no offence to them).

Thanks.


texts: How to interpolate a height-map with normals

texts:
My Task

I want to interpolate a heightmap by using the normal of each nearby point of the heightmap which is calculated before. When having 4 Points before i gonna have 9 points after it. ( See this question to get a image of it how it's working ).

My Approach

I want to interpolate the height of two points by using the normal of them. To do this i need the tangent of both. When having the tangents i want to interpolate this way:

float resultHeight = Interpolate(TangentVector0, TangentVector1, 0.5f);

public float Interpolate(float p0, float p1, float amount)
{
    amount = Math.Sin(x* Math.PI - Math.PI/2) / 2 + 0.5;
    // Move vectors along tangents
    p0 = p0 * (amount - 1f);
    p1 = p1 * amount;
    return (p0 + p1) / 2f;
}

Problem ( Question )

I'm a little bit stuck with the math behind. How to i get the tangent of the x or z axis when having a 3D normal.


texts: Prevent rendering queue from overflowing when using Vsync

texts:
My game loop currently looks something like this:

while (!quit) {
    takeInput(); // Input is sampled however fast loop can run

    time_now = get_time()
    time_passed += (time_now - time_prev);
    time_prev = time_now;

    while (time_passed > SOME_TIME) {
        update(); // Update is done over fixed time-step for determinism
        time_passed -= SOME_TIME_STEP; // This time step is less than or equal to SOME_TIME
    }
    render(time_passed); // Render using interpolation from previously updated position and velocity
}

Basically, I take input as fast as I can, run the movement and physics only in discreet chunks of time after certain period and interpolate the difference in the renderer. The renderer is set to draw at Vsync (using SDL_GL_SetSwapInterval(-1)) and currently, the value of SOME_TIME is set so that update() runs at half of display's refresh frequency (but with a minimum bound of SOME_TIME_STEP which is set to 5 millisecond).

The problem is that I am running the renderer as fast as I can which is submitting frames continuously. Because I am currently loading a test level, the game loop is basically finishing up in a few microseconds (unless there is something wrong with how I am calculating time too). As far as I understand, my program will submit frames to the driver way faster than it is going to draw (because of Vsync) and this should lead to some type of periodic locking up/lagging.

So my question is, how to I prevent this? Should I put the render call in a time bound loop too just like update()? Should I call sleep() manually instead of relying on graphics driver for Vsync?