text:
Babylon.js not rendering scene
I'm very new to Babylon.js and I'm trying to make a simple game with it, but I have a problem: It does not render anything at all.
Here's the playground link: https://playground.babylonjs.com/#R7BDW3#22
I modified the default example (the plane and the sphere) and tried to make the camera rotatable around the sphere (focus is in the sphere), but nothing renders at all.
I googled this problem for like an hour without any results...
Also I tried exporting it and running the HTML file - but the only thing I see in it is just the dark purple backgroud...
Adding scene.render(); before the return scene in the createScene() function also didn't do anything :(
My browser console:

as text:
WEBGL_debug_renderer_info is deprectaed in Firefox and will be removed. Please use RENDERER.           thinengine.ts:1224:43
Babylon.js v6.16.0 - WebGL2                                                                        (5) thinengine.ts:10009:16

What am I doing wrong?


text:
SKNodes in a grid configuration get out of place after falling to fill gaps
I am making a “simple” game where the user will “pop” blocks by tapping on “clusters” of blocks.  When the user taps it destroys the “cluster” of blocks, the other blocks move down to fill in the empty spots on the board, and new ones come in from the top to fill the board back up.  The first time the user taps, everything works perfectly.  All blocks move down to fill in the missing spots and new ones come on screen:

After the user taps the second time, everything seems to get out of place:

The container that the blocks are created in and added as children is an SKShapeNode, and in the screenshot it is the area inside the “gray” line.  The white boxes to the left, right and bottom are my attempt to keep the blocks inside the “level” node from moving out of place.  It obviously doesn’t help.
Here is my code for creating the initial set of “blocks” and adding them to “level”:
func addBlocks() {
    var row = 0
    var col = 0
    var id = 0
    for r in stride(from: 13, through: frame.width, by: blockSize.width) {
        for c in stride(from: 13, through: frame.height - blockSize.height * 4, by: blockSize.height) {
            let color = level!.generateColors.chooseSet(colorSet: level!.generateColors)
            let position = CGPoint(x: r, y: c)
            let block = BlockEntity(name: "Box-\(id)",
                                    color: color,
                                    blockSize: blockSize,
                                    position: position,
                                    pointValue: 60,
                                    column: col,
                                    row: row)
            addChild(block)
            blocks.append(BlockData(id: id,
                                    position: block.position,
                                    block: block,
                                    row: row,
                                    col: col)
            )
            id += 1
            col += 1
        }
        row += 1
    }
}

The code to fill in the empty spots when the blocks are popped is:
func fillInBlocks() {
    repeat {
        let missingBlocks = blocks.filter({ $0.block == nil })
        for missing in missingBlocks {
            let col = missing.col
            let column = blocks.filter({ $0.col == col })
            for missing in column {
                if missing.block == nil {
                    repeat {
                        if let blockExistsIndex = blocks.firstIndex(where: { $0.col == missing.col + 1 && $0.row == missing.row && $0.block != nil }) {
                            if let missingBlockIndex = blocks.firstIndex(where: { $0.id == missing.id }) {
                                guard let existingBlock = blocks[blockExistsIndex].block else { return }
                                let move = SKAction.move(to: blocks[missingBlockIndex].position, duration: 0.25)
                                existingBlock.run(move)
                                blocks[missingBlockIndex].block = blocks[blockExistsIndex].block
                                blocks[blockExistsIndex].block = nil
                            }
                        }
                    } while blocks.first(where: { $0.col == missing.col + 1 && $0.row == missing.row })?.block != nil

                    if missing.position.y.rounded() == 438.0 {
                        if let index = blocks.firstIndex(where: { $0.id == missing.id }) {
                            let color = level!.generateColors.chooseSet(colorSet: level!.generateColors)

                            var position = CGPoint(x: blocks[index].position.x, y: 475)
                            let block = BlockEntity(
                                name: "Box-\(blocks[index].id)",
                                color: color,
                                blockSize: blockSize,
                                position: position,
                                pointValue: 60,
                                column: blocks[index].col,
                                row: blocks[index].row
                            )

                            blocks[index].block = block
                            position = CGPoint(x: blocks[index].position.x, y: 440)
                            let move = SKAction.move(to: position, duration: 0.25)
                            blocks[index].block?.run(move)
                            addChild(block)
                        }
                    }
                }
            }
        }
    } while blocks.filter({ $0.block == nil }).count > 0
}

Does anyone have any suggestions on how I can fix this so that it will reliably move the blocks without causing the “wreck” seen when the user taps the second time?
Also it should be noted that I used this article by Kodeco as inspiration to getting my blocks to align in a grid and get filled in when blocks are removed:
How to make a game like candy crush
Also note, I am not making a game like Candy Crush LOL.
I think I've narrowed it down to this piece of code being problematic:
repeat {
                        if let blockExistsIndex = blocks.firstIndex(where: { $0.col == missing.col + 1 && $0.row == missing.row && $0.block != nil }) {
                            if let missingBlockIndex = blocks.firstIndex(where: { $0.id == missing.id }) {
                                guard let existingBlock = blocks[blockExistsIndex].block else { return }
                                let move = SKAction.move(to: blocks[missingBlockIndex].position, duration: 0.25)
                                existingBlock.run(move)
                                blocks[missingBlockIndex].block = blocks[blockExistsIndex].block
                                blocks[blockExistsIndex].block = nil
                            }
                        }
                    } while blocks.first(where: { $0.col == missing.col + 1 && $0.row == missing.row })?.block != nil

Seems when I comment out the outer repeat loop and the section for adding new blocks to fill in, leaving just the code above, when it moves the blocks down it seems to occasionally leave some "holes", instead of moving them all down.  I think that might be part of why this isn't working...?

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Where did the Unity Market Insights button go in Unity Dashboard?
I'm currently trying to find the Market Insights button in the Unity Dashboard. I'm following this youtube video by Code Monkey called "Make your Game Better with Unity Analytics!" where he shows how to connect a Unity project with the Unity dashboard.
https://www.youtube.com/watch?v=3jDD-E1OUkc&ab_channel=CodeMonkey (at 13:54)
Now, maybe it's because the video 2 years out of date, but I can't seem to find the market insights button. Is it still in the Unity dashboard? Has it been replaced with a new name? Or has it been removed entirely? If someone knows how to get there, please tell me how! Thank you!

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Rendering texture as pure white / filled with color with SDL2
I added a glow or shine effect to make character flash with one color for a short period of time, it looks like this.
The code in draw function:
auto spr = m_currentAnimation->getSprite();
bool shining = m_shineLockedTimer.isActive() || m_shineAlphaTimer.isActive();

renderer_.renderTexture(spr, texPos.x + xoffset, texPos.y, camera_, flip);
if (shining)
    {
        float alpha = 1 - m_shineAlphaTimer.getProgressNormalized();

        auto pw = renderer_.createTexture(m_currentAnimation->getSize());
        renderer_.setRenderTarget(pw);
        renderer_.fillRenderer({255, 255, 255, 0});

        auto blendmode = SDL_ComposeCustomBlendMode(SDL_BLENDFACTOR_ONE, SDL_BLENDFACTOR_ONE, SDL_BLENDOPERATION_MAXIMUM, SDL_BLENDFACTOR_ONE, SDL_BLENDFACTOR_ZERO, SDL_BLENDOPERATION_ADD);
        SDL_SetTextureBlendMode(spr, blendmode);
        renderer_.renderTexture(spr, 0, 0);
        SDL_SetTextureBlendMode(spr, SDL_BLENDMODE_BLEND);
        SDL_SetTextureBlendMode(pw, SDL_BLENDMODE_BLEND);
        SDL_SetTextureColorMod(pw, m_colorShine.r, m_colorShine.g, m_colorShine.b);
        SDL_SetTextureAlphaMod(pw, alpha * m_colorShine.a);

        renderer_.setRenderTarget(nullptr);
        renderer_.renderTexture(pw, texPos.x + xoffset, texPos.y, camera_, flip);
        SDL_DestroyTexture(pw);
    }

On each frame during the flash effect, I create a new texture of the same size as the character's current sprite (which can change during the effect), fill it with white, create a blendmode that basically copies the alpha channel, render the sprite to this texture to get its pure white copy and render this white version with proper colormod and alphamod to the renderer. Here's full .cpp file with this draw function. I have 2 problems with this code:

It seems to be overly complex for a code that runs on each frame, since it recreates and destroyes texture and does a lot of rendering. One way to optimize it I've thought of is to create pure white versions of the textures along with the animations and use them, but this will double memory consumption by textures. Is it a good solution or are there better ones?

It causes this artifact when the effect is applied to both players. It specifically happens with the first renderer character, even if the rendering order changes during the animations. The effect remains on lower framerate. The character use the same SDL_Textures, but my code returns blend mode and render target to normal and the artifact remains even if the characters use different sprites and does not depend on alpha value. For some reason, it has a clear vertical border at some points of the screen, but only for the player with artifact. What could be the reason for it?

UPD. It seems that the reason for this bug was that I destroyed texture before SDL_RenderPresent call


text:
Game character in the browser game appears on Android, but not on iOS
I have a problem with rendering the game on mobile platforms (the game is written on the Impact.js), the problem is only with the iOS actually, the screenshot below shows that the characters are rendered on Android, but not on the iOS
Android:
Example
iOS: Example
As you can see the minimap also works (top left corner) and shows where the players are, but on iOS we can't see the players.
Code:
main.js
...
const rawResponse3 = await fetch('/getcharacterimage?' + character)
let player1Image = await rawResponse3.blob().catch(err => console.log(err))
const rawResponse4 = await fetch('/getcharacterimage?' + rivalCharacter)
let player2Image = await rawResponse4.blob().catch(err => console.log(err))

let imageCharacterUrl = window.URL ? window.URL.createObjectURL(player1Image): window.webkitURL.createObjectURL(player1Image);
let imageCharacter = new Image();

let imageRivalCharacterUrl = window.URL ? window.URL.createObjectURL(player2Image) : window.webkitURL.createObjectURL(player2Image);
let imageRivalCharacter = new Image();

let isImageCharacterLoaded = false;
let isImageRivalCharacterLoaded = false;

function checkBothImagesLoaded() {
  if (isImageCharacterLoaded && isImageRivalCharacterLoaded) {
    let MyGame = ig.Game.extend({
    ...
      init: function() {
        ...
        this.spawnPlayer();
        ...
      },
      spawnPlayer: function() {
        var spawnPos = this.getRandomSpawnPos();
        this.player = this.spawnEntity(EntityPlayer, spawnPos.x, spawnPos.y, {mapID: MapID, image: imageCharacter.src})
      },
      spawnRemotePlayer: function(user, x, y) {
        this.remotePlayers[user.userId] =
          this.spawnEntity(EntityRemotePlayer, x, y, {image: imageRivalCharacter.src});
        return this.remotePlayers[user.userId];
      },
    ...
    })
    ...
  }
)
imageCharacter.onload = function() {
  isImageCharacterLoaded = true;
  checkBothImagesLoaded();
};

imageRivalCharacter.onload = function() {
  isImageRivalCharacterLoaded = true;
  checkBothImagesLoaded();
};

imageCharacter.src = imageCharacterUrl;
imageRivalCharacter.src = imageRivalCharacterUrl;

player.js
...

EntityPlayer = ig.Entity.extend({
...
    init: async function(x, y, settings) {
      ...
      this.animSheet = new ig.AnimationSheet(settings.image, 152, 152);
      ...
    }

...
})


