texts: How to Send Voice over Unity Networking - UNET

texts:
I am able to Record and Run Audio from my Microphone using this code snippet:

  void OnGUI() {
        if (GUI.Button(new Rect(0, 0, 100, 20), "record")) {
           // Microphone.End(Microphone.devices[0]);
            audsourceAttached.clip = Microphone.Start(Microphone.devices[0], false, 3, 44100);
        }
        if (GUI.Button(new Rect(0, 30, 100, 20), "Stop"))
        {
            //Microphone.End(Microphone.devices[0]);
            audsourceAttached.Play();
        }
    }

Now I am willing to send this audio across Network (on my local network-another instance of the game). How can I do this?

I tried to find this on google but unable to find any useful solution/links.

How can I send audio through microphone like real-time Chat in a game/etc.


texts:
I am making a simple gui in libgdx and run into this problem ; when you click on the button it's bounds (?) are wrong since if I click under it, the game registers it as a click.

On the other end, if I click it at the top it won't get the click. It seems like the bounds are a bit under the button. I tried to set manually but nothing.

Also i tried changing sizes.

Looked here : too this is almost the same but no answer..

tabl = new Table();
    stage =new Stage();
    tabl.setSize(stage.getWidth()/2, stage.getHeight()/2);
    tabl.defaults().size(500, 40);

    g = game;

    Gdx.input.setInputProcessor(stage);

    skin = new Skin();

    TextureAtlas te = new TextureAtlas(Gdx.files.internal("uiskin.atlas"));

    skin.addRegions(te);
    skin.add("default-font", new BitmapFont());
    skin.load(Gdx.files.internal("uiskin.json"));

    Pixmap r = new Pixmap(100,100,Format.RGBA8888);
    r.setColor(0xff0000ff);

    r.fillRectangle(1, 1, 13, 13);
    Texture s = new Texture(r);
    SpriteDrawable s1 = new SpriteDrawable(new Sprite(s));

    TextButton gam = new TextButton("new games",skin);

    gam.addListener(new InputListener() {
        @Override
        public boolean touchDown(InputEvent event, float x, float y,
                int pointer, int button) {
            // TODO Auto-generated method stub
            //g.setScreen(null);
            new Logger("e").setLevel(10);
            return true;
        }
    });

    /*super.getS*/
    LabelStyle tt = new LabelStyle(new BitmapFont(), Color.BLUE);
    Label l = new Label("d",tt);

    tabl.add(gam);

    tabl.setDebug(true);

    stage.addActor(tabl);


texts: How to use/apply class inheritance in Enchant.js

texts: You're developing a game using Enchant.js and you just need an Enemy class which multiple enemy classes derive from and every enemy has its own sprite and stuff.


texts: How to get a turret to shoot at player in a shmup

texts: I'm developing a basic vertical shoot em up on the DS and am trying to get stationary turrets to shoot at the player in a shoot em up. Early on I simply had them shooting in fixed 8 directions N, S, E W, NE, NW, SE, SW, depending on the player's relative position, but I want something more specific. My attempts have been awkward at best, and my aiming algorithm is not very crude and often the turrets miss by a mile. I am looking for a simple algorithm that plots a basic straight line trajectory towards the player's xy position. Nothing fancy like predictive aiming. Does anybody know of an algorithm or an article that covers such an algorithm?


texts: Unity keeps reseting my Input Manager settings

texts:
Basicaly, title. I want to change the second Horizontal entry in the Input Manager but when I do it won't save the changes afterwards. I rename the second Horizontal axis to "Strafe", and I'm reffering to it in the script like that, but when I run the game I get this error: "Input Axis Strafe is not setup". This is because there's not input axis called "Strafe", because Unity just reset the default settings for some reason. There's no save button on this window, and I actually got it to save one time and it worked, but the next time it didn't and it reset the axis again! How can I avoid this?

I set it up nicely:

Then it screws me over after running the game once:


texts: Overlay partially transparent texture onto another, but not the background

texts:
I'm using XNA and C#.
I have two shapes (texture2ds), and I want to overlay shape 2 (50% transparent square) over shape 1 (opaque circle), but I want to get Option B, not Option A.

I basically want to render only the part of the square that's over the circle, without rendering the rest of the square over the background.

EDIT: Let me clarify why exactly I want to do this. I'm essentially using something like this as cheap shadows on top-down 2d planets. When a moon, planet, and sun are all in a 180 degree line, the moon is expected to be completely shaded. So I want to put a shadow behind the planet that won't cover the background, but when the moon passes under it, it gets shaded black.


texts:
I would like to build an app like the onw downloadable from here https://playhatch.com/.
How is it possible, technically speaking, to achive such result? Need I to implement some instant app feature? Need I to instantiate a kind of android runtime like a "mini docker image"? What's the technical concept which allows to implement such a feature?

Many thanks


texts: Phaser 3 - How to make 2 object merging after collision (Like Claw Machine)

texts:
I'm new in Phaser 3. I use Matter.js for physics.
I want to create something like Claw Machine :

I have a claw (top) and prize (bottom)
The claw will take a prize from bottom
When claw hit the prize, i want the prize drag by claw.

Right now i use :

Matter.js for prize
Arcade for claw

I confuse how to do it. Any idea?


texts: Shading a concave cube as a convex cube with forced perspective

texts:
Context
I'm building a graphics pipeline for voxel volumes. I'm using an existing game engine (Bevy) which provides a way to put an object in 3D space. In my application, the voxel volumes can be oriented arbitrarily and are not necessarily axis aligned with respect to the world space. The pipeline does front-face culling of these voxel volumes to allow the camera to go inside the bounds of the volume without clipping (imagine a player walking into a sparsely populated volume and looking around). The voxel volumes are rendered using ray marching, starting from a ray's contact point with the front face of the voxel volume.

The Problem
Now of course, this works if there are front faces, but as I said I'm culling them. So what really happens is my frag shader is shading the near side of the cube's back faces. What I need to do is: given the point of contact with the cube's back face, and the direction to the camera, find the point that would have been hit on the front face. This will allow the rest of the program to ray march as though the ray hit a "convex" cube. I've spent quite a while looking at this answer but so far I've been unable to implement it into my shader -- I think it's relevant: https://stackoverflow.com/questions/4248090/finding-the-length-of-a-ray-within-a-cube
Assumptions:

Voxel volume axes are perpendicular to each other, but are not necessarily the same length
A ray from the camera to a back face can hit any one of the 3 back faces, and will only pass through any one of the 3 front faces

Expected Result
Here's an example of what I expect. Below (first image) is what is rendered without "simulating" the front face positions. The second image is what would be rendered with correct front face simulation.

Partial Code
I've removed the irrelevant code. Right now what is rendered for a voxel_volume_size = (16, 16, 16) is 3 16x16 walls along the axes. Of course what should be seen is a 16x16x16 voxel cube.
voxel.vs
#version 450

layout(location = 0) in vec3 Vertex_Position;
layout(location = 1) in vec3 Vertex_Normal;
layout(location = 2) in vec2 Vertex_Uv;

layout(location = 0) out vec3 v_Position;
layout(location = 1) out vec3 v_Normal;
layout(location = 2) out vec2 v_Uv;

layout(set = 0, binding = 0) uniform Camera {
    mat4 ViewProj;
    mat4 View;
};

layout(set = 1, binding = 0) uniform Transform {
    mat4 Model;
};

void main() {
    v_Normal = Vertex_Normal;
    v_Position = Vertex_Position;
    v_Uv = Vertex_Uv;
    gl_Position = ViewProj * vec4((Model * vec4(Vertex_Position, 1.0)).xyz, 1.0);
}

voxel.fs
#version 450

layout(location = 0) in vec3 v_Position;
layout(location = 1) in vec3 v_Normal;
layout(location = 2) in vec3 v_Uv;

layout(location = 0) out vec4 o_Target;

layout(set = 0, binding = 0) uniform Camera {
    mat4 ViewProj;
    mat4 View;
};

layout(set = 1, binding = 0) uniform Transform {
    mat4 Model;
};

layout(set = 3, binding = 0) buffer VoxelVolume {
    vec3 voxel_volume_size;
};

void main(void) {
    vec3 Normal = mat3(Model) * v_Normal;

    vec3 scale = voxel_volume_size / 16.0;

    mat4 InverseView = inverse(View);
    vec3 CameraPosition = (Model * vec4(vec3(InverseView[3]), 0.)).xyz;

    vec3 BackFacePosition = v_Position;
    vec3 BackFaceModelPosition = (Model * vec4(BackFacePosition, 1.0)).xyz;
    vec3 BackFaceRayDirection = normalize(BackFaceModelPosition - CameraPosition);

    vec3 FrontFacePosition = ?;
    vec3 FrontFaceRayDirection = ?; // Differs from BackFaceRayDirection when front face is perpendicular to back face

    vec3 ScaledPosition = ((FrontFacePosition + (scale / 2.0)) / scale) * voxel_volume_size;

    o_Target = vec4(floor(ScaledPosition) / voxel_volume_size, 1.0);
}

I would be extremely grateful if someone could help me fill in those missing variables! Thanks.


texts: How can I switch the default map to UI in order to pause the game?

texts:
I've recently set up the new Input System using Player Input component and invoke unity events. I just have one problem; I want to change the default action map to UI whenever I press the defined pause buttons because pausing won't work when the defualt map is set to Player. I want to do this via code and in PauseInput function. I tried using playerInput.SwitchCurrentActionMap but it didn't work for me. Also, I don't use a generated c# script for the player inputs. Any guidance would be appreciated.
Here's my pause menu code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.InputSystem;

public class PauseMenu : MonoBehaviour
{
    public static bool GameIsPaused = false;
    public PlayerInput playerInput;
    public GameObject pauseMenuUI;

    public void OnPause(InputAction.CallbackContext context) {
      if (context.phase == InputActionPhase.Performed) {

          if (GameIsPaused) {
              Resume();
          } else {
             Pause();
          }
     }
}

    public void Resume()
    {
        playerInput.SwitchCurrentActionMap("Player");
        pauseMenuUI.SetActive(false);
        Time.timeScale = 1f;
        GameIsPaused = false;
    }

   public void Pause ()
    {
        playerInput.SwitchCurrentActionMap("UI");
        pauseMenuUI.SetActive(true);
        Time.timeScale = 0f;
        GameIsPaused = true;
    }
}

As you can see, I want to change the default map from Player to UI whenever the pause button is pressed and switch back to Player whenever the button is pressed again (resume); because there can only be one active map at a time.


