texts: Problem when scaling game screen in Libgdx

texts:
Currently, I'm able to scale the screen by applying this bit of code onto an OrthographicCamera

Camera.setToOrtho(true, Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2);

But something quite strange is happening with this solution, take a look at this picture of my game below

Seems fine right? But upon further investigation, many components are rendered off by one pixels, and the tiles all are.

Take a closer look

I circled a couple of the errors. Note that the shadow of the warrior I circled appears fine for the other warriors. Also keep in mind that everything is rendered at pixel-perfect precision when I disable the scaling.

I actually thought of a possible source for the problem as I'm writing this but I decided to still post this because I would assume somebody else might run into the same issue.


texts: How does Dwarf Fortress keep track of so many entities without losing performance?

texts: In Dwarf Fortress you can have hundreds of Dwarves, animals, goblins, etc in game at any one time, each with their own complex AI and pathfinding routines. My question is how does this not produce noticeable slowdown? Does each Dwarf run in its own thread?


texts: Detecting collisions between orbiting objects in 2D

texts:
I am currently in the process of creating a 2D space debris simulation. I have the orbital physics implemented, but I am currently struggling to find a suitable way of detecting collisions.

There are many objects, all of which are incredibly small and therefore very spread out, but they are travelling at very high speeds. It seems like using a grid would be a good way of detecting collisions between objects, although the objects are all constantly moving at high speeds so they will be moving between cells very often. I also have the issue of only having a limited rate at which I can update the object's positions because otherwise it runs slow, so I believe I need to implement some form of 'swept' collision detection.

Does anyone have any suggestions for a way in which I could efficiently check for collisions, but also make it so they don't miss?


texts: Scrolling background tiles in an isometric environment?

texts:
I'm working on my first game and I've run across an issue, when the character moves around, the "camera" is supposed to follow but I don't know how to make the computer draw only the necessary tiles.

Here is what I currently have

    public void drawBack(Graphics2D g2d) {
    int x = mvmt.getX(),
        y = mvmt.getY();

    int charOffX = mvmt.getCharCamX(),     //the difference between the top
        charOffY = mvmt.getCharCamY();     //left corner and where the
                                           //character is drawn

    for(
        int startCoordX = ????,
            startCoordY = ????,
            startTileMapX = ????,
            startTileMapY = ????;
        startTileMapX < width && startCoordX <= 3 * screenWidth;
        startCoordX += startXadd, startTileMapX++, startTileMapY--
    ) {
        for(
            int drawCoordX = startCoordX,
                drawCoordY = startCoordY,
                tileMapX = startTileMapX,
                tileMapY = startTileMapY;
            tileMapY < height && drawCoordY <= screenHeight;
            drawCoordX -= xadd, drawCoordY += yadd, tileMapY++
        ) {
            if(tile.getTileMap(tileMapX, tileMapY, 1) == 1) {
                g2d.drawImage(tile.getTile(tileMapX, tileMapY), drawCoordX, drawCoordY, 32, 32, null);

            }

        }

    }

I need the tile map to line up with where the character is. Thanks so much in advance, this one really has me scratching my head!


texts: How to keep Lua bindings from cluttering up C++ code?

texts:
I'm writing a game engine that uses C++ and Lua (and Luabind).

Currently, I'm writing all the bindings inside the constructor of the class being binded. I really don't like this because it's cluttering up my code.

Where should I put the Lua glue code so that it is out of the way and not cluttering up my codebase?


texts: Is there a way to determine Android physical screen size?

texts:
We're currently porting our games to Android, and would like to be able to release a universal build for tablets and phones. Is there a way to determine the actual screen size or DPI in order to adjust the size of interface elements accordingly? It took a fair bit of research.

Here's what we have tried:

using UnityEngine;

public class DisplayMetricsAndroid {

 // The logical density of the display
 public static float Density { get; protected set; }

 // The screen density expressed as dots-per-inch
 public static int DensityDPI { get; protected set; }

 // The absolute height of the display in pixels
 public static int HeightPixels { get; protected set; }

 // The absolute width of the display in pixels
 public static int WidthPixels { get; protected set; }

 // A scaling factor for fonts displayed on the display
 public static float ScaledDensity { get; protected set; }

 // The exact physical pixels per inch of the screen in the X dimension
 public static float XDPI { get; protected set; }

 // The exact physical pixels per inch of the screen in the Y dimension
 public static float YDPI { get; protected set; }

 static DisplayMetricsAndroid() {
     // Early out if we're not on an Android device
     if (Application.platform != RuntimePlatform.Android) {
         return;
     }

     // The following is equivalent to this Java code:
     //
     // metricsInstance = new DisplayMetrics();
     // UnityPlayer.currentActivity.getWindowManager().getDefaultDisplay().getMetrics(metricsInstance);
     //
     // ... which is pretty much equivalent to the code on this page:
     // http://developer.android.com/reference/android/util/DisplayMetrics.html

     using (
         AndroidJavaClass unityPlayerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"),
         metricsClass = new AndroidJavaClass("android.util.DisplayMetrics")
     ) {
         using (
             AndroidJavaObject metricsInstance = new AndroidJavaObject("android.util.DisplayMetrics"),
             activityInstance = unityPlayerClass.GetStatic<AndroidJavaObject>("currentActivity"),
             windowManagerInstance = activityInstance.Call<AndroidJavaObject>("getWindowManager"),
             displayInstance = windowManagerInstance.Call<AndroidJavaObject>("getDefaultDisplay")
         ) {
             displayInstance.Call("getMetrics", metricsInstance);
             Density = metricsInstance.Get<float>("density");
             DensityDPI = metricsInstance.Get<int>("densityDpi");
             HeightPixels = metricsInstance.Get<int>("heightPixels");
             WidthPixels = metricsInstance.Get<int>("widthPixels");
             ScaledDensity = metricsInstance.Get<float>("scaledDensity");
             XDPI = metricsInstance.Get<float>("xdpi");
             YDPI = metricsInstance.Get<float>("ydpi");
         }
      }
   }
}


texts:
I followed rbwhitakers tutorial on making a particle engine and I'm wondering how to get more particles on the screen. I was thinking that the "total" variable would do it but it doesnt. Is this something I'm doing wrong in the method or a hardware problem?

private Particle GenerateNewParticle()
    {
        Texture2D texture = textures[random.Next(textures.Count)];
        Vector2 position = EmitterLocation;
        Vector2 velocity = new Vector2(0, 10);
        float angle = 0;
        float angularVelocity = 0;
        Color color = Color.LightSkyBlue;
        float size = (float)random.NextDouble();
        int ttl = 100;

        return new Particle(texture, position, velocity, angle, angularVelocity, color, size, ttl);
    }

    public void Update()
    {
        int total = 100;

        for (int i = 0; i < total; i++)
        {
            particles.Add(GenerateNewParticle());
        }

        for (int particle = 0; particle < particles.Count; particle++)
        {
            particles[particle].Update();
            if (particles[particle].TTL <= 0 || particles[particle].Position.Y > 550)
            {
                particles.RemoveAt(particle);
                particle--;
            }
        }
    }

Im creating rain but I want it to be really heavy rain. Right now it just looks like a heavy sprinkle...I guess I would call it.

            particleEngine.EmitterLocation = new Vector2((float)rand.NextDouble() * (graphics.GraphicsDevice.Viewport.Width), 0);


texts: What algorithm to use to fill a KenKen square board with cages?

texts:
I am working on recreating KenKen, a popular math puzzle involving a blank grid that is divided into "cages". Each cage is just a collection of adjacent squares and has a clue which is generally a number and an operand, shown below:

What type of algorithm would be best to fill the square with cages? Assume the maximum number of cells per cage would be 3 and the board is 4x4 in size, like in the example above.


texts:
I will be working with my friends on our final year project. Our game will be FPS and I have to draw some animations for FPS view and other enemy character that can be programmed easily to make a good game.

I would like to know how game characters are made that are movable? What kind of software and engines are used for these characters?


texts: How can I insert a prefab instance programmatically inside the Canvas, in the bottom-left corner of the Canvas?

texts:
I am trying to create the Snake game in Unity, based on this video tutorial. I have also viewed this tutorial.

I have created the new project with the 3D template and manually added the Canvas. I created a prefab from an Image which loads a texture from the Assets. I have this code:

using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
    public GameObject whiteCellPrefab;
    int N = 30, M = 20, size = 16;

    // Start is called before the first frame update
    void Start()
    {
        Transform p = GameObject.Find("Canvas").transform;
        for (int i = 1; i <= N; ++i)
        {
            for (int j = 1; j <= M; ++j)
            {
                GameObject g = Instantiate(whiteCellPrefab, p);
                g.transform.localPosition = new Vector3(i * size, j * size);
            }
        }
    }

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

    }
}

If I manually add a prefab instance to the Canvas, it is positioned as I want: in the bottom-left corner. But the script above, attached to the Main Camera object, creates the Image objects starting from the center point of the Canvas towards the top-right corner of the Canvas.

In the example shown here, I also added a new prefab instance to the Canvas in the Unity editor. It is positioned correctly even when play testing but the ones added with the script are shown somewhere else.

Screenshots

Download my example

I tried to explain all the steps involved in my problem above, but here is the repo with my problem.

Thank you.


texts: GLSL shader algorithm to render a sprite map with a single draw call (on a single sprite mesh)

texts:
I'm trying to render a tile map world on a single sprite mesh (instead of one sprite per tile.) This significantly reduces the array vertex bus labor for extremely large worlds:

In order to do this, you pass two textures to the shader: the sprite sheet itself, and a texture containing tile IDs.

Sprite map (I know some tiles repeat but ignore that, this could be any spritesheet):

Below: Entire tile world represented by a 128 x 128 texture map, where each RGB value holds actual Tile ID for that location on the map. There are more efficient ways to represent the actual tile ID. Here, for the sake of simplicity, it is stored in the R component.

Putting it all together:

The right-most square is the screen output. On the image I just repeat texture... but what should actually happen is a tile world rendered from tiles on the sprite sheet.

I wrote the shader that is supposed to do this, but I'm stuck. I can render the sprite sheet itself, and even scale it on the sprite mesh, but I can't seem to get the tile IDs render at the proper location, matching the tile world data.

I do think I am really close and there are just a couple of modification needed to the shader -- so what am I doing wrong?

The following shader is what I have so far:

tilemap.vs

#version 330 core

layout (location = 0) in vec3 position;
layout (location = 1) in vec3 color;
layout (location = 2) in vec2 texCoord;

out vec2 TexCoord;

uniform sampler2D ourTexture;
uniform sampler2D ourTilemapDataTexture;

uniform mat4 Model;
uniform mat4 View;
uniform mat4 Projection;