text:
Unable to load texture from temporary directory
I'm developing a game in Ursina. Since my old question did not get any answers, I decided to extract the zip file to a temporary directory and read the assets from there, but not everything runs well.
Part of the code:
sc = 25
with tempfile.TemporaryDirectory() as tempdir:
    print(tempdir)

    zf = zipfile.ZipFile("Game_Data")
    zf.extractall(tempdir)
    zf.close()

    print(os.listdir(tempdir))

    log("Creating scene", gt(time.time())) # logs to game.log file, log() and gt() definitions are not shown because they are irrelevant here.

    t = Entity(model=load_model(tempdir+"\\Terrain.obj"),texture=tempdir+"\\Grass.jpg",collider="mesh")
    t.texture.filtering = "mipmap"
    s = Entity(model="sphere", double_sided=True, texture=tempdir+"\\Skybox.png", scale=10000*sc)

When I run the game, I get the error:
C:\Users\x\Desktop\Game>game.py
package_folder: C:\Users\x\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina
asset_folder: C:\Users\x\Desktop\Game
:prc(warning): Invalid integer value for ConfigVariable win-size: 819.2000122070312
:prc(warning): Invalid integer value for ConfigVariable win-size: 1024.0
Known pipe types:
  wglGraphicsPipe
(3 aux display modules not yet loaded.)
:prc(warning): changing default value for ConfigVariable paste-emit-keystrokes from '1' to '0'.
1.0
:pnmimage:png(warning): iCCP: known incorrect sRGB profile
C:\Users\x\AppData\Local\Temp\tmpt8l3bk9w
['Grass.jpg', 'Skybox.png', 'Terrain.mtl', 'Terrain.obj']
warning: missing texture: 'C:\Users\x\AppData\Local\Temp\tmpt8l3bk9w\Grass.jpg'
Traceback (most recent call last):
  File "C:\Users\x\Desktop\Game\Game.py", line 90, in <module>
    t.texture.filtering = "mipmap"
    ^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'filtering'

C:\Users\x\Desktop\Game>