texts: Drawing circles at the background of a 3D scene and updating their size

texts:
So, here is what I am trying to do in Unity 5 (using C#). I want to draw a a 2D circle at the background of a 3D scene and apply a texture/image to fill it.

Just like it would be if the circle was in the GUI, but now being always behind everything else instead of always in front (think of a moon in the sky of a piloting game, or a distant planet in a space game, etc).

What would be the fastest way to draw such a circle and, of course, update its radius depending on the camera distance? Of course, I don't want to use a sphere, I want to learn how to that with a simple circle that gets bigger or smaller depending on the distance of the viewer.


texts: Unity: how to mimic the lighting of a mesh as seen in the editor view

texts:
I have a camera which shows a "bird's eye view" of a procedurally generated mesh like so:

Currently in the editor view (right), the terrain looks exactly as I would like it to. However, in game (left) I haven't been able to get it to appear as I would like:

I was using a directional light above, which was causing the effect where the centre of the mesh appears "shiny". So I looked around at some forum posts and questions on here and decided to try using ambient lighting instead by altering the settings in Window>Rendering>Light Settings, but this is the result:

This is the material I'm using (EDIT: I'm using a particle shader as the colouration of my mesh is based on altering Mesh.colors. ):

I have tried fiddling around with different material types but I couldn't get better results. My question is: how do I set up my game to use the same lighting that's being used in the editor?

Thanks in advance

EDIT: Camera settings at runtime as requested:

EDIT 2: Just to update; I have still not managed to fully solve this problem. I ended up using some different colours for my heightmap and tweaking the Metallic and Smoothness properties of the material, and the shininess and non-even lighting is somewhat diminished, but it does still exist.

If you watch at about 20 seconds into this video, when the mesh is dully coloured, the "circular" lighting effect is still present, which shadows being cast from the centre outwards, and the middle appearing almost blurred and the edges sharp.

Later in the video you can see a colourful version of the mesh, where these undesirable lighting effects are barely noticeable (note that I don't always want it to be be in bright colours, hence this is still an issue).

I feel like there should be a very simple solution to this. Why can I not get the lighting conditions that I see in the editor in the game view?

I am very happy to keep updating here with further progress/clarifications, and would love to hear any suggestions anyone has.


texts: Does scene2d(libGDX) know when an image is drawn out of the screen?

texts:
I mean, I want to make a tiled map using scene2d, so in the render method of my game...

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

    gameStage.getCamera().position.set(player.getX(), player.getY(), 0);
    gameStage.act(Gdx.graphics.getDeltaTime());
    gameStage.getBatch().begin();
    for(int i=0;i<20;i++)
        for(int j=0;j<20;j++)
            gameStage.getBatch().draw(tile,i*tileSize,j*tileSize,tileSize,tileSize);
    gameStage.getBatch().end();
    gameStage.draw();
}

Does scene2d know if the tile is out of the screen view, so it does not draw it, or do I have to implement code to fix it?

Sorry for my English.


texts:
When I interrupt an Animator Controller during an Animation and reopen it the Armature gets stuck (more or less) at the point where the previous Animation was interrupted. How can I safely and instantly quit an animation without destroying it?

Please watch the Video to fully comprehend the problem: https://youtu.be/O9X5SBATHRw

Screenshot of Problem:

Screenshot of Animator Controller:

Part of the Weapon Switch Script:

disableWeaponModel(weaponNameList[activeWeapon]); //Disable active Weapon Model

if (holsteredWeapon == -1) //If player carries only 1 weapon
    holsteredWeapon = activeWeapon; //Active Weapon is holstered
else //Player already carries 2 weapons
    actionDropGun(); //Active Weapon is thrown (New LOD generated)

activeWeapon = getWeaponIDfromLOD(targetName); //Active Weapon is set to Target LOD

setWeaponVars(activeWeapon); //Set all variables to the active Weapon
setWeaponModel(weaponNameList[activeWeapon]); //Set Weapon Model to the active Weapon
setAnimator(weaponNameList[activeWeapon]); //Set Animations to the active Weapon

setAnimator(string name) Function from above (last code line):

void setAnimator(string name)
{
    //Add new guns here
    if (name == "MP5A3")
        currentWeaponAnimation = MP5A3_Animation;
    else if (name == "Rpk-74")
        currentWeaponAnimation = Rpk74_Animation;
    else if (name == "Skorpion")
        currentWeaponAnimation = Skorpion_Animation;
}

Variables from setAnimator(string name):


texts: Non-physics character movement in a Box2d Environment

texts:
I am in the process of creating a physics platformer. However, I want the player movement to feel very old-school(as in: non-physics like), which means that the character:

Should always move equally fast horizontally, even on slopes.
Has a reasonably fast jumping movement. The 'normal'(earthlike) gravity that is the default of Box2d tends to feel floaty.

Now, I have been trying lots of things to create a Box2d player that works this way. Multiple questions over the past few weeks are related to problems I've encountered with that:

I increased the gravity and the density of the player to ensure they would jump/fall faster. (see this question)
I worked with the 'unicycle' model(a square connected to a circle) to prevent getting stuck behind small corners. The bad part was that the player was now unable to stay on any slope, because they kept sliding down.
To prevent that, I learned that I had to keep the density of both objects low.(see this question) This again created the gravity problem. Also, while the player now was able to keep standing on slopes, moving up on them was still extremely slow (and moving down incredibly fast).

I am getting a bit frustrated now over all this crazy behaviour that doesn't work the way I want it to. Now I am wondering:

Is there something wrong with the approach to handle the player's movement outside of Box2d, and after that let Box2d resolve the new collisions with ground and objects?

Or is this going to be extremely unstable and glitchy because I would 'teleport' the player instead of moving them with forces and is there still another, better way to get the movement I'd like?


texts:
I have recently started a new project with my SO (Significant other)and she is doing the art for my game (Pixel art) now i have always gone with 32x32, 64x64 and so on (Using 16x scale) but she thinks we should only have world objects tiled at that scale i.e the floors and walls etc, but the character and crafted items, weapons etc as whatever other scale, as it wont affect it. Am i correct in thinking this could lead to collision issues, scaling issues etc if we used, say a 50x16 character scale?
I know this may be opinion based (Although im not sure) i just want to know if it will affect things like collision and other mechanic's if the sprites don't all follow the same size scale.


texts:
I have started coding this project using the library SFML a few months ago.

I have implemented a random map generation everytime I load the game thanks to Biome and the Perlin noise Algorithm.

I wish i could increase the TileMap size on the border of the map according to the player position  (Chunk system in minecraft) .

I have managed to do it on the bottom and the right of the map :

But this isn't dynamic.
There is a snap of my code where i add a new "chunck" :

void TileMap::AddChunckToTileSet(sf::Vector2i PlayerTile, char * direction)
{
    int previousWidth = _width;
    int previousHeight = _height;

    _height = _height + 24;
    _width = _width + 24;
    m_vertices.resize(_width * _height * 4);

    int tileNumber = 384; // ToDO

    // on en déduit sa position dans la texture du tileset
    int tu = tileNumber % (m_tileset.getSize().x / _tileSize.x);
    int tv = tileNumber / (m_tileset.getSize().x / _tileSize.x);

    if (direction == "Down")
    {

        for (int i = previousWidth; i < _width; ++i)
        {
            for (int j = previousHeight; j < _height; ++j)
            {
                // on récupère un pointeur vers le quad à définir dans le tableau de vertex
                sf::Vertex* quad = &m_vertices[(i + j * _width) * 4];

                // on définit ses quatre coins
                quad[0].position = sf::Vector2f((i - previousWidth) + PlayerTile.x * _tileSize.x, j * _tileSize.y);
                quad[1].position = sf::Vector2f(((i - previousWidth) + PlayerTile.x + 1) * _tileSize.x, j * _tileSize.y);
                quad[2].position = sf::Vector2f(((i - previousWidth) + PlayerTile.x + 1) * _tileSize.x, (j + 1) * _tileSize.y);
                quad[3].position = sf::Vector2f((i - previousWidth) + PlayerTile.x * _tileSize.x, (j + 1) * _tileSize.y);

                // on définit ses quatre coordonnées de texture
                quad[0].texCoords = sf::Vector2f(tu * _tileSize.x, tv * _tileSize.y);
                quad[1].texCoords = sf::Vector2f((tu + 1) * _tileSize.x, tv * _tileSize.y);
                quad[2].texCoords = sf::Vector2f((tu + 1) * _tileSize.x, (tv + 1) * _tileSize.y);
                quad[3].texCoords = sf::Vector2f(tu * _tileSize.x, (tv + 1) * _tileSize.y);

            }
        }
    }
}

I call the function AddChunckToTileSet like this :

void TileMap::Update(sf::Vector2i PlayerTile)
{

    if (PlayerTile.y + 15 > _height)
    {
        // Increase map on Down according to our X
        printf("Add Chunck Down\n");
        AddChunckToTileSet(PlayerTile, "Down");
    }

}

Do you have any hints on how I could achieve this correctly ?


texts: how can I split the screen into two screens and make Gdx.input.setInputProcessor () accept two processors?

texts:
I want to draw in the first screen portion, and manipulate the buttons in the second part.

This is what I tried:

if (mouse.x <600) {
    Gdx.input.setInputProcessor (new InputProcessor () {

Override
public boolean touchup (int arg0, int arg1, int arg2, int arg3) {
return false;
}
.
.
.
.
.
}
if (mouse.x> = 600) {
Gdx.input.setInputProcessor (stage);
}

the problem is that I have the ability to go from the first part to the second but I'm not allowed to go from the second to the first, it blocks the mouse coordinates in x = 600 This is what I tried


texts:
I've got an annoying problem considering video ads. I've tried different networks and for all video placements (Rewarded and Interstitial) I've got same problem: the Ad shows 1 frame, then disappears, but the ad sound remains. I think It is needed to enable something in Player settings, but I was not able to find what exactly. Banner ads work fine. Currently I am testing Ad Mob. The reward works fine, but the video ad just not displaying correctly.

The example of the ad show failure: https://youtu.be/ykgI4qGCg0c

My Unity version: 2019.1.9f1 Personal
Platform: iOS
Device: iPad mini 2

 void Start()
  {
 AdMobRewardedAd = RewardBasedVideoAd.Instance;
 // Called when an ad request has successfully loaded.
 AdMobRewardedAd.OnAdLoaded += HandleRewardBasedVideoLoaded;
 // Called when an ad request failed to load.
 AdMobRewardedAd.OnAdFailedToLoad += HandleRewardBasedVideoFailedToLoad;
 // Called when an ad is shown.
 AdMobRewardedAd.OnAdOpening += HandleRewardBasedVideoOpened;
 // Called when the ad starts to play.
 AdMobRewardedAd.OnAdStarted += HandleRewardBasedVideoStarted;
 // Called when the user should be rewarded for watching a video.
 AdMobRewardedAd.OnAdRewarded += HandleRewardBasedVideoRewarded;
 // Called when the ad is closed.
 AdMobRewardedAd.OnAdClosed += HandleRewardBasedVideoClosed;
 // Called when the ad click caused the user to leave the application.
 AdMobRewardedAd.OnAdLeavingApplication += HandleRewardBasedVideoLeftApplication;
// Initialize the Google Mobile Ads SDK.
 MobileAds.Initialize(appId);

 this.Load_rewarded_video();
}
//Google ad mob Handlers======================
public void HandleRewardBasedVideoLoaded(object sender, EventArgs   args)
{
 //MonoBehaviour.print("HandleRewardBasedVideoLoaded event received");
}
 public void HandleRewardBasedVideoFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
 Time.timeScale = 1;
 //MonoBehaviour.print(
 //    "HandleRewardBasedVideoFailedToLoad event received with      message: "
 //                     + args.Message);
 }
public void HandleRewardBasedVideoOpened(object sender, EventArgs args)
{
 //MonoBehaviour.print("HandleRewardBasedVideoOpened event received");
}
public void HandleRewardBasedVideoStarted(object sender, EventArgs args)
{
 //MonoBehaviour.print("HandleRewardBasedVideoStarted event received");
}
public void HandleRewardBasedVideoClosed(object sender, EventArgs args)
{
 //MonoBehaviour.print("HandleRewardBasedVideoClosed event received");
 Time.timeScale = 1;

 this.Load_rewarded_video();

 }
 public void HandleRewardBasedVideoRewarded(object sender, Reward args)
 {
 Time.timeScale = 1;
 ContinueGameCalculations();
 }
 public void HandleRewardBasedVideoLeftApplication(object sender, EventArgs args)
 {
 //MonoBehaviour.print("HandleRewardBasedVideoLeftApplication event received");
  }
  private void Load_rewarded_video()
  {
  #if UNITY_IOS
 string ad_unit = "ca-app-pub-5759662936416666/3614416666";
 #endif
 AdMobRewardedAd.LoadAd(new AdRequest.Builder().Build(), ad_unit);
 }

For some reason the very first test ad from Admob shows the way I described above, but the next ones work fine.

Update: the issue remains for both Rewarded and Interstitial Admob ad placements.


texts:
Do you know http://tvtropes.org ?

It's a kind of wiki/database with scenaristic tropes, patterns that you can find in tones of stories, in tv shows, games, books, etc.

Each trope/pattern have a (funny) name and there are references to where it appears, and the other way arround : each book/game/etc. have a list of tropes that it contains.

I'm looking for an equivalent but for game mechanics patterns, something like "Death is definitive", "Perfect physical control (no inertia)", "Excell table gameplay", etc.

I think it would be really useful. I can't find an equivalent for game mechanics (tvtrope is oriented to scenario, not game mechanics).

Do you know any?


texts: Simultaneous line of sight for hundreds of individual agents on a grid?

texts:
I have a large grid with hundreds of individual agents, each of which is moving around based on its own visual inputs and a fast control algorithm.

My question is: How can I efficiently provide each agent with a set of other agents (or walls) that they can see?

Ray casting from each individual works, but is slow.  It seems like I should be able to preprocess the world at each step to speed up this process since I'll be doing it MANY times, but I haven't been able to come up with an appropriate algorithm.  Is there some known trick that I've missed?


texts: Material colours in unity not displaying correctly?

texts: Even though I've picked blue the color is displayed as something pinkish. All colors are like this


texts: Procedural vs Event Driven Paradigm Clash in HTML5

texts:
I've been writing some console-based games in python and got in the habit of having a "mainloop" that looks something like this (if it were JS):

// mainLoop would be
function mainLoop() {
    while ( state === "playing" ) {
        if ( turn === "player" ) {
            playerTurn(table, board);
            turn = "computer";
        } else {
            computerTurn(table, board);
            turn = "player";
        }
    }
}

This is great as I can easily swap out computer for player2 so the basic structure doesn't change much for AI vs 2-player games.

However, in HTML5 things get really confusing. Part of me wants to hold onto the simplicity of my mainloop structure, but since I need the listen for events in JS, it looks like I need to completely shift paradigm.

I did actually get what I want happening using

document.addEventListener( "click", function ( event ) {
    if ( event.target.matches( "#reset" ) ) {
        init( );
    } else if ( event.target.matches( ".cell" ) && turn === "player" ) {
        playerTurn( event, table, board );
        if ( hasFreeSpot( board ) ) { // don't switch player if board full (or win position?)
            computerTurn( table, board );
        }
    }
}, false );

and updating turn to player or computer within playerTurn() and computerTurn()

It's hard to reproduce a working example of what I'm trying to do as the program is quite long. what I'm looking for here if possible is some big-picture advice on how to implement player vs computer games in HTML5 where the player move comprises of clicking on some element.

Is there a basic template I can use for this kind of thing? Is the idea of a mainloop relevant in this context?

Is seems my current approach is a very confusing hybrid of procedural code for the computer turn and even-driven code for the player turn.

I will be happy to edit my question an include a full example if that is what you guys want here.

Thanks in advance.


texts: Is it advisable to maintain a separation between the engine and the game?

texts:
As I'm reading Uncle Bob's Clean Architecture I keep wondering how all the advice presented can be applied in game development. Games are nothing more that highly interactive real-time simulations and shouldn't really differ that much from any other complex systems. Good practices in architecture design should be as much help here as anywhere else.

That said I have some doubts whether obtaining a high level of coupling between game engine and its logic can be easily obtained. Game engine is basically a framework so "Frameworks Are Details" rule should be of use here but from what I see games are practically inseparable from their underlying engines. I haven't seen any use of Clean Code rules in most projects I've encountered. I've heard than even unit testing is a rare occurrence.

How can I even achieve loose coupling if all important subsystems like event handling, physics, renderer and even main loop itself are baked in the engine?

Or should I ignore this since an engine is not a database and it'd be highly unlikely to think about changing it as the project goes by?


texts: Divide two quaternions evenly by a scalar to get a smooth rotation in-between

texts:
How do you divide two quaternions - say A and B - evenly by a scalar, to calculate the rotations between them to render a smoother rotation?

Effectively, say you want to smooth the rotations between A and B
evenly by n. How do you calculate each quaternion value between A and B?

I have found that resorting to .eulerAngles leads to some wild gimbal locking, so I think the math needs to stay in quaternion space...


texts:
I hve that script:
public void ActivateCard(Card card)
        {
            Debug.Log("Activating card: " + card.CardsData);
            if (card.CardsData.creatureName != string.Empty)
                Summon(card);
            else
                CastSpell(card);

            if (_hand.Cards.Contains(card))
            {
                _hand.Cards.Remove(card);
                Debug.Log("Card " + card.CardsData.cardName + " deleted");
                Debug.Log("now we have(cards): " + _hand.Cards.Count);
            }

            _hand.TakingCards(0);
        }

And I expect that card will be removed from the list. But it allways remove only FIRST element in there. Here's what I have(card can't be the same in one list):

ADDICTION:
It's not a full code, but it's all we need I think.
Here's how this method calls:
-I-
public class InputClass
{
  void Update
  {
    if (targetSet)
     {
         if (Input.touches[0].phase == TouchPhase.Ended)
                    Cancel(true);
     }
  }

  void Cancel(bool isDone){ _actCard.Cancel(isDone); }
}

-II-
class ActCard
{
  public void Cancel(bool isDone)
  {
    if (isDone)
     {
        _activator.ActivateCard(_card);
     }
  }
}

-III-
class CardActivator
{
  public void ActivateCard(Card card)
        {
            Debug.Log("Activating card: " + card.CardsData);
            if (card.CardsData.creatureName != string.Empty)
                Summon(card);
            else
                CastSpell(card);

            if (_hand.Cards.Contains(card))
            {
                _hand.Cards.Remove(card);
                Debug.Log("Card " + card.CardsData.cardName + " deleted");
                Debug.Log("now we have(cards): " + _hand.Cards.Count);
            }
        }
}

-IV-
public class Hand
{
  List<Card> _hand = new List<Card>();