void main()
{
    gl_Position = Projection * View * Model * vec4(position, 1.0);

    TexCoord = texCoord;
}

tilemap.frag

#version 330 core

in vec2 TexCoord;

uniform sampler2D ourTexture;
uniform sampler2D ourTilemapDataTexture;

void main() {

    // size of the tile world (128 by 128 tiles on one sprite)
    float cols = 128.0f;
    float rows = 128.0f;

    float tilesPerSide = 8.0f;

    // figure out which tile we´re in from the 3D coordinates
    vec2 tile = vec2(floor(TexCoord.x)/cols, floor(TexCoord.y)/rows);

    // get tile´s texture ID from tile ID texture map
    float tex = texture2D(ourTilemapDataTexture, tile).r;

    vec2 UV = vec2(tex + fract(TexCoord.x), fract(TexCoord.y));

    color = texture2D(ourTexture, UV);

    if (color.a == 0) // remove transparent areas
        discard;
}

PS: I looked at every tutorial I could find on Google, and tried to re-implement it in my shader to no effect. This is as far as I got so far.

Can anyone point out what I'm doing wrong?

Update #1 -- I was able to get position sampling to work.

I painted a bit on the world map:

It's not perfect but definitely a step forward:

Adjustments made to the fragment shader:

float cols = 128.0f;
float rows = 128.0f;

float tex = texture2D(ourTilemapDataTexture, TexCoord).r;
float tey = texture2D(ourTilemapDataTexture, TexCoord).g;

vec2 UV = vec2( (TexCoord.x * (cols) / (tex * 32.0f)),
                (TexCoord.y * (rows) / (tey * 32.0f)) );

color = texture2D(ourTexture, UV);

Sure it's not 100% correct but at least map indexing works now :)


texts: Adapting motion controls to changes in the player's orientation

texts:
I am using gyroscope data (pitch, roll) to move the player's space ship.

It works perfectly as long as you play in a standard position (e.g. sitting down).

Once you start using it lying down (e.g. in the bed), the control does not work anymore as the pitch and roll values I used become too big.

Here is the code I use, written in Objective-C. Any idea on how to improve/fix this?

-(void) gyroUpdate:(ccTime) delta
{
    CMAttitude * attitude;
    CMDeviceMotion * motion = [GameController sharedGameController].motionManager.deviceMotion;
    attitude = motion.attitude;

    float pitch =  attitude.pitch;
    float roll =  attitude.roll;

    ShooterScene * shooterScene = (ShooterScene *) [self parent];
    ShipEntity *playerSprite = [shooterScene playerShip];

    const float roolSpeed = 1000.0f;
    const float pitchSpeed = 1000.0f;

    //Midpoint of pitch is 0.5f, here the Player ship is NOT supposed to move.
    //Moving "forward" is equal to values towards 0.0f-
    //Moving "backwards" is equal to values towards 1.0f+

    float pitchProgression = 0.5f - pitch;

     CGPoint newPosition = CGPointMake(playerSprite.position.x + roll * delta * roolSpeed, playerSprite.position.y   + delta * pitchSpeed * pitchProgression );

    [playerSprite setPosition:newPosition];
}


texts: How to make custom shaped holes in terrain

texts:
So I'm trying to create a game where you fit certain shaped objects into the hole that fits them (similar to the young children's game with different shaped blocks) in Unity 3D.

I've encountered a problem, how do I make the holes in the terrain? Or what type of object should I use for making holes in?

So far I've tried to make a 3d model in unity by using other cubes and planes, it just doesn't feel right.
I guess I need to create a model in another software and import to unity, I don't know any other software I can use. Tips would help.


texts: How can I add array of components to a new gameobject?

texts:
I use Getcomponents to get all components from existing gameobject:

Component[] components = go.GetComponents(typeof(MonoBehaviour));

And I want to add them now to another gameobject:

for (int i = 0; i < components.Length; i++)
                {
                    var comp = components[i];
                    newObject.AddComponent<comp>();
                }

components is type Component[]

But when I try to type components inside the AddComponent<> the variable components not exist. Tried then to make the comp variable but can't type it inside the <> either.


texts: How to order objects with the same depth in the spritebatch cycle?

texts:
I have a tilemap in a isometric 2.5 view and i have also many objects moving and static.
The problem is many statics are standing in a "integer" place for obvious reasons and the depths of each object is calculated based on their position in the tilemap.

So what happens for some strage reasons is that 2 objects standing next to each other if big enough overlap and if they are in an adjacent diagonal tile they also have the same exact depth, but when drawing the order of same depth object seems random... I draw them in the same order every cycle ofc but the overlapped part of the texture sort of flicker being drawed on top or bottom apparently randomly...

Is there a way to use depth to order objects but make the same depth ones be in some kind of order and not random?


texts: How to debug fatal signal 11 code 2 in UnityMain?

texts:
i have searched for the

  fatal signal caused by Render or GxDriver, FlashMuller in unity forum
  says it's google play

the error:

08-03 14:59:47.503 32020-32092/? A/libc: Fatal signal 11 (SIGSEGV), code 2, fault addr 0xcbe8dffc in tid 32092 (UnityMain), pid 32020 (com.tuo3.alive)
08-03 14:59:47.533 32121-32121/? A/DEBUG: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
    Build fingerprint: 'OnePlus/OnePlus5T/OnePlus5T:8.1.0/OPM1.171019.011/1807181208:user/release-keys'
    Revision: '0'
    ABI: 'arm'
    pid: 32020, tid: 32092, name: UnityMain  >>> com.tuo3.alive <<<
08-03 14:59:47.544 32121-32121/? A/DEBUG: backtrace:
        #00 pc 000575d0  /system/lib/libc.so (je_arena_tcache_fill_small+71)
        #01 pc 00077919  /system/lib/libc.so (je_tcache_alloc_small_hard+16)
        #02 pc 00058fc7  /system/lib/libc.so (je_arena_palloc+1650)
        #03 pc 00069bd1  /system/lib/libc.so (imemalign+1164)
        #04 pc 0006d373  /system/lib/libc.so (je_memalign+26)
        #05 pc 001d6f18  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (UnityDefaultAllocator<LowLevelAllocator>::Allocate(unsigned int, int)+24)
        #06 pc 001da888  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (MemoryManager::Allocate(unsigned int, unsigned int, MemLabelId const&, AllocateOptions, char const*, int)+852)
        #07 pc 001da254  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (malloc_internal(unsigned int, unsigned int, MemLabelId const&, AllocateOptions, char const*, int)+128)
        #08 pc 00193bc8  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (core::StringStorageDefault<char>::assign(char const*, unsigned int)+180)
        #09 pc 00a350bc  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (__gnu_cxx::hashtable<std::pair<core::basic_string<char, core::StringStorageDefault<char>> const, ZipCentralDirectory::PathDescriptor>, core::basic_string<char, core::StringStorageDefault<char>>, __gnu_cxx::hash<core::basic_string<char, core::StringStorageDefault<char>>>, std::_Select1st<__gnu_cxx::hash>, std::equal_to<core::basic_string<char, core::StringStorageDefault<char>>>, std::allocator, <ZipCentralDirectory::
        #10 pc 00a34adc  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (_ZZN19ZipCentralDirectory20readCentralDirectoryEvEN3$_08__invokeERK15FileSystemEntryR12FileAccessorPKcRKN3zip4CDFDEPv+508)
        #11 pc 00a38160  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (zip::CentralDirectory::Enumerate(bool (*)(FileSystemEntry const&, FileAccessor&, char const*, zip::CDFD const&, void*), void*)+804)
        #12 pc 00a348d0  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (ZipCentralDirectory::readCentralDirectory()+20)
        #13 pc 00a26630  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (apkAddCentralDirectory+84)
        #14 pc 00a19074  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (Mount(char const*)+84)
        #15 pc 00a090dc  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (UnityInitApplication()+216)
        #16 pc 00a0a660  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (UnityPlayerLoop()+264)
        #17 pc 00a0cc68  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (nativeRender(_JNIEnv*, _jobject*)+228)
        #18 pc 000114cb  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/oat/arm/base.odex (offset 0x10000)

[More discussion][2]


texts: PhysicsJS on mobile devices: how to optimize for speed

texts:
I'm (physics n00b) developing a small animation (gamification) in a mobile HTML5 app (PhysicsJS, HTML5, Cordova, Ionic, JavaScript).

This animation is derived from Basket of verlet constraints. This basket has to carry a lot more bodies (circles).

I'm experiencing performance problems, even on decent hardware (iOS and Android, the latter is worse). The bodies move like if they were in an aquarium. If I remove the basket, the performance is way better, but not yet satisfactory.

How can this be optimized in a sense that users don't have the feeling of watching a film in slow-motion?

Are there any tweaks to control the engine to do less calculation?

Am I using the appropriate physics engine or are there alternatives with significant better performance?

Remark: on my MacBook in Chrome, there is absolutely no performance problem and all movements are very smooth -> no aquarium.


texts: How can I get voice recognition features into the Unity Game Engine? Is there a plug-in or a framework (hopefully freeware) that I could use? If so, do you have any ideas on how to install it? Also, how much of a problem would there be with background noises in the game interfering with the voice inputs into the game? Are there any examples of games on the market that use this? (besides for Spain 3D for the Torque Game Engine).


texts: Creating Animations Without Hardcore Art for 2D Action RPG

texts:
I'm working on a 2D action RPG. One of the issues I run into is art; in the vein of Flash games like FF7, Secret of Mana, or Epic Battle Fantasy, I would like to actually display the weapon with the player while they're walking around, and swap it out with a different image when they change weapons.

As a simple example, if I have a bronze and gold sword, when walking around, attacking, etc. you would see the bronze or gold sword image accordingly. This is an oversimplifcation, because I'm not sticking to only recolouring based on the weapon; I may actually change the design (not 100% sure about this yet).

As such, my core question is: how can I design this to minimize the amount of artwork I need to make for each weapon?

It seems like I need to create standardized weapon sizes (eg. 18x36px sword), positions relative to the character to show them for each frame, and I need to create a sprite-sheet for each frame. (I have four directional images for walking, each with four frames of animation.)

This means, per weapon, I need another 4x4 frames of animation; that's a lot (for a non-artist like me). The other approach would be programmatic animation; but how will that work? I have to worry about:

Positioning must be always similar for each weapon (different sizes?)
Occlusion; the whole weapon appears when looking down, but most of it is hidden when looking up; how can I standardize this?

For reference, see (really) FF7; they did a fairly decent job of this, albeit in 3D.

Sample:


texts: How to calculate a quad based on a triangle pairs shared edge

texts:
Based on two given triangles, I would like to calculate a quad that can be used as a 'fat' line for the edge between the triangles.