It seems like Terrain.obj is loaded successfully (no error), but Grass.jpg results in None, altough all the required assets are in the zip file Game_Data (no file extension because the end user should not know it's actually a zip). Why?

security through obscurity is not really that much helpful and even less if it is a zip file (which would be one of the first things a person who actually tries to use when they decide to try to open/ parse the game data). And how do you know that Terrain.obj is loaded correctly? You got the error on gras when you tried to access it in the next line. Not when you tried to load it


text:
Can Nakama-cpp be used with Godot?
Can "Nakama C/C++ Client SDK" be used with "Godot 4 using C++ GDExtension API" ?

Nakama C++ on Github
Godot C++ on Github

If yes, what are the procedures for using these together ?

Is there a reason you're not using Nakama Godot SDK? https://github.com/heroiclabs/nakama-godot/releases/tag/v3.3.1


text:
Align Cubemap OR Texture2D moon with Unity light rotation?
I am trying to make a custom skybox shader in Unity Shadergraph. I am having difficulty implementing the solutions find here and here.
The solutions themselves are fantastic and work as advertised; however, being new to Shadergraph, I am at a loss for how to align them with the rotation of a moon light object in my scene as opposed to the rotation of the skybox itself.
My shader currently draws the sun by getting the arccosine of the dot product between the sun's direction and the normalized view direction:

This method does not (seemingly) integrate with the above-linked methods, as this method outputs a single value and the those methods require a Vector3 to split. If I plug the arccosine setup into the cubemap solution, I get a textureless moon (presumably because of the lack of Vector3 information):

If I go directly from the normalized view direction node to the split node, the cubemap moon shows up beautifully, but only at the horizon (for lack of direction information).
I've tried using Rotate About Axis nodes, which does change the position of the textured cubemap moon in the sky, but not as desired.

At this point I think I just have a fundamental lack of understanding and so my efforts to throw something at the wall that sticks are less than fruitful. Any guidance would be much appreciated!
PS. I hope it's okay to make a new post on this. I'm new to Stack Exchange and I don't have enough reputation to simply ask the clarifying question on the original post(s).


text:
Unreal 5.2 - foliage texture missing in build
I'm working on a demo in Unreal 5.2 and I would like to share the build. I noticed that when I cook the build, the foliage is missing. In Project settings --> Packaging, I made sure to select Cook everything in the project content directory.
Image left: terrain in the build (without foliage); image right: terrain in the level viewport (with foliage).
Does anyone have suggestions on how to fix this? Thanks


text:
Creating a custom input device for a DTrack wand, using both the new and old input system in Unity 2021
I am currently trying to figure out how to bridge the gap between the old input system and the new one. There is a DTrack wand that I am using, that has a package. Right now, I have a game that is setup for VR, but I want to have a second version that uses this DTrack wand as a controller. I would preferably like it to use the same inputs as an Oculus controller, basically having similar functionality for basic things, like the trigger, and a few of the buttons as well. The main problem is that there is no way for me to actually be able to connect the Dtrack controller directly to the computer, so the only way that its inputs are being read is through the pre setup Dtrack Unity package. Has anyone had any experience with this before, or know how I can proceed? I've linked the package below as well, so that you can take a look.
https://github.com/ar-tracking/UnityDTrackPlugin


text:
Why doesn't my image and text appear?
This is my code in question:
def game():
     screen.blit(font.render('Choose now!',1,black),(WIDTH/2 - 450 , HEIGHT/2-110))

     pygame.time.set_timer(timer_event, 0)

     ding.play()

     if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_r:
                        screen.blit(rock_image,(WIDTH/2 - 450 , HEIGHT/2-110))

        if event.key == pygame.K_p:
                        screen.blit(paper_image,(WIDTH/2 - 450 , HEIGHT/2-110))

        if event.key == pygame.K_s:
                        screen.blit(scissors_image,(WIDTH/2 - 450 , HEIGHT/2-110))

     pygame.display.update()

There is a countdown in the game. The idea is that when the countdown ends, the text "choose now!" will appear and you can press either the buttons r, p or s to show an image. However, the text only appears momentarily and pressing the buttons doesn't result in anything either. I believe it may be due to my placement of pygame.display.update() but I don't know how to put it in correctly. I've tried placing it under every image upload but it hasn't worked. If anyone wants, this is my entire code:
import pygame
import os
from pygame import mixer
FPS = 60
pygame.mixer.init()
WIDTH, HEIGHT = 1000,900
pygame.font.init()
ding=pygame.mixer.Sound(os.path.join("scissors paper stone folder",'decidemp3-14575.mp3'))
screen = pygame.display.set_mode((WIDTH,HEIGHT))
white = [255, 255, 255]
black= [0,0,0]
scissors_image = pygame.transform.scale(pygame.image.load("scissors paper stone folder/scissors-icon-for-web-presentation-logo-infographic-haircut-tailor-hairdresser-haircut-free-vector.jpg"),(100,100))
rock_image = pygame.transform.scale(pygame.image.load('scissors paper stone folder/images.jpg'),(100,100))
paper_image = pygame.transform.scale(pygame.image.load('scissors paper stone folder/cHJpdmF0ZS9zdGF0aWMvaW1hZ2VzL3dlYnNpdGUvMjAyMi0xMi9weDExNDM1MzktaW1hZ2Utam9iMTQyN18xLnBuZw.webp'),(100,100))

font = pygame.font.SysFont('Comicsans',30)

counter = 3
text = font.render(str(counter), True, (0, 128, 0))
timer_interval = 1000

timer_event = pygame.USEREVENT + 1
pygame.time.set_timer(timer_event , timer_interval)

def game():
     screen.blit(font.render('Choose now!',1,black),(WIDTH/2 - 450 , HEIGHT/2-110))

     pygame.time.set_timer(timer_event, 0)

     ding.play()

     if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_r:
                        screen.blit(rock_image,(WIDTH/2 - 450 , HEIGHT/2-110))

        if event.key == pygame.K_p:
                        screen.blit(paper_image,(WIDTH/2 - 450 , HEIGHT/2-110))

        if event.key == pygame.K_s:
                        screen.blit(scissors_image,(WIDTH/2 - 450 , HEIGHT/2-110))

     pygame.display.update()

run = True
while run:
    screen.fill(white)
    keys_pressed = pygame.key.get_pressed()
    clock = pygame.time.Clock()
    clock.tick(FPS)
    for event in pygame.event.get():
     if event.type == pygame.QUIT:
                run = False
                break

     elif event.type == timer_event:
            counter -= 1
            text = font.render(str(counter), True, (0, 128, 0))
            if counter == 0:
                game()

    text_rect = text.get_rect(center = screen.get_rect().center)
    screen.blit(text, text_rect)
    screen.blit(font.render('Hello everyone',1,black),(WIDTH/2 - 450 , HEIGHT/2-290))
    screen.blit(font.render('How about a game of scissors, paper, stone?',1,black),(WIDTH/2 - 450 , HEIGHT/2-250))
    screen.blit(font.render('S button for scissors, p for paper, r(rock) for stone',1,black),(WIDTH/2 - 450 , HEIGHT/2-210))
    screen.blit(font.render('press either of the three once the countdown stops!',1,black),(WIDTH/2 - 450 , HEIGHT/2-160))

    pygame.display.update()


text:
Obstacle avoidance via steering behaviour when near gaps
I'm trying to implement RTS-like character control on C++/SDL2 for a character with a rectangular hitbox. I have a path-finding algorithm ready and I want to implement obstacle avoidance steering behaviour. My current implementation uses the distances from the corners of colliders to the center of the character's collider and calculates the vector sum, here's the code:
//SteeringHandler.h
#ifndef STEERING_HANDLER_H_
#define STEERING_HANDLER_H_

#include "Vector2.h"
#include <vector>
#include <array>

class SteeringHandler
{
public:
    SteeringHandler(float colliderPointRangeLimit_);
    void reset(const Vector2<float> &pos_);
    void addColliderPoint(const Vector2<float> point_);
    Vector2<float> getDirection();

private:
    Vector2<float> m_ownPos;
    float m_colliderPointRangeLimit;
    Vector2<float> m_steeringDir;

};

#endif

//SteeringHandler.cpp
#include "SteeringHandler.h"

SteeringHandler::SteeringHandler(float colliderPointRangeLimit_) :
    m_colliderPointRangeLimit(colliderPointRangeLimit_)
{
}

void SteeringHandler::reset(const Vector2<float> &pos_)
{
    m_ownPos = pos_;
    m_steeringDir = {0, 0};
}

void SteeringHandler::addColliderPoint(const Vector2<float> point_)
{
    auto dirToSelf = m_ownPos - point_;
    auto len = dirToSelf.getLen();
    if (len > m_colliderPointRangeLimit)
        return;

    auto value = m_colliderPointRangeLimit - len;
    m_steeringDir += dirToSelf.normalised() * value;
}

Vector2<float> SteeringHandler::getDirection()
{
    return m_steeringDir;
}

However, it causes weird behaviour while moving through or near gaps:

The blue rectangles are the points of the path, the blue line is the vector returned by SteeringHandler.
If I increase the m_colliderPointRangeLimit value or multiply the returned "avoidance" vector, the character stops passing through the gap. How can I improve my algorithm and fix this issue?
EDIT: I've tried to implement something closer to context steering. I'm comparing the player's collider to the borders of static colliders - if the player is near the border, the vectors towards this border are considered as danger, and if the player is behind the border (for example, in the example above player was behind lower border), the vectors along the normal from this wall are considered as interest. But it's too hard-coded, it doesn't work well though the specific situations vary depending on m_colliderPointRangeLimit and valueMultiplier and it probably will work even worse when I add other units.
//SteeringHandler.h
#ifndef STEERING_HANDLER_H_
#define STEERING_HANDLER_H_

#include "Vector2.h"
#include <vector>
#include <array>

class SteeringHandler
{
public:
    SteeringHandler(float colliderPointRangeLimit_, const Collider &playerCollider_);
    void reset(const Vector2<float> &pos_);
    void addCollider(const Collider &collider_);
    void addDesiredDirection(const Vector2<float> dir_);
    Vector2<float> getDirection();

private:
    void addInterestDir(const Vector2<float> &v_);
    void addDangerDir(const Vector2<float> &v_);
    float dirToVerticalLine(const Vector2<float> &p1, const Vector2<float> &p2);
    float dirTohorizontalLine(const Vector2<float> &p1, const Vector2<float> &p2);

    Collider m_playerCollider;
    Vector2<float> m_ownPos;
    float m_colliderPointRangeLimit;

    std::array<Vector2<float>, 8> m_steerDirs = {
        directions::Up(),
        directions::UpRight(),
        directions::Right(),
        directions::DownRight(),
        directions::Down(),
        directions::DownLeft(),
        directions::Left(),
        directions::UpLeft()
    };

    std::array<float, 8> m_interests;
    std::array<float, 8> m_dangers;
};

#endif

//SteeringHandler.cpp
#include "SteeringHandler.h"

SteeringHandler::SteeringHandler(float colliderPointRangeLimit_, const Collider &playerCollider_) :
    m_colliderPointRangeLimit(colliderPointRangeLimit_),
    m_playerCollider(playerCollider_)
{
}

void SteeringHandler::reset(const Vector2<float> &pos_)
{
    m_ownPos = pos_;
    m_interests.fill(0);
    m_dangers.fill(0);
}

void SteeringHandler::addCollider(const Collider &collider_)
{
    const float valueMultiplier = 0.7f;

    auto playerCollider = m_playerCollider + m_ownPos;

    Vector2<float> p1 = {collider_.x, collider_.y};
    Vector2<float> p2 = {collider_.x, collider_.y + collider_.h};
    float dirToLine = dirToVerticalLine(p1, p2);
    if (dirToLine < m_colliderPointRangeLimit)
    {
        float value = 1.0f - dirToLine / m_colliderPointRangeLimit;
        value *= valueMultiplier;

        if (playerCollider.x + playerCollider.w <= p1.x)
            addDangerDir({value * 0.95f, 0.0f});
        else
            addInterestDir({-value, 0.0f});
    }

    p1 = {collider_.x + collider_.w, collider_.y};
    p2 = {collider_.x + collider_.w, collider_.y + collider_.h};
    dirToLine = dirToVerticalLine(p1, p2);
    if (dirToLine < m_colliderPointRangeLimit)
    {
        float value = 1.0f - dirToLine / m_colliderPointRangeLimit;
        value *= valueMultiplier;

        if (playerCollider.x >= p1.x)
            addDangerDir({-value * 0.95f, 0.0f});
        else
            addInterestDir({value, 0.0f});
    }

    p1 = {collider_.x, collider_.y};
    p2 = {collider_.x + collider_.w, collider_.y};
    dirToLine = dirTohorizontalLine(p1, p2);
    if (dirToLine < m_colliderPointRangeLimit)
    {
        float value = 1.0f - dirToLine / m_colliderPointRangeLimit;
        value *= valueMultiplier;

        if (playerCollider.y + playerCollider.h <= p1.y)
            addDangerDir({0.0f, value * 0.95f});
        else
            addInterestDir({0.0f, -value});
    }

    p1 = {collider_.x, collider_.y + collider_.h};
    p2 = {collider_.x + collider_.w, collider_.y + collider_.h};
    dirToLine = dirTohorizontalLine(p1, p2);
    if (dirToLine < m_colliderPointRangeLimit)
    {
        float value = 1.0f - dirToLine / m_colliderPointRangeLimit;
        value *= valueMultiplier;

        if (playerCollider.y >= p1.y)
            addDangerDir({0.0f, -value * 0.95f});
        else
            addInterestDir({0.0f, value});
    }
}

void SteeringHandler::addDesiredDirection(const Vector2<float> dir_)
{
    addInterestDir(dir_);
}

Vector2<float> SteeringHandler::getDirection()
{
    Vector2<float> sum;
    for (int i = 0; i < m_steerDirs.size(); ++i)
    {
        auto added = m_interests[i] - m_dangers[i];
        if (added > 0)
            sum += m_steerDirs[i] * added;
    }

    return sum.normalised();
}

void SteeringHandler::addInterestDir(const Vector2<float> &v_)
{
    for (int i = 0; i < m_steerDirs.size(); ++i)
    {
        auto val = utils::projectionLen(v_, m_steerDirs[i]);
        if (val > m_interests[i])
            m_interests[i] = val;
    }
}

void SteeringHandler::addDangerDir(const Vector2<float> &v_)
{
    for (int i = 0; i < m_steerDirs.size(); ++i)
    {
        auto val = utils::projectionLen(v_, m_steerDirs[i]);
        if (val > m_dangers[i])
            m_dangers[i] = val;
    }
}

float SteeringHandler::dirToVerticalLine(const Vector2<float> &p1, const Vector2<float> &p2)
{
    auto playerCollider = m_playerCollider + m_ownPos;

    //if (playerCollider.y <= p1.y && playerCollider.y + playerCollider.h >= p2.y)
    if (playerCollider.y <= p1.y && playerCollider.y + playerCollider.h >= p1.y ||
        playerCollider.y <= p2.y && playerCollider.y + playerCollider.h >= p2.y ||
        playerCollider.y >= p1.y && playerCollider.y + playerCollider.h <= p2.y)
    {
        return std::min(abs(playerCollider.x - p1.x), abs(playerCollider.x + playerCollider.w - p1.x));
    }

    if (playerCollider.x + playerCollider.w < p1.x)
        return std::min((p1 - Vector2{playerCollider.x + playerCollider.w, playerCollider.y + playerCollider.h}).getLen(),
                        (p2 - Vector2{playerCollider.x + playerCollider.w, playerCollider.y}).getLen());
    else if (playerCollider.x > p1.x)
        return std::min((p1 - Vector2{playerCollider.x, playerCollider.y + playerCollider.h}).getLen(),
                        (p2 - Vector2{playerCollider.x, playerCollider.y}).getLen());
    else
        return std::min(abs(playerCollider.y + playerCollider.h - p1.y), abs(playerCollider.y - p2.y));

}

float SteeringHandler::dirTohorizontalLine(const Vector2<float> &p1, const Vector2<float> &p2)
{
    auto playerCollider = m_playerCollider + m_ownPos;

    if (playerCollider.x <= p1.x && playerCollider.x + playerCollider.w >= p1.x ||
        playerCollider.x <= p2.x && playerCollider.x + playerCollider.w >= p2.x ||
        playerCollider.x >= p1.x && playerCollider.x + playerCollider.w <= p2.x)
    {
        return std::min(abs(playerCollider.y - p1.y), abs(playerCollider.y + playerCollider.h - p1.y));
    }

    return std::min((p1 - Vector2{playerCollider.x + playerCollider.w, playerCollider.y + playerCollider.h / 2}).getLen(),
                    (p2 - Vector2{playerCollider.x, playerCollider.y + playerCollider.h / 2}).getLen());

    if (playerCollider.y + playerCollider.h < p1.y)
        return std::min((p1 - Vector2{playerCollider.x + playerCollider.w, playerCollider.y + playerCollider.h}).getLen(),
                        (p2 - Vector2{playerCollider.x, playerCollider.y + playerCollider.h}).getLen());
    else if (playerCollider.y > p1.y)
        return std::min((p1 - Vector2{playerCollider.x + playerCollider.w, playerCollider.y}).getLen(),
                        (p2 - Vector2{playerCollider.x, playerCollider.y}).getLen());
    else
        return std::min(abs(playerCollider.x + playerCollider.w - p1.x), abs(playerCollider.x - p2.x));
}

EDIT 2: I tried to use collider corners with a context steering system and it seems to work fine with the doubled weight of colliders for one character, but it causes characters to be struck in the wall when they get pushed away by, for example, other characters:

One question that I have at this point is: Do RTS games actually use colliders to prevent the characters from going through walls or do they only rely on pathfinding and steering algorithms?


text:
Emulating a trail effect
I'm trying to emulate a VFX Graph trail effect I have found, however I'm having an issue with achieving a similar effect. The reference I'm using seems to use some randomness for lifetime and for color, I'm not quite sure but it looks like it's sampling colors from a gradient, but also picks nearby colors in the gradient. The gradient seems to go from red (low opacity) to intense greens and blues (mixing) then to darker blues (low opacity) woth large gaps and single particles near the end of its lifetime. I'd appreciate some tips to make my effect more accurately represent the referece.
Specifically I'm looking at the floor trails either side of the projectile (but not the transparent particle strips).
What I've achieved so far: https://streamable.com/ub4ba9
My VFX Graph:

What I'd like to achieve: https://streamable.com/yvw6f4
Any advice is apprecaited.
(I'd upload the animated gifs to imgur but they are too large to upload, I'm not able to cut the size to 2MB without reducing the visibility of the whole effect.)


text:
How to send camera feed to Python script in Unity?
I have an image recognition code in Python and I need the input image to come from the Webcam in Unity. I've seen the Python Scripting package and the method of using a websocket and take the app as the server and the Python code as the client. And it needs to be seamless in an Android build, what method should I use and how do I get the image from Webcamtexture to Python? I'm using NumPy and the CV2 library, but I just need the data in Python in real-time.


text:
How can I bulk change sprites for my game object?
I'm using an asset pack that has 4 characters and I want the player to rotate between them whenever they respawn or in other words I wanna be able to bulk change an objects sprites. I've been learning about the component-based entity system architecture so that's what I'm using for my project I have a PlayerGraphics component and the idea for it is to store/handle all the assets related to the player so that when I add it to a player object the object will have those assets to work with.
The issue is once the object is created (even before it's created) I don't really have a way to set which assets I want to use.
    PlayerGraphics(Graphics& graphics, AssetManager& assetManager) : graphics(graphics), assetManager(assetManager) {
        CharacterAssets ninjaFrog;
        ninjaFrog.doubleJump = assetManager.loadAsset("Source/Assets/characters/Ninja Frog/Double Jump (32x32).png"); // 6 frames
        ninjaFrog.fall = assetManager.loadAsset("Source/Assets/characters/Ninja Frog/Fall (32x32).png"); // 1 frame
        ninjaFrog.hit = assetManager.loadAsset("Source/Assets/characters/Ninja Frog/Hit (32x32).png"); // 7 frames
        ninjaFrog.idle = assetManager.loadAsset("Source/Assets/characters/Ninja Frog/Idle (32x32).png"); // 11 frames
        ninjaFrog.jump = assetManager.loadAsset("Source/Assets/characters/Ninja Frog/Jump (32x32).png"); // 1 frames
        ninjaFrog.run = assetManager.loadAsset("Source/Assets/characters/Ninja Frog/Run (32x32).png"); // 12 frames
        ninjaFrog.wallJump = assetManager.loadAsset("Source/Assets/characters/Ninja Frog/Wall Jump (32x32).png"); // 5 frames
        // This chunk of code is repeated 3 more times for Mask Dude, Virtual Guy, and Pink Man

        sprite.addAnimation("idle", assetManager.getAsset(ninjaFrog.idle), 11, 32, 32, 50.0f);
        sprite.addAnimation("run", assetManager.getAsset(ninjaFrog.run), 12, 32, 32, 50.0f);
        sprite.addAnimation("fall", assetManager.getAsset(ninjaFrog.fall), 1, 32, 32, 50.0f);
        sprite.addAnimation("jump", assetManager.getAsset(ninjaFrog.jump), 1, 32, 32, 50.0f);
        sprite.addAnimation("doubleJump", assetManager.getAsset(ninjaFrog.doubleJump), 6, 32, 32, 50.0f);
        sprite.addAnimation("wallJump", assetManager.getAsset(ninjaFrog.wallJump), 5, 32, 32, 50.0f);
        sprite.addAnimation("hit", assetManager.getAsset(ninjaFrog.hit), 7, 32, 32, 50.0f);

        sprite.playAnimation("idle");
    }

P.S: I'm using SDL2


text:
Uncaught Syntax Error: Unexpected token .. Doc type is not valid json error
I've a Unity WebGL game.
When I try to load my game hosted on an Ubuntu 20.04 + apache 2.4 server, I get this error:

Uncaught Syntax Error:  Unexpected token .. Doc type is not valid json.

I've already this code in my web.config:
   <configuration>
        <system.webServer>
           <staticContent>
              <mimeMap fileExtension=".unityweb" mimeType ="TYPE/SUBTYPE" />
           </staticContent>
        </system.webServer>
     </configuration>

I don't know if this is your root issue, but the correct mime type is application/octet-stream, not TYPE/SUBTYPE


text:
Help on how to make a FNAF like camera system in game maker studio 2
I'm trying to program a Five Nights at Freddy's type camera system. I already made the flip-up animation by clicking the button at the bottom of the screen but I have problems making it go over to the camera system where the camera buttons will be. I watched a tutorial and they used xview and yview but I read a comment that it won't work on newer versions, instead it would be something like camera_set_view. Also the camera appears behind the middle-room and not over it like it should be. Also you should only be able to look at the camera when your facing the window. Or is there a completely different way to do this?
https://imgur.com/a/u1LXnBy


text:
Isometric camera lookat
I'm trying to make my isometric camera follow my player or lookat any other object
projection matrix is
XMMatrixOrthographicRH(_size * _aspectRatio, _size, _minZ, _maxZ);

view matrix is
void setIsometricEye(XMVECTOR_eye, float _x, float _z)
{
    XMMATRIX t  = XMMatrixTranslationFromVector(XMVectorNegate(_eye));
    XMMATRIX rx = XMMatrixRotationX(toRad(_x));
    XMMATRIX rz = XMMatrixRotationZ(toRad(_z));
    XMMATRIX view   = XMMatrixMultiply(t, XMMatrixMultiply(rz, rx));
}

eye calculation
void setIsometricTarget(XMVECTOR _target, float _x, float _z, float _distance)
{
XMMATRIX rx = XMMatrixRotationX(toRad(_x));
XMMATRIX rz = XMMatrixRotationZ(toRad(_z));
XMMATRIX r   = XMMatrixMultiply(rz, rx);
XMVECTOR d   = XMVector3TransformNormal(VecForward,r);
XMVECTOR eye = XMVectorSubtract(_target, d);
setIsometricEye(eye,_x,_z);
}

But the object/player don't stay in the center of the screen. What can I be missing here?
thanks


text:
Make pygame rectangle disappear when ball collides
So I'm doing a brick breaker game using Pygame. I want that everytime the ball hits a brick, that brick disappears (idk how)
Here's my code:
  bricks_list = [brick := Brick(6, 350, brick_width,brick_height,0),
brick := Brick(76, 350, brick_width,brick_height,0)] # A list of the bricks (rectangles)

#with a class (Brick) that I made

    for BRICK in bricks_list:
    brick_rect = pygame.Rect(BRICK.x, BRICK.y, brick.width, BRICK.height)
    if ball_rect.colliderect(brick_rect):
        yVel *= -1
        brick_break(bricks_list, BRICK) #function that I made (it does "bricks_list.remove(BRICK)")
    else:
        brick_rectangle = pygame.draw.rect(screen, LEVELS[BRICK.level], brick_rect)

If it can help, the problem is, when the ball collide with any of the bricks, that brick disappears ONLY when the ball is still colliding with it


text:
How is it possible that double buffering is enabled yet the back buffer doesn't exist?
I am working on an existing OpenGL application and am currently trying to figure out why I am getting a black screen. So I am wondering how its possible that double buffering is enabled and the back buffer is being drawn to but the back buffer also doesn't exist?
This is what gets printed in Maya: Double buffering present, Back buffer doesn't exist, buffer being drawn to is back.
                glBindFramebuffer(GL_READ_FRAMEBUFFER, m_frameBuffer); // Read frame buffer is bound to our FBO object
            glCheckError();

            // call with a zero passed in breaks the existing binding of a framebuffer object to target.
            glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
            glCheckError();

            GLboolean   doubleBuffer;
            glad_glGetBooleanv(GL_DOUBLEBUFFER, &doubleBuffer);
            if (doubleBuffer) {
                MGlobal::displayInfo("double buffering present");
            }
            else {
                MGlobal::displayInfo("double buffering not  present");
            }

            if (glIsBuffer(GL_BACK)) {
                MGlobal::displayInfo("Back buffer does exist");
            }
            else {
                MGlobal::displayInfo("Back buffer doesnt exist");
            }

            //since framebuffer object is unbound call to draw should draw to default
            //default holds back value for double buffered context

            glDrawBuffer(GL_BACK);
            glCheckError();

            GLint drawBuffer;
            glGetIntegerv(GL_DRAW_BUFFER, &drawBuffer);

            if (drawBuffer == GL_BACK) {
                MGlobal::displayInfo("buffer bieng drawn to is back");
            }

            //check to see if anything is actually drawn to the back buffer

            // glBlitFramebuffer, glBlitNamedFramebuffer — copy a block of pixels from one framebuffer object to another
            glBlitFramebuffer(/* src */ 0, 0, deviceWidth, deviceHeight, /* dst */ 0, 0, deviceWidth, deviceHeight, GL_COLOR_BUFFER_BIT, GL_NEAREST);

Interesting to note as well if I don't add this flag | PFD_DOUBLEBUFFER to the PIXELFORMATDESCRIPTOR then this update loop throws an error at glDraw(GL_BACK).


text:
Godot 3.5 NavigationAgent2D is_target_reached & is_navigation_finished always return False
I have this code in which i attached to a KinematicBody2D:
extends KinematicBody2D

onready var nav_agent := $NavAgent

func _physics_process(delta):

    var move_direction = position.direction_to(nav_agent.get_next_location())
    var velocity = move_direction * 25
    move_and_slide(velocity, Vector2.UP)

func move_to(coord:Vector2):
    nav_agent.set_target_location(coord)
    print(position,nav_agent.get_next_location())
    print(coord)
    print(_arrived_to_location())

func _arrived_to_location():
    return nav_agent.is_target_reached()

The problem is that even though i haven't sent any coordinate to the object the function  is_target_reached & is_navigation_finished always return False.
This is the output when move_to method is called:
(379, 208)(379, 208)
(533.471619, 115.5)
False

I see two issues:

Even after setting the target location to a new coordinate, get_next_location function return the same position of the object actually has.
is_target_reached & is_navigation_finished always return False.

Did i miss something to send/configure to the navigationAgent2D?

Maybe you already did this, but make sure you've either added a NavigationRegion2D to your scene and drawn a polygon for the navigable area, or set up a TileMap with navigation configured.


text:
LWJGL Shader not displaying anything to the screen
My basic shader program isn't displaying anything to the screen. Please Help!
Here's my code:
import org.hootengine.core.Game;
import org.hootengine.scene.Scene;
import org.lwjgl.BufferUtils;

import java.nio.FloatBuffer;
import java.nio.IntBuffer;

import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL30.glBindVertexArray;
import static org.lwjgl.opengl.GL30.glGenVertexArrays;

public class DemoScene extends Scene {

    /*
     * Variables
     */
    private String vertexShaderSrc = "#version 330 core\n" +
            "layout (location=0) in vec3 aPos;\n" +
            "layout (location=1) in vec4 aColor;\n" +
            "\n" +
            "out vec4 fColor;\n" +
            "\n" +
            "void main()\n" +
            "{\n" +
            "    fColor = aColor;\n" +
            "    gl_Position = vec4(aPos, 1.0);\n" +
            "}";
    private String fragmentShaderSrc = "#version 330 core\n" +
            "\n" +
            "in vec4 fColor;\n" +
            "\n" +
            "out vec4 color;\n" +
            "\n" +
            "void main()\n" +
            "{\n" +
            "    color = fColor;\n" +
            "}";
    private int vertexId, fragmentId, shaderProgram;

    private float[] vertexArray = {
            // position               // color
            0.5f, -0.5f, 0.0f,       1.0f, 0.0f, 0.0f, 1.0f, // Bottom right 0
            -0.5f,  0.5f, 0.0f,       0.0f, 1.0f, 0.0f, 1.0f, // Top left     1
            0.5f,  0.5f, 0.0f ,      1.0f, 0.0f, 1.0f, 1.0f, // Top right    2
            -0.5f, -0.5f, 0.0f,       1.0f, 1.0f, 0.0f, 1.0f, // Bottom left  3
    };

    //IMPORTANT: Must be in counter-clockwise order
    private int[] elementArray = {
            /*
                    x        x

                    x        x
             */
            2, 1, 0, // Top right triangle
            0, 1, 3 // bottom left triangle
    };

    private int vaoId, vboId, eboId;

    /*
     * Main Object
     */
    public DemoScene(Game game) {
        super(game, "DemoScene");
    }

    /*
     * Methods
     */
    public void init() {

        /*
         * Vertex
         */
        vertexId = glCreateShader(GL_VERTEX_SHADER);
        glShaderSource(vertexId, vertexShaderSrc);
        glCompileShader(vertexId);

        //Check for errors
        int success = glGetShaderi(vertexId, GL_COMPILE_STATUS);
        if (success == GL_FALSE) {
            int len = glGetShaderi(vertexId, GL_INFO_LOG_LENGTH);
            System.out.println("ERROR: 'defaultShader.glsl' - (vertex) compilation failed!");
            System.out.println(glGetShaderInfoLog(vertexId, len));
            assert false : "";
        }

        /*
         * Fragment
         */
        fragmentId = glCreateShader(GL_FRAGMENT_SHADER);
        // Pass the shader source to the GPU
        glShaderSource(fragmentId, fragmentShaderSrc);
        glCompileShader(fragmentId);

        // Check for errors in compilation
        success = glGetShaderi(fragmentId, GL_COMPILE_STATUS);
        if (success == GL_FALSE) {
            int len = glGetShaderi(fragmentId, GL_INFO_LOG_LENGTH);
            System.out.println("ERROR: 'defaultShader.glsl'\n\tFragment shader compilation failed.");
            System.out.println(glGetShaderInfoLog(fragmentId, len));
            assert false : "";
        }

        /*
         * Link shaders
         */
        shaderProgram = glCreateProgram();
        glAttachShader(shaderProgram, vertexId);
        glAttachShader(shaderProgram, fragmentId);
        glLinkProgram(shaderProgram);

        // Check for linking errors
        success = glGetProgrami(shaderProgram, GL_LINK_STATUS);
        if (success == GL_FALSE) {
            int len = glGetProgrami(shaderProgram, GL_INFO_LOG_LENGTH);
            System.out.println("ERROR: 'defaultShader.glsl'\n\tLinking of shaders failed.");
            System.out.println(glGetProgramInfoLog(shaderProgram, len));
            assert false : "";
        }

        // ============================================================
        // Generate VAO, VBO, and EBO buffer objects, and send to GPU
        // ============================================================
        vaoId = glGenVertexArrays();
        glBindVertexArray(vaoId);

        // Create a float buffer of vertices
        FloatBuffer vertexBuffer = BufferUtils.createFloatBuffer(vertexArray.length);
        vertexBuffer.put(vertexArray).flip();

        // Create VBO upload the vertex buffer
        vboId = glGenBuffers();
        glBindBuffer(GL_ARRAY_BUFFER, vboId);
        glBufferData(GL_ARRAY_BUFFER, vertexBuffer, GL_STATIC_DRAW);

        // Create the indices and upload
        IntBuffer elementBuffer = BufferUtils.createIntBuffer(elementArray.length);
        elementBuffer.put(elementArray).flip();

        eboId = glGenBuffers();
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, eboId);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementBuffer, GL_STATIC_DRAW);

        // Add the vertex attribute pointers
        int positionsSize = 3;
        int colorSize = 4;
        int floatSizeBytes = 4;
        int vertexSizeBytes = (positionsSize + colorSize) * floatSizeBytes;
        glVertexAttribPointer(0, positionsSize, GL_FLOAT, false, vertexSizeBytes, 0);
        glEnableVertexAttribArray(0);

        glVertexAttribPointer(1, colorSize, GL_FLOAT, false, vertexSizeBytes, positionsSize * floatSizeBytes);
        glEnableVertexAttribArray(1);

    }

    public void preload() {

    }

    public void create() {

    }

    //Update (looped)
    public void update(float delta) {

        System.out.println("" + (1.0f / delta) + "FPS");

        glUseProgram(shaderProgram);
        // Bind the VAO that we're using
        glBindVertexArray(vaoId);

        // Enable the vertex attribute pointers
        glEnableVertexAttribArray(0);
        glEnableVertexAttribArray(1);

        glDrawElements(GL_TRIANGLES, elementArray.length, GL_UNSIGNED_INT, 0);

        // Unbind everything
        glDisableVertexAttribArray(0);
        glDisableVertexAttribArray(1);

        glBindVertexArray(0);

        glUseProgram(0);

    }

}

