texts:
This might be really simple but it is giving me a lot grief and I wondered if you guys would be able to shed some light on it. Basically I have a tile map which draws tiles at 64 * 64 and that works very well and they are drawn in a 2D array like this in the game1 class.

TileMap tileMap = new TileMap(new int[,]
    {
        { 2,2,2,2,2,2,2,2,2,2 },
        { 2,2,2,2,2,2,2,2,2,2 },
        { 0,0,0,0,0,0,4,4,4,4 },
        { 0,0,0,0,0,0,1,1,4,4 },
        { 1,1,1,1,1,1,1,1,1,1,},
        { 1,1,1,1,1,1,1,1,1,1,}
    });

Now comes the problem. Basically I want to determine which side the player has hit the tile from. However, with the algorithm below the collision only works correctly for the bottom and left side. if the player hits the tile from the top it will state it was hit from the bottom. if the player hits from the right it will specify the left side was hit. if the player hits from the left or bottom it will show that collision has happened but state it happened on the right or top of it. it will output that the top of the has been hit but only when the player is completely in the tile like this

.

Pretty much the same thing happens when it displays the right side is hit (player moves more to the left)

TileMap

int left = (int)Math.Floor((float)player.playerBounds.Left / TILE_WIDTH);
        int top = (int)Math.Floor((float)player.playerBounds.Top / TILE_HEIGHT);
        int right = (int)Math.Ceiling((float)player.playerBounds.Right / TILE_WIDTH) - 1;
        int bottom = (int)Math.Ceiling((float)player.playerBounds.Bottom / TILE_HEIGHT) - 1;

        Rectangle tileBounds = new Rectangle((int)tilePosX, (int)tilePosY, TILE_WIDTH, TILE_HEIGHT);
        Rectangle playerBounds = player.playerBounds;

        float WidthOfRects = 0.5f * playerBounds.Width + tileBounds.Width;
        float heightOfRects = 0.5f * playerBounds.Height + tileBounds.Height;

        int centerX = (playerBounds.Left + playerBounds.Width / 2) - (tileBounds.Left + tileBounds.Width / 2);
        int centerY = (playerBounds.Top + playerBounds.Height / 2) - (tileBounds.Top + tileBounds.Height / 2);

        for (int y = top; y <= bottom; ++y)
        {
            for (int x = left; x <= right; ++x)
            {

                if (mapCell[y, x].TileID == 1)
                {
                    //minkowski sum
                    if (Math.Abs(centerX) <= WidthOfRects && Math.Abs(centerY) <= heightOfRects)
                    {
                        double wy = WidthOfRects * centerY;
                        double hx = heightOfRects * centerX;
                        if (wy > hx)
                        {
                            if (wy > -hx)
                            {
                                Console.WriteLine("bottom");
                                //newPos.Y = tileCollision.Bottom;
                            }
                            else
                            {
                                Console.WriteLine("right");
                                //newPos.X = tileCollision.Right;

                            }
                        }
                        if (wy > -hx)
                        {
                            Console.WriteLine("left ");
                            //newPos.X = tileCollision.Left - playerBounds.Width;
                        }
                        else
                        {
                            Console.WriteLine("top");
                            //newPos.Y = tileCollision.Top - playerBounds.Height;
                        }
                    }
                    // player.Position = newPos;
                }
            }
        }

Map Cell

public class MapCell
{

    public int TileID { get; set; }

    public MapCell(int tileID)
    {
        TileID = tileID;
    }

Any help would be greatly appreciated.

Thank you.


texts: What are the usual tools for importing models and animations?

texts:
I'm a total noob with regard to game programming (though not a noob to programming) and I'm using pygame + opengl to do some experiments with a little game I've been thinking of.

I've been trying to import OBJ files into my pygame OpenGL "game", but there's apparently different formats of OBJ files, and writing a loader is a fairly nontrivial process. At least from my experience, which is not too large.

So I guess my question is: What do people generally use in the industry to read 3d model files? What about animation? Is there a place I can look into to understand?

Thanks,
Marcelo.


texts:
I just imported latest Google VR SDK into Unity and made a simple scene that has only Main Camera, plane, and single zombie just standing there with T-Pose.

In Main Camera, I added GvrPointerPhysicsRayer component, and it has GvrReticlePointer as child object.

Running in Unity Editor seems fine but when I build and run, whole world is just flipped.

I can't find any related issues about this anywhere, and struggle with this almost a day.

Why camera flipped and how do I fix it? What am I missing?

Using Unity 2019.1.0f2 and gvr-unity-sdk@1.200. Any advice will very appreciate it.

P.S. I saw the warning message in project settings - default orientation:

  Virtual Reality Support is enabled. Upon entering VR mode, landscape left orientation will be the default orientation unless only landscape right is available.

This message never disappear whatever default orientation selected.


texts: How can I create an efficient bloom shader with GLSL?

texts:
I have searched the net for resources related to rendering a bloom effect using GLSL, but haven't found anything. Although the tutorial at Philip Rideout's website is a good one, it performs very poorly on my Nvidia GPU.

Can anyone guide me as to how should I approach this problem and build a fairly efficient implementation of a bloom effect?


texts: Can't change the textures of a .FBX or an .X exported from 3dsmax

texts:
I created a model (real simple) in 3DSMax 2010, exported it to FBX format and loaded it in an XNA 4.0 content project. I also tried with .X files using kW X-port and it has the same behavior.

I can load the model in a game, and it has it's 3DSMax texture. I can't however change the texture of a face (or all) at runtime. When I do this, it doesn't crash or anything, it just doesn't apply the textures.

I've tried with a sample model from a microsoft creative tutorial (the famous spaceship one) and on that model, with my texture, it works. This is why I think my model isn't working properly.

Anyone care to comment/help?

Note: Even though I don't think the problem is there since I've made it work with another model, here is my LoadContent method to load the model and change the texture of all mesh :

protected override void LoadContent()
{
    base.LoadContent();

    ContentManager contentManager = new ContentManager(Game.Services, "Content");

    Model = (Model)contentManager.Load<Model>(ModelName);
    Texture = (Texture2D)contentManager.Load<Texture2D>(TextureName);

    foreach (ModelMesh mesh in Model.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.Texture = Texture;
        }
    }
}


texts: How do I run LibGDX's Particle Editor in Netbeans?

texts:
I am trying to run the Particle Editor that comes with LibGDX in Netbeans.  The gdx-tools-1.9.10.jar file shows up in my dependencies, and I can see all of the packages and class files inside it:

Normally, when I want to run a file, I open the file by double-clicking it in the "Projects" panel, right click anywhere in the file, and then click the "Run File" option.  However, when I use the same process to try to run a class file in gdx-tools, the "Run File" option appears to be grayed out:

I have also tried using the Shift+F6 shortcut, with no effect.  Just as a sanity check, I did also make sure that the class file I am trying to run has a main method:

I have also tried running the Particle Editor from the command line (I'm using Windows).  I navigated to the gdx-tools directory using the following command:
cd C:\Users\<user>\.gradle\caches\modules-2\files-2.1\com.badlogicgames.gdx\gdx-tools\1.9.10\<hash>

I then tried to run the Particle Editor using the following command:
java -cp gdx-tools-1.9.10.jar com.badlogic.gdx.tools.particleeditor.ParticleEditor.class

And the result is simply:
Error: Could not find or load main class com.badlogic.gdx.tools.particleeditor.ParticleEditor.class

How do I run the Particle Editor?  I would prefer to be able to run it in Netbeans, but I would be happy to get it to run at all.  I am using LibGDX 1.9.10, Netbeans 8.2, and Java (JDK and JRE) 8u111 on Windows 10.  I installed LibGDX using their setup app found here.


texts: How to calculate the reachable space of the end effector in an IK chain?

texts:
I have an array of points in a 2d worldspace and I want to calculate which points are reachable by the end effector of a limb controlled with a CCDIK chain (with rotation limits applied).

It's a limb with 2 hinges (upper arm & lower arm)
The upper & lower arm have a fixed length
The 2 hinges have fixed rotation limits
This needs to be recalculated every update (continuously) as the limb is attached to a moving body
I work in Unity using C#

Crude Illustration of the problem:

My idea sofar is to create a polygon collider along the outer edges of the reachable space, and then look if the points are within the bounds of that collider. But I have no idea if this is the smartest solution, or if so, how to achieve this.

How could I solve this issue?


texts: I am new to Unity. Now I am working with FPS camera. While pressing a key down arrow I want my camera to go down and again it come back to normal position. I am not getting any idea how to do it. Anyone, please help.


texts:
Basically, my game has the player's attack hitbox change based on the attack being performed. I tried to make a simple collision test that takes an enemy's coordinates and have it check to see if it's within the range of the player. I don't want to resort to using Sprites and use hitTest() since efficiency is an issue. Anyway, the problem lies in the fact that the function below always returns true (even when the player is nowhere near the enemy).

private function quickHitTest(boxLeft:int, boxRight:int, boxTop:int, boxBottom:int, rangeWidth:int, rangeHeight:int):Boolean

return ((boxLeft > (300 - (rangeWidth/2)) && (boxBottom > (450 + (rangeHeight / 2)) || boxTop < (450 - (rangeHeight / 2)))) || (boxRight < (300 + (rangeWidth/2)) && (boxBottom > (450 + (rangeHeight / 2)) || boxTop < (450 - (rangeHeight / 2)))));

I having difficulties finding the source of the problem. All help is appreciated.


texts:
The following is a copy of our post in Unity Forum (https://forum.unity.com/threads/missing-references-in-built-bundles.1103689/)
Hello,
We have a bundle for our scenes and another one to store our prefabs (actually we have around 10 bundles but let's keep it simple). In every scene we have unpacked prefab instances. We have no problem in playmode using the AssetDatabase but once we use built addressables some unpacked prefab instances in our scenes are broken. Sprites and / or scripts are missing in a inconsistent way; in some scenes those objects are fine and sometime they are not. This comes along multiple warning messages "The referenced script (Unknown) on this Behaviour is missing! ".
Note that the issue also happens when we fully deploy our player.
Unity version : 20193.3.13
Addressables version : 1.16.1

Solution 1 : We tried to remove addressable prefabs (A,B,C in the diagram) from their bundle since we don't really have to instantiate them at runtime for now and it worked.
Solution 2 : We also tried to put scenes and prefabs into the same bundle and it worked too.
Solution 3 : Switch to 1.18.2 and 1.15.1 version of addressable package and it didn't work.
Solution 4 : Finally we tried to use the Duplicate Bundles Dependencies analyzer multiple times in order to have no more issues of this type and it didn't work.
Questions 1: As far as we understand, when addressable groups are built, Unity computes all dependencies and build them inside the bundle along the orignal assets (in my diagram "Scenes" bundles is packed with D'). What we don't understand is why having our prefabs in a separated bundle break references link in the scenes. Our guess is that Unity doesn't know which version of those dependencies to use (the one in the scene bundle or the one in the prefab bundle) and somehow fails to load them properly.
Question 2 : Is splitting our content is a good approach, we did it mostly for visibility but it appears to be more a problem in the long term, what are your guidelines regarding this matter ?
Question 3 : Why Duplicate Bundle Dependency rule has to be processed multiple times to properly fix every issue ? We think that running this rule creates duplication issues itself but we can't really tell..
Thanks.


texts: How to fix the vibration while colliding?

texts:
I'm making a 2D platformer with Unity. My game has a problem:
The player vibrates when it collides with something. It seems like it's spinning or flipping very quickly. I used transform.position in my code before but because of some kind of vibration I changed it to AddForce but still I have that problem.
Thank you in advance.
   using System.Collections;
   using System.Collections.Generic;
   using UnityEngine;
   using UnityEngine.InputSystem;

   public class PlayerController : MonoBehaviour
   {

   [SerializeField] private float jumpSpeed;

    public float maxSpeed = 5f;
    public float maxAcceleration = 50f;
    public float maxDeceleration = 100f;

    [SerializeField] private LayerMask ground;
    private PlayerActionControls playerActionControls;
    private Rigidbody2D rb;
    private PolygonCollider2D pol;
    private Animator animator;
    private Vector2 movementInput;

    private void Awake()
    {
        playerActionControls = new PlayerActionControls();
        rb = GetComponent<Rigidbody2D>();
        pol = GetComponent<PolygonCollider2D>();
        animator = GetComponent<Animator>();
    }

    private void OnEnable()
    {
        playerActionControls.Enable();
    }

    private void OnDisable()
    {
        playerActionControls.Disable();
    }

    void Start()
    {
        playerActionControls.Land.Jump.performed += ctx => Jump(ctx.ReadValue<float>());
    }

    private void Jump(float val)
    {
        if (val == 1 && IsGrounded())
        {
            rb.AddForce(new Vector2(0, jumpSpeed), ForceMode2D.Impulse);

        }
    }
    private bool IsGrounded()
    {

        Vector2 topLeftPoint = transform.position;
        topLeftPoint.x -= pol.bounds.extents.x;
        topLeftPoint.y += pol.bounds.extents.y;

        Vector2 bottomRightPoint = transform.position;
        bottomRightPoint.x += pol.bounds.extents.x;
        bottomRightPoint.y -= pol.bounds.extents.y;

        return Physics2D.OverlapArea(topLeftPoint, bottomRightPoint, ground);
    }
    void FixedUpdate()
    {

        Vector2 movementInput = playerActionControls.Land.Move.ReadValue<Vector2>();

        movementInput = Vector2.ClampMagnitude(movementInput, 1f);

        Vector2 DesiredVelocity = movementInput * maxSpeed;
        AccelerateTo(DesiredVelocity);

        var scale = transform.localScale;

        if(scale.x * rb.velocity.x < 0) {
        scale.x *= -1;
        transform.localScale = scale;
    }

    void AccelerateTo(Vector2 desiredVelocity) {

       var deltaV = desiredVelocity - rb.velocity;
       var acceleration = deltaV / Time.deltaTime;
       float limit = maxAcceleration;

    if (Vector3.Dot(rb.velocity, desiredVelocity) <= 0f)
       limit = maxDeceleration;
       acceleration = Vector2.ClampMagnitude(acceleration, limit);
       Vector2 force = rb.mass * acceleration;
       rb.AddForce(force);
   }
 }
}


texts: Should I bother merging faces in my 3D block-based game?

texts:
Okay, so I have a bunch of cubes in a 3d-world. I already implemented face culling, so that when a cube is next to another cube, their touching faces won't be drawn, or even sent to the buffer. However, a while back when I was still researching how to make a 3d block-based game, I came across a stack overflow question where the asker posted an image of their cubes, which had not only been culled but they had also merged the faces of adjacent cubes into larger rectangular faces. Like this:

My question is, should I do this? Will the drawing time be saved enough to justify the longer update time? And if so, I'm not even sure if it would work some of the time. The cubes aren't textured, they're coloured, so I'm not entirely sure if it would work with multiple colours of cubes.


texts:
I am currently trying to look into techniques that allow the calculation of arbitrary cross-sections of a 3D object or rendered volume. However, I have been unable to find much on the topic. I know of some software packages, such as the SolidWorks CAD package, that employ such techniques; as seen here:

Does anyone know of any available methods, techniques, algorithms, or tutorials that aim to achieve this result? Also, in terms of the theory of this technique and the concept of calculating it on the fly; how performant is such a technique likely to be?


texts: Efficient vertex buffer memory management?

texts:
I am building a voxel engine with a similar mechanism to minecraft(yes, I know...).
It works by loading and unloading individual chunks of 16*64*16 cubes each in a square grid around the player. This works fine for small render distances - like a 9x9 square grid of chunks. However, since updating a single vertex buffer entirely with a new mesh of millions of blocks each time a chunk is loaded/unloaded is inefficient, I have designed it so that each chunk has its own VB of fixed size, and rendering the entire world is basically looping through all the buffers, using d3dDeviceContext->IASetVertexBuffers(...).

When I increase the render distance, say to a square grid of 11x11 (around minecraft's large render distance), creating the vertex buffers simply cannot proceed beyond a certain point, and d3dDevice->CreateBuffer() returns E_OUTOFMEMORY.

So my question is: How do i manage the memory usage of the vertices, to both maintain good FPS (not using a single buffer for the entire terrain) and to have decent memory usage?

Additional Details:
My vertex datatype is a struct composed of x,y,z coords, u,v texture coords and 3 normal coords. I know it can be improved in ways like a single byte for normals, since in voxels there are only 6 possible directions, however this will come later.

The fixed size of each chunk's vertex buffer is 16*16*64*18 vertices (16*16*64 blocks with a maximum of half of the sides showing, or 36/2 vertices max per block). This could also use some work, as each of these buffers is around 10MB.

How do games like minecraft handle this amount of data at once? (not to say i am using 64 blocks high chunks, where minecraft has 256)
I have briefly considered using points as vertex shader inputs and expanding them to cubes in the geometry shader, to save 87.5% of the space, but this seems rather intense on the GPU.


texts: New Unity version copies the settings of previous version

texts:
I use Ubuntu 20.04.
When I download a new version of Unity 3D through Unity Hub, this new version automatically takes the settings of the previous version. I have installed Unity 2020.1, and I am facing the same problem. I created a new project, but it written in 2020.1 that I used preview package. I didn't even installed any package in Unity 2020.1. I did install preview package in 2019.4. But I didn't even open the project with 2020.1. I only have one project with 2020.1. The new project I just created. I asking help because I faced this issue when I first installed 2019.1, 2019.2, etc.
How can I flx it? Thanks


texts: Determining relative velocities on impact?

texts:
I'm trying to figure out a way to determine the relative velocity of a body colliding with another in a 2D environment.

For example if one body is moving at (1,0) and another traveling behind it collides with it from behind at (2,0) the velocity of the impact relative to the first body was (1,0).

I need a method which takes in two velocities, one velocity belonging to the body the velocity is being measured against, and the other for the impacting body and return the relative velocity.


texts: In the libgdx wiki, this particle editor is recommended. And this blog was helpful. But the problem is that I am not sure yet how to use it for my game. Let's say I want to have a fire-effect in my game. How can I get help for this particle editor?


texts: Keyframing or programmatically changing attachment transparency in Spine

texts:
I've just recently been getting to grips with Spine and Unity 2D, porting some
of my assets from different sources (SWFs, SVGs, GIFs, Canvas animations).
Whilst I'm able to reproduce a lot of what I can do in these other systems
— very nicely I might add — one thing that seems to be alluding me
is how to animate an attachment.

Obviously Spine is still developing, so I don't expect to be able to run
full bitmap/vector animations as attachments; but one thing the software does
seem to have already is the ability to set transparency, and to set multiple
attachments to one slot. I was hoping someone out there would know if these
abilities can be combined to at least achieve a faded switch between attachments
— either using the GUI or via coding.

For example, this video shows my
character animated with the two states I wish to switch between.

I'm aware that you can key frame a switch between attachments, but this leads to
a sudden jump in what graphic is shown. I could theoretically create
8 extra attachments on each slot and set their opacity graduating from 0.1 to
0.8 — but this seems like a rather hack way of doing things, and would
also be awkward to shift along the timeline.

My fallback would be to animate the two full states of the character, export them, and leave Unity to handle switching from one to the other.

Any ideas?


texts: Canvas Element Not Render In Proper Position

texts: I don't know what's going wrong. The Text and Slider must be on the red square area. Anyone can help to determine this bug ? Thanks


texts: C++ SFML: Font is clear and the other time blurred

texts:
This is my code.

    TextRenderer->setString(pCurrentUnit->getCHAR()->getNAME());
    TextRenderer->setCharacterSize(16);
    TextSanitizer::CenterOrigin(TextRenderer);
    TextRenderer->setPosition(108, 34);
    pWindow->draw(*TextRenderer);

    TextRenderer->setString(pCurrentUnit->getCLASS()->GetNAME());
    TextSanitizer::CenterOrigin(TextRenderer);
    TextRenderer->setPosition(242, 34);
    pWindow->draw(*TextRenderer);

The font draws perfectly fine with certain texts and other times its really blurry. I've read on the SFML Forum it had something to do with non-rounded positions but mine are already int's.

Is there any way to fix this? It also doesn't matter if I draw the second text first, it's the string it displays that causes the blurriness.

EDIT: It's not the font, I've tested about 10 other fonts and all of them get screwed up in one way or another when below 20px.


texts:
I believe it's a common requirement of MMOs that processing for a single shard or realm can be done over several servers to ease the load. I'm curious as to how this can be done whilst maintaining a unified consistent world where all the players, and all the NPCs can interact.

My question is how is load balancing achieved in MMOs?

Any links, books or general information on how to improve my knowledge on this subject is also appreciated.


texts:
I am building a simple turn-based game in node.js using sockets.io. My web experience with node.js has typically involved saving everything to a relational database. I set this up for my game. I am using sqlite3 for development and I might use something like PostgreSQL or MySQL for production. I will be doing this for account information regardless of what I set up for handling the actual game.

My concern is that, every time an event is emitted from the socket the whole game-state is loaded into memory from the server. I feel that in practice this will be less efficient than just keeping all of the gamestate data in memory. Events will probably be emitted every 5 seconds or so. A gamestate consists of a set of about 120 groups of small strings and integers (about 10 per group but subject to change).

Is it good practice to keep this type of data in memory?

Should I stick with relational databases?

Should I switch to a third option like a file-based storage structure?

Should I not load the whole gamestate in for every event even though that will lead to a lot more read/writes (at least triple)?

Edit* Clarification: Even though the game is turn based I want the player to be able to see what the opponent is doing on their turn in real time and give the player real time feedback about illegal actions.


texts: When should I decide what language and platforms I will use for a project?

texts:
During your development process, when is the recommended phase to decide what platform to aim for, and what language to use?

I figured that it would be better to choose at the beginning what would be your target platform, as it would affect your design decisions, and limit the language you are supposed to use.

However, I have heard several stories of people developing their game with whatever language they were the most confident with, and then porting it to the various platforms.

So, what is the best moment to choose? Before, during, after? If there is not one best choice, what factors should affect the decision?


texts:
I saw there are quite a number of articles and sample code regarding ball bouncing within a rectangle.

Is there any articles or sample code regarding ball bouncing within a polygon? I try to look into Box2D demo, I can't find one yet.


texts: I'm currently planning a simple online multiplayer game. And here is the question. Does it make sense to make the whole game logic on the server and just send the input from the client to the server? Which are the pros and the cons or are there any reasons why I shouldn't do that?


texts:
im trying to destroy a single game object using the following script but it destroys all of them , not the ones I want. I want to destroy the ones that the transform that holds this script collides with.

It's a 2D unity3d game btw.

The script :

var keys : List.<Transform>;

function OnTriggerEnter2D(coll : Collider2D)
{
    for(var i = 0; i < keys.Count; i++)
    {
        Destroy (keys[i].gameObject);
    }
}

I hope I was clear enough , don't hesitate to ask any questions.

Thank you for your time.


texts:
I'm using the Douglas peucker (DP) algorithm to simplify some (2d) closed paths forming a shape. This works pretty good, but not so much for closed paths that have some symmetry. Take for example a pyramid like shape, with the slopes essentially being staircases. Depending where you define the start for DP it will (obviously) result in different simplified shapes.

Does anyone know of some sort of generic symmetry preserving simplification algorithm? In the case of (a top up) pyramid you could force this manually by having DP run from the end vertice of the top line to the first vertice of the bottom line, and another run from the end vertice of the bottom line to the first vertice of the top line. but this is of course very specific to the symmetry of this particular pyramid.


texts: Can i remove the default splash screen of someone else project by publishing it using my unity plus?

texts: If i use my unity plus to remove the default splash screen from someone else project (that person are using free version of unity) , then export the project also using my unity plus , what are the legal concern ?


texts: Determinism in multiplayer simulation with Box2D, and single computer

texts:
I wrote a small test car driving multiplayer game with Box2D using TCP server-client communcations.

I ran 1 instance of server.exe and 2 instance of client.exe on the same machine that I code and compile the executables. I type inputs (WASD for a simple car movement) into one of the 2 clients and I can get both clients to update the simulation.

There are 2 cars in the simulation. As long as the cars do not collide, I get the same identical output on both client.exe. I can run the car(s) around for as long as I could they still update the same. However, if I start to collide the cars, very quickly they go out of sync.

My tools: Windows 7, C++, MSVS 2010, Box2D, freeGlut.

My Psuedocode:

// client.exe
void timer(int value)
{
   tcpServer.send(my_inputs);
   foreach(i = player including myself) inputs[i] = tcpServer.receive();
   foreach(i = player including myself) players[i].process(inputs[i]);
   myb2World.step(33, 8, 6); // Box2D world step simulation
   foreach(i = player including myself) renderer.render(player[i]);

   glutTimerFunc(33, timer, 0);
}

// server.exe
void serviceloop
{
    while(all clients alive)
    {
       foreach(c = clients) tcpClients[c].receive(&inputs[c]);

       // send input of each client to all clients
       foreach(source = clients)
       {
          foreach(dest = clients)
          {
              tcpClients[dest].send(inputs[source]);
          }
       }
    }
}

I have read all over the internet and SE the following claims (paraphrased):

Box2D is deterministic as long as floating point
architecture/implementation is the same.
(For any deterministic engine) Determinism is gauranteed if playback of recorded inputs is on the same machine with exe compiled using same compiler and machine.

Additionally my server.exe and client.exe gameloop is single thread with blocking socket calls and fixed time step.

Question: Can anyone explain what I did wrong to get different Box2D output?


texts: Mobile vs. Desktop Games - Upsides and Downsides?

texts:
what is the opinion on developing a game for Mobile vs. Desktop in terms of monetization and revenue versus time spent?

In my opinion, Mobile has more upside in terms of revenue, but as a developer I am not sure if Mobile is any easier to develop for than Desktop.

Thoughts?

These articles are a good source:

https://venturebeat.com/2017/07/13/mobile-game-revenue-finally-surpasses-pc-and-consoles/
https://www.cnbc.com/2016/04/22/mobile-game-revenue-to-pass-console-pc-for-first-time.html


texts: How can I change the speed mode in Update?

texts:
I want to decide if the speed will be randomly or constant.

In the top of script:

[Header("Speed")]
public float constantSpeed;
public float minRandomSpeed, maxRandomSpeed;
public bool randomSpeed = false;

In Start:

private void Start()
    {
     RandomSpeed();
    }

In Update

private void Update()
    {
        RandomSpeed();
    }

RandomSpeed:

private void RandomSpeed()
    {
        for (int i = 0; i < instancesToMove.Length; i++)
        {
            if (randomSpeed)
            {
                movementSpeeds[i] = Random.Range(minRandomSpeed, maxRandomSpeed);
            }
            else
            {
                movementSpeeds[i] = constantSpeed;
            }
        }
    }

The problem is in the RandomSpeed if randomSpeed is true it will keep giving the movementSpeeds each frame a new random values. But I want that when randomSpeed is true give movementSpeeds new speed values only once. Then if I will set the randomSpeed false then true again then give again new random speed values.


texts: How can I make that also the yradius values will change when the flag is true?

texts:
In this part when I'm changing the xradius slider it's also changing the yradius slider at the same time and same value. But I can't change the yradius when trying to change it's slider. I want to be able either change the xradius or yradius when the flag is true. Both will change to the same values but I want to be able to change also the yradius so it will change the xradius.

if (changeBothRadius)
        {
            yradius = xradius;
            xradius = yradius;
        }

I tried to add the xradius = yradius; but it's not working only when changing the xraiuds it's working.

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

[RequireComponent(typeof(LineRenderer))]
public class DrawCircle : MonoBehaviour
{
    [Range(0, 50)]
    public int segments = 50;
    [Range(1, 50)]
    public float xradius = 5;
    [Range(1, 50)]
    public float yradius = 5;
    public bool changeBothRadius = false;
    [Range(0.1f, 2)]
    public float lineThickness = 0.1f;
    public bool minimumRadius = false;

    private LineRenderer line;
    private List<float> radiusList = new List<float>();

    void Start()
    {
        line = gameObject.GetComponent<LineRenderer>();
        line.positionCount = segments + 1;
        line.useWorldSpace = false;
        CreatePoints();
    }

    void Update()
    {
        line.startWidth = lineThickness;
        line.endWidth = lineThickness;
        CreatePoints();
    }

    void CreatePoints()
    {
        if (changeBothRadius)
        {
            yradius = xradius;
            xradius = yradius;
        }

        float x;
        float z;

        float angle = 20;

        for (int i = 0; i < (segments + 1); i++)
        {
            x = Mathf.Sin(Mathf.Deg2Rad * angle) * xradius;
            z = Mathf.Cos(Mathf.Deg2Rad * angle) * yradius;

            line.SetPosition(i, new Vector3(x, 0, z));

            angle += (360f / segments + 1);
        }
    }
}


texts: Can Neural Network play tic tac toe? Is this have any common sense?

texts:
I'm thinking about theoretical possibility of playing tic tac toe by neural net. Is this have any common sense? Let's consider tic tac toe which contains 3 rows and 3 cols (it's 9 cells). Ok, then the input vector is contains of all our cells: [0..8], where 0 - is: "O", 1 - is: "X" and 2 - is empty cell.

But what we have for the target vector? On every NN's step we need to know some target and make our distance to target shorter. But the target of this game is only win (or maybe draw), I don't understand how we can make shorter our distance to win. Is any suggestions?

My goal is to learn more about neural networks in games that's why I consider such easy game. Maybe it's not the best choice for the NN and I need to consider some other game? :)


texts:
i'm surprised there is so little documentation on this issue. But i'm trying to duck the audio on all the mix buses in Unity so that you can clearly hear the VO of the game.

Now it works great except that I have some reverb zones in the game and any sound that plays in these reverb zones, the actual reverb itself is NOT DUCKED.

So the VO is accompanied with a huge wall of wishy washy muddy noise.

Anyone deal with this before? How can we deal with this?


texts: set model to transparent where texture is transparent

texts:
I finally got around to applying textures to my game, and I noticed that the areas that are transparent on the .png of the texture are not transparent on the actual model.It is illustrated in the image below.

I want the areas of the model that are supposed to be transparent to be transparent. The white areas are the areas that should be transparent. the white areas are transparent on the actual .png. Is there any way to do this using glfw? Is there some sort of transparency function GLFW has? I thought changing RGB to RGBA on the texture generator would fix it but it did not.
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
The data for the actual model is below (its formatted in json but still shows the vertices). The first 3 entries on each row are the coordinates, then 3 entries for the color, then the texture mapping.
{"vertices":[
0.00,0.00,0.0,0.0,0.0,0.0,0.0,0.0,
500.00,0.00,0.0,0.0,0.0,0.0,1.0,0.0,
500.00,500.00,0.0,0.0,0.0,0.0,1.0,1.0,
0.00,500.00,0.0,0.0,0.0,0.0,0.0,1.0

],
"indices":[
0,1,2,
0,3,2
],

"texturePath": "textures/planet1.png"}

Do I have to map the coordinates of the texture to a circular object rather than a square one like it is formatted now. I am hoping I don't, because that would make my life so much simpler.


texts: How to change FPS during runtime in LibGDX?

texts:
I would like to be able to change the desired fps (foregroundFPS) during runtime without having to restart the game. I know how to set it before launch with LwjglApplicationConfiguration but I have no clue how to set it during runtime.

An example use would be in a menu where the player can select his FPS.

How can I do that ?


texts:
I noticed that in very soft gradients, the 24-Bit colordepth is not enough as you can see the transitions of the color. This pops out the most in dark scenes or night skies.

Why doesn't anybody change the colordepth to two bytes per channel? I know that would be alot of work and a lot of hardware would have to be repalced, but I find it a bit annoying. I really don't think that the technology of the hardware isn't mature enough.

So why is no one doing that?

Here's a picture of "The War Z" where you can see what I mean:


texts: How can I make player object collide and keep moving until it is as close as possible to click location?

texts:
I am making a basic point and click adventure game. I can make the player object move towards the location of a mouse click and collide with walls, but movement stops the instant a collision occurs. I would like the player object to keep moving (slide along the wall) and get as close as it can to the mouse click location, without passing through a wall of course. I have Create, Step, Collision & Global Mouse click events. Please see below for code and diagrams.
Any help will be much appreciated.

Create Event code:
//stop player moving on create
enum mouse {
    none
}
xx = mouse.none;
yy = mouse.none;
player_move_speed = 2;

//init
collision_speed = player_move_speed + 1;

Step Event code:
//general keys
if keyboard_check_pressed(vk_escape) {game_end()}

//point and click movement
if (xx != mouse.none and yy != mouse.none) {
    move_towards_point(xx,yy,player_move_speed);
} else {
    speed = 0;
}

if (distance_to_point(xx,yy) < collision_speed) {
    xx = mouse.none;
    yy = mouse.none;
}

Global Left Pressed code:
xx = mouse_x;
yy = mouse_y;


texts: Which version of AndEngine (gles1 or gles2) should I learn?

texts: I m new to Game Development. I've chosen AndEngine, but there are 2 versions: gles1 and gles2. I tried sample code from both and found that gles2 code is not run on an emulator, but required an actual device. And in gles2 there are also BaseGameActivity and SimpleBaseGameActivity. I'm a little confused. Which is best?


texts: How can I adapt "random walk" generation to very large maps?

texts:
The random (or drunkard's) walk is a great, simple algorithm that can generate very organic-looking maps, such as this:

Unfortunately it seems to have poor scalability, making it unsuitable for generating large maps in a reasonable amount of time. For example, a test I performed looking at how many iterations are required to generate a desired range for a 1D random walk yielded what looked like quadratic complexity:

Range | Iterations
------+-----------
10    | 81
100   | 7309
1000  | 585352
10000 | 30656784

For higher-dimension walks I imagine this would be even worse.

How can improve the efficiency of random walk, whilst preserving the overall look of the result, for large maps? I'm hoping for a solution with sub-quadratic complexity.


texts:
I've seen guild banks in Wow, or Dofus, and other MMO games.

In the guild I've been a part of, we mostly used the bank as storage; resources stored that end up not being used are wasted. Sometimes there is a free share policy, but there is always that one guy who will take stuff he does not really need and sells it.

This led me to wonder what is the original purpose of a guild bank, what do players like to use it for, and how can a game help them do it?


texts: Can someone give me an explanation about how to use the Quaternion class in libGDX to move my camera around a sphere or just set it up, manipulate it, and apply it general? I am trying to acheive orbiting my camera around a sphere without gimbal lock, and I'm not having any luck getting the camera to do anything by using quaternions...


texts: DirectX shader - how to spread raytracer computation over multiple frames?

texts:
I'm playing around making a shadertoy style SDF raytracer in HLSL and to make it run faster on high resolutions (1080p and up) I'd like to spread the computation over multiple frames.

Right now I have a fragment shader that does raytracing for every pixel of a screen sized quad. I've noticed that if I discard (clip()) the fragment for every second pixel, I get 0 framerate improvement despite effectively only rendering half the image. But if I lower the render texture resolution to half, I see improvement obviously. Also if I clip a contiguous half of the fragment and render the other half, I get a similar performance boost.

This must mean that the gpu thread groups are by default allocated in a tiled fashion on the screen, and that all threads of a group must be done computing before the (other) resources of the thread group can be used again.

Does anyone know of any magic that can force a fragment shader to only allocate resources for say half the pixels of the screen? (but keep the render target size)

Alternatively I suppose I could assign my own thread groups in a Compute shader system where I manage all this stuff myself. Is that the only way to do it? And how would I handle the render target then? (know any resources?)

I'm also pretty sure I've seen people make this kind of grainy multi-frame raytracers years ago before compute shaders were a thing.


texts:
I'll make a navigation menu in my game and had the good idee to this the enemies to start games or go to the gun store. The problem is when I look in game mode, the enemy named ZomBear in hierarchy and gun are away.

The ZomBear and the gun are 3D elements that I will show on a canvas named StartScreen in hierarchy. How Can I do that?

(Click on image to see full size)

Notes by the hierarchy:

Everything that begin whit Btn are button elements.
StartScreen, PlayButtons and LevelButtons is a panel
Gun and ZomBear are 3D elements form the Prefab folder.

Here you have also a screen from aside:


texts: How to setup input for local multiplayer without split-screen in Unreal Engine 4

texts:
To bind actions and axes in the character blueprint class, I may have multiple such character instances for each new APlayerController.  Merely 1 Action Name (e.g. avoiding UseSkill_P1, UseSkill_P2, etc) is required for each character by adding the node in the Player Controller. However, for more functionality the same is required in cpp.

What I've tried:

When I bind actions and axes (delegates) in the APlayerController's  SetupInputComponent (e.g: InputComponent->BindAction("Attack", IE_Pressed, this, &AMyController::DoSomething);, then spawn multiple players with UGameInstance::CreateLocalPlayer(index, err, true), the editor will crash on pressing Play in Editor (Alt+P).

The error thrown during runtime is: Access violation - code c0000005 (first/second chance not available) and referencing the line where the first ActionBind appeared, e.g: UE4Editor_MyProject!AMyController::SetupInputComponent() [d:\path\to\project\source\private\mycontroller.cpp:66]

A common solution can be found in this wiki post it seems. In short, overwrite GameViewportClient and set it as default, then within, overwrite InputAxis and InputKey and increment the player controller index for each input device (gamepad) used.

As mentioned previously, this would require the project to specify a unique Action Name for each player index e.g. Attack_P4.

There is also some confusion that needs to be cleared up.

An AController will not be created for each input device connected.
1-viewport-multiplayer isn't supported as split-screen. (Weird naming, but good for search engines).
Spawning new Local Players is generally done in your override of AGameMode::BeginPlay. I made it up to the deriving BPs of my Game Mode to call CreatePlayers to create up to the set amount of players.
Setting Skip Assigning Gamepad to Player 1 will allow keyboard to be used for player 1.

Hopefully there are some common best practices to tackle this problem. Any suggestion is very much appreciated!

PS Here is the related unreal answers hub question.


texts: Unity 5 Networking Send Rate: Send Rate is Zero but server movement is still happening

texts:
I have a client server scenario, just a player moving about on the client and he moves about on the server using the built in networking provided in Unity 5. I have my client scene running in the editor and was playing about with the Network Transform Script Values, more specifically the Network Send Rate. Setting this Value to 29 (its highest) the movement on the server is almost smooth. Setting this value to 1 and the movement on the server is very laggy as I expected. However, if I set the network send rate to 0 on the client, I expected it not to move at all on the server, but it moves and alot smoother than the value 29.

Why is it, that when the network send rate is set to 0 that my character still moves on the server?


texts: Getting the rightmost point of gameobject

texts: How do i determin the point on a gameobject that is most to the right (highest x value).


texts: declaring variables in a render/game loop: good idea or bad?

texts:
I was just wondering how most of you like to declare your variables: for a variable you know will be used and changed frequently (i.e. every frame), do you declare those outside of the loop and simply change them? Or do you declare new variables every time around and count on the GC and function scope to clean up 60 little variables every second? Which is more efficient and reliable? Flash has a decent garbage collector, but I've had problems with leaks before.

Here's some example AS3 code with collision checking in Flashpunk:

public function update():void
{
    var bullet:Bullet = collide("bullet", this.x, this.y) as Bullet;

    if (bullet)
    {
        FP.world.recycle(this);
        bullet.destroy();
    }
}

vs.

var bullet:Bullet;

public function update():void
{
    bullet = collide("bullet", this.x, this.y) as Bullet;

    if (bullet)
    {
        FP.world.recycle(this);
        bullet.destroy();
    }
}


texts: Gameobject rotation around anchored pivot

texts:
I'm looking for the best way to rotate the Camera(EYES) around a center of my character (Player Prototype) because if I turn around, the Camera enter inside the character.
My FPS script is attached to Player Prototype, but the Camera isn't because i have to make particular rotation. So I don't know what I have to do.

Have will I make the parent? If I will make it, Eyes will sum rotations to those of the parent.
Or maybe I have to handle this in LateUpdate()?
With RotationAround() I don't understand how to pass the second argument which is a Vector3, but I have a Quaternion.Euler.

So at this point I accept all the advice or examples of what I can do to solve it.


texts: How to work with libddx and Android studio

texts: I am new in game development.I am getting problem with libgdx. when i download libgdx i get zip file.where is setup


texts: How to properly handle attacks in an 2D Platformer?

texts:
I am building an 2D Engine in JavaScript and if my actor attacks an enemy, a hitbox appears for a certain amount of time and then disappears. If the target keeps standing inside of the hitbox he gets drained down for each frame. So for example if the hitbox does 3 points damage and the target only has 9 HP he will be dead after 3 frames. That's too fast.

I've come up with two solutions, both of them are not ideal:

Set the enemy as unattackable for a certain amount of time after each hit.
Save an reference to the enemy that gets deleted after the hitbox disappears.

My explanation is pretty bad but posting my code would be worse since it's way too much.


texts:
My engine is currently implemented using a deferred rendering technique, and today I decided to change it up a bit.
First I was storing 5 textures as so:
DEPTH24_STENCIL8  - Depth and stencil
RGBA32F           - Position
RGBA10_A2         - Normals
RGBA8 x 2         - Specular & Diffuse
I decided to minimize it and reconstruct positions from the depth buffer. Trying to figure out what is wrong with my method currently has not been fun :/
Currently I get this:

which changes whenever I move the camera... weird

Vertex shader
really simple
#version 150

layout(location = 0) in vec3 position;
layout(location = 1) in vec2 uv;

out vec2 uv_f;

void main(){
    uv_f = uv;
    gl_Position = vec4(position, 1.0);
}

Fragment shader
Where the fun (and not so fun) stuff happens
#version 150

uniform sampler2D depth_tex;
uniform sampler2D normal_tex;
uniform sampler2D diffuse_tex;
uniform sampler2D specular_tex;

uniform mat4 inv_proj_mat;
uniform vec2 nearz_farz;

in vec2 uv_f;

... other uniforms and such ...

layout(location = 3) out vec4 PostProcess;

vec3 reconstruct_pos(){
    float z = texture(depth_tex, uv_f).x;
    vec4 sPos = vec4(uv_f * 2.0 - 1.0, z, 1.0);
    sPos = inv_proj_mat * sPos;

    return (sPos.xyz / sPos.w);
}

void main(){
    vec3 pos = reconstruct_pos();
    vec3 normal = texture(normal_tex, uv_f).rgb;
    vec3 diffuse = texture(diffuse_tex, uv_f).rgb;
    vec4 specular = texture(specular_tex, uv_f);

    ... do lighting ...

    PostProcess = vec4(pos, 1.0); // Just for testing
}

Rendering code
probably nothing wrong here, seeing as though it always worked before
this->gbuffer->bind();
gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);

gl::Enable(gl::DEPTH_TEST);
gl::Enable(gl::CULL_FACE);

... bind geometry shader and draw models and shiz ...

gl::Disable(gl::DEPTH_TEST);
gl::Disable(gl::CULL_FACE);
gl::Enable(gl::BLEND);

... bind textures and lighting shaders shown above then draw each light ...

gl::BindFramebuffer(gl::FRAMEBUFFER, 0);
gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);

gl::Disable(gl::BLEND);

... bind screen shaders and draw quad with PostProcess texture ...

Rinse_and_repeat(); // not actually a function ;)

Why are my positions being output like they are?


texts: Draw GUI.Button on certain position on a scrollable background

texts:
Problem is in a 2D game I have a large background around 2 screens wide. And on there I got 4 buttons placed on top of background all over complete width. Now when I swipe of move my mouse around I scripted that the camera will move with it. So for the GUI.Buttons (Unity4.5) to stick on their place I used a variable drawX

 drawX = Camera.main.transform.position.x * 100;

The 100 is for calculating it to pixels. I then add this to my buttons when drawing.

scaleX = Screen.width / 1920f;
 scaleY = Screen.height / 1200f;
 if (GUI.Button(new Rect((500 - drawX) * scaleX, 700 * scaleY, 325 * scaleX, 425 * scaleY), ""))

Now the problem is that under 1920x1200 my target resolution everything works exactly pixel perfect. But when changing the resolution or aspect ratio to something else the drawX increases to much or not enough so the buttons don't move on the same pace as they did in the 1920x1200 version. Somebody got the solution for me?


texts: Is it efficient to have a only-data MonoBehaviours on lots of game objects?

texts:
I'm working on a voxel based game and this solution would make the implementation of networking and other features a lot more easier, it is less error-prone, easier to edit in the Editor, etc.

So the question is:

How bad is it performance-wise to have lots of MonoBehaviours in the scene, if they don't implement any of the MonoBehaviour methods?
(So they only have primitive data stored in them)


texts: Borderless windowed (fake fullscreen) mode doesn't cover the entire screen

texts:
I'm using Direct3D 11 running on Windows 10 20H2, but have seen this problem going back to Windows 7.
I'm adding borderless windowed (fake fullscreen) mode support, and all of the online resources I can find suggest that it's simple: just setup a windowed mode the same size as your display resolution, use WS_POPUP, and that's all you need to do.
The problem is that it doesn't actually work.
Instead, I get (on a 1920x1080 display) a 1920x1060 window, with the bottom 20-pixel high portion of the taskbar still visible.  The odd thing is, the swapchain backbuffer is sized correctly, at 1920x1080, and adding some debug output shows that my WM_SIZE message is coming through at 1920x1080; it's as if something else internal was preventing the window from covering the full screen.
Fullscreen exclusive modes work correctly.
The workflow I'm using to set this mode goes like:

Determine if the window will be the same size as the display.

If so, set WS_POPUP (not sure what to use as the ExStyle so I'm leaving it at 0 for now, but I've also tested WS_EX_TOPMOST with no success).
If not, set the usual array of styes.

Call SetWindowPos with SWP_FRAMECHANGED.
Pump my message loop to make sure that everything is brought up to date.
Call IDXGISwapChain::ResizeTarget to do the actual window resizing.
Respond to WM_SIZE to call IDXGISwapChain::ResizeBuffers, create my views, etc.

Of note is that I don't change the window size using SetWindowPos; I let IDXGISwapChain::ResizeTarget do that for me, and that works for every other combination of windowed-to-windowed, windowed-to-fullscreen, fullscreen-to-windowed and fullscreen-to-fullscreen transition (where "fullscreen" here is fullscreen exclusive).
The only thing that does not work is borderless windowed.
What sorcery am I missing?


texts: How do I update individual sprites within a spritegroup in pygame?

texts:
I have a for loop that takes values from a text file, and then creates and adds a bunch of sprites to a group platformlist_list. The for loop will continue until every line of the text file is read.

self.object = Wall(firstarray[0] , int(firstarray[1]), int(firstarray[2]))

print int(firstarray[3]), ' x ', int(firstarray[4]), ' y'

self.object.rect.x = int(firstarray[3])
self.object.rect.y = int(firstarray[4])

initialization.platform_list.add(self.object)

What I want to be able to do is access these created sprites and move them, but if I use this code to try and move all of the sprites in the platform_list group:

if (loadterrain.character.direction == self.left):
    loadterrain.wall.rect.x += self.movementspeed
    loadterrain.object.rect.x += self.movementspeed
if (loadterrain.character.direction == self.right):
    loadterrain.wall.rect.x -= self.movementspeed
    loadterrain.object.rect.x -= self.movementspeed
    loadterrain.floor.rect.x -= self.movementspeed

The only object on screen that will move is the last object that my for loop has created.

I want to be able to access and modify the x and y positions for every sprite inside of the platform_list but have no idea how to do so because from the research I have done indexing the platform_list is unreliable as it is not ordered.

What is the best way for me to access and modify the positions of all the sprites in that group?


texts: Some OpenGL code not working, but some is

texts:
I'm just starting out using GLEW and GLFW in a C++ project for my rendering code, but I'm having trouble actually getting anything to render.

I know OpenGL is working in some capacity, because I am able to change the background colour, but nothing else is working beyond that.

I'm setting up the OpenGL context with this code:

    //Attempts to initiate GLFW. If it doesn't, it returns immediately
    if (!glfwInit()) {
        fprintf(stderr, "Failed to initialize GLFW\n");
        return;
    }

    //glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // We want OpenGL 3.3
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL

    window = GLFWwindowPtr();
    window.reset(glfwCreateWindow(width, height, windowTitle, NULL, NULL), DeleteWindow);

    if (window.get() == nullptr) {
        fprintf(stderr, "Failed to open GLFW window\n");
        glfwTerminate();
        return;
    }

    glfwMakeContextCurrent(window.get());

    glewExperimental = GL_TRUE; // Needed in core profile
    int errorCode = glewInit();
    if (errorCode) {
        printf("%i", errorCode);
        fprintf(stderr, "Failed to initialize GLEW\n");
        return;
    }

    glClearColor(0.0, 0.0, 0.0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT);

    glfwSwapBuffers(window.get());

A little while after that in my main loop, I call this code every frame:

float ratio;
int width, height;

glfwGetFramebufferSize(WindowHandler::getMainWindowGLPointer(), &width, &height);
ratio = width / (float)height;
glViewport(0, 0, width, height);
glClearColor(red / 255, green / 255, blue / 255, 1.0);
glClear(GL_COLOR_BUFFER_BIT);

Now this code works. I'm incrementing the red, green and blue variables every frame so that I can check that OpenGL is working as a whole and I see the background colour change.

However, when I put the following code after it, I'm seeing nothing different appear.

glBegin(GL_QUADS);              // Each set of 4 vertices form a quad
glColor3f(red/255, green/255, blue/255); // Red
glVertex2f(-0.5f, -0.5f);    // x, y
glVertex2f(0.5f, -0.5f);
glVertex2f(0.5f, 0.5f);
glVertex2f(-0.5f, 0.5f);
glEnd();

I used the code from an existing example found on https://www3.ntu.edu.sg/home/ehchua/programming/opengl/CG_Introduction.html so I had a better chance of it being something in my implementation and not me messing up trying to write OpenGL code.


texts: How are the packet boundaries in the Source engine DEM format determined?

texts:
I'm trying to write a program that reads Source DEM files, and about all I can at this point is the header which is a magic string, few ints and floats and 280-long strings.

The last field in the header is an int which specifies the length of the "sign on" data in bytes, but after reading that much forward into the file then attempting to read a new int for another packet of data, I get garbage values (0's or negative values) after 2-3 packets (I expect a few thousand).

Basically I'm interpreting the documentation as so:

Header Data (less sign-on length)
Sign-on length (int, "Length of the signon data (Init for first frame)")
Sign-on packet (of above specified length)
Next packet length (int)
Next packet data (length above)
...repeat to EOF.

If I consume another 4-bytes between the "sign-on length" and packet itself (it's a bit unclear if the last field in the header is actually part of the header or just the start of the first packet), I also get garbage.

All this is before even trying to parse the contents of the packet data, I'm currently just trying to jump through the recording and chop it up in to the frame packets.


texts: Unity Google VR reticle pointer weird behaviour

texts: I'm using Unity 2017.3.1f1 and Google VR SDK 1.150.0. I added GvrEditorEmulator and GvrEventSystem to the hierarchy, created an empty object and put main camera inside. I also added GvrRecticlePointer as a child of the camera. Then I added a spinning cube and added EventTrigger script onto it. When I point reticle at the cube in the game mode the reticle pointer start shaking. I'm wondering why is that?


texts: MonoGame: Draw thousands of quads without hardware instancing

texts:
In my game, every bit of geometry is a textured quad billboard in 3D. I have many thousands of these things on screen at once, sometimes with overdraw. As I understand it, there are a few ways  I can go about drawing these:

Have a single VBO per type of quad (ie, unique set of texture coords). Batch the VBO and texture, but make multiple draw calls. Looks something like this:

foreach (Quad quad in quadTypes)
{
    // The VBO just contains 4-6 vertices.
    GraphicsDevice.SetVertexBuffer(quad._vertexBuffer);
    Shader.SetTexture(quad._texture);

    // Draw each instance using multiple draw calls
    foreach(QuadInstance instance in quad._instances)
    {
       Shader.SetWorldMatrix(instance._worldMatrix);

       foreach(ShaderPass pass in Shader._passes)
       {
           pass.Apply();
           GraphicsDevice.DrawPrimitive(TRIANGLES);
       }
    }
}

Make a single draw call by somehow combining all the triangles of all the instances of a quad type. Looks something like this:

foreach (Quad quad in quadTypes)
{
    Shader.SetTexture(quad._texture);
    // Probably can cache a vertex buffer for when quads are created/destroyed instead.
    VertexBuffer vertexBuffer = new VertexBuffer();

    foreach(QuadInstance instance in quad._instances)
    {
       // Add all of the (world transformed) triangles of this instance to
       // the vertex buffer
       vertexBuffer.AddAll(instance.CreateTriangles());
    }

    // Draw all the quads with a single draw call and vertex buffer.
    GraphicsDevice.SetVertexBuffer(vertexBuffer);

    foreach(ShaderPass pass in Shader._passes)
    {
        pass.Apply();
        GraphicsDevice.DrawPrimitive(TRIANGLES);
    }
}

True hardware instancing. This is currently how I do it in my (XNA HiDef profile) game, but I can't figure out a way to get it to work in Monogame. With true hardware instancing, each instance is represented as a vertex, and the GPU creates all the necessary duplicate vertices in a single draw call.

In general, which one of these is most desirable? 1) makes many draw calls, but saves the most memory. 2) has a single draw call, but requires creating a vertex buffer for all of the instances, which seems really inefficient, and 3) has the best of both worlds but is not widely supported. Is there a fourth way that I'm missing?


texts: Matrix rotation wrong orientation LibGDX

texts:
I'm having a problem with matrix rotation in libgdx. I rotate it using the method matrix.rotate(Vector3 axis, float angle) but the rotation happens in the model orientation and I need it happens in the world orientation.

For example:

on create() method:

matrix.rotate(new Vector3(0,0,1), 45);

That is ok, but after:

on render() method:

matrix.rotate(new Vector3(0,1,0), 1);

I need it rotate in world axis.


texts: trouble in box2d flash with invoking a setLinearVelocity() from inside an eventHandler

texts:
The set linear velocity doesnt affect a sprite when written inside an event handler.. but if i call setlinear velocity inside the main constructor..ie if the setlinearvelocity is called at the beginning of game code ..it moves..but not when i call it within a event handler..either keypress or mouse,it doesnt work?

Please ..any help would be greatly appreciated


texts:
How can I make a game over pop-up like Flappy Bird in cocos2d-iphone 3?

I tried to add a new Scene, but it adds a new screen on the game, I just want a rectangle with some buttons inside it. I also search how to add multiple scene, but didn't find an example doing it.


texts: Question about designing and controlling a forklift's forks

texts:
I am building a forklift for a game that I am working and I am trying to come up with a valid way of designing it. So far I haven't really liked the way it behaves in game The forklift has three parts to it

Wheels
Main body: Has a rigid body component
Forks : Has a rigid body component and a configurable joint where the connected body is the main body(2).

The movement is perfectly fine but its forks behaviour that is a bit troublesome. I am trying to make it move as a whole with the main body but it appears as if it is trying to detach itself when I hit another rigidbody in the scene(link goes to a screen cast I made of the problem in action). I have adjusted the drag and angular drag parameters of both the main body and the forks, adjusted the linear and rotational configurable joint parameters and yet this problem constantly occurs. According to an answer found on the official unity forums, I shouldn't parent two rigidbodies together. I am thinking about setting the fork as a purely kinematic rigidbody and updating its position every frame. Does anyone else have any other ideas?


texts: XNA Shader working different on different PC's

texts:
I am working on a game in C#/XNA which uses custom shaders for drawing. When the code is compiled on my machine it works perfectly on all computers I tested, but when my team member tries to compile it locally, there are very weird visual artifacts. The walls of our maze are stretched to what looks to be infinity based on that they seem to end at the far plane of the game camera.

We both use visual studio 2013 with XNA game studio 4 and we can't find any differences in our build settings (which should come from our git repository anyway). We also tried copying our code files directly from one computer to another, but it resulted in the same.

Now we are totally lost in what to do next. Any ideas what it could be?

float4x4 mvp_matrix;    // = model * view * projection
Texture2D tex;

SamplerState MeshTextureSampler
{
    Filter = MIN_MAG_MIP_LINEAR;
    AddressU = Wrap;
    AddressV = Wrap;
};

struct VS_INPUT
{
    float3 Position : POSITION0;
    float3 Normal   : NORMAL0;
    float2 TexCoord : TEXCOORD0;
};

struct VS_OUTPUT
{
    float4 Position : POSITION0;
    float3 Normal   : TEXCOORD0;
    float2 TexCoord : TEXCOORD1;
};

VS_OUTPUT VertexShaderFunction(VS_INPUT input)
{
    VS_OUTPUT output;

    output.Position = mul(float4(input.Position, 1), mvp_matrix);
    output.Normal = input.Normal;
    output.TexCoord = input.TexCoord;

    return output;
}

float4 PixelShaderFunction(VS_OUTPUT input) : COLOR0
{
    return float4(tex.Sample(MeshTextureSampler, input.TexCoord).rgb, 1);
}

technique Technique1
{
    pass Pass1
    {
        VertexShader = compile vs_2_0 VertexShaderFunction();
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }

This is our simple shader variant (Both possible shaders have the problem)

Working maze on my PC

Broken maze on their PC

Note that the compiled version works on all the PC's, so I don't think it's probable that it's a problem on the GPU-side.


texts: Why is the standard on displaying missing textures is via a black and purple checkerboard?

texts: In many different games, such as Minecraft and TF2, the default texture is a black and purple checkerboard. Even games that don't use that exact texture incorporate elements of it. Borderlands 2 uses a white and purple checkerboard, and Skyrim uses a solid purple texture. Why is the black and purple checkerboard so prevalent as a default texture?


texts:
I have an entity in 2D space moving around, lerping between waypoints. I would like to make the entity rotate around its own origin to face the current direction that it is going, I.E. towards the next waypoint in the list.

In case the waypoint movement code is needed, I'm using the following (this is contained inside of the entity that is following the waypoints) :

    private void GoToWaypoint() {
        if (waypointList.Count > 0) {
            Vector2 origin = helper.GetOrigin(position, width, height);
            int nodeWidth = 50;
            int nodeHeight = 50;

            if (moveToPosition != waypointList[0]) {
                moveToPosition = waypointList[0];
                moveToPositionOrigin = helper.GetOrigin(moveToPosition, nodeWidth, nodeHeight);
                distanceToPosition = moveToPositionOrigin - origin;
            }

            if ((Math.Ceiling(distanceToPosition.X) < 0)) {
                position.X -= moveSpeed;
                distanceToPosition.X = (int)Math.Round(distanceToPosition.X + moveSpeed);
            }
            else if ((Math.Floor(distanceToPosition.X) > 0)) {
                position.X += moveSpeed;
                distanceToPosition.X = (int)Math.Round(distanceToPosition.X - moveSpeed);
            }

            if (Math.Ceiling(distanceToPosition.Y) < 0) {
                // Check if the entity moves below the top boundary
                if (position.Y > 0) {
                    position.Y -= moveSpeed;
                    distanceToPosition.Y = (int)Math.Round(distanceToPosition.Y + moveSpeed);
                }
                else {
                    distanceToPosition.Y = 0;
                }
            }
            else if (Math.Floor(distanceToPosition.Y) > 0) {
                // Check if the entity moves below the bottom boundary
                if (position.Y < 550) {
                    position.Y += moveSpeed;
                    distanceToPosition.Y = (int)Math.Round(distanceToPosition.Y - moveSpeed);
                }
                else {
                    distanceToPosition.Y = 0;
                }
            }

            // If the entity gets in the waypoint, or the distance to the waypoint is 0 on both axis (which can occur due to screen boundaries)
            if ((helper.InNode(position, moveToPosition, width, height, nodeWidth, nodeHeight)) || ((distanceToPosition.X == 0) && (distanceToPosition.Y == 0))) {
                waypointList.RemoveAt(0);
            }
        }
    }

I know this may have been asked elsewhere, and the bit of searching that I did on this type of problem, didn't really help me. I'm slightly math retarded, so I don't understand the explanations that don't really explain what the math is exactly achieving. So any help that breaks down the math and functions needed to achieve this would be greatly appreciated.

Thanks.


texts:
For one segment of my game, the player is in a fixed position (no movement) and has to aim and shoot at enemies in a first person 3D perspective using the Mouse. The player is holding a wand that shoots projectiles (which I have working) and I need it to rotate and aim towards the cursor as an aiming reticle. I also want to limit how much the player can rotate, so they can look around, but can't turn more than 180 degrees (sort of like this). However, I'm a designer and am having trouble programming this myself. I haven't been able to find a proper solution.

So far, I've been able to cobble the following code together, but the aiming is super wonky and doesn't properly point to the mouse position, making it impossible to actually aim at anything. I would really appreciate some help with figuring this out.

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

public class PlayerShoot : MonoBehaviour {

public float magnifier = 0.5f;
public Rigidbody shotPrefab;
public Transform barrelEnd;
public float shotSpeed = 500;
public Rigidbody sparkPrefab;

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

    Ray mouseRay = Camera.main.ScreenPointToRay (Input.mousePosition);
    float midPoint = (transform.position - Camera.main.transform.position).magnitude * magnifier;

    transform.LookAt (mouseRay.origin + mouseRay.direction * midPoint*magnifier);

    if (Input.GetButtonDown("Fire1"))
    {
        Rigidbody shotInstance;
        shotInstance = Instantiate(shotPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
        shotInstance.AddForce(barrelEnd.forward * shotSpeed);
        sparkBlast();

    }
}
// Particle recoil effect
void sparkBlast () {
    Rigidbody shotSparks;
    shotSparks = Instantiate(sparkPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
    Destroy (shotSparks,0.5f);
}

}


texts: Is there a common invitees/players ratio during closed beta?

texts:
The question itself is fairly straight forward, but the answer takes a lot of industry insight.

To give an example scenario, I am playing a game that's in closed beta right now. They have about 5000 people invited and the game is only open from Fridays to Mondays. On average there are only about 200-400 players online at any given time, across EU and US. For a closed beta, this looks like a bit of a low turn-over if you ask me.


texts: How to deal with race conditions on a game server between network and physics update loops?

texts:
I am new to game networking.
In various articles on the internet, I found that there are usually two loops on the server: one for physics updates and the other for sending snapshots to the client (network updates). As I understand, loops can run in parallel, which makes me think they should run on different threads.
Now, in terms of concurrency, physics thread is the writer and the network thread is the reader. Given that the threads can run concurrently, there can be race conditions: reader thread can read inconsistent game state if the writer thread is currently modifying it.
How to deal with this race condition? The crude approach would be just to use lock on the game state, but it seems to me that this will introduce delays. For some reason I can't find anything on the web.


texts: What is wrong with my Item collection/Itemcounter Script

texts:
So I am making a script for item collection and a counter for it. I have a script made but for some odd reason I can't seem to the get the GUI part right. The compiler error says something like "This isn't a member of UnityEngineGUI" IDK what I am doing wrong. Could someone help out?

#pragma strict
var Collectable : GameObject;
var Counter : int;
var CounterGUI : GUI;

function OnTriggerEnter (other : Collider){
    if (other.gameObject.tag == "Player"){
        Collectable.SetActive(false);
        Counter += 1;
        CounterGUI.GUI = Counter.ToString();
    }
}


texts: XNA: Retrieve texture file name during runtime

texts:
I'm trying to retrieve the names of the texture files (or their locations) on a mesh.

I realize that the texture file name information is not preserved when the model is loaded.

I've been doing tons of searching and some experimenting but I've been met with no luck. I've gathered that I need to extended the content pipeline and store the file location in somewhere like ModelMeshPart.Tag.

My problem is, even when I'm trying to make my own custom processor, I still can't figure out where the texture file name is. :(

Any thoughts? Thanks!

UPDATE:

Okay, so I found something kind of promising. NodeContent.Identity.SourceFilename, only that returns the location of my .X model. When I go down the node tree he is always null. Then there's the ContentItem.Name property. It seems to have names of my mesh, but not my actual texture file names. :(


texts:
Remember this beauty? I'm playing it now on my old Amiga 1200.

My question is: How do you think they represented the terrain, data structure wise? Obviously it's some kind of points, with a height. Or hexagons. And how did they decide which dots were buildable?

EDIT: I could rephrase the question to say "how do I achieve this kind of terrain", but I would still only be interested in how to do it on a machine with 1 MB of RAM and a 7 Mhz processor, because this is the machine i currently developing games for. If that seems like a vague or meaningless question to you, that's alright, but I'm still curious if someone has any knowledge about this.


texts:
I'm trying to create an isometric game and would like to use some tiles from Open Transport Tycoon Deluxe
newGRF library link
The atlas I'm used to work with are basically a big image that can be splitted in 64x32 tiles, so I can use any Atlas import tool or just easily extract the tiles with a loop.
However, OpenTTD uses atlas that I don't understand. The files look something like this, where each tile has a numer and starts at positions that are not evenly distributed.
I assume it might exist some file with metadata that contains the locations and sizes of each tile, in order to be extracted and used.
Has anybody experience with this type of Atlas? How can I extract the tiles so I can use them?
Thanks


texts: How to render IDirect3DSurface9 in my window?

texts:
I have some code that captures the screen and save data into a surface.

g_pDirect3D_Device->GetFrontBufferData(0, pSurface);

All is ok, now I want to display pSurface in my window. I want to have the image in my whole window.

Is it possible, or should I use a texture?


texts: As3 Character movement in diffrent directions with labels?

texts:
I hope you can help me with the following problem:

I made a character in Illustrator. The player sees the character from above.
When you press the left arrow key character.gotoAndStop('left'); the character moves to the left. (Same goes for the right direction with label 'right'
When you release the left or right arrow key (upKey) the character goes back to the label 'up'.

I'm trying to accomplish the following:
When the character is facing down ('down'). the left key should go to the ("facingdownleft") label and on release back to the label ('down'). (Same for the right direction)

stage.addEventListener(KeyboardEvent.KEY_DOWN, downKey);
function downKey(event:KeyboardEvent)
{
 if(event.keyCode==39){
 isRight=true;
 character.gotoAndStop('right');}
 if(event.keyCode==37){
 isLeft=true;
 character.gotoAndStop('left');}
 if(event.keyCode==38){
 isUp=true;
 character.gotoAndStop('up');
 }
 if(event.keyCode==40){
 isDown=true;
 facingdown=true;
 character.gotoAndPlay('down');}
}

if( facingdown == true && isLeft == true)
{
 character.gotoAndPlay('downleft');
}

stage.addEventListener(KeyboardEvent.KEY_UP, upKey);
function upKey(event:KeyboardEvent){
 if(event.keyCode==39){
 isRight=false;
 character.gotoAndPlay('up')}
 if(event.keyCode==37){
 isLeft=false
 character.gotoAndPlay('up')}
 if(event.keyCode==38){
 isUp=false;}
 if(event.keyCode==40){
 isDown=false}
 }

I made a boolean for facingdown and an if statement for downleft:

  if( facingdown == true && isLeft == true)
    {
     character.gotoAndPlay('downleft');
    }

But before I make numerous amounts of if statements again, I would like to know if I'm on the right track and if you can help me accomplish this?
Thank you so much in advance and feel free to ask questions.


texts: Creating a top-view racing game, do I have the right ideas, any suggestions?

texts:
I am creating a top-view, multiplayer, arcade-ish racing game, and I want to know if you guys think that I am on the right track, or not. It will work basically like this:

-There are 3 races, and one demo derby in a round.

-Each race will be a 15 lap circuit (they are very small tracks, the  tracks will be visible within the entire screen, tracks will  be chosen at random.)

-The winners will be displayed after each race, in leaderboard style. 1st place- 100pts. 2nd place- 75pts. 3rd place 50 pts. 4th and below- 10pts.

-After all 3 races, averaged scores will be displayed; the final top 3 scores will then battle to the death in a demo derby "bonus round" type thing. (This will also serve as a tiebreaker, if that is necessary.)

-The winner of the demo derby will receive 250pts., all others including non-participants get nothing.

-The person with the highest averaged pts.  at the end of each round wins, and a new round begins.

-I also plan to include a garage type thing, where you can buy, upgrade, and customize cars.

And that’s about it. Does my basic idea sound correct? Do I have any flaws? Please give me ways I could improve/edit this, thanks!


texts: Load all bitmaps at once or only when needed?

texts:
I am starting to get a pretty hefty amount of bitmaps in my 2d game for android. I load them all in 3 colors to save some memory but the thing is, I load all of them when "Start game" is pressed, even the ones that wont be used for another 5-6 levels. And There is no switching activities between levels, its all controlled using states to make the game smoother. I lack knowledge in memory-management so any kind of advice or preferred methods would be greatly appriciated. For example, if the bitmaps from level 1 never needs to be used again, do I need to delete them from memory manually or does the GC do that for me?

Also, does anyone know a good method for re-using bullets? I imagine just creating new ones will take a toll on memory? Cus Right now Im at 16mb heap when running my game, which makes no sense at all, even when I disable 80% of my game heap-size stays high, so Im obviously missing something.


texts: Handling Event for multiple Sprite with one Event Listener in Andengine

texts:
In my app i need to add multiple sprite and add event to them. What i am doing now is using individual event listener for each and every sprite which is a kind of mess.

buttonS[0] = new Sprite(x_pos += 0, y_pos, orangeNumImage[0], this.getVertexBufferObjectManager()) {
        @Override
        public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
            if(pSceneTouchEvent.isActionDown()) {
                //Perform Some task
                }
                return true;
            } else {
                //Perform Some task
                return false;
            }
        }
    };

    buttonS[1] = new Sprite(x_pos += 115, y_pos, orangeNumImage[1], this.getVertexBufferObjectManager()) {
        @Override
        public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
            if(pSceneTouchEvent.isActionDown()) {
                //Perform Some task
                }
                return true;
            } else {
                return false;
            }
        }
    };

I was searching to handle this event with just one event listener and make the code shorter.

In normal android (without andengine) we could use something like this (by using android:onclick to areaTouched in button):-

public void areaTouched(View view) {
    Button nextclick = (Button) findViewById(R.id.button_nextClick);
    Button b = (Button)view;
    int check = Integer.parseInt(b.getText().toString());
    if (check == i){
          ........
    }
}


texts: How can I connect multiple explorable regions into one large map?

texts:
I am planning a 2-D science fiction game involving spaceships. A major thing that I am having trouble figuring out is how to create a 2-d array of smaller maps that the player can explore.

My inspiration is the Flash game Starfighter: Disputed Galaxy:

The map here is composed of a 2-D array containing smaller maps called sectors.  Each sector is connected to surrounding sectors, such that when the player moves to the edge of a sector, they go to the next.

For example, if I was in sector [05][01] and I move up until I cross the edge, I am taken to sector [06][01], then I go to the right, crossing the right edge of the sector, I am now taken to sector [06][02].

However, if I am at a sector like [0][5] and attempt to go down, It will not allow me to cross the edge line of the sector. In other words, a huge map made out of smaller maps.

I'd like to know how to implement those transitions. How do I programmatically determine which sector to move to (or not allow movement) when crossing over a boundary?


texts: Opengles 2.0 multi Textures fade out one by one

texts:
I have multi textures, A was drawed on top of B, B was on top of C ...., ( like Picture 1) .I want to fade out A first, then B will appear and fade out either... But when A fade out, background color appeared on top of B, ( like Picture 1 )? Why? What should I do?
I have enable Blend like this

glClearColor(0, 104.0/255.0, 55.0/255.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

and Fragment shader

"void main(void) { // 2\n"
"gl_FragColor = texture2D(Texture, TexCoordOut);\n"
"gl_FragColor  *= alpha;\n"

" }\n"

Picture 1：  background color is green, A and B are both rectangle, A is on top of B

Picure 2 When I fade out A, the result like this:

I aso try to use glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); but it doesn't work either.

**Update 1 shader **

const GLchar *vertex_shader_source_ =
{
    attribute vec4 Position;

uniform mat4 Projection;
uniform mat4 Modelview;

varying vec4 DestinationColor;

attribute vec2 TexCoordIn; // New
varying vec2 TexCoordOut; // New

void main(void) {
    gl_Position = Projection * Modelview *Position;
    TexCoordOut = TexCoordIn;// New

"}

};

const GLchar *fragment_shader_source_ =
{
    uniform highp float alpha;
    uniform sampler2D Texture;// New

varying highp vec2 TexCoordOut; // New

void main(void) { // 2
gl_FragColor = texture2D(Texture, TexCoordOut);
"gl_FragColor.a  = alpha;

}
};


texts:
I want to make a game data archive that contains all the game assets, now I could use zlib or lz4 to just make a simple zip archive type thing, but I need a bit more security, does anyone have any recommendations on adding AES encryption to the whole thing? I was also thinking maybe I need like a MPQ archive type system where I can mount the thing in the game engine and it acts as an interface to accessing the individual files inside, allowing streaming?

Any ideas appreciated, thanks.


texts: How small should touch triggers be at minimum?

texts:
Is there a known minimum physical size for reliable touch select triggers, considering  only selection (no long-press or drag). From personal experience, I would guess it to be about 5x5 mm (0.2x0.2 inch). Is there a canonical answer?

Context: I want to make my chess-like game board have as many cells as possible, but I still want users to be comfortable selecting cells, as it will be a frequent action.


texts: Raymarching signed distance function resulting in holes on surface - step size required?

texts:
I've been learning about raymarching and signed distance functions, and I implemented a raymarching fragment shader in Unity. It works fine for geometric shapes such as cubes and spheres, but when I started trying to build terrains with it I started running into issues.

I think I've narrowed down the problem to my signed distance function and not the raymarching implementation. To simplify things I've reproduced the problem using a sin wave, which seems to have the same result I'm seeing with noise functions.

The first issue is I'm getting strange holes in the surface - at least I think they are holes. At many points it's rendering inside the volume instead of the surface:

Here is a modified color output where I color each pixel based on the signed distance value.

color = 0 - signedDistance

Red: surface not hit
Black: At or very near surface
White: Inside the volume

I would expect to not see any white at all in this image. The results should be either black (surface found) or red (surface not found, ray marching loop stopped).

The other problem, which I believe is closely related to the first, is I'm getting inaccurate surface normal values at relatively large distances resulting in a wavy appearance. However, I'm fairly certain this is caused by the normal calculation using the same signed distance function which is returning inside the volume (which would provide incorrect, probably inverted, distance results), so I'm focusing on that issue first.

I've reproduced the issue I'm having on Shadertoy. While it's not exactly the same code, the basic algorithm is the same on both the GLSL Shadertoy sample and my Unity HLSL shader.

First, here is the most basic signed distance function I've used successfully. It just renders a flat plane at y=0:

float map(float3 position) {
    float sdist = position.y;
    return sdist;
}

Now I add a sine wave on top of this flat plane:

float map(float3 position) {
    float sdist = position.y + sin(x);
    return sdist;
}

What I expect is to see the plane move up and down as a sine wave along the x axis. I do see that, but I also see those odd holes (in the images above) through the surface. It's as if the ray marching portion goes right through past the surface and then stops inside of the volume.

I can somewhat mitigate this by stepping in much smaller steps than the calculated signed distance. Here is an example with the step size at 0.05:

But this decreases performance since each raycast / marching step now traverses much smaller distances.

Is stepping shorter distance than the calculated distance function result the way to fix this?

Just for completeness, here is a stripped down version of the ray marching function:

// March forward multiplier
float stepSize = 1.0;
// maximum number of times to march forward
float maxRayCasts = 128;
// The minimum distance considered to be the surface
float precis = 0.01;

vec3 castRay( in vec3 ro, in vec3 rd ) {
    float tmin = 0.01;
    float tmax = 600.0;

    vec2 res;

    float t = tmin;
    float m = -1.0;
    for( int i=0; i<maxRayCasts; i++ ) {
        res = map( ro+rd*t );
        if( res.x<precis || t>tmax ) break;
        t += res.x*stepSize;
        m = res.y;
    }

    if( t>tmax ) m=-1.0;
    return vec3( t, m, res.x );
}


texts: Question about coding rarity and non-MonoBehaviour referencing

texts:
I have a non-MonoBehaviour script called Item which contains two classes.

public class Item
{
    public string itemName;
    //public string itemRarity;

    public Item(string newItemName)
    {
        itemName = newItemName;
    }
}

and

public class ItemRandomizer
{
    List<Item> itemContainer = new List<Item>();

    public void AddItem(Item item, int amount)
    {
        for (int i = 0; i < amount; i++)
        {
            itemContainer.Add(item);
        }
    }

    public Item GetRandomItem()
    {
        int index = Random.Range(0, itemContainer.Count);

        // want to return item combined with rarity
        return itemContainer[index];
    }

I want GetRandomItem to not only return a random item "type", e.g., gloves, contained in the itemContainer list, but also combine it with a rarity (common, rare, legendary) and return that if possible.

How can I code this functionality in a flexible way so that two base items with the same drop chance can have varying drop chances when it comes to their rare versions? Swords and axes have the same drop chance, but a rare sword might be rarer than a rare axe. I'd like to maintain that kind of flexibility.

Also, if I make public string itemRarity a property of the Item class, but I want to set the rarity tier in GetRandomItem() in the ItemRandomizer class, how should I do that? Thus far, I've almost exclusively used MonoBehaviour classes so any pointers are appreciated.


texts:
A thought occurred to me after seeing this question:
Storing data - think character data for an online game - on the user`s computer is definitely less safe (maybe an understatement) than on a server under your control, but...

Is such a mechanism feasible? (while preventing cheating and such, of course...) If yes - why is it not used? Is it just me who hadn't seen it?

Some elaboration and ramblings:

A hypothetical advantage to this would be a need to store VERY little data on the server itself while still being able to handle a HUGE bookkeeping for the character, recording amounts of data you wouldn't dream of while storing the data on your server (think looking back on the exact date of your first attack in a game... sweet, useless, nostalgia :) ).

(Of course, there's a limit to how much you would do this way as well - your user isn't likely to condone a 1GB game save file... or they would... who knows.
Maybe an option for what data to keep could give users the choice between conservative and extensive logging of their adventures?)

Take the following example: I think that an attempt to:

Store a hash of the user's data on the server.
On the next run, request the data from the user`s end.
Hash it.
Compare the hashes.

is bound to fail.

The user could change the data on his end after the verification.
I'm assuming there will always be a 'hole' somewhere even if the programmer utilizes tons of checks throughout the game, verifying every action.

This could very well be a reason for not doing this... just remember I'm asking about feasibility, not practicality.

There are some more considerations, of course:

The user's data being at their hands can be less safe and less available.
They could lose it, have it stolen, forget their flash drive containing the file at home etc etc.

But it could also mean that the server has very little data on it to be compromised - say, if all of the user's data will be in their file, and the server will only be able to verify its authenticity via hashing mechanism and whatnot.

It will also be very easy to back up a server containing so little data.

The mechanism for the user should be a simple encryption/signature of the data file... or is that bound to fail as well?


texts: Why is my OpenGL enabled Java game not detected by Fraps?

texts:
Recently I found out that I could enable OpenGL hardware acceleration in my Java game with the line

System.setProperty("sun.java2d.opengl", "True");

Initial tests showed a big boost in performance. However, several days later I wanted to make a small test video using Fraps but I found out that it didn't recognize my application (as in the  FPS counter did not show and I could not record anything). After I removed the earlier mentioned line of code (thus disabling OpenGL hardware acceleration) it recorded just fine.

Is there any way to use Fraps while I have OpenGL enabled in my Java game?


texts: Freetype: create Signed Distance Field based font

texts:
I am trying to implement Font Rendering in my OpenGL C++ game.

I read many articles on the subject and got to know different methods, but I am still learning.

Valve has published a paper for Signed Distance Fields and how you can use them with Shaders to generate sharp edges for you text.
This has turned out to be the preferred method.

In my project I create all of my characters with Freetype in a loop, bind them to a texture object and reuse them whenever I need a specific character.

I perfectly know that it is not very efficient. Unfortunately, I haven't found a good way to load a bitmap with all the letters and use only single sections.
That's why I'm going to use this way for now.

I got everything working (creating the letters, binding the textures and use them for text), but without Signed Distance Fields.

So my Question is how to generate all of my character textures as a Signed Distance Field with the help of Freetype?

This is what my procedure looks like so far:

struct Character {
    GLuint textureID, advance;
    glm::ivec2 size, bearing;
};

.

FT_Library ft;
if( FT_Init_FreeType( &ft ) )
{
    throw std::string( "Could not initialize Freetype Library. Abort" );
}

FT_Face t_face;
if( FT_New_Face( ft, t_fontname.c_str(), 0, &t_face ) )
{
    throw std::string( "Could not load " + t_fontname + ". Abort" );
}

// set font size
FT_Set_Pixel_Sizes( t_face, 0, 48 );

// Disable byte-alignment restriction
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

std::map< GLchar, Character > characters;

for( GLubyte c = 0; c < 128; c++ )
{
    // Load character glyph
    if ( FT_Load_Char( t_face, c, FT_LOAD_RENDER ) )
    {
        throw std::string( "Could not load glyph from font. Abort" );
    }

    // Generate texture
    GLuint tex;
    glGenTextures(1, &tex);
    glBindTexture(GL_TEXTURE_2D, tex);
    glTexImage2D
    (
        GL_TEXTURE_2D,
        0,
        GL_RED,
        t_face->glyph->bitmap.width,
        t_face->glyph->bitmap.rows,
        0,
        GL_RED,
        GL_UNSIGNED_BYTE,
        t_face->glyph->bitmap.buffer
    );

    // Set texture options
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

    // Now store character for later use
    Character character =
    {
        tex,
        t_face->glyph->advance.x,
        glm::ivec2( t_face->glyph->bitmap.width, t_face->glyph->bitmap.rows ),
        glm::ivec2( t_face->glyph->bitmap_left, t_face->glyph->bitmap_top )
    };

    characters.insert( std::pair< GLchar, Character >( c, character ) );
}

glPixelStorei(GL_UNPACK_ALIGNMENT, 4);

I already fount this project on github which seems to be a solution. It also depends on Freetype, but to be honest I don't quite understand how the Signed Distance Fields are generated. It might also be too overkill for my intentions.

There are many websites that unfortunately use the old fixed pipeline or are not intended for C++.


texts:
I'm working on drawing lines in Unity, but find there is no way to draw clear, fine and smooth line in Unity, neither LineRenderer nor GL.LINES, both of them got jaggy, pixelated and coarse lines, even set Anti-Aliasing to 8x, just a tiny improvement. But when I turn to see iOS, I find it's easy to draw perfect and smooth line with the original iOS Graphic API, just as the screenshot of Paper app in iOS below, while we can see the screenshot of Unity drawing with LineRenderer, it's really ugly, even use Bezier, still jaggy.

Isn't there any way to draw smooth line in Unity? Will Shader do some great help? Does anyone have a good idea? Very appreciate it.

Paper on iOS

Unity with LineRenderer


texts: Should a 4x game use one class per planet type?

texts:
I'm try to make a small 4x game for my own educational purposes.

Currently I have interfaces like IStarSystem which contains a list of IPlanets. My next step was to make classes implementing those interfaces. Is it better to make classes like BarrenPlanet, GasPlanet, et cetera or is it better to make a single Planet class and define the different types in a XML file?