I have googled around and while it is very easy to draw lines in OpenGL or DirectX, the problem is that you can only guarantee a thickness of 1 pixel.

To overcome this I need to generate a quad for the line.

So given the below image...

I have a set of triangles, and I want to draw a line where the red dots are.
I know the start and end vectors for this line. And all the details of the triangles

I need to create a quad so that I can define the thickness (seen as the blue arrow)

An extra complication is that the triangles may not be on the same plane.

So from the side perspective, the 'line' would need to be created with its edge growing like this. Where both black lines are the sides of two separate tringles and the shared edge is from the point and moves into the screen.

All the calculation for this will be done offline

I am hoping that just a nudge in the right direction and I will be able to hammer this out on my own. (maybe)

OR if there is another way to solve the fat line problem then let me know.
I will be rendering this using OpenGL ES 1 (without a shader)

Thanks.


texts: Animation loop finishes in 8 meters at 17 frames, how fast is it going?

texts: So I made this model in Blender and synced its walk cycle using an animated path that was 8 meters long at 17 frames. But I don't know how to sync it when moving the model using a rigidbody.


texts: In Unity, how do you check if a camera is rendering anything? (Unity 2018.3)

texts:
I'm trying to have a camera automatically disable if it's not rendering anything.

Is there a simple way to check if a camera is blank/empty?

Edit: Alternatively, is there a way to prevent a camera from rendering if there is nothing in it's view?

For example, I do not want MSAA applied to a blank camera. (I'd hope it would attempt AA, but effectively do zero work)


texts:
I'm looking to generate noise that looks like this:

(images courtesy of Understanding Perlin Noise)

I'm basically looking for noise with lots of small "ripples". The following is undesirable:

Are there any simple ways to do this? I've been looking at perlin and simplex for a week now and I can't seem to ever get it to work in JavaScript, or when I do, I don't have the correct parameters to generate such images, or it is excruciatingly slow.

I understand that the 3 images I posted could probably be achieved by the same algorithm but at a different scale, but I don't need that algorithm. I just need a very simple algorithm to achieve something like in the first image ideally. Maybe some kind of blurring would do the job, but I can't manage to have results.

I'm developing this in JavaScript but any kind of code or even a simple and detailed explanation will work.


texts: What kind of book I read, that should do a full indie game?


texts:
When I close my application, I get the following errors in the Direct3D Debug output:

Direct3D9: (INFO) :MemFini!
Direct3D9: (ERROR) :Memory still allocated!  Alloc count = 20
Direct3D9: (ERROR) :Current Process (pid) = 0000162c
Direct3D9: (ERROR) :Memory Address: 05fb7d0c lAllocID=50 dwSize=000170d8, ReturnAddr=0615e508 (pid=0000162c)
Direct3D9: (ERROR) :Memory Address: 08c86594 lAllocID=1046 dwSize=00004bc4, ReturnAddr=0614d5ea (pid=0000162c)
(...)
Direct3D9: (ERROR) :Memory Address: 08d0c31c lAllocID=1471 dwSize=00001a40, ReturnAddr=0615e784 (pid=0000162c)
Direct3D9: (ERROR) :Total Memory Unfreed From Current Process = 258932 bytes

I've carefully looked over my code and the one thing I found suspect was a texture and a surface I got from the texture. I realised that surface->Release() wasn't returning 0, which means, I believe, that someone else still has a reference to it. So just to try something, I released it several times in a while loop until it returned 0. Direct3D then returned the following error:

Direct3D9: (ERROR) :A level of a mip-map has been released more often than it has been add-ref'ed! Danger!!

I don't get it. That surface is somehow referenced more than once but hasn't been "add-refed" more than once? How can I debug who is holding a reference to it?

Thanks.


texts: OpenGL tesselation doesn't change geometry shape

texts:
I implemented tessellation control and evaluation shaders in OpenGL, but the effect it has on my terrain was not what I expected.

I expected that the low poly-count curves and shapes on the terrain would be smoothed out with new vertices between the old ones but instead I get the effect shown below.

This tessellation seems to simply create a high poly-count version of the exact same model with no difference in shape.

How do I remedy this, or am I misunderstanding the purpose of tessellation?

Without Tessellation

With Tessellation

Tessellation Control Shader

#version 450

layout(vertices = 3) out;

in VS_OUT {
    vec3 normal;
} tesc_in[];

out TESC_OUT {
    vec3 normal;
} tesc_out[];

uniform vec3 view_position;

/* Return level of tessellation based on distance */
float tess_level(vec4 pos1, vec4 pos2) {
    const float d = distance(pos1, pos2);
    if(d < 0.5) { return 25; }
    if(d < 1.0) { return 20; }
    if(d < 1.5) { return 15; }
    if(d < 2.0) { return 10; }
    if(d < 2) { return 5; }
    if(d < 3) { return 2; }
    return 1;
}
float tess_level(vec3 pos1, vec3 pos2) {
    return tess_level(vec4(pos1, 1.0), vec4(pos2, 1.0));
}

/* Sets tessellation levels */
void set_LoD() {
    vec4 d1 = vec4(gl_in[1].gl_Position.xyz + (gl_in[2].gl_Position.xyz - gl_in[1].gl_Position.xyz) / 2, 1.0);
    vec4 d2 = vec4(gl_in[0].gl_Position.xyz + (gl_in[2].gl_Position.xyz - gl_in[0].gl_Position.xyz) / 2, 1.0);
    vec4 d3 = vec4(gl_in[0].gl_Position.xyz + (gl_in[1].gl_Position.xyz - gl_in[0].gl_Position.xyz) / 2, 1.0);

    vec4 view_position_v4 = vec4(view_position, 1.0);
    float e0 = tess_level(d1, view_position_v4);
    float e1 = tess_level(d2, view_position_v4);
    float e2 = tess_level(d3, view_position_v4);
    float m = min(e0, min(e1, e2));

    gl_TessLevelInner[0] = floor((min(e0, min(e1, e2)) + max(e0, max(e1, e2))) / 2);
    gl_TessLevelOuter[0] = e0;
    gl_TessLevelOuter[1] = e1;
    gl_TessLevelOuter[2] = e2;
}

void main() {
    if(gl_InvocationID == 0) {
        set_LoD();
    }

    tesc_out[gl_InvocationID].normal = tesc_in[gl_InvocationID].normal;
    gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;
}

Tessellation Evaluation Shader

#version 450

layout(triangles, fractional_even_spacing, ccw) in;

in TESC_OUT {
    vec3 normal;
} tesc_in[];

out TESE_OUT {
    vec3 normal;
    float height;
    vec4 shadow_position;
} tesc_out;

uniform mat4 model_view;
uniform mat4 model_view_perspective;
uniform mat3 normal_matrix;
uniform mat4 depth_matrix;

vec3 lerp(vec3 v0, vec3 v1, vec3 v2) {
    return (
        (vec3(gl_TessCoord.x) * v0) +
        (vec3(gl_TessCoord.y) * v1) +
        (vec3(gl_TessCoord.z) * v2)
    );
}

vec4 lerp(vec4 v0, vec4 v1, vec4 v2) {
    return (
        (vec4(gl_TessCoord.x) * v0) +
        (vec4(gl_TessCoord.y) * v1) +
        (vec4(gl_TessCoord.z) * v2)
    );
}

void main() {
    gl_Position = lerp(
        gl_in[0].gl_Position,
        gl_in[1].gl_Position,
        gl_in[2].gl_Position
    );

    tesc_out.normal = normal_matrix * lerp(
        tesc_in[0].normal,
        tesc_in[1].normal,
        tesc_in[2].normal
    );

    tesc_out.height = gl_Position.y;

    tesc_out.shadow_position = depth_matrix * gl_Position;
    gl_Position = model_view_perspective * gl_Position;
}


texts: Rotating cube as child of another gameObject results in it skewing in 2 of 3 axes

texts:
I have added a cube and changed its scale and position but not its rotation.
I added a second cube as a child of that first cuboid.  I was hoping to rotate it but instead it just skews the second cuboid.
The skew only happens in 2 out of 3 of the axes.
Additionally the skew does not happen if the child cuboid is not a child of the first cuboid.

Screen shots attached below.  Skew happening in one of the two axes:

Rotation correctly occurring in third axis:

How do I rotate it in all axes?
Also as Skew seems useful.  How do you control skewing it in all axes?


texts:
I'm currently using the following general pattern for most of my configurable components (i.e. MonoBehaviours):

public class MyComponent : MonoBehaviour
{
    // Configurable fields
    [SerializeField]
    private bool someParameter;
    [SerializeField]
    private int anotherParameter;

    // Fake constructor to act as a replacement for GameObject.AddComponent
    // with additional parameters.
    public static MyComponent AddTo(GameObject gameObject, bool someParameter, int anotherParameter)
    {
        var myComponent = gameObject.AddComponent<MyComponent>();

        myComponent.someParameter = someParameter;
        myComponent.anotherParameter = anotherParameter;

        return myComponent;
    }

    // Public properties and other methods
    // ...
}

This works around the lack of constructors for MonoBehaviours but still encapsulates the parameters in such a way, that they can only be set at the time the object is created, or through the Inspector (which is effectively the same thing once the game is built).

Unfortunately, this approach doesn't help once I want to use my component inside a prefab. When I instantiate the prefab, the component has already been created, and I can no longer touch those parameters. And as far as my google-fu can tell, there's no way to pass parameters into prefab instantiation (much like there isn't a way to pass a parameter into AddComponent). It seems like everyone just instantiates their prefabs and then fiddles with some public properties to configure them.

So the question is, is there any way to set things up, such that I can configure some fields on my prefabs, but without exposing them publicly and breaking encapsulation?

(I realise that I could add a similar static "factory" method which instantiates a specific prefab and then configures the component inside that prefab, but a) this means adding one such method for each prefab and b) it breaks down once I want to configure multiple components within the same prefab.)


texts:
I've read up on several ways of doing this but can't seem to find one that works for what I need. I have a method that is called and performs some logic, and then I need it to wait for a period of time, then continue with more logic in the same function. I had planned on using a coroutine which is what I did with another part of the game, but I'm running into an issue because the class doesn't directly inherit from Monobehaviour so it can't start a coroutine. I've tried Thread.sleep, but that just makes the game stop, so that isn't what I want. I don't know if there is some way to put a timer in there that will wait and then continue the function or if there is something else that I'm overlooking.

Here is the current code:

public void AssaultRifleShot (GameObject mainBall)
{
    if (AmmoRemaining > 0)
    {
        //if there is ammo remaining, set the main ball to just a normal ball so it can be destroyed on impact and then start coroutine
        mainBall.GetComponent<Ball> ().mainBall = false;
        mainBall.GetComponent<Ball> ().onBallHitPaddle -= AssaultRifleShot; //unsubscribe to event when mainBall is set to false.
        StartCoroutine(timer, coroutineHost);

        AmmoRemaining -= 1;
    }
    else
    {
        DestroyPickUp();
    }
}