Here's the window program as well:
package org.hootengine.display;

import org.hootengine.core.Game;
import org.hootengine.input.KeyListener;
import org.hootengine.input.MouseListener;
import org.hootengine.time.TimeManager;
import org.lwjgl.Version;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.opengl.GL;
import org.lwjgl.opengl.GLUtil;
import org.lwjgl.system.MemoryUtil;
import static org.lwjgl.glfw.Callbacks.glfwFreeCallbacks;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;

/**
 * @author Patrick Carroll
 */
public class Window {

    /*
     * Variables
     */

    /**
     * The game object.
     */
    private Game game;

    /**
     * The window instance.
     */
    public static Window instance = null;

    /**
     * The window saved to memory.
     */
    private long glfwWindow;

    /**
     * The width (in pixels) of the window.
     */
    private int width;

    /**
     * The height (in pixels) of the window.
     */
    private int height;

    /**
     * The title of the window.
     */
    private String title;

    /*
     * Main Objects
     */

    /**
     * Sets the properties of a new game window.
     */
    private Window(Game game) {

        this.game = game;

        width = game.getConfig().getWidth();
        height = game.getConfig().getHeight();
        title = game.getConfig().getTitle();

    }

    /*
     * Methods
     */

    /**
     * Initializes the window and starts the refresh loop.
     */
    public void run() {
        System.out.println("Window created using LWJGL version " + Version.getVersion() + "!");

        init();
        startLoop();

        //Free the memory
        glfwFreeCallbacks(glfwWindow);
        glfwDestroyWindow(glfwWindow);

        //Terminate GLFW and the free the error callback
        glfwTerminate();
        glfwSetErrorCallback(null).free();
    }