  public List<Card> Cards
        {
            get { return _hand; }
            set { _hand = value; }
        }
}
```


texts: Algorithm/ Logic of identifying a circle in Go game

texts:
I'm trying to create a 2 players Go-like game. Unfortunately I can't get the capturing system to act correctly. At the moment the system is half done, however I cannot think of a perfect way for it to recognize a circle correctly. This is the logic that I'm planning at the moment (let say it's currently White's turn):

1.Using the newest placed piece as the starting point, run a flood fill (Up, Down, Left, Right) code to find all the affected nodes/Black piece, and place them in a "suspects list".

2.Using the suspects list, find any White piece that is near them (Up, Down, Left, Right, UpLeft, UpRight, DownLeft, DownRight). Adds those pieces into a "circle candidate list".

3.Run through the circle candidate list and remove any piece that doesn't connect to at least 2 other candidates. Keep doing this until all candidate are connected to at least 2 other candidates or the number of candidates are less than 4 (which won't be possible to make a circle).

4.Using a recursive method checks whether we can make a circle using all the candidates. The last piece must be connected to the first one.

5.If a circle is identified, get all the nodes that are between the candidates, first checks from top-to-down then left-to-right. Records all the nodes that were identified in both checks as dead zones. Kill any Black piece inside the dead zone and any Black piece that is place inside there after this will automatically die.

Here's where the problem is, I noticed that 3 pieces that are next to each other will still be connected to 2 other piece. Which means the system will still see them as a legitimate candidate even if they aren't part of a circle. And secondly the way I use to check if there is a circle can easily fail if there are more than necessary pieces to make the circle since it could turn the wrong way and then unable to get back to the starting point.

I've been struggling with this capturing process for a week now, and tested a number of different ways. All of it will have a problem in certain scenario which resulted in a bug (either they're not capturing piece that should be captured, or capturing piece that should not be captured). So any help are greatly appreciated. Thank you.


texts: Create borders and clickable areas from image

texts:
Crusader Kings, Europa Universalis and several other strategy games use provice based maps where "tiles" are not squares nor hexagons. Border style indicates different ranks/owner.

I've done some research and this is what I found from modding guides: they seem to use a source image to dynamically generate the borders which are used to separate the provices but also to indicate currently selected areas (border changes color or flashes etc) and Im pretty sure that same file is used for "clickable areas" (click on provice to get province details screen).

Source image contains all the provinces painted with solid colors. This image is same size as height map (water bodies and land masses) to align geographical shapes with provinces.

Then there's some sort of dictionary file (text, JSON etc) that has all the province colors that maps these colors to meta data about the province. It also makes provinces "loopable" for game engine in order to add them to in-game database and to use colors to find the correct shapes from image.

Example in JSON:

// "key" is RGB color that points to correct province in previous image
"253:28:37": {
  "name": "Kent",
  "otherStuff": 13
},
"142:133:150": {
  "name": "Oxford",
  "otherStuff": 54
}

How to create referenceable borders and clickable areas from source image?


texts: DirectX 11 Predication(Occlusion culling)

texts:
Right now I'm using Predication to cull my BV tree after I first cull it with a few different view frustums, to get different ranges of objects to pass on to other parts of the engine. Life is good it works and has been a big save for me!

What I basically do is cull all the extracted BV trees nodes against the current depth buffer and it takes a few frames but I then do this:

 If g_pPredicate IsNot Nothing Then
        Dim tester As Boolean = _context.IsDataAvailable(g_pPredicate)
        If tester Then
            Dim ds As DataStream = _context.ImmediateContext.GetData(g_pPredicate)
            Predication = ds.Read(Of Boolean)
            ds.Dispose()
            ds = Nothing
        End If
    End If

to check the current occlusion of the BV tree node when I next update on the cpu, like I said it happens a few frames late but I can live with that for now.

The way I hide the lag is by only using the Predication result on tree nodes that are far from the camera and I also only update the visible tree nodes every 6 frames.

I also know after read the MSDN docs that I can use a different flag to just do the actual drawing of the object with the Predication hint and not return a value to the cpu but I don't think it will work with my instance drawing and I imagine that testing BV nodes would be faster than testing all the objects because BV nodes hold objects so if I cant see a node then I know that the objects want bee seen.

My question is, should I be down sampling the depth buffer and doing the Predication query's in a smaller resolution because that would allow me the get the returned value faster? Would it still take the same amount of time or am I doing it wrong?


texts:
I'm looking to have people share game content, save files, or characters on a mobile game platform.  That means they need to be able to upload and download from their phone, other iOS device, or computer.

What's the best way to do this?

Does Apple have a history of allowing games to download 'content' (incl. graphics) that hasn't been approved?

Are there any apps that do this, that I can try out?

Thanks,

[EDIT]

The files I want to share will be simple *.plist files, probably in binary format.


texts:
I am currently trying to sample a texture in screen space. This works well :

float4 positionCS = vertexInput.positionCS / vertexInput.positionCS.w;
screenPos = ComputeScreenPos(positionCS).xy;
float aspect = _ScreenParams.x / _ScreenParams.y;
screenPos.x = screenPos.x * aspect;

But I would like to be able to constrain uv position and scale based on object's position and distance from camera. I found some example but I also faced some issues and for the moment I don't see how to fix them. Here's the code :

float4 positionCS = vertexInput.positionCS / vertexInput.positionCS.w;
screenPos = ComputeScreenPos(positionCS).xy;
float aspect = _ScreenParams.x / _ScreenParams.y;
screenPos.x = screenPos.x * aspect;

float4 originCS = TransformObjectToHClip(float3(0.0, 0.0, 0.0));
originCS = originCS / originCS.w;
float2 originSPos = ComputeScreenPos(originCS).xy;
originSPos.x = originSPos.x * aspect;
screenPos = screenPos - originSPos;

// You can match object's distance like this
float3 cameraPosWS = GetCameraPositionWS();
float3 originPosWS = TransformObjectToWorld(float4(0.0, 0.0, 0.0, 1.0));
float d = distance(float4(0.0, 0.0, 0.0, 0.0), cameraPosWS - originPosWS);
screenPos *= d;

And here's the issue I am facing. You can notice that when the object is near screen edges the texture starts to move. Is there a way to avoid that ?

https://thumbs.gfycat.com/HairySpryArawana-mobile.mp4

I am using URP but this doesn't really matter.


texts: What framework provides mouse-interactive components as game sprites?

texts:
Background:

I wish to make a really flashy chess game.  The squares on the board will be unique terrain. The pieces will be colourful images.  The pieces will be animated. The pieces will sometimes be overlaid with each other at times.  It will have sound, allow saving, and need keyboard input sometimes.

The basic question (tl;dr):

I am looking for a free framework that will allow me to use interactive GUI components as sprites, that would make such a game easy to develop.

Things I want:

I need to be able to overlay partially transparent/translucent images on some sort of game canvas.
The images, or an invisible component holding them, should receive mouse events like clicks, click-and-drag, and mouse-over.  Pre-defined checking methods/functions are ok too.
The framework should allow animation of the images.
The framework must not exclude easy support for music, sound effects, keyboard or file IO.  I am happy to use compatible libraries or frameworks top do these things separately, but there's no point saving effort on mouse interaction only to find it has made everything else too difficult.
The framework and all its dependencies must be free.  I want to be able to distribute my game, free or for profit, without ever having to pay money for the tools or frameworks used in development. (Even if you think this is unfair or unrealistic, you won't change my mind.)
Documentation must be available.
Cross-platform i.e. should look and behave the same on linux or windows without major tweaking.

Things I don't care about:

Whether what you suggest is technically a framework, a library, an engine, or even a tutorial on how to easily do it.
I don't need bleeding-edge performance like you need for a fast-paced shooter.
The precise language or paradigm used.
Your (correct) belief that flashy graphics won't improve the chess experience. :-)
Anything relating to chess AI, marketing, or other important but out-of-scope considerations.

I appreciate any suggestions.


texts:
I am making a game which has a playing arena which renders a lot of grid of lines. The lines are colored. Now to have a good effect I thought of giving it the tron like effect of glowing lines. Now after surfing the net I came to know that I could achieve that effect using the bloom effect. Now for that I needed to GLSL in opengl which I have read to some extent but now I want to clear certain doubts of mine.

What is the difference between a shader having ".verg" and ".frag" extension against a ".glsl" shader?

Also given a ".glsl" shader. How can I get the ".verg" and ".frag" shader from it?

Any good tutorial for implementing bloom effect on the edges of a cube or edges of a rectangle?

I am using OpenGL and am programming on Ubuntu. Thanks


texts: Procedural generation for a text adventure game

texts:
I'm working on a text adventure game written in Python and I am at the point where I need to implement procedural generation for the map. As the user moves around, spots are generated, so the entire map is not generated at once but rather it's generated as the user gets closer. For example, the user begins at the position (0, 0) and so the spots generated in the beginning of the game are the eight spots/squares surrounding (0, 0) and of course (0, 0) itself.

I'm have trouble finding a simple way to decide if a "spot" or square is plains, forest, beach, ocean, mountains, etc. I don't want it to be totally random, I want there to be some cogency.

Any help would be appreciated. Thank you.


texts:
I tried many buttons but I can't connect them with the (Java)Script.

So I made 2 gui buttons: one for jump which was easy because I have an if statement and if it's true then jump.

But I have problems with the crouch button. Bellow is my script but I can't figure out how I can do this from Update in function Gui.

(Or if you know how to connect buttons with JS functions, please tell me: it's always a better option :D )

This is my script:

#pragma strict
private var tr: Transform;
private var dist: float; // distance to ground

function Start(){
   tr = transform;
   var ch:CharacterController = GetComponent(CharacterController);
   dist = ch.height/2; // calculate distance to ground
}

function Update()
{
  var vScale = 1.0;
  if (Input.GetKey("s")){
     vScale = 0.5;
  }

  var ultScale = tr.localScale.y;
  tr.localScale.y = Mathf.Lerp(tr.localScale.y, vScale, 5*Time.deltaTime);
  tr.position.y += dist * (tr.localScale.y-ultScale);
}

function OnGUI ()
{
  if(GUI.Button(new Rect(15, 330, 200, 100), "Shrink"))
  {
  }
}


texts: How to get started with game development?

texts: I m a engineering student. I have intermediate knowledge of programming languages. I know how to program in C and C++, and i have no experience regarding graphics, sound or implementing physics in programs. But i am really interested in game development and want a little guidance on how to begin.


texts: How to check in Unity whether tile B can be reached in a straight line from tile A?

texts:
I'm currently trying to smooth out my A* paths based on this article.

This is what I want to achieve:

But sadly I'm stuck at implementing the Walkable method.

I don't know how could I check whether a unit can reach tile B in a straight line from tile A.

(Let's keep it simple, and currently every unit is 1 tile wide.)


texts: Ways to track time and character ages across many years of game time?

texts:
I'm working on a system to track large numbers of characters across long periods of time. Characters grow old and die, give birth to new characters, etc. It's a grand-strategy game, with warring nations and long scenarios.

Of course, this means I need to track the passage of years. My first idea was to create a class Calendar, with methods like increment_year() that would go through the list of every person, faction, etc in the game and call their methods (update_age() and so forth).

However, this would mean Calendar would be a singleton, which is sometimes considered an antipattern.

Alternatively, I could make a global variable for the current time, and update that as part of the main() game loop--using globals sounds like a dirty thing to do, though.

Is there a good reason to use a Calendar singleton (or even a reason to have multiple separate Calendars?)


texts: How can I highlight and move to adjacent tiles in an isometric grid?

texts:
I trying to create a turn-based strategy game where you move a game object from one tile of a grid to another tile near it. I have created the grid using sprites and game objects but can't sort out the movement part.

How can I highlight adjacent tiles given the 'current' tile, and then allow a game object to move to any of those highlighted tiles?


texts: Having unity game saved to SD card can't run on certain devices but after it's moved to phone memory it works.. why?

texts: A game I made ends up not being able to run (it shows the loading screen but after that it gets stuck), happens on nexus 5, sony experia z3 and I found this happening because the game was downloaded into the sd card memory. After moving it to the phone the game runs. I'm not sure why this is happening. Please help?


texts: Why does physics not behave consistently in Unity?

texts:
I'm making a game in which AI players throw a ball.

In the screenshot, you can see the arena which is separated by a net in the middle. Each side of the arena has 6 players belonging to one of 2 teams. Right now, one of the players on the right side has the ball (the top-right player). He is going to throw the ball to the left side.

According to my code, the ball should always land on the same place, because the player always applies the same force to the ball. However, I have noticed that the ball doesn't always land in the same place. I have marked where I've seen the ball land with several red circles.

Interestingly, on my main PC, the ball almost always lands on the right-most circle. It rarely lands on the other circles, although that does happen. On 3 other PCs I've tested this game on, however, the ball most often lands on the legs of the top-left player, sometimes on his head or behind him, but never on the right-most circle (in front of him).

My game relies heavily on physics. The AI is supposed to calculate how to throw the ball to get it to land on a very specific location, as well as guess where it'll land depending on the ball's position and movements. If the physics don't behave consistently on all machines all the time, how is the AI supposed to calculate all of this accurately?

Here is the code in charge of throwing:

private IEnumerator Serve()
{
    var ball = GameObject.Find("Ball").GetComponent<BallController>();
    if (ball.ServingPlayer != this)
        yield break;

    yield return new WaitForSeconds(3);

    Vector3 shootDirection = transform.forward.normalized;
    var q = Quaternion.AngleAxis(-45, transform.right);

    ball.RigidBody.AddForce(q * shootDirection * 20f, ForceMode.VelocityChange);
}

As you can see, the ball is always thrown "forward" (facing the net) at a 45° upward angle, using a normalized vector and a constant speed (20f).

Before each throw, the position of the players is reset to the exact same location (and rotation) they are seen on the screenshot.

player.transform.localEulerAngles = new Vector3(0, playerRotation, 0);
player.transform.position = startingposition + posOffset;

In this case, playerRotation is either 90f or -90f depending on which side the player is on, startingposition is their "horizontal" position (relative to the net), and posOffset is their "vertical" position.

The ball has its velocity and angular velocity reset, but not its rotation (since it's a sphere, its rotation shouldn't influence anything). Its position is also set to a fixed location relative to whichever player has to serve the ball.

rb.velocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
transform.position = ServingPlayer.ServingPosition;

Here, rb is the ball's RigidBody.

Finally, I am not influencing the ball's movement in any way. I simply apply a force to it when serving, which happens only once. 3 seconds after the ball lands, the match is reset and everything repeats.

The flow is basically like this (pseudocode):

Start()

ResetCourt()
StartCoroutine(Players[0].Serve())
event BallLanded()
wait for 3 seconds

// repeat starting with ResetCourt()

I really need the ball's trajectory to be reproducible every single time on every possible machine. Obviously I'm doing something wrong here, but what?


texts:
I have this game client which connects to the server and sends requests and getting responses.

I have created a separate thread for listening to the server. Based on the response from the server, I want make GameObjects.

But the problem is, the server response is taken into my game using a separate thread. And as far as I know, we cannot create game objects in unity in any other thread than Main Thread.

How to create game objects based on the server response?

I am new to c# and unity. Sorry if this is a silly question. I did some research on the topic and I couldn't find and answer. There were posts saying to use coroutines; but I can't quite understand them.


texts: How to implement this kind of ripples with a GLSL fragment shader?

texts:
So I have already implemented the reflection part:

uniform sampler2D texture;
uniform vec2 resolution;
uniform vec3 overlayColor;

void main()
{
vec2 uv = gl_FragCoord.xy / resolution.xy;

if (uv.y > 0.3)// is air - no reflection or effect
{
    gl_FragColor = texture2D(texture, vec2(uv.x, uv.y));
}
else
{
    // Compute the mirror effect.
    vec4 color = texture2D(texture, vec2(uv.x, 0.6 - uv.y));
    //
    vec4 finalColor = vec4(mix(color.rgb, overlayColor, 0.25), 1.0);
    gl_FragColor = finalColor;
}
}

source

Now the question is how are these ripples implemented?


texts: Shader issues when creating projection using CreateOrthographicOffCenter instead of CreateOrthographic

texts:
Pre. Having these matrix transformations:

var scale = Matrix.CreateScale(50f);
var eye = new Vector3(0, 0, 10.0f);
var view = Matrix.CreateLookAt(eye, Vector3.Zero, Vector3.Up);
var projection = scale * Matrix.CreateOrthographic(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 1.0f, 1000f);
var rotation = Matrix.CreateRotationX(-MathHelper.PiOver2)*Matrix.CreateRotationY(MathHelper.PiOver2);

and then for each mesh producing “world” like this:

var localWorld = transforms[mesh.ParentBone.Index] * rotation;

and then applying these parameters to the effect:

effect.Parameters["World"].SetValue(localWorld);
effect.Parameters["View"].SetValue(view);
effect.Parameters["Projection"].SetValue(projection);
effect.Parameters["Bones"].SetValue(boneTransforms);
effect.Parameters["WorldInverseTranspose"].SetValue(Matrix.Transpose(Matrix.Invert(localWorld)));

I’m getting nice model like this:

Post. But after I changed CreateOrthographic to CreateOrthographicOffCenter like this:

var projection = scale * Matrix.CreateOrthographicOffCenter(-GraphicsDevice.Viewport.Width / 2f, GraphicsDevice.Viewport.Width / 2f, GraphicsDevice.Viewport.Height / 2f, -GraphicsDevice.Viewport.Height / 2f, 1.0f, 1000f);
var rotation = Matrix.CreateRotationX(MathHelper.PiOver2) * Matrix.CreateRotationY(-MathHelper.PiOver2);

I’ve got this:

Can someone give me a hint what am I doing wrong?


texts: Is there an accepted architecture for these classes?

texts:
I am coding a game in python and so far so good, but I feel like my classes are not very modular. This is a simplification of what I've done:

class Game:
def __init__(self):
    self.characters = []
    self.walls = []
    self.background = None
    self.canvas = None
    self.keyInputs = None

def update(self, inputs):
    self.keyInputs = inputs
    for character in self.characters:
        if character.died:
            self.characters.remove(character)
        else:
            character.update()

def draw(self):
    self.background.draw()
    for wall in self.walls:
        wall.draw()
    for character in self.characters:
        character.draw()

class Character:
    def __init__(self):
        self.horizontalPosition = 0
        self.verticalPosition = 0
        self.game = None
        self.died = False
        self.sprite = None
        ...

    def draw(self):
        self.game.canvas.draw(self.sprite, self.horizontalPosition, self.verticalPosition)

    def interactWith(self, character):
        ...

    def detectCollition(self, wall):
        ...

    def handleInputs(self):
        inputs = self.game.keyInputs
        ...

    def update(self):
        self.handleInputs()
        for character in self.game.characters:
            if character != self:
                self.interactWith(character)
        for wall in self.game.walls:
            self.detectCollition(wall)

This way Characters and Walls need to have a variable for which Game they are in, and a Game needs to have a variable for each Character or Wall that is in it.

Is there a better way to define these classes? Are there design patterns for this?


texts: What happens to data between vertex shader and pixel shader?

texts:
Short version: What can happen to the output of a vertex shader that leads to no(or very few) pixels being drawn, especially in relation to a perspective matrix.

Long version:

My problem refers to the fact that when using a projection matrix very few pixels are actually drawn, more often than not, no pixels are drawn. I have used the built-in debugger in VS2012 and inspecting the output of the vertex shader reveals that the transformations are most likely correct, it is only when it is passed to the pixel shader that things start to go astray.

What I tried:

use different built in matrices for calculating perspective
check the code for indirect modifications
set "CULLING_NONE" as a rasterizer state, that only increased the chance of something actually being drawn
set the "w" component of the SV_POSITION vector to 1, that also seemed to help to a certain degree
checked winding of triangles

My implementation performs the View-Projection multiplication first (of their transposes)
and then multiplies the position with the result of the former. I believe that's not where the problem lies due to the associative property of matrix multiplication.

I'd prefer it if I wouldn't have to resort to all sorts of hacks that can only increase the chance of something being drawn at all (never in the right way) as it seems clear that the problem lies in my implementation.


texts:
What is the most important thing to know about PR for indie developers?

I'm considering spending some time learning about PR in general, but it seems that the indie field is quite different than other fields in general.

What should most indie developers know about PR in general? Are PR-managers usually worth the money (and time?)?


texts: Unity bounds includes the center of the scene

texts:
I'm trying to get the bounds of an object and put a box around it.

Sounds simple right? I just encapsulate all the bounds together and use its center and size to do so.

But the problem is one corner of the box is always at the center of the scene, like a part of the object is there, unless the center of the scene is in the bounds.

This is when object is at the center

This is when it isn't

This is the code i'm using:

    public static Bounds Calculate(Transform TheObject)
    {
        Renderer renderer = TheObject.GetComponent<Renderer>();
        Bounds combinedBounds = new Bounds();
        if (renderer != null)
            combinedBounds = renderer.bounds;
        var renderers = TheObject.GetComponentsInChildren<Renderer>();
        foreach (Renderer render in renderers)
        {
            if (render != renderer) combinedBounds.Encapsulate(render.bounds);
        }
        return combinedBounds;
    }


texts:
My question is relatively hard to explain(for me, at least), so I'll go one step at a time and just tell me in the comments if it's not clear enough.

So I'm making a "Defend Your Castle" type 2D game, where two players own a castle and create units that will move horizontally to try to destroy the opponent's base. Here's a screenshot of the game:

The distance between both castles is much bigger in a real game though, bigger than the screen's width actually.

Because the distance is bigger than the screen's width, I had to implement a simple 2D camera: Camera2D, which only holds a Location Vector2 (and I always make sure this camera is within the field area).

Then, I just move all the game elements(castles, units, health bars) by that location, so that if a unit is at (5, 0), and the camera's location is (5, 0), then the unit's position will be moved by 5 units to the left, making it (0, 0) on the screen.

At first, I simply used a static background with mountains and clouds(yeah, those are supposed to be mountains and clouds). Obviously, this looked awful: when you moved the camera, the background would stay immobile.

Instead, I'd like to make a moving background, kind of a "scrolling" one. But rather than making a background with the same width as the distance between the castles, I'd like to make one that is a little bit smaller(but still bigger than the screen's width). I thought this would create an effect of "distance" with the background(but it might just look awful, too).

Here's the background I'm testing with:

I tried different ways, but none of them seems to work. I tried this:

float backgroundFieldRatio = BackgroundTexture.Width / fieldWidth;//find the ratio between the background and the field.
float backgroundPositionX = -cam.Location.X * backgroundFieldRatio;//move the background to the left

When I run this with fieldWith = 1600, BackgroundTexture.Width = 1500 and while looking at the rightmost area, the background is offset to the left by a too big amount, and we can see the black clear color in the back, as you can see here:

I hope I explained properly what I'm trying to achieve.

Thank you for your time.

Note: I didn't know what to look for on Google, so I thought I'd ask here.


texts: Why are my exported illustrator graphics blurry and messy in-game?

texts:
Currently I use illustrator to create artwork for my Android games.  My art size is pretty small, just 32x32. It looks OK in illustrator, but when exporting, my art is blurry and looks messy! Could you give some advice? How can you get vector-like art? And which is better for small images, pixel art or vector?

My large-size export image:

This is my exported result (The pixel is so bad when zooming):


texts:
I am currently working on a project in p5JS.
So lets say i've got a texture and top of it, i've got a radial gradient that is overlapping on the texture. I want to make this like a cool vision range effect in 2D. I believe you can imagine this stitation.
So how am i able to start this thing?
Should i use another framework to do this?


texts:
I am making a RTS game, and I'd like some advice on how to best render fog of wars, given what I'm already doing.

You can imagine this game as being a classic RTS like Age of Empires 2, where the fog of war will basically be handled by a 2D array telling if a given "tile" is explored or not.
The specific things to consider here are :

1) I'm only doing a few draw calls to draw the whole screen, using shaders, and I'm not drawing "tile by tile" in a 2D loop

2) The whole map is much bigger than the screen, and the screen can move every frame or so

In that case, how could I draw the fog of war ? I have no issue maintaining on the CPU-side a 2D array giving the fog of war for each tile, but what would be the best way to actually display it dynamically ?
thanks!


texts:
I am struggling to Center my image in my game's Steam page.

[img][center] --> Error

[center][img] --> Just prints a text "center" before and after the image :(.

How would a mere mortal center the image on Steam?


texts: How to load game resources correctly regardless of the working directory?

texts:
I am writing a resource manager for a hobby game project that reads textures/fonts etc.

Up to now, I was giving the location of the files relative to the executable path, like:

my_texture.loadFromFile("textures\\my_texture.png");

However, now I realized that the relative path I'm giving is relative to the working directory of the game. So, for example, if I run the executable from my IDE (which sets the working directory to the project directory instead of executable directory), the game fails to load the texture and crashes.

I was thinking about using the main's argv[0] and did some research on it, but apparently it is not reliable (it might just give the name of the exe).

So, how can I get the path to my resource files reliably? How does the professionals do it?

I'm using the SFML and C++17. I would like a portable solution if possible, otherwise Windows.

I checked this question but it wasn't helpful.


texts:
How can I detect the 'steepness' of a curve? For example, if the user swipes their finger across the screen in a curve, what's the best way of detecting whether the curve is almost a semi-circle, or whether it's straight?

Is it also possible to extend this to possibly recognise multiple curves (e.g. a sigmoidal shape)?

Thanks for any advice


texts: Storing voxels for a voxel Engine in C++

texts:
I am trying to write a little voxel engine because it's fun, but struggle to find the best way to store the actual voxels. I'm aware I will need chunks of some sort so I don't need to have the entire world in memory, and I'm am aware I need render them with reasonable performance.

I read about octrees and from what I understand it starts with 1 cube, and in that cube can be 8 more cubes, and in all those 8 cubes can be another 8 cubes etc. But I don't think this fits my voxel engine because my voxel cubes/items will all be the exact same size.

So another option is to just create an array of 16*16*16 size and have that be one chunk, and you fill it with items. And parts where there aren't any items will have 0 as value (0 = air). But I'm afraid this is going to waste a lot of memory and won't be very fast.

Then another option is a vector for each chunk, and fill it with cubes. And the cube holds its position in the chunk. This saves memory (no air blocks), but makes looking for a cube at a specific location a lot slower.

So I can't really find a good solution, and I'm hoping someone can help me with that. So what would you use and why?

But another problem is rendering. Just reading each chunk and sending it to the GPU using OpenGL is easy, but very slow. Generating one mesh per chunk would be better, but that means every time I break one block, I have to rebuild the entire chunk which could take a bit of time causing a minor but noticeable hiccup, which I obviously don't want either. So that would be harder. So how would I render the cubes? Just create all the cubes in one vertex buffer per chunk and render that and maybe try to put that in another thread, or is there another way?

Thanks!


texts: Why does the D3DXCOLOR structure not work as I expect?

texts:
I looked up some R G B values for certain colours, such as "Indian red" for example, which has the RGB values (238, 64, 4).

If I use those values into a D3DXCOLOR structure like this: D3DXCOLOR(238, 64, 4, 255), the colours display oddly - as white! This displays as yellow: D3DXCOLOR(238, 64, 0, 255). Why is this?


texts: Unity : I can't turn on my realtime shadow

texts:
I just add new project using 2019.4.4f1 and setup for Android build. Nothing fancy, i add a plane and sphere. Put sphere on top of plane. There's only 1 light (directional light with default setting). i can't see any shadow. I turn on all shadow setting, but still no shadow. I turn off both realtime global illum and baked global illum, just to reduce the complexity. All the objects are NON static.
scene :

My project setting :

My directional light setting :

MY lighting setting : NONE ( i turned off realtime GI and Baked GI so i can ignore these parameters)
Does anyone know what the problem is ?


texts: Is render to texture available in blender?

texts: I don't know is render to texture available in blender like in 3dsmax if it is available please tell me step by step method to do that thanks in advance.


texts: How to draw 2d road similiar to Outrun, Lotus, Pitstop, Cisco Heat games?

texts:
* UPDATED 23/05/2018 *

I've managed to implement road generation and curves using the techniques described here

I made a short gameplay video.

Hope it helps to anybody looking for answers.


texts:
As a DirectX noob i'm trying to wrap my head around depth buffers and specifically how pixel shaders are called for obscured pixels.

From what i understand, the rasterizer calls the pixel shader for each pixel that is covering the primitive beeing drawn, then later in the output merger stage, the output merger checks the depth buffer and either discards, writes or blends the pixel in the back buffer.

This seems wasteful though if i'm rendering a simple opaque object in front of a very complex one, so it seems it would be useful to have the rasterizer check the depthmap Before even calling the pixel shaders for the complex object.

Doing research i've found references to early Z test / conservative Z testing and so on, but there also seems to be very little documentation about it. i looked for a way to configure that on the rasterizer state desc object, but i only found anything like that on the OM state desc.

It also seems like this was possible to set with SetRenderState in DX9 (i have no experience with DX9 either though)

From my research it seems like this is something some hardware just does if i render objects front to back, is that correct? How can i even tell? With all the Control DirectX gives you it seems weird that there is no control over this, as it seems to be a good optimization :)

Any info or references on this is appriciated


texts:
I maintain a small rendering engine that displays models in Direct3D 9. I'm currently migrating this to Direct3D 11, and I've hit a snag in how I display points on the model. Using a sphere mesh, I translate to each point in the local coordinates, and draw the mesh. In Direct3D 9, I was using the fixed function pipeline for the drawing of the mesh. So, I would just change the world matrix for each point and draw the mesh. Obviously in Direct3D 11, I need to use shaders and update constant buffers.

The problem I've run into is the high volume of Map/Unmap calls I need to make so that I can set the constant buffers with the updated world matrix. This is creating a bottleneck and the framerate is slower than the Direct3D 9 implementation. If I remove the Map/Unmap calls, performance is much better, but obviously the meshes are in the wrong spot when I do this.

Am I missing something? Is there a better way to be doing this? It seems strange to me that I can't mirror the same performance I got from Direct3D 9. One thing I should note is that this is done in C++/CLI, so there is some marshaling going on, but from what I can tell via benchmarking, that doesn't have anything to do with the slow down.

Here is my code:

D3D11_MAPPED_SUBRESOURCE mappedResource;
HRESULT result;

result = device->UnmanagedContextPointer->Map(d3dBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
Marshal::StructureToPtr(data, IntPtr(mappedResource.pData), false);
device->UnmanagedContextPointer->Unmap(d3dBuffer, 0);

Any insight would be greatly appreciated, thanks!


texts: Balance advantage of having the first turn

texts:
I'm developing a game in which two players compete for area domination. Each player can play four moves per turn, ideally conquering four tiles.
Edit: Here a little more detail on the mechanics: Each player is given the same amount of cards (about 20). Each card has a value. The board consists of 4x5 tiles which you conquer by placing a card on it. If there already is a card on the tile, your can still conquer the tile but your card must have a higher value than the card on the tile.

The problem is that player two could technically (almost) always just undo player ones moves by conquering the same areas immediately. Of course this isn't fun at all and no human player would play this way, but I'm working on implementing an AI opponent, and I've seen the above happen a few times:

Player one conquers four tiles with pretty low value cards
player two immediately takes them
player one takes them back again because not doing so would be a disadvantage
player two takes them back again etc...

So as you can see, this is definitely not the best strategy as it becomes ridiculously expensive to possess the tiles of interest, but there are strategies or situations in which you might play like this.

How should I balance this? Are there any common design solutions for this problem?

(Having player one play more moves in the first turn would give player one a huge advantage as it would allow him/her to conquer highly strategic areas in the first turn. (Unfortunately, the "immediately undo player ones moves" strategy is actually not mathematically bad for player two, but that's another issue))


texts: How do I render my 3D game in ASCII art?

texts:
I'm trying to create an Easter egg for a 3D game in Unity3D. I want to render my game momentarily in ASCII art.

My first idea is to create a shader to do that, but I'm not sure if it's the right way.


texts: How do I set up the microphone for an Android device in Unity?

texts:
I'm developing a simple android app that needs to use the microphone. I'm able to load my app on my Android phone using developer mode, but I do not understand how to enable the mic. How can I enable the microphone and use the input?

I started with a brand new Unity 2D project. I created a TextMeshPro Text object to display logs and set this reference on the script via the inspector. I have attached the following script to the Main Camera.

using UnityEngine;
using UnityEngine.Android;
using TMPro;

public class RequestPermissionScript : MonoBehaviour
{
    public TextMeshProUGUI logs;

    void Start()
    {
        if (Permission.HasUserAuthorizedPermission(Permission.Microphone))
        {
            // The user authorized use of the microphone.
            logs.text = "has authorized";
        }
        else
        {
            // We do not have permission to use the microphone.
            // Ask for permission or proceed without the functionality enabled.
            logs.text = "has not authorized";
            Permission.RequestUserPermission(Permission.Microphone);

        }
    }
}

I then Build and Run this as Android and the app is loading on my Android phone attached via USB.

I expect a pop-up to appear asking for permissions to the mic, but this does not happen and the logs says "has not authorized". What am I missing or doing wrong?


texts: Perpendicularity of a normal and a velocity?

texts:
I'm trying to fake angular velocity on my vehicle when it hits a wall by getting the dot product of the normal of the edge the car is hitting and the vehicle's velocity:

            Vector2D normVel = new Vector2D();
            normVel.equals(vehicle.getVelocity());
            normVel.normalize();
            float dot = normVel.dot(outNorm);
            dot = -dot;
            vehicle.setAngularVelocity(vehicle.getAngularVelocity() +
                    (dot * vehicle.getVelocity().length() * 0.01f));

outNorm is the normal of the wall.

The problem is it only works half the time. It seems no matter what, the car always goes clockwise.

If the car should head clockwise:

--------------------------------------
       /
      /

I want the angular velocity to be positive, otherwise if it needs to go CCW:

--------------------------------------
       \
        \

Then the angular velocity should be negative...

What should I change to achieve this?

Thanks

Hmmm...

Im not sure why this is not working...

        for(int i = 0; i < buildings.size(); ++i)
        {
            e = buildings.get(i);
            ArrayList<Vector2D> colPts = vehicle.getRect().getCollsionPoints(e.getRect());

            float dist = OBB2D.collisionResponse(vehicle.getRect(), e.getRect(), outNorm);
            for(int u = 0; u < colPts.size(); ++u)
            {
                Vector2D p = colPts.get(u).subtract(vehicle.getRect().getCenter());
                vehicle.setTorque(vehicle.getTorque() + p.cross(outNorm));
            }


texts: How To Find Out Which Package That Asset Belongs To?

texts:
I have just messed up my project with some conflicting plugins, so i need to clean all plugins and reimport them, but i can't make sure which files to delete.

So how can i find out which package an asset belongs to?

Thanks in advance.


texts: 2D Rendering with OpenGL ES 2.0 on Android (matrices not working)

texts:
So I'm trying to render two moving quads, each at different locations. My shaders are as simple as possible (vertices are only transformed by the modelview-projection matrix, there's only one color).

Whenever I try and render something, I only end up with slivers of color! I've only done work with 3D rendering in OpenGL before so I'm having issues with 2D stuff.

Here's my basic rendering loop, simplified a bit (I'm using the Matrix manipulation methods provided by android.opengl.Matrix and program is a custom class I created that just calls GLES20.glUniformMatrix4fv()):

Matrix.orthoM(projection, 0, 0, windowWidth, 0, windowHeight, -1, 1);
program.setUniformMatrix4f("Projection", projection);

At this point, I render the quads (this is repeated for each quad):

Matrix.setIdentityM(modelview, 0);
Matrix.translateM(modelview, 0, quadX, quadY, 0);
program.setUniformMatrix4f("ModelView", modelview);
quad.render(); // calls glDrawArrays

and all I see is a sliver of the color each quad is! I'm at my wits end here, I've tried everything I can think of and I'm at the point where I'm screaming at my computer and tossing phones across the room. Anybody got any pointers? Am I using ortho wrong? I'm 100% sure I'm rendering everything at a Z value of 0. I tried using frustumM instead of orthoM, which made it so that I could see the quads but they would get totally skewed whenever they got moved, which makes sense if I correctly understand the way frustum works (it's more for 3D rendering, anyway).

If it makes any difference, I defined my viewport with

 GLES20.glViewport(0, 0, windowWidth, windowHeight);

Where windowWidth and windowHeight are the same values that are pased to orthoM

It might be worth noting that the android.opengl.Matrix methods take in an offset as the second parameter so that multiple matrices can be shoved into one array, so that'w what the first 0 is for

For reference, here's my vertex shader code:

uniform mat4 ModelView;
uniform mat4 Projection;

attribute vec4 vPosition;

void main() {
    mat4 mvp = Projection * ModelView;
    gl_Position = vPosition * mvp;
}

I tried swapping Projection * ModelView with ModelView * Projection but now I just get some really funky looking shapes...


texts: If I'm using an angle with a value of somewhat below 0.1 degrees in Quaternion.AngleAxis, the quaternion will not apply a rotation at all. Why is this?


texts: Managing audio in a RTS - when do I play sounds?

texts:
Building an RTS I have several hundred units on screen at one time.

Whenever a Unit attacks/gathers something, I want to play a sound (if camera is close enough).

My question is, how do most RTS games do this? Do I play 1 sound per attack per unit, i.e if 200 units are fighting do I play 200 individuals sounds (one sound each time a unit attacks)?

Same goes for gathering, if 20 workers gather wood, do I play a sound each time they hit a tree?

Does this not use up a lot of resources? Is there a better way?


texts: How do I cycle through a BufferedImage array of images and display them?

texts:
So, I'm coming from Python and Pygame here, porting most of my code because I didn't like the performance. A lot of the syntax is similar, but I've been having some trouble with a few things, namely this animation function.

I'm attempting to cycle through an array of images and have them display an animation. Here's my code so far:

//Animation images.
private BufferedImage[] idling = {Sprite.loadSprite("1"), Sprite.loadSprite("2"), Sprite.loadSprite("3"), Sprite.loadSprite("4"),
         Sprite.loadSprite("5"), Sprite.loadSprite("6")};
private BufferedImage[] walkingLeft = {Sprite.loadSprite("L1"), Sprite.loadSprite("L2"), Sprite.loadSprite("L3"), Sprite.loadSprite("L4"),
         Sprite.loadSprite("L5"), Sprite.loadSprite("L6"), Sprite.loadSprite("L7"), Sprite.loadSprite("L8")};
private BufferedImage[] walkingRight = {Sprite.loadSprite("R1"), Sprite.loadSprite("R2"), Sprite.loadSprite("R3"), Sprite.loadSprite("R4"),
         Sprite.loadSprite("R5"), Sprite.loadSprite("R6"), Sprite.loadSprite("R7"), Sprite.loadSprite("R8")};

Then my actual animate function (which I suspect is where the issue is).

public Image animate() {
    Image animation = idling[0];
    int current_image = 0;
    int current_image_add = 1;
    if (xa == 0 && ya == 0) {
        if (current_image >= 5)
            current_image_add = -1;
        if (current_image <= 0)
            current_image_add = 1;
        if (current_image >= 6)
            current_image = 0;
        current_image += current_image_add;
        animation = idling[current_image];
    }
    if (xa == game.speed) {
        if (current_image >= 7)
            current_image_add = -1;
        if (current_image <= 0)
            current_image_add = 1;
        current_image += current_image_add;
        animation = walkingRight[current_image];
    }
    if (xa == -game.speed) {
        if (current_image >= 7)
            current_image_add = -1;
        if (current_image <= 0)
            current_image_add = 1;
        current_image += current_image_add;
        animation = walkingLeft[current_image];
    }

    return animation;
}

While I was looking over this class, I actually noticed that I had no curly brackets surrounding my if statements, and that might be causing problems. Python doesn't require them, so I forgot that Java did. So, I answered my first question before I even asked it.

The draw function, simple as it is.

public void paint(Graphics2D g) {
    animate();
    g.drawImage(animate(), x, y, null);
}

Now that it will actually swap BufferedImage arrays when I change directions, how do I get it to cycle through the images? Apparently my if statement functions will only swap to the first image and not change to the next ones.

Edit: Alright, I figured that adding some clarification on what this does might help. The arrays contain all of the images for the animations. The animate() function sets the current_image variable to the first index of the array, which is the start of the animation. xa and ya are modified by a move() function elsewhere in the class, which the animate() function checks the value of to determine if the character is moving or not. If xa and ya are zero, the character isn't moving and the idling[] array is chosen. Likewise, if xa is positive or negative game.speed, right or left is chosen, respectively.

The point of this function is to cycle through the indexes by returning Image animation as whatever array and index of that array should be running at the time based on movement. At the end of each if block, it sets animation equal to whatever animation set and the current_image variable to choose the image and index.


texts: How can I randomly generate achievements?

texts:
Novice programmer here.
To challenge my self i want to create an achievement system that randomly generates achievements for me based on a set of trackable metrics within my game.

To keep it as abstract as possible my game is a turn based highscore chaser. Each game has 13 turns. Each turn consists of placing 4 tiles, each tile can have an individual score which together form the turn score. There are 5 different tile types that can be individually combined to raise each tile's score differently. Each turn one of the 5 tiles gets a bonus making it worth double points. Also in each turn you can form "hands" similar to poker where for example two tiles of the same type next to each other are a pair, which nets a hand bonus for individual turns.

Here's what my generated achievements should look like:

Get a turn score of 15 and create a pair using tile type x.
Create a tile type y that has 5 points.
Create 5 hands of type x and use tile type x or y.
Get a total score of 50 without creating more than 3 hands of type x.

Obviously this seems kind of complicated and i'm kind of asking myself how to create such "complex" achievements. Seems like i need to establish some kind of syntax that i can feed the system to produce these kinds of requirements. But i'm kind of stuck since i couldn't find any info on this issue yet.

Maybe you have done something similar?


texts: Is there a sprite sheet creator that satisfies these requirements?

texts:
I'm looking for a decent sprite sheet packer.

Features:

Command line interface for Linux.
Effective packing algorithm.
Configurable padding between sprites in the sheet.
Configurable fixed sprite sheet size (i.e. pack to many sheets).
Duplicate sprites detection, preferably with some tolerance to allow for FP errors when packing rasterized vector images.
Auto-crop by transparent pixels (i.e. sprite is cropped when packed and it is correctly reflected in the data).
Support for web-graphics formats (jpg, png at least).
Reasonable data output format (sprite sheet indes).

Paid software is okay as long as the price is reasonable.


texts:
Have an idea to set the texture to 3D material slowly. It would be like some animation, that change previous texture to new sloowly from bottom to top.
I need it to my game... Can't find the solution...
Can you help me with this problem?


texts: Tips for Component Based Entity System message handling

texts:
I'm trying to implement a component-based entity system but am a bit confused on how I should handle the messaging. There are two problems I'd like to resolve so I can test the system. Below is the code I have so far,

The Entity class:

class Entity{
public:
    Entity(unsigned int id):
    id_(id)
    {};
    void handleMessage(BaseMessage &message){
        for(auto element: components_){
            element.second->handleMessage(message);
        }
    }
    template<class T>
    void attachComponent(T *component){
        //Consider making safer in case someone tries to attach same component type twice
        components_[typeid(T).hash_code()] = component;
    }
    template<class T>
    void detachComponent(void){
        components_.erase(typeid(T).hash_code());
    }
    template<class T>
    T* getComponent(void)const{
        return *components_.find(typeid(T).hash_code());
    }
    unsigned int getInstanceID(void)const{
        return id_;
    }
private:
    unsigned int id_;
    std::map<size_t, BaseComponent*> components_;
};

The Base Component and Message classes:

class BaseComponent{
public:
    virtual void handleMessage(BaseMessage &message){};
};

class BaseMessage{
public:
    virtual int getType(void) = 0;
};

1. Message Type Handling

My first question is how I should handle the different (derived from BaseMessage) message types.

I have thought of two ways for handling the message types of the derived message types. One is to generate a hash (i.e. using FNV) from a string that names the message type and use that hash to determine the message type. So the handleMessage(BaseMessage &message) function, would first extract this hash from the message and then do a static_cast to the appropriate type.

The second method is to use a template as follows (similar to the attachComponent methods of the entity class),

template<class T>
handleMessage(T& message){};

and make specializations for each message type the specific component is going to make.

Are there any drawbacks using the second method? What about performance-wise, why don't I see this kind of use more often?

2. Input Handling

My second question is what would be the optimal (in terms of latency and ease of use) way to handle input?

My thought was to create an InputHandlerComponent which registers with the keyboard class to listen to specific key presses defined possibly in some file. For example

keyboard.register( player.getComponent<InputHandler>() , 'W')

I wish there was a more concise guide to component based systems but I guess there are many different ways to do the same things. I have more questions but I think it'd be wiser to first try implementing what I can.


texts: libGDX - orthographic camera and world units

texts:
I've followed the advice in this post to handle world/screen coordinates, but I'm getting results I don't quite understand, as I'm not terribly good in math.

So, when I use this code:

SpriteBatch batch;
OrthographicCamera camera;
public static float width = 0, height = 0;

private void setupGraphics(SpriteBatch batch) {
    height = Constants.TILES_Y; // 20
    float pixelsPerUnit = Gdx.graphics.getHeight() / height;
    width = Gdx.graphics.getWidth() / pixelsPerUnit;
    Gdx.app.log("debug", "Width: " + width + " height: " + height + " ppu: " + pixelsPerUnit);
    camera = new OrthographicCamera(width, height);
    camera.position.set(0, 0 / 2, 0);
    camera.update();
    batch.setProjectionMatrix(camera.combined);
}

...the result looks like this - it seems that the view height is now 20 pixels, not 20 32x32 tiles:

However, when I add a multiplier to the height, like 16, the result looks like this, which is more like what I want:

Here's the changed code:

    height = Constants.TILES_Y * Constants.TILES_MULTIPLIER; // 20 * 16

How would I modify the code to avoid having to supply the multiplier every time when I handle coordinates?


texts: Need opinions on my component based design

texts:
I have an Entity class and a Component class. The Entity class has a list of attached components, and each component also has a member variable that is a reference to the entity that it is attached to (cyclical design).

Then, there is the EntityManager class, which has a list of (you guessed it!) entities, and each entity also has a reference to its encapsulating entity manager.

The reason for this cyclical design is due to data reliance. To explain further, my Entity class is essentially just a giant bucket of data: any data any type of entity needs already exists on this class when it is instantiated. However, in order to make use of this data, the Entity needs the relevant components attached. For example, my Rendering component takes the Entity's spriteData member and draws it to the backbuffer. Without a rendering component, spriteData is not utilized. Since my components need to access the Entity's member variables, each component needs a reference to the Entity it is attached to.

For an example of why my entity needs a reference to the entity manager, it is because some components (such as collision) need to access other entities' data buckets in order to function (for collision, this would be checking nearby entities' position vector and comparing it to the component's referenced entity).

There is more to it than this, but I just wanted to highlight the central idea of what I was doing, and wanted opinions on whether a cyclical approach like this (with little data encapsulation as well..) is a good idea or not. Maybe I'm just overthinking it /shrug. Opinions on how to steer the design would be hugely appreciated, as well.


texts:
I am making a LibGDX app, and I need to get the view to put to an Android app.
Here is the code to get the view:

package jangkoo.game.shadowfiend.android;

import jangkoo.game.shadowfiend.ShadowFiendGame;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
public class LibGdx extends AndroidApplication {
    private static final String TAG = "LibGDx";
    public View view;
    Bundle savedInstanceState;
    @Override
    protected void onCreate (Bundle savedInstanceState) {
        if(savedInstanceState == null)
        this.savedInstanceState = getIntent().getExtras();
        Log.e(TAG,savedInstanceState + "");
        super.onCreate(savedInstanceState);

        AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
        view = initializeForView(new ShadowFiendGame(), config);

    }
    public LibGdx(){
        onCreate(new Bundle());
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        }
}

And I want to get the libGDX.view from this,for a class that doesn't extend AndroidApplication.

protected void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    interstitialAd = new IntestialAds(this);
    inflater = LayoutInflater.from(this);
    config = new AndroidApplicationConfiguration();
    libGdx = new LibGdx();
    Log.e(TAG,libGdx.view + "");
}

However, the onCreate function has nullpointer exception. How can I handle this?


texts:
Is this possible?

To elaborate, I am making a PacMan offshoot. Essentially it is a "zoomed in" version of the game, but the board is randomly generated. I have 11 .png files each to be used as a background for different hallway shapes. You have your straightaways, corners T junctions and cross intersection. They are very simple, each has a black background and the walls are blue. What I am looking for is a way to stop the player from walking on the blue parts of each image. Is that possible?

My current set-up is that I have a Piece class that holds the image, Entry points as bools (up down left right) for when I randomly select the image to be used so that a path can be created, size, etc. I then have a Board class that holds a list of Pieces (size 11 (One for each image))) and then 2D an array "board" (currently 9x9) that randomly but intelligently generates the map. When it comes to player pathing, I was manually going to add to the Piece class code that adds invisible rectangles over the blue walls and then have the Player class, or some other class, check for collision. This would take a ton of extra code because each image is different so each would need to be manually done.

I was just thinking there must be an easier way to do this, and the whole color idea occurred to me. If i could just check if it intersects the blue and then change its position back that would be much easier.

I am at work currently, but if there is any code you would need to see, or any other helpful information let me know and I will add it as soon as I get home!

TL;DR Is there a way to check collision via color, or add rectangle automatically over a specific color.


texts: How do you know when you are ready for game programming?

texts:
I've been programming for a while now and I want to make games or game engines. But I don't really know how much of programming one does need to learn to have the proper knowledge to make games. My question is, how hard it it really ? And what is the proper knowledge of programming when you're getting started ?

I've programmed mostly in C#, Java and C++.


texts: Unity Tilemap's WorldToCell always return with (0, 0, 0)?

texts:
Based on a Vector2 I want to know the coordinate of the tilemap at that position.

But for some reason, it always returns (0, 0, 0). Why?

Why?

var position = new Vector2(1.5, -0.5);
for (int i = 0; i < 8; i++)
{
    position += new Vector2(1, 3);
    var coordinates = tilemap.WorldToCell(position);
    Debug.Log(position + ", result: " + coordinates);
}


texts: How to prevent top down sprite snapping during diagonal movement upon keyboard release

texts:
I have a sprite that faces 4 directions depending on input. This is all working well except for my keyboard input..

If I am pressing down-right at the same time on the keyboard and release both keys there is a moment where I am pressing only the right key. This creates a snapping of my sprite upon key release where now im suddenly facing right instead of down.

basically i would like to release both the x and y buttons at the same time but i dont have a good way of detecting this. its TOO sensitive.

    pressed_vector.x = int(directions.right) - int(directions.left)
    pressed_vector.y = int(directions.down) - int(directions.up)

    dpad_vector = pressed_vector.normalized()
    owner.direction_changed(dpad_vector)

its the standard input code you see everywhere.

I have the player mapped to a virtual joystick, dpad etc and i dont have this issue because on release you're going to be releasing your x and y keys at the same time. not sure how to handle this with the keyboard.


texts: How to have an event occur after x seconds?

texts:
I want a method to run after every 10 or 15 seconds.

My timer is set to:

timer = (double) gameTime.ElapsedGameTime.TotalSeconds;

What would be the logic to check for every 10 or 15 seconds?


texts: How to add an icon to a script registered as a class?

texts:
While learning Godot, the tutorial dictates how to add an icon to a class.
Tutorial

You may add a comma and an optional path to an image to use as an icon. You will then find your new type in the Node or Resource creation dialog.

Steps taken:

Added a 16x16 svg file to the resources named something.svg  .

Created a script with a path to that icon.

Added a node of that kind.

I don't see that icon? Not sure why.


texts:
I want to draw the depth buffer in the fragment shader, I do this:

Vertex shader:

varying vec4 position_;

gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
position_ = gl_ModelViewProjectionMatrix * gl_Vertex;

Fragment shader:

float depth = ((position_.z / position_.w) + 1.0) * 0.5;

gl_FragColor = vec4(depth, depth, depth, 1.0);

But all I print is white, what am I doing wrong?


texts:
I have been developing an Android app using OpenGL 1.0 for quite some time using a naive approach to rendering, basically making a call to glColor4f(...) and glDrawArrays(...) with FloatBuffers each frame.  I am hitting a point where graphics is becoming a huge bottleneck as I add more UI elements and the number of draw calls increases.

So I'm now looking for the best way to group all of these calls into one (or two or three) draw calls.  It looks like the cleanest, most efficient and canonical way to do this is to use VBO objects, available from OpenGL ES 2.0 on.  However, this would require a HUGE refactoring on my part to switch my whole graphics backend from ES 1.0 to ES 2.0.  I am not sure if this is a good decision, or if there are acceptable ways to group my drawing calls in 1.0 that would work fine for relatively simple 2D data (squares, rounded rectangle TRIANGLE_FANs, etc.), or if it really might be worth biting the bullet and making the switch.  I might also mention that I have a HEAVY reliance on translation and scaling that is so convenient with the fixed pipeline of ES 1.0.

Looking around, I am surprised to find almost NO people in my position, talking about the tradeoffs and complexity at hand for such a switch.  Any thought?


texts: Move circle inside semi-circle based on external object

texts:
I have a circle that I'd like to move around in semicircle with it's location following an external object.
I can get the direction the circle should be facing with something like this:
Vector3 targetDir = X.transform.position - circle.transform.position;

How can I stick the movement of the circle inside a semicircle?