There are other method calls inside the code for the coroutine, so those would end up going after whatever timer or someting goes in instead of the coroutine.


texts: Why I'm getting exception ArgumentException: Scene to unload is invalid ? Should I change to UnloadScene without async?

texts:
The script is attached to a button in the Inspector to the On Click:
The script is attached to both StartGame and StartGameButton:

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

public class LoadSceneOnClick : MonoBehaviour
{
    public void ActivatePlayer()
    {
        SceneManager.UnloadSceneAsync(0);
    }
}

The exception is on the line:

SceneManager.UnloadSceneAsync(0);

ArgumentException: Scene to unload is invalid
UnityEngine.SceneManagement.SceneManager.UnloadSceneAsync (Int32 sceneBuildIndex) (at C:/buildslave/unity/build/artifacts/generated/common/runtime/SceneManagerBindings.gen.cs:196)
LoadSceneOnClick.ActivatePlayer () (at Assets/My Scripts/Scenes/LoadSceneOnClick.cs:10)
UnityEngine.Events.InvokableCall.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:165)
UnityEngine.Events.UnityEvent.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent_0.cs:58)
UnityEngine.UI.Button.Press () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:36)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:45)
UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:50)
UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:261)
UnityEngine.EventSystems.EventSystem:Update()


texts: How to split login and game logic when writing servers?

texts:
I'm building a poker like game server, I was going to have all logins and game logic to be handled on one server, but from my research on the web, I learn that this would not scale, and it would make sense to split the work into a login and game servers. But what I don't get is after I handled authentication in the login server, and have the client make a new connection to the game server, how would I know which client is which? Would I not have to re-login again and thus defeat the purpose of having a server for login? Is there some way to pass a connection across processes and machines that I don't know about?
Excuse my little knowledge of networking.


texts: Drawing a simple triangular prism in opengl in 3D

texts:
Is there a simple way to draw a triangular prism in opengl?

I'm using lighting and a non-orthographic camera. I basically need a 3d object, not just vertices.

edit: well I've tried searching, and I tried doing it with two cubes. One that is rotated at an angle from the other, but logically that doesn't work. I have to get an object with angles less than 90 degrees.

I basically need something like this:


texts:
I'm trying to get some particles to work properly - they should blend among themselves but not with the background color. For this I'm using additive blending, textures with premultipled alpha and set the color as (r*a, g*a, b*a, 0) on textures I want to add up.
I'm using the blend mode: glBlendFunc(GL11.GL_ONE, GL_ONE_MINUS_SRC_ALPHA); for everything.

I found out that what I want to do can be achieved by rendering and additively blending the particles in a framebuffer and then render that framebuffer on top of the background with standard alpha blending. In theory I think this should work..however i'm still getting the same result as I did before which is very bright particles at bright areas of the background.

So what I'm doing is simply:
1)Render the background as usual with color (r*a,g*a,b*a,a)

2)Bind my fbo

3)Use GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); GL11.glClearColor(0f, 0f, 0f, 0.0f);

4)Render all the particles with color as (r*a,g*a,b*a,0)

5)Unbind the fbo and render it on top of the bg with (1,1,1,1) color.

Why doesn't this work?


texts:
At the moment I'm writing a little OpenGL application. For now I have a car which can drive down a road. This works really good because I simply put the car on the street plane. Now let's say on the road is a little ramp and my car should be able to drive along that ramp. How can I do this? At the moment I only have translation along the z axis. Let me describe how I would do it:

Calculate angle between ramp and street normal
Rotate car by this angle and translate it

First of all: Is there an easier way to do it? My main problem from this idea is how should I get the normal from the triangle the car is interacting with? And of course I can not rotate the car the full angle at the beginning because then a part of the car is under the ground. So what is the usual way to do this?


texts: Using Ninject for DependencyInjection on Xbox, noticable impact?

texts:
This may be classed as a slightly subjective question but there is very little information on this at the moment, so I just thought I would ask here incase anyone has any experience with this.

I am working on a simple(ish) game for XNA at the moment, but there are quite a few situations where I am wishing I had dependency injection available. Take an example of having a map object which relies upon a tile collection to draw things to the screen, this could be a list of tiles or a spatially partitioned object which would optimise the drawing  and update routines. There are lots of other parts where I would rather move the responsibility of binding my application together to a higher level, hence a DI configuration step.

So I know you can use Ninject on XNA with Windows/Xbox/Win7Phone, however I was just wondering if you have any noticeable impact (that is the subjective part). As Ninject must store in memory all its possible bindings ready to dish them out whenever required, although most of the instantiation would be done within IFactory based implementations for relevant entities etc, but I am just worried that Ninject may impose a small performance impact upon loading and storing the bindings in memory.

I am assuming the notice is barely worthwhile noting providing you are just binding your topmost elements and your factory implementations and not making it create EVERYTHING for you, but just wanted to know if anyone had used it before on a major project and any pros/cons they found doing things this way rather than just hard-coding your application composition in your game (or other class).

(I wanted to add the Ninject keyword but dont have enough rep to do so on here)


texts: Turning a 2D character to face left or right

texts:
So far I know of the following ways to turn a 2D character to face the other direction (in my case the char can only walk left or right):

Mirror the right walk animation and use that as a separate state in the animation controller.
Simply set a 180 rotation on the game object that hold all of my characters parts when he turns the other way.
Create a transition animation by blending (I don't know if it's called exactly like this) the left oriented sprite and the right one.
Orient the sprite based on its movement direction using this code:

void OrientChar()
{
    Vector3 moveDirection = gameObject.transform.position - _origPos;
    if(moveDirection != Vector3.zero)
    {
        float angle = Mathf.Atan2(moveDirection.y, moveDirection.x) * Mathf.Rad2Deg;
        gameObject.transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
    }
}

1 and 2 will create a rather abrupt change and might not look smooth. How do I make them or is it possible to make them smooth?

For number 3 I have a very basic idea on how to do it. Can I do it directly Unity?


texts: How to Fetch a Frame Number from Animation Clip

texts:
I'm trying to find out how to fetch the frame number from an animation clip accurately. I don't want to get a value between 0 and 1 that shows as a percentage-as-a-decimal how much of the animation has played (example: 0.5 = the 5th frame of 10 frames) because it doesn't seem to be accurate. This also seems impractical, so is there a way to accurately fetch a frame number from an animation clip?

Thanks.


texts: Why won't my sprite move with this code?

texts:
When I ran the android application, The sprite image will not move when I press the input keys. I followed a tutorial based on input keys and wish to know what's wrong. Can anyone see what's wrong? Not sure if its my android emulator.

EDIT: website where the tutorial is located http://www.gamefromscratch.com/post/2013/10/15/LibGDX-Tutorial-4-Handling-the-mouse-and-keyboard.aspx

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;

public class otherSide implements ApplicationListener
{
    private SpriteBatch batch;
    private TextureAtlas textureAtlas;
    private Texture texture;
    private Sprite sprite;
    private Animation animation;
    private float elapsedTime = 0;

    @Override
    public void create()
    {
        float h = Gdx.graphics.getHeight();
        float w = Gdx.graphics.getWidth();

        batch = new SpriteBatch();
        texture = new Texture(Gdx.files.internal("image.png"));

        sprite = new Sprite(texture);
        sprite.setPosition(w/2-sprite.getWidth()/2, h/2 - sprite.getHeight()/2);
        //textureAtlas = new TextureAtlas(Gdx.files.internal("spritesheet.atlas"));
        //animation = new Animation(1/15f, textureAtlas.getRegions());
    }

    @Override
    public void resize(int width, int height)
    {

    }