    /**
     * Creates a game window and sets the callbacks.
     */
    private void init() {

        GLFWErrorCallback.createPrint(System.err).set();

        if (!glfwInit()) {
            throw new IllegalStateException("Unable to initialize GLFW.");
        }

        glfwDefaultWindowHints();
        glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
        glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
        glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        //glfwWindowHint(GLFW_MAXIMIZED, GLFW_TRUE);

        //Create the window
        glfwWindow = glfwCreateWindow(width, height, title, MemoryUtil.NULL, MemoryUtil.NULL);
        if (glfwWindow == MemoryUtil.NULL) {
            throw new IllegalStateException("Failed to create the GLFW window.");
        }

        //Set mouse callbacks
        glfwSetCursorPosCallback(glfwWindow, MouseListener::mousePosCallback);
        glfwSetMouseButtonCallback(glfwWindow, MouseListener::mouseButtonCallback);
        glfwSetScrollCallback(glfwWindow, MouseListener::mouseScrollCallback);

        //Set key callbacks
        glfwSetKeyCallback(glfwWindow, KeyListener::keyCallback);

        //Make the OpenGL context current
        glfwMakeContextCurrent(glfwWindow);
        //Enable v-sync
        glfwSwapInterval(1);

        //Show window
        glfwShowWindow(glfwWindow);

        //IMPORTANT!
        GL.createCapabilities();
        GLUtil.setupDebugMessageCallback();

        if (game.getSceneManager().getCurrentGameScene() != null)
            game.getSceneManager().getCurrentGameScene().start();

    }

    /**
     * Start the window refresh loop.
     */
    public void startLoop() {

        float beginTime = TimeManager.getTime();
        float endTime;
        float delta = -1.0f;

        while (!glfwWindowShouldClose(glfwWindow)) {
            //Poll events
            glfwPollEvents();

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

            glfwSwapBuffers(glfwWindow);

            //Update the scenes
            if (delta >= 0)
                game.getSceneManager().update(delta);

            endTime = TimeManager.getTime();
            delta = endTime - beginTime;
            beginTime = endTime;

        }

    }

    /*
     * Getters & Setters
     */