    @Override
    public void render()
    {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        if(Gdx.input.isKeyPressed(Input.Keys.LEFT))
        {
            if(Gdx.input.isKeyPressed(Input.Keys.CONTROL_LEFT))
            {
                sprite.translateX(-1f);
            }else
            {
                sprite.translateX(-10.0f);
            }
        {

        if(Gdx.input.isKeyPressed(Input.Keys.RIGHT))
        {
            if(Gdx.input.isKeyPressed(Input.Keys.CONTROL_RIGHT))
            {
                sprite.translateX(1f);
            }else
            {
                sprite.translateX(10.0f);
            }
        }

        batch.begin();
        //elapsedTime += Gdx.graphics.getDeltaTime();
        //batch.draw(animation.getKeyFrame(elapsedTime, true), 0, 0);
        sprite.draw(batch);
        batch.end();

    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void dispose()
    {
        batch.dispose();
        texture.dispose();

    }
}


texts: Why do I get syntax error: identifier FHttpRequestPtr

texts:
I'm trying to add HTTP requests to my game and everything compiles fine until I try to set up a delegate for when the response is ready. Adding this function causes the compiler to fail for syntax error identifier FHttpRequestPtr.

header

void OnSaveTokenResponse(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);

cpp

void UGamejoltApi::OnSaveTokenResponse(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{

}

I have both #include "Http.h" and #include "Interfaces/IHttpRequest.h". I also have this in my build file PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "HeadMountedDisplay", "HTTP" });.


texts:
How does one create a Texture2D Array in DirectX11? The texture I am trying to create is not multisampled, and I want only one mip level. I can't find a working example of a Texture2D Array. I have a buffer of 2D images that I want to use as a Texture2DArray in a shader.

The following code snippet works when sTexDesc.ArraySize=1 (as a Texture2D). With sTexDesc.ArraySize=2 the subsequent call to CreateTexture2D crashes with this Access violation inside DirectX:

  Unhandled exception at 0x000007fef5d6771a in test.exe: 0xC0000005: Access violation reading location 0xffffffffffffffff.

With larger values of ArraySize CreateTexture2D returns E_INVALIDARG. ubImageStorage contains valid data. As a Texture2D I can add multiples of the slice offset to this buffer address when assigning pSysMem and read each slice from a shader. What am I missing? I have tried all combinations of bind and usage flags and various values for MipLevels with no success.

D3D11_TEXTURE2D_DESC sTexDesc;
sTexDesc.Width = 1024;
sTexDesc.Height = 1024;
sTexDesc.MipLevels = 1;
sTexDesc.ArraySize = 2;
sTexDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sTexDesc.SampleDesc.Count = 1;
sTexDesc.SampleDesc.Quality = 0;
sTexDesc.Usage = D3D11_USAGE_IMMUTABLE;
sTexDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
sTexDesc.CPUAccessFlags = 0;
sTexDesc.MiscFlags = 0;

D3D11_SUBRESOURCE_DATA sSubData;
sSubData.pSysMem = ubImageStorage;
sSubData.SysMemPitch = (UINT) (1024 * 4);
sSubData.SysMemSlicePitch = (UINT) (1024 * 1024 * 4);

ID3D11Texture2D* pTexture;

hr = m_pd3dDevice->CreateTexture2D(&sTexDesc,&sSubData,&pTexture);

Here are the relevant pages from MSDN:
ID3D11Device::CreateTexture2D Method
D3D11_TEXTURE2D_DESC Structure


texts: Potential Field Pathfinding in a non Axis Aligned World

texts:
I am trying to create a game that has player created obstacles which can be placed anywhere in free space, and which has a large amount of enemy agents. In persuit of maximizing the number of agents I can have active at any given time, and as a secondary goal of maximizing the possible size of my map, I found potential/vector fields to be a very appealing solution, except for one thing.

Since the geometry is not aligned to any particular grid I have the problem of what to do when I have a narrow alley between obstacles that is approximately the size of one of my units (As such:)

In this case, cells approximately the same size as the unit would consider this route impassable. One solution would be to use a smaller size of cell, but this of course means more computational resources. Does anyone know of an alternative solution to this problem?


texts: How can a NodeJS server be used from Game Maker HTML5?

texts:
I want to create a client-server game that runs on Game Maker HTML5-NodeJS. The NodeJS server will be an AI server - a bot that acts like a human opponent and plays against the human player at a front-end game client that is coded in GM HTML5.

How can a NodeJS server be used from GM HTML5. Are there any examples of such a system?

I already got an iOS game that can talk to a remote AI server (coded in Lua) using TCP sockets. Can this be done with Game Maker HTML5 and NodeJS.


texts: How can I handle ball interaction with lanes in a pinball game?

texts:
In a pinball game, how can I handle collision or constraints on the ball for convincing movement on those highway rails/tracks?

I assume using physics and a mesh collider would not work, even when the poly count is really high the ball still bashes into all those faces instead of hugging a smooth, round wall. I could constrain the ball to a spline but I foresee problems with the balls speed and proper physics.

I'm wondering if it is possible to tell the ball that mesh corners below a certain degree should be treated as round. Perhaps only when coming from a certain angle?


texts: I'm still starting out anf i'm making a 2d game where a ball which jumps through different blocks. The ball jumps a fixed height when i place the blocks that the ball should dodge i place them randomly so let's say 0 4 8 11 17 so the distance between two blocks is not always the same my problem is that i cant find a way to do algorithm for a systematic way to determine how hard is this level so if i made a sequence 0 6 11 19 21 i try it to see how difficult is it.. i want a way so that the blocks positions are determined in a way where i could know how difficult it is and that it is possible to pass this level. It is know the height the ball reaches as well as the time he ball moves in the x-direction as well as the time it takes to jump and get back to its original position..


texts: How to set LOD specifications for all meshes in unreal at once?

texts: I have a large model and want to avoid separately setting the LOD specifications for each component in the model. Is there are way set LOD specifications for all meshes in unreal at once since I want to set the same specifications for each one? (percentages, how many LOD's, and at what screen distance they kick in, using Unreal's autogenerated LOD's).


texts: Is it necessary to know some programming language before learning to use Unity

texts: I had learnt a bit of Java programming in school...is there any other programming language that I should learn to be able to work using Unity?


texts: How to prevent the "Too awesome to use" syndrome?

texts:
When you give the player a rare but powerful item which can only be used once but is never really required to proceed, most players will not use it at all, because they are waiting for the perfect moment. But even when this moment comes, they will still be reluctant to use it, because there might be an even better moment later. So they keep hoarding it for a moment which will never come.

In the end, they will carry the item around until it is outclassed by other, more readily available resources, or even until the very end of the game. That means that such one-shot items don't provide any gameplay-value at all. They are simply too awesome to use.

What can you do to encourage the player to make use of their one-shot items and not hoard them?


texts: How should I attenuate sound in a 2D game where you can zoom in and out?

texts:
In my 2D game, I have some ambient sounds like the noise of a waterfall or the humming of a generator. However, it is not practical to play these sound all the time at full volume as in a large level the overlap of many of such noises would be quite unpleasant to the ear.

I am currently thinking about a system that modulates the volume of certain sounds depending on their distance to the player. However, this is partly not a great solution as (for example) in a zoomed state the player might be quite far away from the sound source (like a water fall) but still be able to see it on screen but not hear it (due to the distance) which is quite awkward.

Is there a solution for such a problem?


texts:
This is the first game I have developed. Please correct me if I'm mistaken.

I want to build an online 2-player turn based card game (Shithead). I want to code it in Java as that is what I have most experience in.

Networking

From my research, I've gathered that for turn based card games a TCP connection is best (reliability over the need for constant packets). I plan to have a single Java game server that will be able to host multiple concurrent games using sockets to pair clients together in an events-based manor. I've read that it makes most sense to have the game state on the server in order to protect against cheating etc.

Client1 (C1) sends move to server.
Server validates move. If valid - Server sends updated game state (with certain information hidden such as opponents hand) to clients & tells C1 to wait for C2 and for C2 to make a move.
C2 sends move to server. Repeat.

Does my plan sound sensible? I don't want to start going down this route if I've miss-understood something.

A problem I am having is knowing which java frameworks (if any? SpringBoot?) to use to achieve this. Could anyone recommend any to me?

Client

I was planning on making the client browser-based but after some thought I think I would prefer to make a desktop client. I plan to make a Java client that uses the JavaFX GUI library that the user interacts with by clicking on cards to perform certain actions - would I be able to embed this in a webpage if I changed my mind? Would it take a lot of work?

At this point I don't want to put too much time into making a fancy GUI (by using a more sophisticated game engine) as I'd rather focus on making a mini-max AI player (and given I have time, a neural network AI to learn from playing tons of games against the mini-max AI).


texts: How do I make my glsl RGB displacement map look like this

texts:
I want to use a RGB texture as described in this video here.

Here is my texture so far.

The author says the first line has no R channel and ranges from B = 0 to B = 255.
While each other line has R channel = 255 and B = 255 to B = 0 as seen.

His colors do not match with mine. I wrote my shader like this:

  #version 110
  uniform sampler2D texture;
  uniform sampler2D pattern;
  uniform float progress;

  void main()
  {
    vec4 displacement = texture2D(pattern, gl_TexCoord[0].xy);
    displacement = ((displacement * 2.0) - 1.0) * progress;

    vec2 newTexCoord = gl_TexCoord[0].xy + displacement.xy;
    vec4 pixel = texture2D(texture, newTexCoord);

    vec4 color = gl_Color * pixel;
    gl_FragColor = color;
  }

which is based off his earlier videos but I'm not getting the effect at all. At best I see interlaced layers moving away but they move diagonally instead of left-right. Plus they clamp instead of leaving black color behind as seen in his video.

Here's what mine looks like: click to view


texts: How does collisions caculates when developing game in Build an HTML5 Game book

texts:
I don't understand author's logic when calculating collisions between two circles (bubbles). Here is the Calculating collisions section.

Author writes:

  The bubble being fired follows a set of coordinates defined by the
  equations:

  px = ex + tdx py = ey + tdy

  where px and py are points on the trajectory of the bubble’s center
  point. The calculation of px and py happens in jQuery’s animate method
  and is the standard equation for moving a point along a line. Next,
  we’ll calculate t at the closest point on this line to the center of
  the bubble that we’re checking against:

  var t = dx * distToBubble.x + dy * distToBubble.y;

I don't understand what t is  and why it calculates by the following formula:

var t = dx * distToBubble.x + dy * distToBubble.y;?


texts: OpenGL Uniform Standard Buffer Alignment confusion

texts:
Although i asked the same question over StackOverflow, i thought i can get more info from here too.

I have been reading about std140 Uniform block in OpenGL Superbible 6th edition, where in page 111 the following example is given :

layout(std140) uniform TransformBlock
{
      //Member                        base alignment    offset  aligned offset
      float scale ;                   // 4              0       0
      vec3 translation;               // 16             4       16
      float rotation[3];              // 16             28      32 (rotation[0])
                                      //                        48 (rotation[1])
                                      //                        64 (rotation[2])
      mat4 projection_matrix;         // 16             80      80 (column 0)
                                      //                        96 (column 1)
                                      //                        112 (column 2)
                                      //                        128 (column 3)
}

I am having hard time understanding the alignments, even using the rules that have described earlier in that page, it still don't make sense.To be specific thing that confuses me is :

What is the Offset and what is aligned offset, why 2 different offset?
Why is the rotation[0] offset starts at 28, and why aligned offset is 32?

Hopefully someone can clear my confusions.I would highly appreciate.
Thanks


texts: Create a normal map using a script? Unity

texts: I don't have a software that can create normal maps from an image so I usually make a grayscale image and then let unity make the normal map from that image. But I can't save the image to use for later, Instead I have to convert it to a normal map every time I use it. So how would I make a normal map from a greyscale using a script? i prefer c# but js works fine.


texts: Enemy shake/vibrate when following character

texts:
I am using the arongranberg A* path finding project to create way points for one enemy to follow the player. However, the enemy vibrates back and forward by about 0.1 - 0.2 unit distance when moving. I have done a lot of research regarding this problem in the past few days but to no avail I could not find a solution that solves it. This is link to a gif to show what I mean.

I have tried,

changing    Application.targetFrameRate = 30;

changing fixed update to update and vice versa;

using rigidbody2d and turn interpolate on plus using velocity to move;

turning iskinematic on and off;

using translate to move.

none of the above solution works. Below is the script I have for my enemy. Any advice would be appreciated.

    using UnityEngine;
    using System.Collections;
    //Note this line, if it is left out, the script won't know that the class 'Path' exists and it will throw compiler errors
    //This line should always be present at the top of scripts which use pathfinding
    using Pathfinding;

public class AstarAI : MonoBehaviour
{
    //The point to move to
    public Transform target;

    private Seeker seeker;

    //The calculated path
    public Path path;

    //The AI's speed per second
    public float speed = 200;

    //The max distance from the AI to a waypoint for it to continue to the next waypoint
    public float nextWaypointDistance = 0.02f;

    //The waypoint we are currently moving towards
    private int currentWaypoint = 0;

    Rigidbody2D rb;

    public void Start ()
    {
        rb = this.GetComponent<Rigidbody2D> ();
        seeker = GetComponent<Seeker>();

        //Start a new path to the targetPosition, return the result to the OnPathComplete function
        seeker.StartPath( transform.position, target.position, OnPathComplete );
    }

    public void GoToNewTarget(Transform newTarget) {
        //path = null;
        currentWaypoint = 0;
        nextWaypointDistance = 0.02f;
        target = newTarget;
        seeker = GetComponent<Seeker>();
        seeker.StartPath( transform.position, target.position, OnPathComplete );
    }

    public void OnPathComplete ( Path p )
    {
        Debug.Log( "Yay, we got a path back. Did it have an error? " + p.error );
        if (!p.error)
        {
            path = p;
            //Reset the waypoint counter
            currentWaypoint = 0;
        }
    }

    public void Update ()
    {
        if (path == null)
        {
            //We have no path to move after yet
            return;
        }

        if (currentWaypoint >= path.vectorPath.Count)
        {
            Debug.Log( "End Of Path Reached" );
            return;
        }

        //this.GetComponent<Rigidbody2D> ().MovePosition (path.vectorPath[currentWaypoint]);
        //Debug.Log (path.vectorPath[currentWaypoint]);
        //Direction to the next waypoint
        Vector3 dir = ( path.vectorPath[ currentWaypoint ] - transform.position ).normalized;
        //GetComponent<Rigidbody2D> ().velocity = new Vector2 (dir.x * 3, dir.y * 3);
        //Vector3.MoveTowards(transform.position, path.vectorPath[ currentWaypoint ], 2*Time.fixedDeltaTime);
        dir *= speed* Time.deltaTime;
        rb.velocity = dir;
        //this.gameObject.transform.Translate( dir );

        //Check if we are close enough to the next waypoint
        //If we are, proceed to follow the next waypoint
        if (Vector3.Distance (transform.position, path.vectorPath [currentWaypoint]) < nextWaypointDistance) {
            currentWaypoint++;
            return;
        }
    }
}


texts: Best practices on separating Update and Draw on game loop

texts:
I've been working on my first HTML5 prototype and I found a good model that uses the regular Update and Draw loop we see in game dev. My question is, where does one end and the other begins?

The question popped when I wanted to rotate and draw an Image, and I kept wondering if the work of changing the tranformation matrix (that I presume would be a bit expensive since it works on the whole pixel array of an image) and calculating the right position do draw it would characterize drawing work, or maybe not, since after that I may need to check for collision or something similar.

Thinkig of it, seems like a silly question, but I would like some advice from more experienced developers. Where does does update ends and draw starts?

Thanks in advance.


texts: How to get direction and velocity of movement of an object dragged with the mouse in Unty (C#)

texts:
I have an object that is dragged by the mouse (X and Z positions) over a table, with the following simple code:

 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
 if(Physics.Raycast(ray, out hit));
 pos = new Vector3(hit.point.x,myobject.transform.localScale.y/2,hit.point.z);
 myobject.GetComponent<Rigidbody>().MovePosition(pos);

The dragging works as expected. What I am struggling with is how can one retrieve the direction and velocity of such a movement, i.e. the direction and the velocity of that object when moved by being dragged by the mouse (I use Unity, C#). I have searched online, but only found the common ways to retrieve velocity and movement when using standard Rigidbody movement, not when dragged by the mouse.


texts: When I create new C++ Project (Base Code), UE4 opens only code editor (MS VSCode). Then when I close code editor and I open this project, UE4 opens its editor. Why?


texts:
I have a set of moving chess pieces and am now trying to implement the rules to prevent them from going anywhere. The pawns use this code to move: (Sorry for the blurriness, the IDE did it automatically when I zoomed out so I could get it all.)

When I go to move the Pawn, it won't move at all. Weirdly, when I had the if statement at the top set to true, it would work just fine, just excluding the moving double on the first move.

What is causing this problem, and how can I fix it?


texts: Moving an object forward relative to the distance traveled by another object

texts:
I am trying to achieve the camera follow like Ketchapp's game "Zigzag".

I will try to explain the best I can; I have two objects, Player (a sphere) and Camera:

Player can only move to the left and forward.
Camera moves forward and always keeps the same distance from the player.

I have tried different things like moving the camera and player at the same speed and decreasing/increasing the speed of camera depending on the distance between them, but in vain.

You can watch the gameplay here https://www.youtube.com/watch?v=5XbPcubaTJI
Note how the camera follows the player and just moves forward (not to the left or to the right).


texts: Confused about DXT/DDS compression and color depth

texts:
I have done my research on DDS/DXT compression, and the information is kind of "everywhere." It is rather difficult to even find good, organized, sensible information on color depth. However, it is apparent that DXT5 changes the image to... RGB565?

Alright, so I am restricted to 16 bit color and RGB565. Makes sense.
I also read that converting it yourself, choosing the colors in the image, can stop or even entirely prevent loss of detail.

Nvidia's Photoshop plugin seems to degrade the quality to something much worse than other programs are capable of when converting an image to RGB565.

In particular, I use an absolutely wonderful tool which allows me to choose the colors. I altered my image to actually only include 128 colors. This is less than the 256 allowed by RGB565.

However, Nvidia's Photoshop plugin seems to ignore those colors, and chooses its own- as if I never changed the image in the first place. It's identical to what it was if I convert it to DDS from 24 bit Truecolor.

Why is Nvidia's tool not keeping my color table?
Why is it still lossy, and significantly worse at Nvidia's 256 colors, when my 128 color version is so superior and loses no quality or detail?

Currently, I am using "COLOR QUANTIZER", which is the best tool I have found to lower the number of colors without losing image quality.

I might be a little confused, as apparently TexturePacker's RGBA5555 is 20 bit and unsupported in a lot of frameworks, which confused me thinking RGB565 and RGBA5555 were both 16 bit. (Dur! The non-existence of RGBA5555 in google threw me off bigtime.) However, I assume I could easily achieve RGBA4444 (16 bit with alpha) because my colors can degrade in COLOR QUANTIZER to 128 colors, and RGBA4444 supports 256 colors. When I use TEXTUREPACKER or other programs, it is worse quality than in COLOR QUANTIZER. This program is simply superior in my experience, and I have been obsessive with all tools available to find the best one.

My images: PNG with pre-multiplied alpha. Can degrade to 128 colors, in COLOR QUANTIZER, before losing any quality. Alpha is a very big requirement, so RGB565 and DXT1 are out of the question. These are small sprites, which are smaller than 100x200.

My Goal: Low memory consumption and compression. Obviously, the best way to handle this would be DDS/DXT5 so I can keep the textures compressed in memory. Although I could handle RGBA4444, it is only a 2:1 compression, while DXT5 is 4:1. I would much prefer to use the DDS format.


texts: How to set the z axis bound of the collider of child of an instantiated object to zero

texts:
I have attached a script to an empty GameObject to instantiate a prefab and the script is:
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using UnityEngine;

public class Circles : MonoBehaviour
{
    [SerializeField] float Xmax;
    [SerializeField] float Xmin;
    [SerializeField] float Ymax;
    [SerializeField] float Ymin;

    [SerializeField] float outsideMaxsize;
    [SerializeField] float outsideMinsize;
    float insideMaxsize;
    float insideMinsize;

    public GameObject[] enemy;
    GameObject enemyObject;

    int enemyNo;

    float Xpos;
    float Ypos;
    float outsideSize;
    float insideSize;

    // Start is called before the first frame update
    void Start()
    {
        enemyNo = Random.Range(0, 4);

      instantiator();
    }

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

    }
    public void instantiator()
    {
        Xpos = Random.Range(Xmin, Xmax);
        Ypos = Random.Range(Ymin, Ymax);

        outsideSize = Random.Range(outsideMinsize, outsideMaxsize);

        Vector2 circlePos = new Vector2(Xpos, Ypos);
        transform.position = circlePos;

        enemyObject = GameObject.Instantiate(enemy[enemyNo], transform.position, transform.rotation,transform.parent) as GameObject;

        var enemies = enemyObject.transform;
        var outsideComponent = enemies.GetChild(0);
        var insideComponent = enemies.GetChild(1);
        outsideComponent.transform.localScale=new Vector2(outsideSize, outsideSize);
        insideMaxsize = outsideSize * 0.5f;
        insideMinsize = 0.15f;
        insideSize = Random.Range(insideMinsize, insideMaxsize);
        insideComponent.transform.localScale = new Vector2(insideSize, insideSize);

        enemyNo = Random.Range(0, 4);
    }
}

And I have attached a script to the prefab which is being instantiated and that script is:
 using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class destroyer : MonoBehaviour
{

    Circles circles;

    CircleCollider2D collider1;
    Collider2D collider2;

    private void Start()
    {

        circles = FindObjectOfType<Circles>();

        print("1 max"+collider1.bounds.max);
        print("1 min" + collider1.bounds.min);
        print("2 max" + collider2.bounds.max);
        print("2 min" + collider2.bounds.min);

    }

    private void OnEnable()
    {
        collider1 = gameObject.transform.GetChild(0).GetComponent<CircleCollider2D>();
        collider2 = gameObject.transform.GetChild(1).GetComponent<Collider2D>();
    }

    void OnTriggerStay2D(Collider2D other)
    {
        print("star max"+other.bounds.max);
        print("star min" + other.bounds.min);

        if (collider1.bounds.Contains(other.bounds.max) && collider1.bounds.Contains(other.bounds.min))
       {

            if (other.bounds.Contains(collider2.bounds.max) && other.bounds.Contains(collider2.bounds.min))
            {

                    Destroy(other.gameObject);
                    Destroy(gameObject);
                    circles.instantiator();

            }

        }
    }
}

the problem is that the z axis bounds of the colliders are coming out to be 15.8
when the prefab is instantiated and when I drag the prefab to scene then the z axis bounds of the collider is 0. I want the z axis bounds of the colliders to be 0 when the prefab is instantiated


texts: Should I Include the W-component of a vector when calculating it's length or dot product?

texts:
The reason I'm asking this is because I saw an implementation which did it that way but I don't quiet understand it. I mean, usually I want to get the distance between two points in 3d space and if W is something other than 0 the result is not correct. The same when calculating lighting using the dot product.

float Vector::Length() const{
    return sqrtf(X * X + Y * Y + Z * Z + W * W);    //W necessary?
}

float Vector::Dot(const Vector& other) const{
    return X * other.X + Y * other.Y + Z * other.Z + W * other.W;
}

Edit: There are suggestions that my question is a duplicate of already existing ones. But the questions referred to are about whether you need the W component at all and for what. I know what I need it for, I'm just not sure about it's role in the operations I specified.


texts: How can I calculate when a spesific amount of time has passed

texts:
I am trying to get something to happen, when a spesific amount of time has passed(in my case it is in secounds). I have tried using this method:

   long elapsed = (System.nanoTime()-startTime)/1000000;
   if(elapsed > 1000)
   {
       score++;
       startTime = System.nanoTime();
   }

with the starttime beiing initiated in the constructor. But when I attack(part of the game) the app either:
chrashes
the things the game renders dissapears, and everything turns black.

I have tried asking google, but it in general gave me the save way. Any new improved ideas?


texts:
I'm using OpenGL (Version 4.4) (and C++ if that matters).

I've created a terrain renderer, the terrain is stored as a 3D scalar field (isosurface/voxels). It uses a slightly modified version of Marching Cubes, to perform polygonization (converting the scalar field to triangles).

Currently I'm texturing the terrain using a horizontal (grass) texture and a vertical (dirt) texture. Then when applying the texture I simply calculate the amount of the horizontal and vertical texture that is required on the current triangle, depending on the normals of the current triangle. Thereby the more a normal is pointing upwards (or downward) the more dominant the horizontal (grass) texture will be.

Terrain Renderer in Action

Fullscreen Image

Now the question is, what would be the best (or a good) way to perform Multi-Texturing on the terrain? I will give all the values in the scalar field a voxel type value as well. So the main question is how should the rendering be handled. I have a couple of ideas of how this could be done, but I'm not sure which of my ideas would be the best one to do or if there's even a better way.

First Idea

Bind all the needed textures, thereby call glActiveTexture(...) for each texture there is.
Now the mesh can be rendered using a single glDraw*(...) call.
This of course only works if the Shader knows when and where to use each texture, or
that the info for using each texture, is stored within the buffer, as some sort of
value which the Shader uses, to "detect" which texture should be used. As mentioned previously this could be the voxel type value.

Problem: The maximum amount of textures which can be bound simultaneously is very limited, so that could (and probably would) create some problems.

Second Idea

Bind a single texture and call glDraw*(...) with a specific first and count value, so that only a part of the mesh is rendered. Which of course is the part which uses the bound texture.
Thereby loop the above until the whole mesh is rendered using all the individual textures.

I don't see any real problem with this idea, the only extra thing we need to take in mind, is that all the triangles need to be sorted according to their voxel type value.

Though we wouldn't be able to fade the textures, like in the image above.

Third Idea

Split the mesh into individual buffers (VBOs and VAOs), so that each buffer only uses a single (or a couple) texture(s). Basically the same as the Second Idea though here the buffer would physically be split according to the textures.

Fourth Idea?

or is there an even better way?

Side Note

Each texture has it's own handle, thereby none of them can be used as a Texture Atlas.


texts:
How do I perform get and post requests from Gdscript in Godot?
I am trying to get a map API and use it in the game.


texts: Replacing assets in Unity real-time but keeping the references intact

texts:
I'm looking forward to adding mod support into my game by allowing users to easily replace some assets with their own versions.
The way I want it to work - if there's, say, a certain texture in some folder in my compiled game, I replace the texture with the same name in my resources, but I keep references intact. That means that the texture will be replaced for every material using this texture. I don't want to change materials themselves to reference the new texture, mainly because I'll have to keep a list of materials for each texture, and because materials might be replaced by potential modder as well. It's also important to note that I want to give people the ability to change basically anything (but scripts). Sounds, music, textures, meshes, materials, fonts, localization files, shaders, so the list of references might be absolutely changed upside down and that is absolutely not the solution.


texts: Problem about underground block generation for voxels

texts:
I've been working at a voxel sandbox game and have already implemented chunk generation and stuff.
But I just found that generating underground blocks with the surface ones is impossible, since that causes lag.
My game only generates surface blocks for now.
Are there any available chunk generation algorithms that covers the solution for my problem?
Please give a link or clearly state the method.
Thanks


texts:
I've got the following code in a shader:

// v & y are both uints
nPixel = v;
nPixel << 8;
nPixel |= y;

and this gives me the following error in compilation:

shader.fx(80,10): error X3535: Bitwise operations not supported on legacy targets.
shader.fx(92,18): ID3DXEffectCompiler::CompileEffect: There was an error compiling expression
ID3DXEffectCompiler: Compilation failed

The error is on the following line:

nPixel |= y;

What am I doing wrong here?


texts: std::map for storing static const Objects

texts:
I am making a game similar to Minecraft, and I am trying to fine a way to keep a map of Block objects sorted by their id. This is almost identical to the way that Minecraft does it, in that they declare a bunch of static final Block objects and initialize them, and then the constructor of each block puts a reference of that block into whatever the Java equivalent of a std::map is, so there is a central place to get ids and the Blocks with those ids.

The problem is, that I am making my game in C++, and trying to do the exact same thing. In Block.h, I am declaring the Blocks like so:

//Block.h
public:
    static const Block Vacuum;
    static const Block Test;

And in Block.cpp I am initializing them like so:

//Block.cpp
const Block Block::Vacuum = Block("Vacuum", 0, 0);
const Block Block::Test = Block("Test", 1, 0);

The block constructor looks like this:

Block::Block(std::string name, uint16 id, uint8 tex)
{
//Check for repeat ids
if (IdInUse(id))
{
    fprintf(stderr, "Block id %u is already in use!", (uint32)id);
    throw std::runtime_error("You cannot reuse block ids!");
}
_id = id;
//Check for repeat names
if (NameInUse(name))
{
    fprintf(stderr, "Block name %s is already in use!", name);
    throw std::runtime_error("You cannot reuse block names!");
}
_name = name;

_tex = tex;
//fprintf(stdout, "Using texture %u\n", _tex);

_transparent = false;
_solidity = 1.0f;

idMap[id] = this;
nameMap[name] = this;
}

And finally, the maps that I'm using to store references of Blocks in relation to their names and ids are declared as such:

std::map<uint16, Block*> Block::idMap = std::map<uint16, Block*>(); //The map of block ids
std::map<std::string, Block*> Block::nameMap = std::map<std::string, Block*>(); //The map of block names

The problem comes when I try to get the Blocks in the maps using a method called const Block* GetBlock(uint16 id), where the last line is return idMap.at(id);. This line returns a Block with completely random values like _visibility = 0xcccc and such like that, found out through debugging.

So my question is, is there something wrong with the blocks being declared as const obejcts, and then stored at pointers and accessed later on? The reason I cant store them as Block& is because that makes a copy of the Block when it is entered, so the block wouldn't have any of the attributes that could be set afterwards in the constructor of any child class, so I think I need to store them as a pointer.

Any help is greatly appreciated, as I don't fully understand pointers yet. Just ask if you need to see any other parts of the code.


texts: XNA & HLSL - rendering a model with its original materials (colors)

texts:
I am currently trying to code my own HLSL effect file, in order to render an FBX model I made with Autodesk maya, and to which I have applied some materials (colors).

before trying to write an effect file, I have tried using XNA's BasicEffect, which rendered the model as expected with the materials I had set in maya.
Now though, when I'm using my own HLSL effect file, there's always an error saying that my model doesn't have any colors:

  The current vertex declaration does not include all the elements
  required by the current vertex shader. Color0 is missing.

My HLSL effect file (partially leared from riemers.net):

float4x4 xWorldViewProjection;

float4x4 xWorld;
float3 xLightPos;
float xLightPower;
float xAmbient;

struct VertexToPixel
{
    float4 Position     : POSITION;
    float4 Color        : COLOR0;
    float3 Normal        : TEXCOORD0;
    float3 Position3D    : TEXCOORD1;
};

struct PixelToFrame
{
    float4 Color        : COLOR0;
};

float DotProduct(float3 lightPos, float3 pos3D, float3 normal)
{
    float3 lightDir = normalize(pos3D - lightPos);
        return dot(-lightDir, normal);
}

VertexToPixel SimplestVertexShader(VertexToPixel input)
{
    VertexToPixel Output = (VertexToPixel)0;

    Output.Position =mul(input.Position, xWorldViewProjection);
    Output.Normal = normalize(mul(input.Normal, (float3x3)xWorld));
    Output.Position3D = mul(input.Position3D, xWorld);
    Output.Color = input.Color;

    return Output;
}

PixelToFrame OurFirstPixelShader(VertexToPixel PSIn)
{
    PixelToFrame Output = (PixelToFrame)0;

    float diffuseLightingFactor = DotProduct(xLightPos, PSIn.Position3D, PSIn.Normal);
    diffuseLightingFactor = saturate(diffuseLightingFactor);
    diffuseLightingFactor *= xLightPower;

    Output.Color = PSIn.Color* (diffuseLightingFactor + xAmbient);

    return Output;
}

technique Simplest
{
    pass Pass0
    {
        VertexShader = compile vs_3_0 SimplestVertexShader();
        PixelShader = compile ps_3_0 OurFirstPixelShader();
    }
}

And my XNA code:

foreach (ModelMesh mesh in MainRoom.Meshes)
    foreach (ModelMeshPart meshPart in mesh.MeshParts)
        meshPart.Effect = roomEffect.Clone();

...

private void DrawModel(Model model, Matrix world)
{
    Matrix[] bones = new Matrix[model.Bones.Count];
    model.CopyAbsoluteBoneTransformsTo(bones);

    foreach (ModelMesh mesh in model.Meshes)
    {
        foreach (Effect currentEffect in mesh.Effects)
        {
            Matrix worldMatrix = bones[mesh.ParentBone.Index] * world;

            roomEffect.CurrentTechnique = roomEffect.Techniques["Simplest"];
            currentEffect.Parameters["xWorldViewProjection"].SetValue(worldMatrix * camera.view * camera.projection);
            currentEffect.Parameters["xWorld"].SetValue(worldMatrix);
            currentEffect.Parameters["xLightPos"].SetValue(lightPos);
            currentEffect.Parameters["xLightPower"].SetValue(lightPower);
            currentEffect.Parameters["xAmbient"].SetValue(ambientPower);
        }
        mesh.Draw();
    }
}

I'm fairly new to HLSL (but not to XNA though), any help would be nice.

EDIT: I have also tried rendering a different model with materials, but it just gives the same error.

Solution: Thanks to Cole Campbell's answer and, the full working code can be found here


texts:
I have a quad rendered that extends from the top left of the window to with width of the window that is also 64 pixels high. When I resize the window, from its initial size, the quad and text scales proportionately bigger or smaller in the same say Photoshop can scale a image. What I'm seeking on a basic level is that regardless of how I resize the window, everything drawn remains the same. From the below image, the right side is the initial size and the left side is what happens when I drag the window to be a smaller size. The red bar and text scales with it. This is how Im handling my resizing:
glfwSetWindowSizeCallback(pWindow, WindowSizeCallback); // initialized after context

void WindowSizeCallback(GLFWwindow* window, int width, int height)
{
    glfwSetWindowSize(window, width, height);
}


texts: Is it legal to develop a game using software which is unavailable in my region due to legal reasons?

texts:
I was wondering: what would happen if I published a game while the software I used is not available in my area?

I was planning to make a game using Unity Personal, and it just happened that it's not available in my area (Syria). Should I keep looking for alternatives or is it okay to publish it since I could download the software?

Here's the text that appears when I try accessing either unity.com or unity3d.com without a VPN connection:

  Access Denied

  You don't have permission to access "http://unity3d.com/" on this
  server. Reference #18.c7581002.1562292126.1b42107


texts: Please help me find the error in a pygame code for Tetris?

texts:
I am creating a Tetris game using Pygame. However, instead of calling a single shape, but code calls all the functions for the shapes randomly one after the other. I tried called the NewShape at different places, but nothings working. If it calls a single shape, then the keyboard control does not work. Please let me know what is wrong. Thank you!

x=50
y=50
def ShapeL(screen,x,y):
    pygame.draw.rect(screen, Cyan, [x,y-50,50,150])
    pygame.draw.line (screen,Cyan, [x, y], [x+50,y])
    pygame.draw.line (screen,Cyan, [x, y+50], [x+50,y+50])
    pygame.draw.line (screen,Cyan, [x, y+100], [x+50,y+100])
    pygame.draw.rect(screen, Cyan, [x+50,y+50 ,50,50])

ShapeChosen=False
def NewShape(screen,x,y):
    ListShapes=[ShapeS, ShapeT, ShapeL, ShapeI, ShapeSquare]
    Shape=random.choice(ListShapes)(screen,x,y)#chooses random shape
    ShapeChosen=True

def BasicGame(x,y):
    Done=False
    while not Done and y!=500 and ShapeChosen!=True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                Done=True
            elif event.type == pygame.KEYDOWN:
                if event.key ==pygame.K_LEFT:
                    x=x-50
                elif event.key==pygame.K_RIGHT:
                    x=x+50
                elif event.key==pygame.K_DOWN:
                    y=y+50
                elif event.key==pygame.K_SPACE:
                    y=500
            if x==0:#Borders so the shape doesn't leave the screen.
                x=50
            elif x==400:
                x=350
            if y==550:
                y=500
    screen.fill(White)
    NewShape(screen,x,y)

I tried passing the parameter ShapeChosen to the function, however, it did not work as well. I tried passing global ShapeChosen, but it prevents the keyboard functions to work.


texts: The farther I move my character, the more its projectiles fire in the wrong direction

texts:
I'm making a top down shooter, and the movement is working fine.
However, I'm having trouble getting my Fire function to work correctly. When I run the game, it kind of fires in the right direction, but the more I move, the more off the shooting becomes. Anyone have any idea why?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    private float _horizontalInput = 0;
    private float _verticalInput = 0;

    public int movementSpeed = 2;
    public int rotationSpeed = 2;

    Rigidbody2D rb2d;

    float coolDown = 0;

    public Rigidbody2D bulletPrefab;
    public float attackSpeed = 0.5f;
    public float bulletSpeed = 500;
    public float yValue = 1f; // Used to make it look like it's shot from the gun itself (offset)
    public float xValue = 1f; // Same as above

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

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

        MovePlayer();
        RotatePlayer();
    }

    void Update()
    {
        GetPlayerInput();

        // Determines if the player can fire
        if (Time.time >= coolDown)
        {
            if (Input.GetKeyDown(KeyCode.Space))
            {
                Fire();
            }
        }
    }

    private void GetPlayerInput()
    {
        _horizontalInput = Input.GetAxisRaw("Horizontal");
        _verticalInput = Input.GetAxisRaw("Vertical");

    }

    public void MovePlayer()
    {
        rb2d.velocity = transform.right * Mathf.Clamp01(_verticalInput) * movementSpeed;
    }

    private void RotatePlayer()
    {
        float rotation = -_horizontalInput * rotationSpeed;
        transform.Rotate(Vector3.forward * rotation);
    }

    private void Fire()
    {
        Rigidbody2D bPrefab = Instantiate(bulletPrefab, new Vector3(transform.position.x + xValue, transform.position.y + yValue, transform.position.z), transform.rotation) as Rigidbody2D;

        bPrefab.GetComponent<Rigidbody2D>().AddForce(transform.position * bulletSpeed);
        coolDown = Time.time + attackSpeed;
    }
}


texts: UE4 Drag and Drop: Place PaperCharacter Over Image Widget

texts:
I'm working on adding drag and drop functionality to my game. I have it working with the exception of I can't get what I'm dropping to be placed where it was dropped. I've tried a number of different things but I can't seem to get it to work.

The image shows my OnDrop with some leftovers of things I have been trying. And when I adjust the MakeTransform manually, a change of 1.0 seems to move the character much more than 1 pixel. The item I am creating in the OnDrop is a PaperCharacter.

Here is an image from part of the level showing the result. The white blocks circled in red are UMG images so I can eventually adjust them to look better and change dynamically as the player is dragging. The player can only drop the item over one of there squares. This functionality works. But no matter which square I drop over the item always gets placed at the point circled in green or nowhere to be seen in the viewport. This is a 2d game so everything has to be in the viewport to be seen. The white squares are attached to a PaperSpriteActor. Not sure if that matters or not.

What I need to have happen is when the player drops the item above one of the squares, the PaperCharacter must be dropped right in the middle of that square. How do I go about making that happen?

EDIT

Another observation, if I manually set the MakeTransform location to 0, 0, 0 and drop the item on the same white square multiple times, the item is dropped in a slightly different spot each time.


texts: How to dynamically construct a reference to a game object by name

texts:
I have game objects tagged MenuOption0, MenuOption1, MenuOption2, etc. I want to keep a currentIndex var, which gets incremented each time the user swipes on the controller. That swipe should increment the currentIndex var, and switch the reference to a new game object, whose text color will be changed.

This is what I'm trying as a test:

GameObject testText = GameObject.Find("MenuOption" + 4);
TextMeshProUGUI thisTextMesh = testText.GetComponent<TextMeshProUGUI>();
thisTextMesh.color = colorWhite;

How do I dynamically construct a reference to MenuOption1,2,3,4,etc? Or is there a better way to handle this without writing a big long conditional?


texts: Would using Lua scripts to define game logic for an MMO server be a lot slower than compiled in C++?

texts: I am using an entity system for my MMO server and I was thinking about defining the behavior of "actions" using Lua scripts. The server is written in C++. I am not very familiar with the speed/memory usage of Lua in C++ but I have used it for scripting the GUI of the client. Would using Lua to define the game logic on the server side cut the performance by a lot?


texts:
I have drawn a ship using three lines, and would like to rotate the ship around its axis in opengl, I have tried the following, but the ship translates while rotation!.

void Ship::Draw( )
{
    gl::pushMatrices();
    gl::translate(Vec2f(-m_Pos.x, -m_Pos.y));
    gl::rotate(m_Angle);
    gl::translate(Vec2f(m_Pos.x,m_Pos.y));
    gl::color(ci::Color(1,0,0));
    gl::drawLine(Vec2f(281,70),Vec2f(383,123));
    gl::drawLine(Vec2f(310,85),Vec2f(310,160));
    gl::drawLine(Vec2f(383,123),Vec2f(281,176));

    gl::popMatrices();
    m_Angle+=0.2f;
}


texts:
I thought that particles were basically GPU-powered sprites. After looking at the following demo, I'm not totally sure of that anymore : http://vimeo.com/18715688

How are done those snake-like particles ? I don't see any defect in the shape, and I assume that there is not a particle for each pixel unit of a snake.


texts: Reusing a render target to create multiple Texture2D's (XNA)

texts:
i want to be able to loop through a hole bunch of textures, and render them on an object. I then want the rendered image to be placed onto a texture2D.

The point? well hopefully i will end up with an array of Texture2D's containing a model with multiple skins.

Here's my code:

        for (byte i = 1; i < allBlockIso.Count(); i++)
        {
            DisplayBox.SetValue(i);
            GraphicsDevice.SetRenderTarget(cubeTarget);
            GraphicsDevice.Clear(Color.Transparent);
            DrawIsoCube();
            GraphicsDevice.SetRenderTarget(null);
            allBlockIso[i] = (Texture2D)cubeTarget;
        }

DisplayBox.SetValue is a function which goes through and sets the texture. This is working! DrawIsoCube() draws the cube (the test model) and this is working too.
The problem is definitely something to do with the unreusability of the render target.

Pretty simple yet it's not working. It appears that whatever the last image being rendered is, is shown in every image of the allBlockIso array.

Anyone know a fix?
Cheers.

P.S. sorry if this wan't explained well. I'm not very good at explaining :P


texts: Winning isn't everything (organic Hierarchy)

texts:
Suppose that you have a simple online browser based game* in which the characters are all landed nobles - Barons.

When the game starts all players are on relatively equal footing.

There is a game mechanic that allows players to swear fealty to another player.  However, it's easy to assume that no amount of asking nicely will get another human player to swear fealty to you, especially since he/she theoretically has just as much muscle as you do.

So: war.

If you go to war with someone because you want them to be your vassal, what happens - realistically?

You defeat them, and they acknowledge your superiority and swear fealty.
They send you rage filled notes and continue to stubbornly resist, despite having no strength remaining to challenge you.
Ragequit.
Due to a coded mechanic, when their armies are defeated, they auto-vassal to you, and then ragequit.

My goal at this point is somewhat experimental: Can players create an organic hierarchy?  Could a bunch of players haggle and battle and create a pecking order - whether stable or constantly shaken up?

*browser based game: more a PHP based role playing game with some management and activity actions, not a clickfest flash game.


texts: Why the rotation using the Coroutine is rotating but the object is in slant ? and how to rotate it with Coroutine non stop?

texts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Spin : MonoBehaviour
{
    public Vector3 targetRotation;
    public float duration;
    public bool spinInUpdate = false;

    // Start is called before the first frame update
    void Start()
    {
        if (spinInUpdate == false)
        {
            StartCoroutine(LerpFunction(Quaternion.Euler(targetRotation), duration));
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (spinInUpdate == true)
        {
            transform.Rotate(new Vector3(0, 1, 0));
        }
    }

    IEnumerator LerpFunction(Quaternion endValue, float duration)
    {
        float time = 0;
        Quaternion startValue = transform.rotation;

        while (time < duration)
        {
            transform.rotation = Quaternion.Lerp(startValue, endValue, time / duration);
            time += Time.deltaTime;
            yield return null;
        }
        transform.rotation = endValue;
    }
}

slant I mean this is how it's rotating with the Coroutine the small cube that rotate is in slant :

When using the Update way it's rotating fine and this is how it should rotating also with the Coroutine for example on the X only :

The small cube when rotating either in update or in the Coroutine  should not be slant. but it's slant in the Coroutine.
And how can I add a speed factor to the Update to control the rotation in the Update in case using the Update ?
About controlling the speed in the Update I just added a global float variable and in the Update :
transform.Rotate(new Vector3(0, Time.deltaTime * rotationSpeed, 0));

and it's working for the speed.