    /**
     * @return The game window instance.
     */
    public static Window get(Game game) {

        if (Window.instance == null) {
            Window.instance = new Window(game);
        }

        return Window.instance;

    }

}
```


text:
Why are global constraints so ineffective?
There are two objects here, each with 3 constraint points.
I use formula:
$$
\lambda=(JM^{-1}J^{T})^{-1}(-JV-b)
$$
$$
\Delta V=M^{-1}J^{T}\lambda \
$$
I put the information of the three constraint points (normals, constraint point radius) into the formula to calculate.
But the result was not ideal. Instead of shortening the distance between the three constraint points, it became farther.
I don’t want to use iterative calculation. I have used iterative calculation. It needs to be iterated 10000+ times to get better results. This is too slow.
Is there any good solution?


text:
Export a Gameobject to USDZ in Unity for Android and iOS
I have tried using the usd sdk from Unity and it seems like there is no support for usdz export in runtime for iOS and Android in Unity. I was wondering:

If anyone is familiar with any other external Plugins to Achieve this?
If there is no directly available solution, how can I approach this? Can you give me some direction?

So far I tried the usd sdk from unity, looked into a few blog posts on how to do it natively in iOS , and found a way to do it on webXR using Needle Engine SDK in Unity. But no lead so far with iOS , and Android


text:
pygame.error: video system not initialized
I don't know what's going on when I try to run pygame this error occures everytime no matter how much changes I have made.
HERE'S THE CODE:
import pygame
import tine
import random

WIDTH, HEIGHT = 1000, 800
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Dodgers")

def main():
    run = True

    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                break

pygame.quit()

if __name__== "__main__":
    main()

How have you tried applying previous answers about this particular error message?


text:
Workflow for editing a 2D tiled level with some layers that are whole images?
Context
I'm making a 2.5D game from scratch using C/C++.
Issue/question:
I specifically want a way to edit my levels that lets me enter an image for each layer of the level, like hoodcraft.py in POSTAL.
Would what I'm looking for be a level editor where the floor, buildings, vfx, etc. are just images layered on top of each other while still having tilemaps for players, AI and other interactable objects?
I need some help setting up a workflow to produce such levels — are there existing tools I can use to do this (and if so, how do I do this in those tools), or standard terminology that will help me find suitable tools/techniques?

Even the good old rpg maker can export maps (tile map editor with multiple layers). For 2.5d just search for a tile editor, your favorite search engine will show a lot of results for that


text:
How can i translate this code into java?
My only problem translating the code from this question/answer is the Vector2 method. In the web i could only find this replacement (Vector2f). But i can not import it : can't resolve reference. Also i do not understand the use ofVelocity as is.  Can i just do it each for posx and posy?
ublic void update() {
    if (posy < 1920-radius) {
        Velocity += gravitation * TimeStep;
    }
    Velocity -= Vector(Math.pow(Luftwiderstandinnewton, remainingTime),
            (Math.pow(Luftwiderstandinnewton, remainingTime))
            * Velocity;
    //Position
            posy+= Velocity * TimeStep;

    if (posx < 0 +radius|| posx > 1080 -radius) {
        // We've hit a vertical (side) boundary
        if (posx < 0 +radius) {
            remainingTime = -posx / velocityy;
            posx = 0+radius;
        } else {
            remainingTime = (posx - 1080-radius) / velocityx;
            posx = 1080-radius;
        }

        // Apply friction
        Velocity -=((Math.pow(stein, remainingTime)+
                Math.pow(stein, remainingTime)))
                * Velocity;

        // Invert velocity
        velocityx = -velocityx;
        posx = posx + velocityx * remainingTime;
    }

    if (posy < 0 +radius || posy > 1920-radius) {
        // We've hit a horizontal boundary
        if (posy < 0 +radius) {
            remainingTime = -posy / velocityy;
            posy = 0 +radius;
        } else {
            remainingTime = (posy - 1920-radius) / velocityy;
            posy = 1920-radius;
        }

        // Remove excess gravity
        velocityy -= remainingTime * gravitation;

        // Apply friction
        Velocity -= ((Math.pow(gras, remainingTime) +
                Math.pow(gras, remainingTime)))
                * Velocity;

        // Invert velocity
        velocityy = -velocityy;

        // Re-add excess gravity
        float OldVelocityY = (float) velocityy;
        velocityy += remainingTime * gravitation;
        // If velocity changed sign again, clamp it to zero
        if (velocityy * OldVelocityY <= 0)
            velocityy = 0;

        posy = posy + velocityy * remainingTime;
    }
}

Ball Physics : Smoothing the final bounces as the ball comes to rest
org.newdawn.slick.geom.Vector2f

Any ideas?


text:
Resolve dependency between two installers in Zenject
Im trying to implemet dependency injection in my Unity project by using Zenject. I have two installers. The first one is Monoinstaller who is responsible for injection and creation of scene objects, such as transform parents in which objects will spawn:
        public class SceneInstaller : MonoInstaller
    {
        [SerializeField] private Transform _safeArea;
        [SerializeField] private Transform _mangersParent;
        public override void InstallBindings()
        {
        print("scene");
        Container.Bind<Transform>().FromInstance(_safeArea).AsCached().WithConcreteId("SafeArea").NonLazy();
        Container.Bind<Transform>().FromInstance(_mangersParent).AsCached().WithConcreteId("Managers Parent").NonLazy();
        Container.Bind<Transform>().FromNewComponentOnNewGameObject().AsCached().WithConcreteId("Field Parent").NonLazy();
        Container.Bind<Transform>().FromNewComponentOnNewGameObject().AsCached().WithConcreteId("Apple Parent").NonLazy();
    }
}

And the second one is ScriptableObjectInstaller that creates and injects the game field and object manager
   public class FieldManagerInstaller : ScriptableObjectInstaller
{
    [SerializeField] private ExpandFieldData _expandField;
    [Inject(Id = "Safe Area")] private RectTransform _safeArea;
    [SerializeField] private FieldManager _fieldManager;
    [Inject(Id = "Managers Parent")] private Transform _fieldManagerParent;
    public override void InstallBindings()
    {
        Debug.Log("field");
        var expandField = Container.InstantiatePrefabForComponent<ExpandFieldData>(_expandField, _safeArea);
        Container.Bind<ExpandFieldData>().FromInstance(expandField).AsSingle();
        var fieldManager = Container.InstantiatePrefabForComponent<FieldManager>(_fieldManager, _fieldManagerParent);
        Container.Bind<FieldManager>().FromInstance(fieldManager).AsSingle();
    }
}

The problem is that SOinstaller uses some variables from Monoinstaller e.g. _fieldManagersParent which is parent for every manager on scene. But as far as i understood SOInstallers initialize earlier then Monoinstallers. And when FieldManagerInstaller already started to install his bindings SceneInstaller still not working and Zenject resolver throws an exception:
ZenjectException: Unable to resolve 'RectTransform (ID: Safe Area)' while building object with type 'FieldManagerInstaller'. Object graph:
FieldManagerInstaller
ZenjectException: Unable to resolve 'Transform (ID: Field Parent)' while building object with type 'FieldManager'. Object graph:
FieldManage

Logs also confirm this. Does anybody knows how to execute installers in specified order? By the way is it good practice to create a new gameobject and inject it by using FromNewComponentOnNewGameObject or there is another better ways?


text:
How to synchronize pausing and unpausing game using Photon Unity Networking (PUN)
I need some help figuring out how to synch pausing and unpausing the game to other players.
I have a UI button where players can pause using the code I have posted below. Pausing works fine with all the players, however unpausing the game gives me a problem.  Only the player who pressed that unpause button successfully unfreezes while other players remain in the paused state.
[PunRPC]
void SetPause(float time) {
    Time.timeScale = time;
}

// this goes to UI button
public void PauseTime(float time) {
    PV.RPC("SetPause", RpcTarget.All, time);
}


text:
Casting out vision rays for 2D car in pyglet to return distance from objects?
I am working on a machine learning project that involves training a 2D car to drive around a top-down racing track. I'll be training neural networks using different algorithms and one essential form of data I need to give the model is vision input. I'm modeling the car and track in the python module Pyglet.
Looking at other similar projects it seems this would work best by casting out rays from multiple angles and calculating the distance of each ray from the nearest point. I'm also trying to optimise for performance because I need to cut down training time as much as possible.
I've already been able to convert the track png data into all kinds of forms, including a dictionary which has image pixel coordinates as keys and stores a 1 if the pixel is part of the track, and a zero if it is not. I also have made a list of all pixels which are the track.
Also, I've already run the math on which angles I need to project the lines out of, and I think I have the right math for the lines themselves. Below is code that accurately casts 8 rays, explained in the comments of the code. The issue is I don't know how to combine the data of the line co-ordinates, with the dictionaries and lists  containing the data of the track.
Any help would be greatly appreciated, if I am doing some other fundamental part of this process wrong any direction would also be appreciated. I've been stuck on this for weeks. I've attached images to help visually understand where I am thus far.
# presets stores the pre-calculated angle and length of each
# line in a tuple, totalling 8 tuples for 8 lines. Angles and
# length are calculated to reach the 4 corners of the car, and
# the midpoints of the four lines. The lines can then be
# lengthened by changing the leng variable.
presets = (
   (116.56505117707799 - player_angle, 21.242645786248),
   (180 - player_angle, 9.5),
   (243.43494882292202 - player_angle, 21.242645786248),
   (270 - player_angle, 19.0),
   (296.565051177078 - player_angle, 21.242645786248),
   (0 - player_angle, 9.5),
   (63.43494882292201 - player_angle, 21.242645786248),
   (90 - player_angle, 19.0),
)
leng = 0
lis = []
for i in presets:
    pos = (int(math.cos(math.radians(i[0])) * (i[1] + leng) + player_rect[0]),int(math.sin(math.radians(i[0])) * (i[1] + leng) + player_rect[1]))
# creates line by converting the angle preset to radians, using the cos of that
# value for x coordinate and the sin for the y coordinate, and mulitplies both by
# the preset length.

    lis.append((pos[0], pos[1], player_rect[0], player_rect[1]))

Here is the car with the lines projecting out from it

Here is the car with the entire track in frame aswell

This image shows running the program and setting leng to 10.

Dictionaries are not your friends here. Your queries are spatially coherent (if you query one pixel, you're likely to soon query the pixels beside it), but dictionaries randomize access patterns, thrashing your cache and making it harder for the CPU's prediction and prefetching mechanisms to stay ahead. Why not store a collection of straight line segments and circular arcs? You could build this track out of just 36 such primitives, which is far less data to query than thousands of pixels, and testing a ray against each one is just a tiny bit of math.


text:
How can I halt a check for intersections of sets in python when it discovers one member of the intersection?
How can I halt a check for intersections of sets in python when it discovers one member of the intersection? I want to do this so that when checking for collisions the moment an intersecting point is discovered, it will immediately halt the check and consider a collision.

How are you iterating over the sets?


text:
How do I add a Mesh to an AActor at runtime in c++ in Unreal Engine 5.3
For Unreal 5.0, 5.1 and 5.2 I used the following code to do this:
TCHAR* name = "someasset";

UStaticMesh * o = Cast<UStaticMesh>(StaticLoadObject(UStaticMesh::StaticClass(), NULL, name, name));
actor = munrealcontext->uworld->SpawnActor<AActor>();
meshcomponent = NewObject<UStaticMeshComponent>(actor);
meshcomponent->RegisterComponent();
actor->SetRootComponent(meshcomponent);
meshcomponent->SetStaticMesh(mesh);

Since UE 5.3, it crashes at meshcomponent->SetStaticMesh(mesh);
What has changed? What's wrong?
The Exception thrown is "Access violation reading location 0x0000000000000005."
callstack:
    UnrealEditor-Core.dll!00007ffc9ec8fccf()    Unknown
    UnrealEditor-CoreUObject.dll!00007ffca8e2442d() Unknown
    UnrealEditor-CoreUObject.dll!00007ffca8da1c8d() Unknown
    UnrealEditor-Core.dll!00007ffc9efc5180()    Unknown
    UnrealEditor-Engine.dll!00007ffbbc925321()  Unknown
>   GameLib.dll!MUnrealSpawn::Init(UStaticMesh * mesh) Line 56  C++
    GameLib.dll!MUnrealMesh::Init(UStaticMesh * mesh) Line 15   C++
    GameLib.dll!StaticLevel::VisInit() Line 69  C++
    GameLib.dll!SyncState::Init() Line 620  C++
    GameLib.dll!Application::OnlineProcess() Line 1213  C++
    GameLib.dll!Application::Process() Line 697 C++
    GameLib.dll!MApplicationRunner::Process() Line 221  C++
    GameLib.dll!GameLibRender() Line 162    C++
    UnrealEditor-Game-Win64-DebugGame.dll!AGameActor::Tick(float DeltaTime) Line 207    C++


text:
Decrease size of hitboxes for a sprite in PixelPAD
I need to make the hitboxes of spikes smaller, so that it's not impossible for the player to get through. How do I do that?

I'm browsing the documentation for PixelPAD, and not finding methods to change the hitbox of a sprite separate from the sprite's rendered width and height. Have you considered splitting your spikes into two objects, a small one that handles hits, and then the rest of the image on an object that does not trigger spike collision code?


text:
Ignoring global rotation in gyroscope controller
I'd really appreciate some advice from you guys. I am trying to process a gyroscope input and map it to my game, i.e. player tilts their device and the character on screen moves left and right.
Essentially, I have it working. The following two scenarios occur in my game, as desired. You can see that the player is standing still, facing one direction. When they yaw their device (blue rectangle) around its local y-axis (going from the top of the screen down towards gravity), I am able to correctly process the input and move the character on-screen. Great!

BUT! I have a problem. Let's consider Scenario 3 below:

Here, the player is technically not yawing their device. They are moving their physical body position in world space. You can see that whilst the device has moved 45° globally, it is still facing the player face-on. This should not be registered in the game and it should be ignored by the character. I am really struggling to achieve this.
Right now, I see no way of distinguishing the global rotation from the local rotation, and then ignoring it. The result is unpredictable and undesirable movement. Let's say if the player was sat in a rotating chair and turning their body slightly whilst playing, the game misinterprets this and turns the character. I need to prevent this from happening. Does anyone have any advice on how to achieve this?
Notes: I am using Unity 2020.3 and the standard UnityEngine.Input class (not the new Input Manager). I also have deliberately avoided showing code, because the code to get this far is extensive. I am using the Gyro exclusively so far and nothing from the accelerometer. I can show code if needed, but first I thought it might be better to just hear advice.

Comments have been moved to chat.


text:
Euro Truck Simulator Standard Telemetry Format
My son's enjoying Euro Truck Simulator 2 on a Windows PC. I've ben looking a the SDK to extend its functionality. I thought it would be useful to serve the telemetry and build a physical dashboard around it.
It seems several folk have already developed such servers, however the version my son prefers is by Stryder-IT and it allows him to create a "dashboard" on his tablet using their own app.
In reading through the documentation, it became clear to me that many console-based simulation games publish telemetry data, including Euro Truck Simulator 2. The Windows versions of these games don't tend to; they require this additional server shim, which presumably accesses the telemetry using a shared memory method, and republishes it by TCP/IP.
Specifically, my aim would be to connect to the server using a raspberry Pi, which would control several actual physical truck gauges which I have acquired.
I want to grab the telemetry data from the Stryder-IT program, but I can't see the protocol documented anywhere. Not even the IP port number. It strikes me that if this ability is built into some console games, then there must be some kind of standard.
Question is: where can it be found?
I don't even know if I'm correct in my assertion that there must be a standard: If there was, does it have a name? It would seem odd if it was some kind of closed, proprietary protocol.
I have noted that if I try to forward the ETS2 telemetry by UDP using the Stryder-IT server, the ETS2 game does not appear on the list. There is a note that if it's not on the list, it doesn't require forwarding of telemetry. This implies to me that it's already sending telemetry. Is this a sensible conclusion? How could I find out the protocol?
Thanks.


text:
Missing tiles when rendering an isometric Staggered tilemap in Unity
I'm trying to show tiles on an isometric staggered tilemap in Unity, but some tiles are missing. I think the problem might be with where I'm placing the tiles or some floating-point precision issues.
The Main Issue:
I read tiles from a JSON file and try to put them on a Unity Tilemap. But, some tiles just don't show up. I've double-checked my math and even tried some small adjustments, but I still have missing tiles.
Here's the code I'm using:
MapLoader.cs - Responsible for loading the map data from a file path
using System.IO;
using UnityEngine;

public static class MapLoader
{
    public static MapDataStructure.MapData LoadMapFromPath(string path)
    {
        if (!IsValidPath(path)) return null;
        return DeserializeMap(File.ReadAllText(path));
    }

    private static bool IsValidPath(string path)
    {
        if (File.Exists(path)) return true;
        Debug.LogError($"Cannot find or access map file at: {path}");
        return false;
    }

    private static MapDataStructure.MapData DeserializeMap(string jsonData)
    {
        return JsonUtility.FromJson<MapDataStructure.MapData>(jsonData);
    }
}

TilePlacer.cs - Contains logic for determining which tile to place and its world position.
using UnityEngine;
using UnityEngine.Tilemaps;

public class TilePlacer
{
    private readonly Tilemap _tilemap;
    private readonly Tile[] _tileAssets;

    public TilePlacer(Tilemap tilemap, Tile[] tileAssets)
    {
        _tilemap = tilemap;
        _tileAssets = tileAssets;
    }

    public void PlaceTileAtCoordinates(int[] tileData, int x, int y, MapDataStructure.MapData mapData)
    {
        int tileIndex = GetTileIndex(tileData, x, y, mapData);

        if (IsValidTileIndex(tileIndex))
        {
            PlaceTile(tileIndex, x, y, mapData);
        }
        else
        {
            Debug.LogWarning($"Invalid tile index {tileIndex} at position {y},{x}");
        }
    }

    private int GetTileIndex(int[] tileData, int x, int y, MapDataStructure.MapData mapData)
    {
        return tileData[y * mapData.width + x] - 1;
    }

    private bool IsValidTileIndex(int tileIndex)
    {
        return tileIndex >= 0 && tileIndex < _tileAssets.Length;
    }

    private void PlaceTile(int tileIndex, int x, int y, MapDataStructure.MapData mapData)
    {
        Vector3 tileWorldPosition = ComputeTileWorldPosition(x, y, mapData);
        Vector3Int cellPosition = _tilemap.WorldToCell(tileWorldPosition);
        _tilemap.SetTile(cellPosition, _tileAssets[tileIndex]);
    }

    private Vector3 ComputeTileWorldPosition(int x, int y, MapDataStructure.MapData mapData)
    {
        float worldX = x * mapData.tileWidth;
        float worldY = y * mapData.tileHeight / 2;

        // Adjust x for odd rows
        if ((y & 1) == 1)
        {
            worldX += mapData.tileWidth / 2;
        }

        return new Vector3(worldX, worldY, 0);
    }
}

TilemapRenderer.cs - Manages the process of rendering the tiles to the Tilemap.
using System.IO;
using UnityEngine;
using UnityEngine.Tilemaps;

public class TilemapRenderer : MonoBehaviour
{
    [SerializeField]
    private string mapFileName = "WorldMap.json";

    [SerializeField]
    private Tile[] tileAssets;

    private Tilemap tilemap;
    private TilePlacer tilePlacer;

    private const int DEFAULT_LAYER_INDEX = 0;

    private void Start()
    {
        tilemap = GetComponent<Tilemap>();
        tilePlacer = new TilePlacer(tilemap, tileAssets);
        LoadAndRenderMap();
    }

    private void LoadAndRenderMap()
    {
        string filePath = BuildFilePath();
        MapDataStructure.MapData mapData = MapLoader.LoadMapFromPath(filePath);

        if (mapData != null)
        {
            RenderTilesFromLayer(mapData, DEFAULT_LAYER_INDEX);
        }
        else
        {
            Debug.LogError("Failed to deserialize map data from the file.");
        }
    }

    private string BuildFilePath()
    {
        return Path.Combine(Application.streamingAssetsPath, mapFileName);
    }

    private void RenderTilesFromLayer(MapDataStructure.MapData mapData, int layerIndex)
    {
        if (mapData.layers == null || layerIndex >= mapData.layers.Length)
        {
            Debug.LogError("Invalid map layer.");
            return;
        }

        int[] tileData = mapData.layers[layerIndex].data;
        for (int y = 0; y < mapData.height; y++)
        {
            for (int x = 0; x < mapData.width; x++)
            {
                tilePlacer.PlaceTileAtCoordinates(tileData, x, y, mapData);
            }
        }
    }
}

Important Parts of the Code:
The ComputeTileWorldPosition function in TilePlacer.cs calculates the world position for a given tile based on its coordinates x and y. After calculating the world position, the function _tilemap.WorldToCell is used to convert this world position to a cell position.
Screenshots:
https://imgur.com/a/WVFLuF0
What I've Tried:
If I add a small offset (like 0.1) to where I place each tile, or if I change the grid's position to -0.5, it seems to fix it. But it feels like I'm just patching the problem instead of really fixing it.
Here's the adjusted ComputeTileWorldPosition function:
private Vector3 ComputeTileWorldPosition(int x, int y, MapDataStructure.MapData mapData)
    {
        float worldX = x * mapData.tileWidth;
        float worldY = y * mapData.tileHeight / 2;

        // Adjust x for odd rows
        if ((y & 1) == 1)
        {
            worldX += mapData.tileWidth / 2;
        }

        worldX += 0.1f;
        worldY += 0.1f;

        return new Vector3(worldX, worldY, 0);
    }

Has anyone had this problem before or see what I might be doing wrong? Any help would be great! Thanks!


text:
Camera.main.WorldToScreenPoint does not return correct position
I have a cube in the center of my camera view, when I call Camera.main.WorldToScreenPoint(transform.position) I expect to get the same result as if I called new Vector3(Screen.width / 2, Screen.height / 2, 0)). But its not even close, why?
Debug.Log("1: " + new Vector3(Screen.width / 2, Screen.height / 2, 0));
Debug.Log("2: " + Camera.main.WorldToScreenPoint(transform.position));

My first suspicion was this might be due to DPI scaling on a high-resolution display, but I've just tested this on a 4K monitor with scaling activated and I'm still getting a perfect match between the calculated value and the one returned by WorldToScreenPoint. Can you walk us through the steps to build a Minimal Complete Verifiable Example, starting from a new, empty project? Make sure the only object running this script is the one instance in front of the camera, and that it's running after any screen resizing due to e.g. the "Maximize on Play" setting.


text:
How do I change the motion reference in an animation state during runtime?

I tried this solution: https://discussions.unity.com/t/how-to-change-animation-clips-of-an-animator-state-at-runtime-is-there-a-way/183135/4
But this doesn't work if I try to use a different animation clip. I also want to reuse the same state for swapping different animation clips but this just changes animation clip and not the motion state.
Is there better solution?


text:
How to extract data about in-game events?
I recently started playing New World, and I thought I would like to create something like a "data collector".
It would report data like: during the session,

I fired X bullets,
type of bullets: Y,
price of bullets: z,

...but I can't find information about downloading "data" from the game without using an API.
My question is:
Is it possible to extract data from the game without using a dedicated API?

Have you looked into memory-scanning tools like CheatEngine? It's up to you to figure out where in memory to look, but any data the game uses will be there somewhere at some point.


text:
Change width/height of ellipse to always be circular, independent of viewing angle
I have the following shader graph attached to a quad that draws two circles at some position.

Naturally, when viewed at an angle, the circles appear to be ellipses.

I'd like to know how to adjust the width/height parameters of the ellipse nodes to always appear as circles, roughly like this:

(Note that the green sphere in this picture is still a bit smaller because it is further away, this is correct.)


text:
Convert legacy OpenGL script to a newer one
I have a script drawing 3D chart, three axes and a surface. Unfortunately, it was implemented using old OpenGL approach with Begin and End. This makes it extremely inefficient and it gets very slow if I try to use more than 100 points per dimension. I would like to rewrite it using array buffers, possibly shaders, but all tutorials are focusing on drawing primitives.
Question
I was looking for a tutorial explaining how to draw continuous surface and lines or grids using modern OpenGL. If there is no tutorial explaining this explicitly, could somebody provide a sample array or shader and explain how OpenGL maps vertices to a surface. Specifically, in the old script, it has an array of vertices and array of colors

Meanwhile, the new approach, e.g. demonstrated in Silk.NET framework shows continuous array buffers with 5 dimensions - X, Y, Z, U, V.

Explicit references to the code

Old: https://www.codeproject.com/Articles/5294893/A-Csharp-3D-Surface-Plot-Control
New: https://github.com/dotnet/Silk.NET/blob/main/examples/CSharp/OpenGL%20Tutorials/Tutorial%202.1%20-%20Co-ordinate%20Systems/Program.cs

Excerpt from the code
Old:
void DrawShadedSurface(VertexStore vertices)
{
  float axisScaling = 0.25f * _axisScaling;

  GL.Begin(PrimitiveType.Triangles);
  for (int index = 0; index < vertices.Vertices.Length; index += 5)
  {
    float midpointX = (axisScaling * (vertices.Vertices[index].X + vertices.Vertices[index + 1].X + vertices.Vertices[index + 2].X + vertices.Vertices[index + 3].X));
    float midpointY = (axisScaling * (vertices.Vertices[index].Y + vertices.Vertices[index + 1].Y + vertices.Vertices[index + 2].Y + vertices.Vertices[index + 3].Y));
    float midpointZ = (axisScaling * (vertices.Vertices[index].Z + vertices.Vertices[index + 1].Z + vertices.Vertices[index + 2].Z + vertices.Vertices[index + 3].Z));

    float midpointR = 0.25f * (vertices.Vertices[index].Colour.R + vertices.Vertices[index + 1].Colour.R + vertices.Vertices[index + 2].Colour.R + vertices.Vertices[index + 3].Colour.R);
    float midpointG = 0.25f * (vertices.Vertices[index].Colour.G + vertices.Vertices[index + 1].Colour.G + vertices.Vertices[index + 2].Colour.G + vertices.Vertices[index + 3].Colour.G);
    float midpointB = 0.25f * (vertices.Vertices[index].Colour.B + vertices.Vertices[index + 1].Colour.B + vertices.Vertices[index + 2].Colour.B + vertices.Vertices[index + 3].Colour.B);

    for (int offset = 0; offset < 4; ++offset)
    {
      int indexStart = index + offset;

      GL.Color4(midpointR, midpointG, midpointB, 1f);
      GL.Vertex3(midpointX, midpointY, midpointZ * ZScale);
    }
  }

  GL.End();
}

New
private static IWindow window;
private static GL Gl;

private const int Width = 800;
private const int Height = 700;

private static BufferObject<float> Vbo;
private static BufferObject<uint> Ebo;
private static VertexArrayObject<float, uint> Vao;
private static Texture Texture;
private static Shader Shader;

//Setup the camera's location, and relative up and right directions
private static Vector3 CameraPosition = new Vector3(0.0f, 0.0f, 3.0f);
private static Vector3 CameraTarget = Vector3.Zero;
private static Vector3 CameraDirection = Vector3.Normalize(CameraPosition - CameraTarget);
private static Vector3 CameraRight = Vector3.Normalize(Vector3.Cross(Vector3.UnitY, CameraDirection));
private static Vector3 CameraUp = Vector3.Cross(CameraDirection, CameraRight);

private static readonly float[] Vertices =
{
  //X    Y      Z     U   V
  -0.5f, -0.5f, -0.5f,  0.0f, 0.0f,
   0.5f, -0.5f, -0.5f,  1.0f, 0.0f,
   0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
   0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
  -0.5f,  0.5f, -0.5f,  0.0f, 1.0f,
  -0.5f, -0.5f, -0.5f,  0.0f, 0.0f,

  -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
   0.5f, -0.5f,  0.5f,  1.0f, 0.0f,
   0.5f,  0.5f,  0.5f,  1.0f, 1.0f,
   0.5f,  0.5f,  0.5f,  1.0f, 1.0f,
  -0.5f,  0.5f,  0.5f,  0.0f, 1.0f,
  -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,

  -0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
  -0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
  -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
  -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
  -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
  -0.5f,  0.5f,  0.5f,  1.0f, 0.0f,

   0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
   0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
   0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
   0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
   0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
   0.5f,  0.5f,  0.5f,  1.0f, 0.0f,

  -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
   0.5f, -0.5f, -0.5f,  1.0f, 1.0f,
   0.5f, -0.5f,  0.5f,  1.0f, 0.0f,
   0.5f, -0.5f,  0.5f,  1.0f, 0.0f,
  -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
  -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,

  -0.5f,  0.5f, -0.5f,  0.0f, 1.0f,
   0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
   0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
   0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
  -0.5f,  0.5f,  0.5f,  0.0f, 0.0f,
  -0.5f,  0.5f, -0.5f,  0.0f, 1.0f
};

private static readonly uint[] Indices =
{
  0, 1, 3,
  1, 2, 3
};

private static void OnLoad()
{
  Gl = GL.GetApi(window);

  Ebo = new BufferObject<uint>(Gl, Indices, BufferTargetARB.ElementArrayBuffer);
  Vbo = new BufferObject<float>(Gl, Vertices, BufferTargetARB.ArrayBuffer);
  Vao = new VertexArrayObject<float, uint>(Gl, Vbo, Ebo);

  Vao.VertexAttributePointer(0, 3, VertexAttribPointerType.Float, 5, 0);
  Vao.VertexAttributePointer(1, 2, VertexAttribPointerType.Float, 5, 3);

  Shader = new Shader(Gl, "shader.vert", "shader.frag");
}

private static unsafe void OnRender(double obj)
{
  Gl.Enable(EnableCap.DepthTest);
  Gl.Clear((uint) (ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit));

  Vao.Bind();
  Shader.Use();
  Shader.SetUniform("uTexture0", 0);

  //Use elapsed time to convert to radians to allow our cube to rotate over time
  var difference = (float) (window.Time * 100);

  var model = Matrix4x4.CreateRotationY(MathHelper.DegreesToRadians(difference)) * Matrix4x4.CreateRotationX(MathHelper.DegreesToRadians(difference));
  var view = Matrix4x4.CreateLookAt(CameraPosition, CameraTarget, CameraUp);
  var projection = Matrix4x4.CreatePerspectiveFieldOfView(MathHelper.DegreesToRadians(45.0f), Width / Height, 0.1f, 100.0f);

  Shader.SetUniform("uModel", model);
  Shader.SetUniform("uView", view);
  Shader.SetUniform("uProjection", projection);

  //We're drawing with just vertices and no indicies, and it takes 36 verticies to have a six-sided textured cube
  Gl.DrawArrays(PrimitiveType.Triangles, 0, 36);
}

Shader.frag
#version 330 core
in vec2 fUv;

uniform sampler2D uTexture0;

out vec4 FragColor;

void main()
{
    FragColor = texture(uTexture0, fUv);
}

Shader.vert
#version 330 core
layout (location = 0) in vec3 vPos;
layout (location = 1) in vec2 vUv;

uniform mat4 uModel;
uniform mat4 uView;
uniform mat4 uProjection;

out vec2 fUv;

void main()
{
    //Multiplying our uniform with the vertex position, the multiplication order here does matter.
    gl_Position = uProjection * uView * uModel * vec4(vPos, 1.0);
    fUv = vUv;
}


text:
Raycast suspension simulation rebounds car on landing
I'm expecting the car to land and engage the suspension to dampen the landing. The code I'm using currently has this effect:

# vehicle.gd
extends RigidBody3D

# Suspension variables
@export var suspension_rest_length: float = 0.5
@export var suspension_max_length: float = 1.0
@export var suspension_stiffness: float = 500.0
@export var dampening_sensitivity: float = 450.0
@export var dampening_max: float = 30.0

# Suspension Raycasts
@onready var fr: RayCast3D = $FR
@onready var fl: RayCast3D = $FL
@onready var rr: RayCast3D = $RR
@onready var rl: RayCast3D = $RL

# Wheel nodes
@onready var fr_wheel: Marker3D = $FR/Wheel
@onready var fl_wheel: Marker3D = $FL/Wheel
@onready var rr_wheel: Marker3D = $RR/Wheel
@onready var rl_wheel: Marker3D = $RL/Wheel

func _physics_process(delta):
    if fr.is_colliding():
        # Get distance to ground
        var dist = fr.get_collision_point().distance_to(fr.global_transform.origin)

        # Get dampening, clamp between 0 and max dampening
        var dampening = clamp(fr_wheel.get_velocity().length() * dampening_sensitivity, 0, dampening_max)

        # At location of raycast, apply suspension forces
        self.apply_force(Vector3.UP * (suspension_stiffness * (dist - suspension_rest_length) + dampening), fr.global_transform.basis.y)

        # Set location of wheel to raycast collision point
        fr_wheel.global_transform.origin = fr.get_collision_point()

    if fl.is_colliding():
        var dist = fl.get_collision_point().distance_to(fl.global_transform.origin)
        var dampening = clamp(fl_wheel.get_velocity().length() * dampening_sensitivity, 0, dampening_max)
        self.apply_force(Vector3.UP * (suspension_stiffness * (dist - suspension_rest_length) + dampening), fl.global_transform.basis.y)
        fl_wheel.global_transform.origin = fl.get_collision_point()

    if rr.is_colliding():
        var dist = rr.get_collision_point().distance_to(rr.global_transform.origin)
        var dampening = clamp(rr_wheel.get_velocity().length() * dampening_sensitivity, 0, dampening_max)
        self.apply_force(Vector3.UP * (suspension_stiffness * (dist - suspension_rest_length) + dampening), rr.global_transform.basis.y)
        rr_wheel.global_transform.origin = rr.get_collision_point()

    if rl.is_colliding():
        var dist = rl.get_collision_point().distance_to(rl.global_transform.origin)
        var dampening = clamp(rl_wheel.get_velocity().length() * dampening_sensitivity, 0, dampening_max)
        self.apply_force(Vector3.UP * (suspension_stiffness * (dist - suspension_rest_length) + dampening), rl.global_transform.basis.y)
        rl_wheel.global_transform.origin = rl.get_collision_point()

Three issues:

suspension_stiffness is 500 which seems like a very large massive force to apply. (Maybe the car is so heavy that this level is necessary?)
Assuming your RayCast3D are casting below the wheel's neutral contact point, checking fl.is_colliding() means when the wheels
are on the ground, they are applying the upward force. So the car
will never want to rest on the ground.
An upward "dampening" force is applied whenever the wheels are moving (in any direction).

Adjust your RayCast3D so they end their cast just above the lowest acceptable position for the wheel.
Step through your code and see what kinds of force values you're getting. Use a local variable so you can easily see the force strength:
var force_magnitude = suspension_stiffness * (dist - suspension_rest_length) + dampening
self.apply_force(Vector3.UP * force_magnitude, fl.global_transform.basis.y)

Try removing the damping component of the force so it can sometimes be zero. You may need to omit the call to apply_force if the total force is zero.
Try using a CSGSphere3D and changing its colour to indicate different states in your code to make it easier to see what's going on (or use the godot_debug_draw_3d plugin). You can also draw debug text and record your screen so you can scrub back and forth to see what's happening.


text:
Change colors after drawing lines in Pangolin using OpenGL
I am drawing a bunch of lines using pangolin library. Each line has 4 vertex pairs. My goal is to give each line a different colour. Here is the code snippet I am using. In each render loop I do the following -
    Eigen::Matrix<float, 4, 1> color[4] = {{255,0,0,255}, {0,255,0,255}, {0,0,255,255}, {255,255,255,255}};
    int index = 0;
    for (const auto pair : vertexPairs) {
        glColor4ubv(color[index++].data());
        auto point1 = pair.first;
        auto point2 = pair.second;
        pangolin::glDrawLine(static_cast<float>(point1(0)),
                             static_cast<float>(point1(1)),
                             static_cast<float>(point1(2)),
                             static_cast<float>(point2(0)),
                             static_cast<float>(point2(1)),
                             static_cast<float>(point2(2)));
    }

For each line, I update the stack using glColor4ubv() with a different colour. But I dont see different colours. Is this correct way to update the colours for each line.


text:
How do you do vehicle rendezvous?
If you want to have a missile track and hit a target, Proportional Navigation is a common technique.
But that's simple intercept and collision, getting the pursuer to the same X, Y, Z as the target.
But how about when you want to rendezvous with the target? Two vehicles with arbitrary vectors, the target on a stable (i.e. not trying to evade, but not necessarily straight) course, what techniques are folks using directing the pursuer to match the position, velocity, and heading of the target?
I think this is a different problem from station keeping or flocking (where the two vehicle are already close), but maybe not.

You may be interested in "How can I maneuver an AI pirate ship for a sea battle?" which discusses a version of this problem for ships on a 2D ocean plane.


text:
How to implement 2D rigid body motion?
I'm already depending on two NPM packages for 2D collision and differential equations:

sat
rungeKutta

I've a basic simulation structure, but don't know where to start with to use these two packages in my step() forward method that should iterate rigid bodies and their joints:
export default class Simulation {
    /**
     * Global gravity.
     */
    gravity: Vector;

    /**
     * Timestep length during a step.
     */
    timestepLength: number;

    // Contained rigid bodies
    private readonly _bodies: Body[] = [];

    // Joints between rigid bodies
    private readonly _joints: Joint[] = [];

    constructor(options: SimulationOptions) {
        this.gravity = options.gravity;
        this.timestepLength = options.timestepLength === undefined ? 1 / 60 : options.timestepLength;
    }

    step() {
        for (const body of this._bodies) {
            //
        }
    }
}
```


text:
How can I write the same code, but for Cinemachine?
I have a code for recoil, and this recoil rotates the camera upwards, and then returns smoothly back to the starting point.So, when there is a Cinemachine Virtual Camera component on the camera, the view will not be changed by rotating the transform itself, but only by the settings in the virtual camera itself AIM vertical/horizontal value, right ? Then the question is, how to make exactly the same recoil mechanics if the camera needs to be rotated through the Cinemachine virtual camera? This script was supposed to find a camera on the object.Here is the recoil code:
private Vector3 currentRotation;
private Vector3 targetRotation;

[SerializeField] private float recoilx;

[SerializeField] private float recoily;

[SerializeField] private float recoilz;

[SerializeField] private float snappiness;

[SerializeField] private float returnSpeed;

void Update()

targetRotation = Vector3.Lerp(targetRotation, Vector3.zero, returnSpeed* Time.deltaTime);
currentRotation = Vector3.Slerp (currentRotation, targetRotation, snappiness Time.fixedDeltaTime);
transform.localRotation = Quaternion.Euler (currentRotation);

public void RecoilFire()

targetRotation += new Vector3(recoilX, Random.Range(recoily, recoilY), Random.Range(recoilz, recoilz));
```


text:
Unreal 5.3 ignores changes in Visual Studio Code
I’m using Unreal 5.3 on Ubuntu 23.04 “Lunar.” I’m not using Windows (I really can’t stand it), and there is no Visual Studio on Linux. (It's not even supported by Wine.) But we have VS Code, the development platform that Epic and Unreal recommend for Linux. So far so good.
My only problem is that, when I make a change in my C++ code, my game does not notice. (Yes, I did save, otherwise VS Code would not build the changes at all.) If I close the whole game window and then start the editor from VS Code, with the option Launch GameNameEditor (Development) (workspace), the editor will eventually open with the changes. But I can’t, in practice, close and reopen the editor at every single change in the code. I tried running make GameNameEngine from the terminal. That too builds the game, but the editor still ignores the changes.
The simplest change I make to verify that there is a change is change the name of a UPROPERTY variable editable in the “Details” pane of the editor. Or add or remove some. It usually takes me hours of attempts to see them appear, get removed, or get modified. Again: the problem seems to only be that the editor ignores the changes.
Is there anything I can do?
Thanks.


text:
Box2d's SetLinearVelocity not working as expected
I'm working in a SFML and Box2d project, and I stumbled with a problem related to the linear velocity of bodies.
I've created a simplified version of the project, and the problem still persists, this is the code:
int main()
{
    sf::RenderWindow window(sf::VideoMode(800.f, 800.f), "SPACE BATTLE");

    sf::Event evnt;

    sf::Clock clock;

    b2BodyDef bodyDefinition;
    bodyDefinition.type = b2_dynamicBody;
    b2Body* body = world.CreateBody(&bodyDefinition);

    b2PolygonShape bodyShape;
    bodyShape.SetAsBox(2.f, 2.f);

    b2FixtureDef bodyFixture;
    bodyFixture.shape = &bodyShape;
    bodyFixture.density = 1;
    bodyFixture.friction = 0.3;

    body->CreateFixture(&bodyFixture);

    body->SetLinearVelocity(b2Vec2(0.f, 5000.f));

    window.setFramerateLimit(60);

    while (window.isOpen())
    {
        while (window.pollEvent(evnt))
        {

            if (evnt.type == sf::Event::Closed)
            {
                window.close();
            }
        }

        auto time = clock.getElapsedTime();

        world.Step(time.asSeconds(), 6, 2);

        clock.restart();
    }
}

After the first call to world.Step(), if I try to get the linear velocity of the body, it will be totally different than what I set before body->SetLinearVelocity(b2Vec2(0.f, 5000.f));.
For example, sometimes I get 522.23f, these values can vary, but they are always different than what I set the linear velocity to be before the main loop starts, why is this happening?