texts: How to handle multiple events in SDL2 and C++?

texts:
I'm working on an entity component based game and I ran into this problem.
I've got a component called PlayerControlComponent:

void PlayerControlComponent::HandleInput() {
    SDL_Event event;
    while(SDL_PollEvent(&event) != 0) {
        if(event.key.keysym.sym == SDLK_RIGHT) {
            Entity->MoveRight();
        }
        else if(event.key.keysym.sym == SDLK_RIGHT) {
            Entity->MoveLeft();
        }
        else {
            Entity->Stay();
        }
    }
}

and I've got a GameManager class that handles the input for the window, like if you hit escape it will quit:

void GameManager::HandleInput() {
    SDL_Event event;
    while(SDL_PollEvent(&event) != 0) {
        switch(event.key.keysym.sym) {
        case SDL_QUIT:
        case SDLK_ESCAPE:
            Quit();
        }
    }
}

After I put everything in my main function, it looks like this:

while(GameManager::GetInstance().IsRunning()) {
        //Inputs
        GameManager::GetInstance().HandleInput();
        player->GetComponent<PlayerControlComponent>()->HandleInput();
        //Update, Draw, etc..

My problem is that wich ever I put first gets executed only. So in this example the player won't handle inputs. If change it up and put the player first like so:

while(GameManager::GetInstance().IsRunning()) {
            //Inputs
            player->GetComponent<PlayerControlComponent>()->HandleInput();
            GameManager::GetInstance().HandleInput();
            //Update, Draw, etc..

..my player will move but than the window won't quit if I hit escape. For some reason wich ever input handling function is called first, gets executed. I figured out it has something to do with SDL_PollEvent(). So I created a global SDL_Event variable and changed up the code a bit so there is only 1 SDL_PollEvent() call wich happens in main:

while(GameManager::GetInstance().IsRunning()) {
        //Inputs
        while(SDL_PollEvent(&event) != 0) {
            GameManager::GetInstance().HandleInput();
            player->GetComponent<PlayerControlComponent>()->HandleInput();
        }
        //Update, Drawing, etc..

So as I said, the event variable is now global and both GameManager and Player uses the (only) same event variable.b Now everything works fine, but is that really the only option? (If so, than I don't know why would they allow us to declare multiple SDL_Events.)
So my question is:

Is there a way around this, can I handle multiple input events?


texts: Weird stuttering with fixed-timestep, variable-framerate game loop

texts:
I've been trying to set up fixed-timestep loop for my game, using the technique from here. I have no need for the interpolation step as I intend to run the logic at or above vsync speed.

Here is a simplified version of my test code (C#):

const double MILLISECONDS = 1000.0;
const double TARGET_SPEED = 60.0; //Logic tick rate in hertz

const double dt = MILLISECONDS / TARGET_SPEED;

double currentTime;
double accumulator = 0.0;
Stopwatch logicTimer = new Stopwatch();

double theta = 0;
float spinSpeed = 0.005f;

//Game loop:
while (true)
{
    double newTime = logicTimer.ElapsedMilliseconds;
    double frameTime = newTime - currentTime;

    currentTime = newTime;
    accumulator += frameTime;

    while (accumulator >= dt)
    {
        theta = (theta + spinSpeed * dt) % (Math.PI * 2.0);
        accumulator -= dt;
    }

    //Draw sprite, rotated theta radians
    Draw();
}

With TARGET_SPEED at 60Hz on a 60Hz monitor, most of the time it runs smoothly. However, often when I run the test I see periodic jumps in the rotation. The time to complete a revolution does not change, but it appears to stand still for an extra frame or two and then jump ahead to make up the difference. The frequency of these stutters is constant during a run, but subsequent runs with the same settings will stutter at different rates.

I've measured how much theta changes each logic step, and it's rock steady across multiple runs regardless of stuttering.

This leads me to believe the problem is something to do with differences between my game's clock and my monitor's refresh clock. However, I can't figure out anything beyond that.

The problem still happens whether vsync is on or off. It happens less often when TARGET_SPEED is a multiple of 60; for any other value it happens on every run. Increasing TARGET_SPEED past 1000 or 10,000 Hz appears much smoother, but there's no way I can run a real game that fast. Drawing more or fewer sprites to control the time spent rendering doesn't seem to have any consistent effect on the problem.

So basically I'm completely stumped. Any idea why this is happening and how I can fix it?

Here's the full source file for my test project (XNA) if you want to try it for yourself.


texts: Best way to calculate unit deaths in browser game combat?

texts:
My browser game's combat system is written and mechanically functioning well.  It's written in PHP and uses a SQL database.  I'm happy with the unit balance in relation to one another.  I am, however, a little worried about how I'm calculating unit deaths when one player attacks another because the deaths seem to pile up a little fast for my taste.

For this system, a battle doesn't just trigger, calculate winner, and end.  Instead, it is allowed to go for several rounds (say one round every 15 mins.) until one side passes a threshold of being too strong for the other player and allows players to send reinforcements between rounds.

Each round, units pair up and attack each other.  Essentially what I do is calculate the damage:

AP = Attack Points
HP = Hit Points

Units AP * Quantity * Random Factors * other factors (such as attrition)

I take that and divide by the defending unit's HP to find the number of casualties of defending units.  So, for example (simplified to take out some factors), if I have: 500 attackers with 50 AP vs 1000 defenders with 100 HP = 250 deaths.  I wonder if that last step could be handled better to reduce the deaths piling up.

Some ideas:

I just change all the units with more HP?
I make sure to set the Attacking unit's AP to be a max of the defender's HP to make sure they only kill 1 unit.  (is that fair if I have less huge units vs many small units?)
I spread the damage around more by including the defending unit's quantity more? i.e. in that scenario some are dead and some are 50% damage.  (How would I track this every round?).  This kind of seems like the best idea, but not sure how i'd track it in the DB.
Other better mathematical approaches?


texts: Multiple points of gravity in GameMaker Studio 2

texts: I'm trying to make a simple 2D prototype in GameMaker Studio 2 where there're multiple points of gravity, essentially static objects in the scene that attract the player-object based on distance and mass of the object. Does anyone know if this would be complicated to get working? I've been trying to find resources on how to do this, but so far I've not found much helpful, so if anyone has any pointers for me that would be much appreciated.


texts: Specular Maps, understanding cryengine hints

texts:
i am reading the cryengine documentation, but i don't understand the following hint. Is there any reference to know the logic behind it?

"Create proper specular maps for the objects, and then store in diffuse alpha and enable the material to use gloss in the diffuse alpha. A good specular map can fake a lot of detail. Sometimes, you don't even need a normal map for the object. Do not just increase the contrast/levels on the diffuse map. This is a waste of memory."


texts: UI Element only showing in sceneview and not game in Unity3D

texts:
I have a game and in one part, in the start of a scene its supposed to trigger an animation that shows a UI element that covers the whole screen to make a smooth transition from one scene to another.
When I click a button it will trigger a function that triggers an ienumerator (just a function basically) which starts the animation, waits some time, then opens the next scene. The animation it triggers makes the UI show up.
The code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class levelLoad : MonoBehaviour
{
    public Animator transition;
    public float waitTime = 1f;

    public void transitionLoad(int li)
    {
        Debug.Log("Message through, activating script.");
        StartCoroutine(loadScene(li));
    }

    IEnumerator loadScene(int levelIndex)
    {
        // the set trigger sets the trigger 'starts' which starts the animation that shows the ui element

        transition.SetTrigger("Starts");
        Debug.Log("animations, go");

        yield return new WaitForSeconds(waitTime);

        Debug.Log("Loading Scene");

        // loads scene
        SceneManager.LoadScene(levelIndex);

        Debug.Log("Scene Loaded");
    }
}

So in the animator tab, there is a trigger called "starts" that when triggered, activates crossfade_end which shows the UI element.
crossfade_start hides the UI element.
I get all the debug logs in the code correctly and in game I checked animator, it says that its playing the animations yet in game I don't see the UI element showing up.
Does anyone have a solution? I'm using unity 2019.17.4 lts.
Also, the UI element is in a different canvas then the main canvas, a canvas that is in the sceneloader gameobject, which has the code above. Also that canvas is in layer default, and I checked, default layer is set to showing.
Can anyone fix my problem of the UI element showing in scene view but not in game? (this isn't build)
this is an android game.


texts: Server Side Speed Hack Detection Techniques

texts:
I have a client side speed hack detection that initiates a timer on both the client and server on connection. When the difference becomes too much the client gets detected as using speed hack.

But I have one problem, they found a way to run a speed hack program and close it but keeping the speed hack activated on the game client (odd) which made the counter on the client run normally even with speed hack enabled.

So I added detection to the server by using the movement packets and checking the time difference between 2 different movement packets come in. The design was okay, it did detect the speed hack by checking that the difference is not less than 50ms but when someone was lagging (queued movement packets) it also detected it as speed hack.

So I improved this by considering a factor of how fast it would process each packet that arrived in bulk which means microseconds. Now I adjusted the detection to less than 50ms but greater than 1ms. This was better it didn't detect lagging too much but it still did.

Now my problem is how can I implement this in a way that I can still check how fast the packets are coming in but not detect the people that are experiencing lag falsely. Or should I just keep adjusting the parameters for detection until I get to the sweet spot?


texts: How are photorealistic models' textures created?

texts: I've been learning Blender and have made some decent progress. I've made some neat models, but so far, they haven't been textured. I understand how to unwrap a model so as to get the UV coordinates, but how do I actually create a texture to fit this coordinates? I've looked around and so far, it seems like a lot of people spend time hand-painting their models. Then I look at games like Counterstrike: Source, Call of Duty, etc., and I'm wondering how their models look photorealistic. It's all a bit of a mystery to me, but I'm hoping somebody could clarify. So, how exactly are photorealistic models created?


texts: How can the Unreal Development Kit be used with Android?

texts:
I've read the UDK will support Android development, I checked the download page on the site and found nothing related to Android.

also read that Dungeon Defenders Android game was built with Unreal engine.

so is there a way to use the UDK with Android ?


texts: How can I find the collision response between a moving sphere and cube?

texts:
I'm implementing my own algorithm for sphere and cube collision response. So far I'm able to only test if both of them overlap.

My problem is: A cube is rotating around its axes i.e x and z axes. And the sphere is moving at a velocity that being Vx,Vy and Vz in all the 3 axes. How do I find the collision response between them without considering angular velocity of cube i.e when the cube and sphere collide cube is not having an velocity but angles with 2 axes. After collision I don't want the sphere to have angular velocity.


texts: What debugging info should I put in the "About" box

texts:
I'm developing an Android game with the idea of publishing it, and I wonder what info should I put in the "About" dialog that many main menus have.

The idea is to make bug report and debugging easier. Users can click in the "About" box and read the details of their device, and include them in any bug report they send me - I know Google sends relevant device data to the developer when there's a crash, but I'm thinking in bugs that not necessarily end with an abnormal program termination.

So far, I've added API number of device, screen size, screen density, and number of processors.

My current "About" screen is something like this:

  Game titleGame iconAPI versionScreen sizeScreen densityNumber of
  processors (just in case, because game uses threading)Game version numberDeveloper e-mailCopyright information

If anyone has experience publishing and maintaining an app, specially in Android, I want to know what can I add there to make user reporting and debugging easier.


texts:
I'm using LibGDX and Box2D for my physics but my characters bounce all over the place when moving and if there is a small slope in the terrain they launch off of it.
I've tried tweaking settings but it either seems to completely kill the motion or send the player off to space. How can I get movement closer to Worms where there is a little bounce but the players for the most part stick to the floor.

For reference I want it to be like this:

https://www.youtube.com/watch?v=zMDfo2czbu0&t=5s

What kind of things can I tweak to get that kind of motion?


texts:
is possible to get the 'Height' of a font drawed with the drawWrapped methods (with a wrapWidth) ?

getMultiLineBounds only works when \n is used, but when drawing with drawWrapped it doesn't give the right Height.

Text

String text = "hello this is very lonnnnng text without new line";
float wrapWidth = 100;

Display code :

 font.drawWrapped(batch, text, x, y, wrapWidth, alignment);

My 'get the displayed height code' :

 font.getMultiLineBounds(text).height;

Output :

 hello this is very
 lonnnnng text without
 new line

Problem :

How to have the total height of the displayed text by the methods : DrawWrapped

Can you help me please ? thanks you


texts: Which is the best network solution for MMORPG?

texts:
we are developing a mmorpg with a small team. There are 2 structures we can create on the server side for managing clients and processing packages. I wonder what structure is better. I would be very happy if there is a good structure that you can recommend.

First Structure

In this structure, idle sessions (IdleSessionQueue) are initially created and there is a thread (NetworkListenerThread) that listens to the network and accepts users. This thread takes a session from idle sessions when a new user arrives and adds the session to the active sessions table (ActiveSessionMap) using the values of SessionId and Session. then creates a thread (ClientListenerThread) to listen to the session added to the table. a ClientListenerThread occurs for each user.  When the client has disconnect, it is added back to IdleSessions again.

When the client sends a request (Packet), that request is added to TaskQueue. A certain number of workersThreads are created in advance. As long as there is a package in TaskQueue, WorkerThreads receives the package and processes it and adds the new package to SendQueue. SenderThreads receives and sends each packet in SendQueue to client.

Second Structure

In this structure, idle sessions (IdleSessionQueue) are initially created and there is a thread (NetworkListenerThread) that listens to the network and accepts users. This thread takes a session from idle sessions when a new user arrives and adds this session to the active sessions table (ActiveSessionMap) using the values of SessionId and Session. then creates a thread (ClientListenerThread) to listen to the session added to the table. a ClientListenerThread occurs for each user. When the client has disconnect, it is added to IdleSessions again. When the client sends a request (Packet), that request is processed by ClientListenerThread and the result is sent to one or more clients.

Which one is better solution or what is the best solution for this problem?


texts: Idle+Walk animation problem and double-button input axes

texts:
I have 2 problems with unity3d.

First, I created an animator and attached it to player. In animator I put 2 condition, Speed and Running (first is float, second is boolean). Default Animation is Idle. Then player press W, I want animation to fade from idle to walk and when he stop press the button, I want the animation to fade from walk to idle. Here is my problem.

When I press W, he make walk animation, but after it he play half of idle animation and after it he enter again in walk animation. How can I loop the walk animation until he release W? And if he release, even if the animation isn't totally played, I need the animator to make transition to idle.
How can I make this "transition"? Then I release W, he just go from walk to idle animation without any transition (and it is a kind of wear).

Second, How can I put 2 input buttons on axes? I mean: If he press W, there should go vertical axes. When he press W+Left Shift, there should go running axes. How can I attach 2 buttons to 1 axes?

I am new in unity and I want to figure out how to work with this things.


texts: Access alpha value of opengl texture pixels

texts:
I'm trying to get the alpha values of each pixel of an image that I'm loading onto a texture so i can use it to check for per pixel collision.
I have a texture class:

struct GLTexture {
    std::string filePath = "";
    GLuint id;
    int width;
    int height;
    std::vector<std::vector<int>> alphaPixels;
};

When i bind the texture i want to do something like this:

//Generate the openGL texture object
glGenTextures(1, &(texture.id));

//Bind the texture object
glBindTexture(GL_TEXTURE_2D, texture.id);
//Upload the pixels to the texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, &(out[0]));

for(int i = 0; i < width; i++)
{
    for(int j =0; j<height; j++)
    {
        alphaPixels[i][j] = getAlpha(GL_TEXTURE_2D); ///<something like this line but i don't know how to access to alpha value
    }
}

How can i get the alpha value of each pixel of the image? Is this even a feasible thing to do or is there a better way to do this?


texts: How are minimaps rendered for open worlds?

texts:
When I've created minimaps for smaller to medium levels before I would use a large texture mapped to a plane for the minimap and world map. The minimap/world map camera would then view this texture from a top down view.

For larger, open world style environments though I'm facing a performance vs fidelity issue. For example, a large environment requires a large texture to fit everything in, but at the same time the texture also needs to be a high enough resolution for when the player decides to zoom in onto a specific point in the map. I can make the map high resolution with enough detail up close but this creates quite a large texture size. Or I can make a lower res map which is more efficient but it becomes blurry/pixelated when zooming in.

Is this just a balance that I have to play with, or is there a better way to handle this? For example, creating a simple 3d mesh whose shape would act as the map. Or instead of using a texture using a vector graphic. How is this usually done?


texts: How do I save my game with highscores and player positioning in LibGDX?

texts: So I have a game that needs to save high scores for the number of waves, what guns the player has, positioning of the player and the zombies, and so on. I saw something about SharedPreferences but have no clue how to use them. Can someone point me to the right direction or willing to tell me how to use them correctly?


texts: Rule of thumb for enemy art design in 2D platformer

texts: I'm at the early stages of developing a 2D side scrolling open ended platformer (think Metroidvania) and am having a bit of difficulty at enemy design inspiration for something of a scifi, nature, fantasy setting that isn't overly familar or obvious. I haven't seen too many articles, blogs or books that talk about the subject at great length. Is there a fair rule of thumb when coming up with enemy art with respect to keeping your player engaged?


texts: Calculate occluded parts for planet like object

texts:
So I have camera position (it's dynamic), planet position (also dynamic), radius and coordinates for every side (node) corners and I want to hide side that is beyond horizon (with some safety margins). I think I could easily calculate in 2D using trigonometry, but in 3D have no idea right now. I found some code online:

TileNode.prototype.isWithinHorizon = function () {
  var r = this.master.getRadius();
  var camToTile = this.master.getCamToTile(this);
  var camToCenter = this.master.getCamToCenter();

  var camDistToCenter = camToCenter.length();
  var dotCtCc = camToTile.dot(camToCenter.divideScalar(camDistToCenter));

  return dotCtCc - this.scale*0.5 < (camDistToCenter - r*r/camDistToCenter);
};

but can't make sense of it, as it is not commented. Any help appreciated!

P.S. i hope i use the term "occluded" right here


texts: creating a process to run in c++ // i need to run a process in c++

texts:
Hey I don't know why that when I compile this code that the fear.exe process is not running I am using visual studio for my coding ide choice the project is a win32 project // application method, that I am using..

I should say that I added a new item a c++ file called main.c++ and should I use the code file that Defines the entry point for the application. or does it matter.

#include "iostream"
#include "Windows.h"
#include "OVR_CAPI_D3D.h"
#include "Win32_DirectXAppUtil.h"
#include "stdio.h"
#include "string.h"
#include "Shlobj.h"
#include "Shlwapi.h"

using namespace std;

int WINAPI WinMain(HINSTANCE hinst, HINSTANCE, LPSTR, int)
{
    STARTUPINFO startinfo = { 0 };

    PROCESS_INFORMATION processinfo = { 0 };

    BOOL bsuccess = CreateProcess(TEXT("E:\SteamLibrary\steamapps\common\FEAR Ultimate Shooter Edition\FEAR.exe"), NULL, NULL, NULL, FALSE, NULL, NULL,
        NULL, &startinfo, &processinfo);

    if (bsuccess)
    {
        cout << "Process Injected" << endl
            << "Process ID:\t" << processinfo.dwProcessId << endl;

    }
    else
    {
            cout << "Error to start the injected process" << GetLastError() << endl;
        }
        cin.get();
        return(0);
    }


texts: How can I use Jung, GraphStream or JGraphT with LibGDX?

texts: All libraries I found (JUNG, JGRAPHT, GraphStream) use Swing when I use libGDX. How you can use them with LibGDX


texts: I am use to XNA and starting to learn XNA for Silverlight 5. My Question is that in XNA when you create a Model and load it using content.load you are able to access the models Position, scale etc.. In Silverlight XNA these options are not available. It would be possible  to change the Models position using World Translate, but I need the models position for collision detectection using boundingSphere Any Advice??


texts: Unity3D GUI - what exactly it does when create controls and check their statuses?

texts:
On unity3d website in the manual on this page: http://unity3d.com/support/documentation/Components/gui-Controls.html

I found an example of "GUI.changed" function usage(below). And it looks like it creates toolbar object on every frame. Am I right or not?

/* GUI.changed example */

// JavaScript
private var selectedToolbar : int = 0;
private var toolbarStrings = ["One", "Two"];

function OnGUI () {
    // Determine which button is active, whether it was clicked this frame or not
    selectedToolbar = GUI.Toolbar (Rect (50, 10, Screen.width - 100, 30), selectedToolbar, toolbarStrings);

    // If the user clicked a new Toolbar button this frame, we'll process their input
    if (GUI.changed)
    {
        print ("The toolbar was clicked");

        if (selectedToolbar == 0)
        {
            print ("First button was clicked");
        }
        else
        {
            print ("Second button was clicked");
        }
    }
}


texts: How to drag an object with mouse with collision?

texts:
I want to drag a GameObject with the mouse but I need collision. The basic mouse dragging code simply sets the position of the object to the hit.point with an offset from the difference at the start of the drag.

As for collision, I've tried using kinematic rigidbodies and setting the position with rigidbody.MovePosition(uh) but that allows the object to rotate while pushing it up against a corner on one side.  With rotation constraints enabled, it flickers a lot and still intersects a lot. I also tried playing with collision detection and interpolation. None of the settings improved it.

I also tried Physics.ComputePenetration but that is extremely messy because some of the objects I'm dragging, have several colliders. The distance it calculates is per collider so it doesn't calculate the offset required to separate the entire object. I tried disabling all the colliders and then adding a single box collider sized to fit the bounds of the object. That had bad flickering problems.

The last thing I tried was box casts on each side that would find the closest point and offset the mesh in that direction. But if I moved the mouse too fast it would go inside the other mesh and would no longer register any colliders intersecting the box casts. It also suffered from flickering problems.

Ideally, I want to have fairly accurate detection. I don't want to approximate the other colliders (not the ones on the object I'm dragging). Assume the other colliders could be any type (box/capsule/sphere/mesh).

The image below shows the problem I'm having. The green dot shows approximately where the cursor was (also the hit.point from the raycast on the surface of the red cube). What I expect is that the couch should be offset so that it was close to the cursor but prioritizes not intersecting other meshes over sticking to the mouse.


texts: Transform 3D vectors between coordinate systems

texts:
I've got 6 points in 3D space: A,B,C,D,E,F, that represent 4 vectors. AB is perpendicular to AC and DE is perpendicular to DF.

I need to find a transformation matrix M, that transforms AB to DE and AC to DF. In other words: M⋅AB=DE, M⋅AC=DF

If no scaling was involved, this could be solved with a simple rotation matrix. But since the ratios |AB|/|DE|, |AC|/|DF| might be different, I'm not sure how to proceed.


texts: Box2d world width and height ratio with screen width and height

texts:
I have view, for example GameView which extends SurfaceView . I have integrated Box2D physics in GameView. I have two widths ,

GameView width, height and Box2D physics world width ,height. I need to get the position of box2d world with the GameView co-ordinates.

For example,

Total width of screen = 240
Total height of screen = 320

Screen points needed to be mapped onto box2d co-ordinates (x,y) = 127, 139

For this i need to get the max width and height of the Box2d physics world. Is there is any way to get the max width and height of Box2d world.

or

Can i limit the width and height of box2d world within the screen resolution.


texts:
I am going to use texture atlasing for the first time in my games, and at first it seemed like a great idea to split textures into atlases by categorizing them by terrain themes e.g ForestTextures, WinterTextures etc.

But that could cause a problem when for example a flower has to use transparency shader and other models use a diffuse shader. So those cannot be atlased into the same texture. Thus, would atlasing textures into themes as mentioned before and then splitting them by shader like ForestDiffuse and ForestTransparent be good? Or is there a better way to categorize and build them?


texts: How do you calculate a gradient value within multiple colors (gradient stops)

texts:
In WPF/Silverlight XAML you can have a brush with multiple gradient stops at different points along the color line.

I was able to replicate this behavior with two colors, a single color lerp, from this answer to my previous question: Code to generate a color gradient within a texture using a diagonal line

How do I do the same thing in that question, but with multiple color steps even at different widths from each other.


texts: C++ OpenGL Basic Binary Object File Loader

texts:
I have looked around for a in-depth explanation on what is a binary file (For a Opengl Object), how to make them and also how to load them, but I can't find many references... Can someone point me in the right direction?

EDIT.
I'm wanting to load a models vertex positions from a file. I currently am using obj but I want to use something faster, such as binary files.


texts:
I am trying to make a simple game where the player jumps and collects animated coins. After collecting all the coins, the scene is supposed to change. For some reason, my character collects the coins but the scene doesn't change.

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

public class Coins : MonoBehaviour
{
    [SerializeField] private string newLevel;
    public int coinAmount;
    int coins ;

        void OnTriggerEnter2D(Collider2D other)
        {
        if (other.CompareTag("Player"))
        {
            coins += 1;

            Destroy(gameObject);
            addCoins();

        }
    }

    void addCoins()
    {
        coins++;

        if (coins == coinAmount)
        {
            SceneManager.LoadScene(newLevel);
        }
    }
}

This is a screenshot of the game:


texts: Is it possible to connect an external source machine to Live Link?

texts:
I would like to be able to connect multiple external machines to Unreal Engine via Live Link in order to stream solved motion capture from one of the Vicon run-time solvers/retargeter (i.e. Pegasus). In one of the streams, it was mentioned that Vicon provides a client-side plug-in for Unreal that was used in the Siren demo. I decided to test Live Link's capabilities by connecting from a different machine to UE4 from Maya (I assume that the concept is the same regardless of the source program because at the end of the day we are sending solved animation data, right?). It turned out that Live Link in Unreal out-of-the-box only detects the incoming data from the source machine that is on the same computer where Unreal is running. I am curious as to whether it is possible to modify Live Link or build a custom plug-in using Live Link that would enable me to connect from an external machine to the engine over the network.

The whole topic is very new to me, but I am tasked with providing a solution, so any information would be appreciated. Please correct me if I misunderstand the process. If you know where to look for more details regarding the problem, please tell me.


texts: Render imgui on top of existing Java framework

texts:
I have never done this before, but we need to build game editor, on top of our existing java game SDK.

We want to use java version of imgui. I can easily create imgui window and put UI into it, but how can I also put there our game?

Or run our game and render imgui on top of it?
Basically have scene view like in UI / Unity, but editor and windows on top.


texts: Do old games still generate revenue for their developer companies?

texts:
For the purpose of this question, let's say an "old" game is one released over 20 years ago, or for which the platform it runs on has become unavailable.

Do the developers still earn revenue off of titles this old?

If the answer is no, why aren't more of these titles made available for free (officially)?


texts:
I have some code that worked with no issues on MacOS Sierra, but when I update to Mojave, my compiler always says that it can't find SDL2.

Here's the error:

20:24:40 **** Incremental Build of configuration Debug for project Causality ****
make all
Building file: ../src/engine/SE.cpp
Invoking: Cross G++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/engine/SE.d" -MT"src/engine/SE.o" -o "src/engine/SE.o" "../src/engine/SE.cpp"
In file included from ../src/engine/SE.cpp:1:
../src/engine/SE.h:6:10: fatal error: 'SDL2/SDL_events.h' file not found
#include <SDL2/SDL_events.h>
         ^~~~~~~~~~~~~~~~~~~
1 error generated.
make: *** [src/engine/SE.o] Error 1
"make all" terminated with exit code 2. Build might be incomplete.

20:24:42 Build Failed. 2 errors, 0 warnings. (took 1s.304ms)

I'm using SDL 2.0.9

My project structure is this:

src
|main.cpp
|engine
 |SE.h
 |SE.cpp
 |SE_Audio.h
 |SE_Audio.cpp
 |SE_Graphics.h
 |SE_Graphics.cpp
 |SE_Input.h
 |SE_Input.cpp
 |SE_Structs.h

I'm including the libraries with -framework SDL2 -framework Cocoa -framework SDL2_image

I'm using the exact same settings that I used before and that worked in MacOS Sierra. Please tell me what more details you need before down-voting


texts: Camera that pivots in the direction that the player is moving

texts:
I'm trying to recreate Rocket League's freeform (non ball-locked) camera, which basically is a camera that follows the player but pivots to allows face the direction the player is moving in (not necessarily facing). Here's a video of Rocket League's implementation for reference: https://www.youtube.com/watch?v=RSpB6ocrIX8&t=37s

What are the main things needed to accomplish this?


texts: Why Does unity_LightPosition[0] Seem to Depend on Camera Position?

texts:
I'm trying to write a fairly basic shader but I keep running into lighting issues with Unity.  My first problem was trying to figure out which variable stored the light's position in world space.  (I'm only working with one light, at least at the moment).

I finally found something that responds to movement of my light source: unity_LightPosition[0].  However the shader still didn't do what I wanted it to do, so I did some debugging:

I have a basic vertex and fragment shader and what I'm currently doing in the fragment shader is:

float4 c = float4(0, 0, 0, 1);
float3 lp = normalize(unity_LightPosition[0]);
c.rgb = lp;
return c;

This should just set the color of my object to the normalized position of the light source, correct?  What I see in my scene is my object changes colors when I move my camera around it (I'm not moving the light source at all, it is a separate entity).  The color also seems to increase in strength as I zoom in.

To me, it seems as if unity_LightPosition[0] is related to my camera's position, as well as orientation and zoom level, yet the documentation I've found says it should represent the position of the light in world space.

I tried switching to using the following:

float3 lp = float4(
    unity_4LightPosX0[0],
    unity_4LightPosY0[0],
    unity_4LightPosZ0[0],
    1.0
);

...but that only colors my object red regardless of the light's actual position.

Additionally, I've set the LightMode tag to Vertex.

It seems like simply getting the world position of the light source shouldn't be this difficult.  What am I not doing correctly?

EDIT:
I've been playing around with the camera and light position and I think that unity_LightPosition[0] actually puts out position in the projection space.  If I place the light source in the lower-left corner of the screen, the object is black.  Upper-left the object is green (0, 1), upper-right is orange (1, 1), and lower-right is red (1, 0).  When I place it in the lower-left (0, 0) and move the camera in front of it, it becomes blue.  This is consistent with the depth value behavior.  (0, 0, >0) would appear as blue.

Now, how to get it from projection back to world?...or should I use a different variable?


texts:
I want to use basic rectangular collision detection.  I have a rotating sprite and a method that calculates the bounding box every time in the Update() method.  I simply check for intersection between all the lines of the box with all the lines of the other sprite's boxes.

Here is what I have for calculating the corners of the rotating bounding box:

double baseAngle = Math.Atan(this.Height / this.Width);
double len = Math.Sqrt(this.Height * this.Height / 4 + this.Width * this.Width / 4);

Vector2 tr = new Vector2(
  (float)(Math.Sin(baseAngle + this.Rotation) * len) + this.Position.X,
  (float)(Math.Cos(baseAngle + this.Rotation) * len) + this.Position.Y);
Vector2 tl = new Vector2(
  (float)(Math.Sin(Math.PI - baseAngle + this.Rotation) * len) + this.Position.X,
  (float)(Math.Cos(Math.PI - baseAngle + this.Rotation) * len) + this.Position.Y);
Vector2 bl = new Vector2(
  (float)(Math.Sin(Math.PI + baseAngle + this.Rotation) * len) + this.Position.X,
  (float)(Math.Cos(Math.PI + baseAngle + this.Rotation) * len) + this.Position.Y);
Vector2 br = new Vector2(
  (float)(Math.Sin(2 * Math.PI - baseAngle + this.Rotation) * len) + this.Position.X,
  (float)(Math.Cos(2 * Math.PI - baseAngle + this.Rotation) * len) + this.Position.Y);`

My box is square shaped, and my texture of that rotating sprite is Rectangular.  How can I scale the bounding box so it will be closer to the texture's size?


texts:
I want to publish an app created with libGDX (HTML/JS publishing). Here are the steps I am doing.
Right Click on the Project -> Google -> Gwt Compile -> Compile.
After the compilation there is no .html file in the /war directory . There are 3 folders assets,html,WEB-INF . What am I doing wrong?


texts: why My canvas buttons are behind the object?

texts: I don't want this to happen. Screen space overlay no problem, but when screen space camera does this.


texts: Rotate from Current Rotation to Another using Angular Velocity

texts:
I am attempting to calculate an angular velocity that will get me from the current gameObject.transform.rotation to a given Quaternion rotation using angular velocity.  I've tried several methods but all of them seem to cause oscillation (maybe due to the gimbal nature of Vector3 for angular velocity).

Here are the pieces of code that I have tried:

Quaternion rotationDelta = Quaternion.Inverse(gameObject.transform.rotation) * remoteRotation;
return (rotationDelta.eulerAngles / PlayerMovement.BROADCAST_INTERVAL);

Another attempt using toAngleAxis:

rotationDelta.ToAngleAxis(out angleInDegrees, out rotationAxis);
Vector3 angularDisplacement = rotationAxis * angleInDegrees * Mathf.Deg2Rad;
return angularDisplacement / PlayerMovement.BROADCAST_INTERVAL;

Using Eulers:

 Vector3 difference = new Vector3(Mathf.DeltaAngle(gameObject.transform.rotation.eulerAngles.x, remoteRotation.eulerAngles.x),
                                  Mathf.DeltaAngle(gameObject.transform.rotation.eulerAngles.y, remoteRotation.eulerAngles.y),
                                  Mathf.DeltaAngle(gameObject.transform.rotation.eulerAngles.z, remoteRotation.eulerAngles.z));

 Vector3 differenceInRadians = new Vector3(difference.x * Mathf.Deg2Rad,
                                           difference.y * Mathf.Deg2Rad,
                                           difference.z * Mathf.Deg2Rad);

 return differenceInRadians / PlayerMovement.BROADCAST_INTERVAL;


texts: What does `FPSManager.lastticks` stand for in SDL_gfx?

texts:
I'm having trouble finding documentation on SDL_gfx, and I can't figure this out. I've managed to use SDL_gfx to automatically cap the framerate, and I it's working a lot better than my manual attempt (combining SDL_Delay and SDL_Getticks).

Now I've been trying to learn more about it, and I stumbled onto something.
Here's the whole struct:

typedef struct {
             Uint32 framecount;
             float rateticks;
             Uint32 lastticks;
             Uint32 rate;
     } FPSmanager;

Most variables in this struct are pretty straightforward, but I have no idea of what lastticks stands for. Does anyone know?


texts: How do I set up a beta channel for my Steam game?

texts:
I have a released game on Steam. I'm working on a new version, but before releasing it to the public, I want to be able to test it with my friends on Steam, through a beta channel that can be accessed through this menu:

Can I do this, and how?


texts: Is copying UI and layout of other apps legal?

texts:
I would like to develop an Android App for Google Play and I am going to use Facebook and Whatsapp UI as background of the game (as a back-story). I will use icons without copyright to emulate/duplicate the style of Facebook and Whatsapp (they are not part of original drawable of the external app). I will inform the user about the objective of the game. I won't include any direct references to the emulated apps such as the title "Facebook" or "Messenger". The user is free to interpret what he is seeing. I will add the text

  "any name and reference is fictitious".

However I have some great doubts:

After the development, will I be able to upload the app on an app store such as Google Play?
Is copying UI and layout of other external apps legal?
Does it break any law or rule?


texts:
i have a simple triangle mesh which i want to explode.
so i am looking for an algorithm that makes every triangle to move outwards from the centerpoint.
is there already something premade like this?

thanks!


texts: How to deal with VBO and obj files for physics simulation?

texts:
I'm having a hard time struggling with obj files and clothing simulations.
I first made the obj file processor class that deals with the typical obj file problem: having multiple indices for vertex position, vertex texture coordinates, and vertex normals like this f 52/49/224 57/54/224 279/270/224. I made a function that shrinks the multiple index arrays to one index array.

class VERTEX{
public:
    glm::vec3 position;
    glm::vec2 uv_coord;
    glm::vec3 normal;
};

std::vector<VERTEX> out_vertices;
std::vector<unsigned int> out_indices;

void reorderData(){
        for(int i=0;i<vertexIndices.size();i++){
            VERTEX vertex;
            // add -1 to each index as indices for obj files start from 1, not 0.
            int vi = vertexIndices[i]-1;
            int uvi = uvIndices[i]-1;
            int ni = normalIndices[i]-1;
            vertex.position = temp_vertices[vi];
            vertex.uv_coord = temp_uvs[uvi];
            vertex.normal = temp_normals[ni];
            //assign new index here for the VERTEX object
            int index = getVertexIndex(vertex);
            //If it's a new index, it means it's a new VERTEX. Store it in out_vertices.
            if(index==out_vertices.size()){
                out_vertices.push_back(vertex);
            }
            out_indices.push_back(index);
        }
    }

Then I use out_vertices and out_indices to set up the VAO, VBO, and EBO for rendering. The problem here is that in the VBO, there are multiple VERTEX objects that have the same position value.

However, in order to do physics simulation, I need a particle class that deals with calculating the force, speed, position for every loop of each cloth particle.

class particle{
public:
    glm::vec3 position;
    glm::vec3 force;
    glm::vec3 speed;
    float mass;
}

And if I just copy the the VERTEX objects' position values to the particle objects, then there will be multiple particle objects with the same position value. But this doesn't seem right as there should be only one particle object for each unique position.

So my solution at the moment is, to first make particle objects that each have unique position values. Then, after each physics loop calculating a particle's speed, force, position, I update all the VERTEX objects whose position value has changed for the corresponding 'position' object. Lastly I update the VBO.

Would this be the right approach? I am afraid that linearly searching the multiple VERTEX objects who have the same position value as the particle object is going to take a lot of time. Any help would be appreciated. Thanks in advance!

To be short what I want to seek advice about is how to seperate and handle the rendering data and the physics simulation data efficiently.


texts:
I'm attempting to create a simulation of car traffic and to model the flow, it seems like Poisson Distribution would be useful here. I'm still trying to get my head around the variables I would incorporate, but at the moment I know what I want the arrival rate at a certain point to be, the speed limit, and the minimum gap (time) between cars.

Currently, cars spawn on one end of the road after a preset amount of time and accelerate to the speed limit, checking for cars in front and slowing down if necessary so as to keep at least a the minimum gap between the two of them.

I'm not sure how to incorporate variables such as acceleration into the Poisson Distribution. Does anybody have any experience implementing something similar?


texts: Restrict A* pathfinding to overlapping "safe zones" within map

texts:
I've been bashing my head against this idea for a few days without luck, I'm hoping someone sees something I don't.
So I have a 2D map containing walls and obstacles, and I have a unit that navigates through it (A* and funnel algorithm). So far so good. Now, for gameplay purposes, I need to limit the movement of this unit to circular safe zones that I can place on the map. Think of them like cell towers, the unit has to stay within range of at least one tower, with the max range dictated by the tower (possibly different for each tower). Effectively, imagine drawing a set of interlocking circles over the map, and the unit must remain within that.
Now for the complicated part. The map is a constrained Delaunay triangulation, not a grid, so the triangles that A* is using can vary in size and shape. With a grid, I could imagine limiting individual grid cells by circle distances, but in my case these triangles could be larger than any one circle. There could even be cases where the start and end points of a path are within the same triangle, but because of the network of circles, an indirect path would have to be chosen to stay within the circles.
The only option I can think of involves adding these circles into the triangulation as additional edges, altering the map. This would mean rebuilding the map triangulation each time a player adds or removes these circles, and would require that I maintain a separate copy of that triangulation per player. And since these circles don't care about map walls, I'd have to alter my triangulation method to allow edge splitting and removal, to prevent overlapping lines from rendering the triangulation invalid.
I feel like there has to be another way to do this. I've considered:

Running A* purely on the circles first, then placing that intermediate path on the map and re-pathing it to avoid obstacles.
Finding all of the circle intersections between the start and end points, and treat those lines as portals that I must pass through, somehow altering the A* pathing to prioritize passing through them.
Performing a regular path search on the triangulation, but forcing a dead-end whenever entering a triangle that is too far from a circle. Then refining that path to conform to the circles themselves.

Each of these have issues, or scenarios where they fall apart.
Has this been done before? Any input on how this might possibly be achieved would be appreciated.
Edit: Adding an image to show what I'm trying to accomplish. The red lines show the path that A* would generate using just the map triangulation. The green lines show the desired path, taking the circle bounds into account.


texts: How to save am image of a screen using JOGL

texts:
Hope this is a better place to ask things like this.
I have a 2D scene with some sprites drawn in Swing frame. I need them to be saved as an image. The problem is every tutorial I found seem to be obsolete.

I found using glReadPixels and putting result to a BufferedImage should help but all those snippets look stale, API has changed. I'm using JOGL 2.1.5 that is current at the moment.

I have a feeling this should be a widely known use-case for professionals.
Any help would be appreciated!

Updated:
I adopted some stale snippets (please, don't tell me API hasn't changed significantly, there're dozens of movings and renamings)
No the problem is I'm getting black screen in png file. It comes from byte buffer being read to with zeros only.

   public static void main(String[] args) {
        TestPNGSaver saver = new TestPNGSaver();
        saver.run();
    }

    private void writeBufferToFile(GLAutoDrawable drawable, File outputFile) {
        int width = drawable.getWidth();
        int height = drawable.getHeight();

        ByteBuffer pixelsRGB = Buffers.newDirectByteBuffer(width * height * 3);

        GL2 gl = drawable.getGL().getGL2();

        gl.glReadBuffer(GL.GL_BACK);
        gl.glPixelStorei(GL.GL_PACK_ALIGNMENT, 1);

        gl.glReadPixels(0, 0, width, height, GL.GL_RGB, GL.GL_UNSIGNED_BYTE, pixelsRGB);

        int[] pixels = new int[width * height];

        int firstByte = width * height * 3;
        int sourceIndex;
        int targetIndex = 0;
        int rowBytesNumber = width * 3;

        for (int row = 0; row < height; row++) {
            firstByte -= rowBytesNumber;
            sourceIndex = firstByte;
            for (int col = 0; col < width; col++) {
                if (pixelsRGB.get(sourceIndex) != 0) {
                    System.out.println(sourceIndex);
                }

                int iR = pixelsRGB.get(sourceIndex++);
                int iG = pixelsRGB.get(sourceIndex++);
                int iB = pixelsRGB.get(sourceIndex++);

                pixels[targetIndex++] = 0xFF000000
                        | ((iR & 0x000000FF) << 16)
                        | ((iG & 0x000000FF) << 8)
                        | (iB & 0x000000FF);
            }

        }

        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        bufferedImage.setRGB(0, 0, width, height, pixels, 0, width);

        try {
            ImageIO.write(bufferedImage, "PNG", outputFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void display(GLAutoDrawable drawable) {
        GL2 gl = drawable.getGL().getGL2();
        gl.glClear(GL.GL_COLOR_BUFFER_BIT);
        gl.glBegin(GL.GL_TRIANGLES);
        gl.glColor3f(1, 0, 0);
        gl.glVertex2f(-1, -1);
        gl.glColor3f(0, 1, 0);
        gl.glVertex2f(0, 1);
        gl.glColor3f(0, 0, 1);
        gl.glVertex2f(1, -1);
        gl.glEnd();
    }

    private void run() {
        GLProfile.initSingleton();
        GLProfile glp = GLProfile.getDefault();
        GLCapabilities caps = new GLCapabilities(glp);
        final GLCanvas canvas = new GLCanvas(caps);
        canvas.addGLEventListener(this);

        Frame frame = new Frame();
        frame.setSize(400, 400);
        frame.add(canvas);
        frame.setVisible(true);

        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                writeBufferToFile(canvas, new File("/whatever/text.png"));
                System.exit(0);
            }
        });
    }


texts:
At the moment I'm writing an Android OpenGL ES 2.0 game but now I get stuck on rendering a SkyBox. Here is my (a bit simplified) code for the SkyBox:

float vertices [] = {-1,1,1,1,1,1,-1,-1,1,1,-1,1,-1,1,-1,1,1,-1,-1,-1,-1,1,-1,-1};
byte drawOrder[] = {1,3,0,0,3,2,4,6,5,5,6,7,0,2,4,4,2,6,5,7,1,1,7,3,5,1,4,4,1,0,6,2,7,7,2,3};

private final void bindTexture()
{
    int shaderTextureUnit = GLES20.glGetUniformLocation(shaderProgram, "u_TextureUnit");

    GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
    GLES20.glBindTexture(GLES20.GL_TEXTURE_CUBE_MAP, texture);
    GLES20.glUniform1i(shaderTextureUnit, 0);
}

public void draw(float[] viewMatrix) // viewMatrix = Camera = data array
{
    GLES20.glUseProgram(shaderProgram);
    bindTexture(); // Load Texture

    shaderPosition = GLES20.glGetAttribLocation(shaderProgram, "a_Position");
    shaderMatrix = GLES20.glGetUniformLocation(shaderProgram, "u_Matrix");

    // get handle to shape's transformation matrix
    GLES20.glUniformMatrix4fv(shaderMatrix, 1, false, vpMatrix, 0);

    // Prepare the triangle coordinate data
    GLES20.glEnableVertexAttribArray(shaderPosition);
    GLES20.glVertexAttribPointer(shaderPosition, 3, GLES20.GL_FLOAT, false, 0, vertexBuffer);

    // Draw the object to the screen GL_UNSIGNED_BYTE
    GLES20.glDrawElements(GLES20.GL_TRIANGLES, orderBuffer.capacity(), GLES20.GL_UNSIGNED_BYTE, orderBuffer);
    GLES20.glDisableVertexAttribArray(shaderPosition); // Free the position in shader
}

I think this code should be perfect because I got it from an OpenGL for beginners book. My problem now is that it looks like this if I render the SkyBox to the screen. I initialize my Camera with this code and here you have also the code for my touch event. If my considerations are right this should produce a circle around the origin so I can see all sides of the SkyBox.

private float angle = 90;

Matrix.setLookAtM(data, 0,   0, 0, 0,   0, 0, -1,   0, 1, 0); // the viewMatrix
// Z+ out of screen     Z- in screen

public void onTouch()
{
    angle += 2;

    float s = (float) Math.sin(angle * Math.PI / 180);
    float c = (float) Math.cos(angle * Math.PI / 180);

    Matrix.setLookAtM(data, 0,   0, 0, 0,   c, 0, -s,   0, 1,  0); // the viewMatrix
}

The draw Method from the SkyBox is called with the data Matrix from the camera (ViewMatrix) and with disabled depthBuffer. Do you have any ideas why the SkyBox is rendered so strange? What is wrong with my code? Only to be sure that all is right with my shaders here is the code from them:

FragmentShader

precision mediump float;

uniform samplerCube u_TextureUnit;
varying vec3 v_Position;

void main()
{
    gl_FragColor = textureCube(u_TextureUnit, v_Position);
}

VertexShader

uniform mat4 u_Matrix;
attribute vec3 a_Position;
varying vec3 v_Position;

void main()
{
    v_Position = a_Position;
    v_Position.z = -v_Position.z;

    gl_Position = u_Matrix * vec4(a_Position, 1.0);
    gl_Position = gl_Position.xyww;
}


texts: How do I play multiple animations at once with an MonoGame skinned mesh?

texts:
I am working with the SkinnedMesh from this tutorial.
I am at the point where I want to let my character run (which already works), but when I press the punch key on my keyboard, I only want the upper half of the body to play the punching animations while the lower part of the model continues running. What would I need to change in this example to accomplish this effect?


texts: Unity: how to implement a sound detection ?

texts:
I want to trigger an event if an enemy (or player) can hear a sound generated from other enemy/player.

How to implement a sound detection system ?

Thanks


texts: Rectangular area light illuminance - colour banding

texts:
I'm currently working on an implementation of rectangular area lights but I am having some issues with the illuminance calculation, which gives me serious colour banding across the entire lit area. I'm using the paper published by DICE, "Moving Frostbite to Physically Based Rendering" (http://www.frostbite.com/2014/11/moving-frostbite-to-pbr/) as my base for implementation (Listing 12).

This is the relevant code used:

Solid angle of the rectangle

#define M_PI 3.14159265358979323846
float RectangleSolidAngle(vec3 worldPos, vec3 p0, vec3 p1, vec3 p2, vec3 p3)
{
    vec3 v0 = p0 - worldPos;
    vec3 v1 = p1 - worldPos;
    vec3 v2 = p2 - worldPos;
    vec3 v3 = p3 - worldPos;

    vec3 n0 = normalize(cross(v0, v1));
    vec3 n1 = normalize(cross(v1, v2));
    vec3 n2 = normalize(cross(v2, v3));
    vec3 n3 = normalize(cross(v3, v0));

    float g0 = acos(dot(-n0, n1));
    float g1 = acos(dot(-n1, n2));
    float g2 = acos(dot(-n2, n3));
    float g3 = acos(dot(-n3, n0));

    return g0 + g1 + g2 + g3 - 2.0f * M_PI;
}

Illuminance calculation

float RectangleIlluminance(vec3 worldPos, vec3 worldNormal, AreaLightData lightSource)
{
    float result = 0.0f;

    if (dot((worldPos - lightSource.position), lightSource.normal) > 0.0f)
    {
        float hWidth = lightSource.halfWidth;
        float hHeight = lightSource.halfHeight;

        vec3 p0 = lightSource.position + lightSource.right * -hWidth + lightSource.up * hHeight;
        vec3 p1 = lightSource.position + lightSource.right * -hWidth + lightSource.up * -hHeight;
        vec3 p2 = lightSource.position + lightSource.right * hWidth + lightSource.up * -hHeight;
        vec3 p3 = lightSource.position + lightSource.right * hWidth + lightSource.up * hHeight;

        float solidAngle = RectangleSolidAngle(worldPos, p0, p1, p2,    p3);

        float illuminance = solidAngle * 0.2f * (
                            Saturate(dot(normalize(p0 - worldPos), worldNormal)) +
                            Saturate(dot(normalize(p1 - worldPos), worldNormal)) +
                            Saturate(dot(normalize(p2 - worldPos), worldNormal)) +
                            Saturate(dot(normalize(p3 - worldPos), worldNormal)) +
                            Saturate(dot(normalize(lightSource.position - worldPos), worldNormal)));

        result = illuminance;
    }

    return result;
}

The paper mentions some level of banding but it should not be on the level which I am currently getting, which can be seen in motion in this video: https://youtu.be/gmkOOxIYc9s .
These images show the illuminance without shadows or anything.

From what I can gather from the paper, the code is correct. The current solution is deferred, reconstructing position using the depth stencil texture and sampling normals from a RGBA32F texture (trying to eliminate precision issues). A directional light also seems to produce some level of banding, although not as visible as with the area light, which can be seen in the following images.

So maybe it's still just a precision issue? The code for handling my depth and position reconstruction looks like this:

uniform sampler2D gDepthStencil;

vec4 ReconstructWSPosition(float z, vec2 uv_f)
{
     vec4 sPos = vec4(uv_f * 2.0f - 1.0f, z, 1.0f);
     sPos = gInvProjView * sPos;
     return vec4((sPos.xyz / sPos.w ), sPos.w);
}

void main()
{
    ivec2 pixel = ivec2(gl_GlobalInvocationID.xy);
    float depth = texelFetch(gDepthStencil, pixel, 0).r * 2.0f - 1.0f;
    vec4 wPosition = ReconstructWSPosition(depth, uv);
}

Which to me looks correct, but I might be missing something. Any other ideas or suggestions? Maybe a matter of tonemapping/HDR problems?


texts:
I have gotten into quite a bit of trouble getting my rendering correct in my tile based 2D game.

  This kind of shader is surprisingly annoying to write, I've heard (we used it in one of our 3D games and kept running into unsightly edge cases). One thing you might want to consider is encoding the outline directly into the sprite texture with a specific color like (0, 255, 255, 0), and just have the shader transform that color when the sprite is selected. Then the shader is a trivial color change, and you have a high level of artist control over the outline and any details you want. https://gamedev.stackexchange.com/a/3822/25297 by "Joe Wreschnig"

I'm trying to do as Joe Wreschnig suggests.

It works fine for the color part, for example if the HighlightState of an object is set to None, then I render the outline transparent so you can not see it.

If the HighlightState is Friendly then i render it as LighGreen, Enemy is Red and so on, the color switching is done with a parameter in the shader as I wanted to draw the objects in one batch (because I have to sort the sprites on Y position to render from TOP to BOTTOM to make sure that a tall object on a tile below another one is rendered on top of the one above).

However, this is where the trouble occurs. I need to change an Effect Parameter depending on the HighlightState of the object that is to be drawn. If I render with any SpriteSortMode other than SpriteSortMode.Immediate, every object will get the outline color of the last rendered object (since it is batched). Sadly, SpriteSortMode.Immediate is not a choice since there can be quite many objects on the screen at one time.

To avoid the issue with the same color upon rendering all the objects as one batch, I thought, why not split the object list into many, one for each HighlightState? This worked terrific, except for one small issue. The Y sorting. If I render them as separate batches, there is no way to tell that one object in one batch should be placed behind another in a different batch or vice versa, which makes me wonder if it feasible to render the outline using a shader or if I have to resort to two sprites per sprite, one slightly enlarged white sprite(color tinted) rendered behind the first one to fake a highlight..

How would I solve this issue in the best manner? If you need code, I will post it but the problem is not really the code I guess, more like the logic itself.

EDIT (SOLUTION):

Based on Nathan's(THANK YOU) answer I managed to implement a shader that can handle different color outlines depending on the state of the object, meaning if it is friendly, an enemy etc.

If you run into this problem yourself, trying to set parameters for each sprite drawn in a single batch and you notice that you only get the last set parameters for ALL the sprites in the batch, it probably be solved.

I for example, wanted to set the outline color individually for each sprite and it worked great using the SpriteBatch.Draw's Color parameter (which sets the vertex color in the VertexDeclaration I assume), I could then use that color in my pixel shader to set the correct outline color.


texts: Wwise with Unity Rigidbody 2d or Collider 2d

texts: I'm half way in making a 2D game in Unity and found that Wwise needed the game objects to have a normal 3D RigidBody, since that's quite some work to replace everything, is there any way around?


texts:
I'm trying to create a minimap for my game but am having an issue.

I'm using Direct2D as the graphics API and have a ID2D1Bitmap* which contains the pixel data for the loaded area of the world.

I'd like the minimap to be around 100 x 100 pixels but the ID2D1Bitmap* contains about 3500 x 3500 of pixel data. When I try to render 3500 x 3500 pixels in a 100 x 100 pixel area, the image becomes very distorted and unpleasant.

In most cases, I thought this was solved by generating a mipmap chain but I don't see any options like this offered by Direct2D.

How can I create a clear minimap using DirectX?


texts: How do I properly apply root motion when using a blender exported FBX in Unity?

texts:
So I realize the common way for animations to be done is in-place with sliding feet, then control the animation playback to coincide with the character's feet, etc. However, given a scenario such as a chess game, where you'd want to play an animation of the chess piece moving forward, then when it stops you'd want its root position updated so the next animation that played would start from the new "square." Note that this is just an example, and that the same requirement could be in place for a person doing a ground roll, a blobular mass moving forward, etc.
   Rather than try to type everything I tried here, I have put together a short 8 minute screencap walking through the exact steps I took to replicate the issue in Blender 2.7 and Unity 5.

http://youtu.be/BZll5aisY7k

Basically, the "Apply root motion" option does not work as expected (or at least as I expected). in the end, I'm looking fir a viable way of doing in-place animation in Blender and getting the root motion to be properly applied in Unity.

Let me know if you need any specifics, thanks!

EDIT: A (rather lengthy) tutorial on the 'right way' to do it. I geared it towards novice-level users, so it goes through the modeling, rigging, animating, exporting, and Unity steps, but if you're here looking for the solution to this question, there are annotations pointing to the different sections.
https://www.youtube.com/watch?v=yKP2Qy-yKhE


texts: In the Unity Editor, how to push a parent's transform down to its children?

texts:
I've inherited a Unity scene with quite a deep object hierarchy. Some GameObjects in the hierarchy don't have any geometry of their own, and just exist to group their children and apply a MonoBehaviour to all of their children. Because of the way the scene was authored, some of these objects have arbitrary transforms, which makes it hard to edit the child transforms, to align the children with other objects outside the group.

As a one-off operation in the editor, I'd like to reset these objects' transforms, without changing the world-space positions and orientations of the children. Put another way, I'd like to push the effect of the transform down to the children.

What's the easiest way to achieve this in the editor? I've seen a lot of questions from people who want to achieve this in code, to have the effect of detaching the parent and child transforms while keeping the relationship, but that's not what I want. I'm just looking for a one-off, manual operation to make my scene file easier to edit.


texts: Designing Efficient 2D Collision for Topdown Shooter

texts:
This makes it the first time I'm posting here, so apologies if I stumble over beloved conventions.

Currently, I'm trying to figure out how I want to handle collisions for a large number of entities on screen (a bullet hell, top-down shooter). I've done a prototype of the game with some friends in the past before and we reached about 300 circular entities (a point with a radius "hitbox") checked against 3 every 1/60 seconds before considerable performance drops. The implementation was cringe worthy; due to lack of experience and a very stringent deadline, we didn't have time to do anything but a brute force distance check with each entity, making 900 pythagorean calculations per game loop.

This time I'd like to approach it with some intelligence. Since I'm simply checking for collision and not retaining any kind of directional information, I've managed to come up with two strategies. Unfortunately, they have their benefits and drawbacks:

Localized Checking - Essentially, creating a 2D array and checking only cells that the 3 entities exist in. The problem with this is that edge cases become an issue - say, if an allied entity is on the edge of a cell and an enemy entity is on the adjacent edge of an adjacent cell, I should have to check both, meaning there would be additional adjacent cell checks. While I can overcome this with a mandated "all cells that share a vertex" check and reduce the size of the cells to [standard entity radius * 2], it restricts the size of entities or forces me to use a separate system of checking for larger-than-standard entities. Obviously, avoiding this would be ideal.

More importantly, while this drastically lowers calculations made during collision detection, the reassignment of an entity to another cell due to movement would create a computational step on all moving entities (most of them) during each iteration of the game loop. Furthermore, an additional call must be made to move an object from one cell to another when it has to migrate into another cell, which will be much more common as the cell size drops. This is not ideal.

Mathematical Checking - The theory goes that if we think of bullet patterns not as separate entities but as mathematical formulas expressed as the intersection of equations (linear, quadratic, etc.) and a sinusoidal function (determining position of an entity based on the y position on that function), checking would be simplified to 3 entities against the sum of all formulas present. Unfortunately, I lack the mathematical background to do this. Furthermore, designing bullet patterns becomes a giant headache, so the cost of designing levels rises (and I am of the opinion that the most expensive work is that performed by humans).

What's more, if we take a basic curved formula such as a hyperbola, it is incredibly difficult to keep entities perfectly circular along the curves. Without a really good grasp of math, entities would appear oblong or pinched as the entity moves across the curve. This is extremely difficult to graphically represent without doing it dynamically, which would limit the visual vocabulary I am able to utilize. Also not ideal.

I'm not exactly sure how I'd like to proceed with this. Any thoughts out there? Standards that I've managed to miss?


texts: Rotate the player in a certain way that makes it look like he is sliding

texts:
I'm trying to make my first game in Unity: a 3d platformer inspired by the classic Crash Bandicoot games.
I've managed to make most of the movement with the character control script below. However, I don't know how I can do a slide/crouch.
What I want to do is to rotate and move the player down closer to the ground and give him some more speed that decreases over time until he reaches a normal waking state.

I thought about making the player rotate on a specific axis but when he turns the axis doesn't change so now I'm kind of lost in what to do.
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{

    public CharacterController controller;

    public float speed = 10f;

    //turnning smoothness

    public float turnSmoothTime = 0.1f;
    float turnSmoothVelocity;

    //jump controls

    public float jumpHeight = 3f;
    public float gravity = -29.43f;
    Vector3 velocity;
    bool isGrounded;

    //gravity check
    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;

    // Update is called once per frame
    void Update()
    {
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

        if(isGrounded && velocity.y < 0)
        {
            velocity.y = -1f;
        }

       //player movement on both axis

        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");

        Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;

        velocity.y += gravity * Time.deltaTime;
        controller.Move(velocity * Time.deltaTime);

        if (Input.GetKeyDown("space") && isGrounded)
        {
            velocity.y += Mathf.Sqrt(jumpHeight * -2f * gravity);
        }

        if (direction.magnitude >= 0.1f)
        {
            //player turning depending on where moving

            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
            transform.rotation = Quaternion.Euler(0f, angle, 0f);

            controller.Move(direction * speed * Time.deltaTime);

        }

    }
}


texts: Best approach to get clicked objects from a display list (2D)

texts:
I'm implementing a display list to manage my visuals on screen.

I want to know which object is clicked.

My objects already have z-order variable.

With my current knowledge (almost nothing) the only thing which comes to my mind is make a linear search and get all the objects which contains the clicked point. And then select the object with the highest z-order. But I know there are far better approaches.

I think it's something with trees (binary search?).
- container display objects and search recursively?

just don't know where to start looking, for this concrete case. Any hint link or concrete solution is welcome.


texts: How to fade determine properties to fade materials out for the line renderer

texts:
I am trying to fade consistently fade a Line Renderer by adjusting the color property of it's material. I got the code I'm using from the accepted answer to How can I fade a game object in and out over a specified duration?.
When I used the Default-Line material for the line renderer I got the following error:

  Assertion failed: Material doesn't have a color property '_Color'
  UnityEngine.Material:get_color()

When I used the Default-Diffuse material, nothing happened.

Finally, when I used the Sprites-Default material it worked perfectly.

How can I make the line renderer fade out consistently based on different material?


texts: Get GameObject which instantiated me in Unity

texts:
How can I get a GameObject from another GameObject? If I know, that the GameObject I want to get instantiated(using function Instantite()) the GameObject from which I want to get it.

If there is no solution, how can I get the direction in which should move the instantiated bullet? I mean should it be 1 or -1.


texts: Projected Light Cookie Has Its Texture Edges Instead of Spotlight Circular Edges

texts:
The projected light of Unity Spotlight on a flat surface is almost a circle:

But when I add this light cookie:

It renders the following projection:

I expect the projected image takes the spotlight's edges.

Unity version: 2017.4.11f1

light source settings:

Light cookie settings:

Please note that I've already added black padding to the light cookie.


texts: Lerping to a center point while in motion

texts:
I have an enemy that initially flies in a circular motion, while facing away from the center point. This is how I achieve that:

position.Y = (float)(Math.Cos(timeAlive * MathHelper.PiOver4) * radius + origin.Y);
position.X = (float)(Math.Sin(timeAlive * MathHelper.PiOver4) * radius + origin.X);

if (timeAlive < 5)
{
   angle = (float)Math.Atan((0 - position.X) / (0 - position.Y));

   if (0 < position.Y)
      RotationMatrix = Matrix.CreateRotationX(MathHelper.PiOver2) * Matrix.CreateRotationZ(-1 * angle);
   else
      RotationMatrix = Matrix.CreateRotationX(MathHelper.PiOver2) * Matrix.CreateRotationZ(MathHelper.Pi - angle);
}

That part works just fine. After five seconds of this, I want the enemy to turn inward, facing the center point. However, I've been trying to lerp to that point, since I don't want it to simply jump to the new rotation. Here's my code for trying to do that:

else
{
   float newAngle = -1 * (float)Math.Atan((0 - position.X) / (0 - position.Y));
   angle = MathHelper.Lerp(angle, newAngle, (float)gameTime.ElapsedGameTime.Milliseconds / 1000);

if (0 < position.Y)
   RotationMatrix = Matrix.CreateRotationX(MathHelper.PiOver2) * Matrix.CreateRotationZ(MathHelper.Pi - angle);
else
   RotationMatrix = Matrix.CreateRotationX(MathHelper.PiOver2) * Matrix.CreateRotationZ(-1 * angle);
}

That doesn't work so fine. It seems like it's going to at first, but then it just sort of skips around. How can I achieve what I want here?


texts: Is a large-scale simulation of movable land possible?

texts:
I was recently reading about a nuclear waste containment area buried far beneath the desert in New Mexico (WIPP), and upon looking at diagrams I wondered if it would be possible to create something of the sort in a game/sandbox.

Imagine a square mile of land with packed yet completely movable sand/soil that can be excavated using any tools you see necessary. Under the soil would be rock that can be drilled or broken through just as in real life. Think Minecraft, but without the blocks and instead particles that behave near how they would in the real world.

What's stopping games/sims like this from being created, and is there any prospect of a realistic earth-moving sandbox in the future?


texts: Best way to prevent UIPanGestureRecognizer from firing when moving sprites in cocos2d

texts:
Im using UIPanGestureRecognizer in my cocos2d game to do drag and drop of sprites. I have a row of sprites and when I drag a sprite on top of another one, the sprite underneath it and any other sprites between should shift left or right out of the way to allow space to drop the currently selected sprite.

This is working ok, however, if I am too quick at dragging the sprite around the screen, this triggers another round of the UIPanGestureRecognizer's callback method, and screws up the logic, as the sprites are in-between shifting.

I need a way to freeze the callback from firing, whilst the other sprites are shifting, then once they have finished moving, re-enable the callback to fire.

Whats the best way to do this?


texts: How can I detect that the mouse is over a button so that I can display some UI text?

texts:
I have a scene, where a panel containing 24 buttons. I need to show some piece of text when hover a mouse cursor over the button. For example, for detecting clicks, I'm using onClick event trigger, but I can't find anything related to something like a onHover event. I have Googled and read the docs, but could not find anything. Can anybody help me with that?

Code:

var button = panel.GetChild(0).GetComponent<Button>();


texts:
Won't it slow my game if I use FreeType lib and convert 2 fonts from .ttf instead of using preloaded BitmapFont .png? Or may be FreeType so fast, that I can use fonts both ways?
All I need is to change color and size of my text.
P.S. I use 3 fonts in my project


texts: Component based architecture in TypeScript

texts:
I'm doing a game using Phaser with TypeScript. I want to implement a component based architecture for Actors.
What I'm trying to achieve is this:

var component:AwesomeComponent = actor.getComponent<AwesomeComponent>();

I know there's a workaround by constructing objects of type T. But I don't like it because I'd probably need to define tons of different constructors to represent all differents kinds of components.

What I'm doing so far is passing a string with the type (of course a number would be better, but I'm still prototyping):

getComponent<T>(componentType:string): T
{
    for (let i = 0; i < this.components.length; i++)
    {
        if (componentType == this.components[i].componentType)
        {
            return <T><any>this.components[i];
        }
    }
    return undefined;
}

It works, but the result is not good, you have to type the class name twice:

var animComp = actor.getComponent<AnimationComponent>("AnimationComponent");

Any suggestions on how to solve it?

Thank you for your time!


texts: Is it worthwhile investing time learning Unreal Script when UDK 4 will be replacing it with C++?

texts: Should I continue to get more familiar with Unreal Script or just wait for UDK4 with C++?


texts: What is "Rapid" in reference to the MSN Games GDK?

texts:
I have herd a little talk about the MSN Games GDK lately, and what wondering what Rapid was.

It sounds like some sort of testing environment, is this true? How can I get access to it? Or find out more about it?


texts: Why isn't occlusion culling working correctly?

texts: Occlusion culling doesn't seem to be behaving the way I was expecting. I've set the yellow wall as static and have baked an occlusion map using the occlusion window in unity. However when visualising the occlusion - the red cylinder behind the wall is still visible despite not being seen in the camera preview. Any clue what I'm doing wrong?


texts:
When I start a blank project I have noticed that I get one t2dSceneGraph and one t2dTileMap (under the project tab). I selected the t2dTileMap and gave it a name 'tilemap'.

In my game.cs function startGame I added

%LayerCount = tilemap.getTileLayerCount();

...but when I execute the project and inspect the variable %LayerCount in Torsion I first of all get an error:

Unable to find object: 'tilemap' attempting to call function 'getTileLayerCount'

How do I access the default t2dTileMap?


texts: Mix of Procedural and Manual level design / creation in UE4

texts:
I'm trying to design a maze using a mix of procedural and manual generation. I have the maze already generated and would like to place other objects in the maze manually in the editor. The issue is the maze object is created on BeginPlay and so I'm unable to view it in the Editor itself while dragging the object to the Outliner. Any suggestions?

I'm thinking of doing something in the Construction Script or the object Constructor but not not sure if that would be the way to go.

I'm still getting familiar with the Engine code base and only have a little experience in Maya or Blender since I'm a programmer.


texts:
Is there a possiblilty to select the polygons of the model that the brush will apply to? This is what happens when I paint the insides of a house.

Inside:

Outside:

As if the absence of WASD Camera controls wasn't bad enough, every brush stroke smears up faces around it. Painting indoor environments is a pain in Substance Painter but I don't see any other program that can do the job.


texts: How do I iterate over map tiles visible within a rectangular portion of an isometric view?

texts:
I have an isometric map broken up into terrain tiles.
the area of the map on-screen is given by a rectangle rotated 45 degrees (in red below).

Given the position of the corners of the visible rectangle,
how would I go about iterating over all visible tiles (shaded),
such that no tile down or to the right of tile A is iterated upon before tile A


texts: Apply Secondary Normal Map to Standard Shader by Script

texts:
I have a material with an existing normal map.  I added a secondary normal map to represent damage via script.  I assign to the appropriate texture property _DetailNormalMap, assign the required keywords, _DETAIL_MULX2 _NORMALMAP, and set a scale via _DetailNormalMapScale.
I have ensured there is a material in the resources folder with the same settings, to ensure that the variant is available in builds, though this shouldn't be an issue in editor.
However, it does not show up, at least not initially:

If I do darn near anything with it in the editor, even alt+tabbing, will cause the secondary normal map to show up:

I recall back in the day keywords were the issue, but I clearly have done that. I recall this working in the past. I am still using Unity 2018.4.6f1, so I would be surprised if there are any major changes.
Thanks for your assistance.


texts: "ui is not declared in current scope" error

texts:
I just started development for a game I have to design for school. When using gd in the script to make the character move right I get an error:

extends KinematicBody2D

var motion = Vector2()

func _physics_process(delta):

    if input.is_action_pressed(ui.right):
        motion.x = 100

    move_and_slide(motion)

This is the line that is giving me problems

if input.is_action_pressed(ui.right):

and it keeps saying that ui is not declared in the current scope


texts: Using the DTLS protocol for multiplayer games

texts:
I am considering using the DTLS protocol for my online multiplayer game. For those who don't know, it is essentially a port of TLS to UDP datagrams.

According to this paper, the main overhead of the protocol is in the handshake phase, which took 950 ms in their tests. However, this study (broken link; see copy on archive.org) indicates that during actual encrypted transport, there is often less than 1 millisecond of delay.

This sounds like a godsend for realtime games. It is a low latency, highly secure encrypted channel that operates over UDP. It provides reliability and protection for the handshake phase, then steps out of the way. Yet, I have never heard of it being used in a game before, even though the RFC spec was written in 2006 and it's implemented in OpenSSL.

Why doesn't every game use it?


texts: Why are microtransactions more or less universally hated?

texts:
In many games nowadays we see micro-transactions in the form of in-game purchases. The benefits of these purchases can be anything from disabling ads, cosmetic unlocks, or in-game currency. Here's an example:

That is of course an extreme example of pricey micro-transactions. But it seems that even more "reasonable" in-game purchases are more or less despised by the community as a whole, even though they are there to help monetize the game and without them the game wouldn't exist.

So why are micro-transactions so despised?


texts: Transform.LookAt rotates the sprite and collision not triggering

texts:
I've applied the below script to a gun object to instantiate bullets to the direction of the mouse position.

The bullet collision is not getting triggered since the bullet has been rotated.

How to solve this.

void FixedUpdate()
    {

        mousePosition = Input.mousePosition;
        mousePosition.z = 0.0f;

        //Gun Rotation

        objectPosition = Camera.main.WorldToScreenPoint(transform.position);

        mousePosition.x = mousePosition.x - objectPosition.x;
        mousePosition.y = mousePosition.y - objectPosition.y;

        angle = Mathf.Atan2(mousePosition.y, mousePosition.x) * Mathf.Rad2Deg - 90;

        Vector3 rotationVector = new Vector3(0, 0, angle);
        transform.rotation = Quaternion.Euler(rotationVector);

        //Gun Rotation

        if (Input.GetMouseButtonDown(0))
        {
            GameObject bullet = (GameObject)Instantiate(bulletObject, transform.position, transform.rotation);
            bullet.transform.LookAt(mousePosition);
            bullet.GetComponent<Rigidbody2D>().AddForce(bullet.transform.forward * bulletSpeed);
        }

    }


texts: Modifying z axis position of a canvas and adapting it to camera

texts:
I have a camera with y rotation of 0.

And i have a canvas with position value of (0f,76.29f,41.82f).
The size value of the canvas is (194.1f,307.8f).
I want to modify the z value of the canvas to -10.

public Canvas textcanvas;
void Start () {
textcanvas.anchoredPosition = new Vector3 (0f, 24.5f, -10f);
}

But i get an error "error CS1061: Type UnityEngine.Canvas' does not contain a definition foranchoredPosition' and no extension method anchoredPosition' of typeUnityEngine.Canvas' could be found. Are you missing an assembly reference?"

Also, when i succeed moving the canvas, does the size of it adapting to the camera automatically?


texts: When does a parallel-tasks engine becomes a good solution?

texts:
I'm often tempted to break the game I'm working on to try a parallel-tasks based architecture, but that don't seem a big requirement for my project so I avoid this for the moment. I'm planning to just try it in a toy project first, to "play with the concept."

Now, what I'm asking is, as lot of (non AAA) games do not require really really high performance, it feels like using a task-based engine isn't worth bothering until... what cases?

At the moment, I'm only guessing that it's necessary when you really need to exploit maximum performance of the (multi-core) hardware. Is there other cases where it's a good idea to use task-based engine? Or maybe, for new projects, it's always good to start with a task-based engine?


texts: How to get collision area within a circle in libgdx

texts:
I have a ball inside of a multi-colored circle, the ball will hit the inner area of the circle like this bellow circle image

And the Circle will be rotated clockwise or anti-clockwise based on user input.
How would I know, where the ball hit the Big Colored circle.

I just need to identify in which color of my circle sprite has made a collision with the ball.

I have tried a lot, googled a lot but still, the solution has not been found yet.

Experts, please help me.


texts: Unity assembly files missing from "Temp/bin/Debug"

texts:
I'm trying to use VS Code on a Mac with Unity and C#. When I try to open a Unity project in VS Code, it can't load Assembly.dll* files from few locations which are defined by default in .csproj files; "Temp\bin\Debug\".

When I check the *Temp\bin\Debug* paths, while Unity is running, they are empty; they doe not contain the assembly files, where I assume they should. The files are in "Library/ScriptAssemblies". Moving them is not an option, because I would have to do that manually every time I change sth. in any script file. Changing the path in the .csproj files is also not a good idea, because those files get rewritten every time you open a project in Unity.

This issue causes lot of problems in the editor:

  [WARNING:OmniSharp#MSBuild] Unable to resolve assembly '/[...]/Temp/bin/Debug/Assembly-CSharp-firstpass.dll'
  [INFORMATION:OmniSharp#MSBuild] Update project: Assembly-CSharp-Editor-firstpass
  [WARNING:OmniSharp#MSBuild] Unable to resolve assembly '/[...]/Temp/bin/Debug/Assembly-CSharp-firstpass.dll'
  [INFORMATION:OmniSharp#MSBuild] Update project: Assembly-CSharp-Editor
  [WARNING:OmniSharp#MSBuild] Unable to resolve assembly '/[...]/Temp/bin/Debug/Assembly-CSharp-Editor-firstpass.dll'
  [WARNING:OmniSharp#MSBuild] Unable to resolve assembly '/[...]/Temp/bin/Debug/Assembly-CSharp-firstpass.dll'

All type references coming from my custom scripts and the UnityEngine namespace are missing, and highlighted as errors:

However, intellisense seems to be working fine for UnityEngine types:

I tried to reinstall MonoDevelop it a few times, including a brew and downloadable package. MonoDevelop seems to be installed properly:

  $ mono --version
   Mono JIT compiler version 4.6.2 (mono-4.6.0-branch/ac9e222 Wed Dec 14 17:02:09 EST 2016)
   Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
    TLS:           normal
    SIGSEGV:       altstack
    Notification:  kqueue
    Architecture:  x86
    Disabled:      none
    Misc:          softdebug
    LLVM:          yes(3.6.0svn-mono-master/8b1520c)
    GC:            sgen

.NET works as well:

  $ dotnet --version
  1.0.0-preview2-1-003177

How do I fix this?


texts:
By "going full AABB" I mean using only AABBs for all of your objects (both dynamic and static), with dynamic objects colliding both with each other and static objects. In what specific ways does this simplify physics calculations? Are there any special techniques that require a world made entirely of AABBs? Some way to, say, remove the need for TOI-ordering (or similar) by taking advantage of that fact that all objects are AABBs?

In particular I'm looking for specific large-scale benefits, not just small things like collision detection being slightly faster. There seem to be quite a few games that use only AABBs, like Minecraft for example, so there must be a significant benefit to it or they wouldn't be doing it. Only thing I can think of is getting to do position/velocity corrections per-axis, though I'm not sure how one would exploit that to its full potential.


texts: Determining the probability of a successful attack based on the equipped weapon?

texts:
Take this example, a player has a sword composed of the handle and a blade. Together, they generate a strength of X and that combination adds qualitative attributes (induce more damage to fire creatures). If the player encounter 2 enemies, both at same defence level, but one is made of fire. Then, I need to calculate the probability of hitting the enemies, knowing that it may be higher for the fire creature.

Given the example, I need to calculate the:

Weapon's strength, by combining different parts?
Probability of the outcome of an encounter?
Inclusion of qualitative attributes in the calculation?

So far, I though of the following and I am not sure if it is good enough.

For the weapon, I would associate a value to each component. Then, I would determine that the handle represents 25% of the total strength; allowing me to calculate the total strength
The enemy will get a defence value.
For the encounter, I would generate a random number between 1 and the (player strength)+(enemy defence). If that number is higher than the enemy's defence, than it's a hit. This means that if they are equal, then it's 50% chance of success.
For the physical attributes, if the enemies has a weakness towards an elements, then I would deduct a certain value of he's defence before calculating the probability.

Is this a viable approach? If not, what would be a suitable implementation? or where can I find more ressources on these kinds of problems.


texts: Handle a canvas in a windows form application

texts:
I want to create a level editor, i've started it on XNA but finally it would be better using a WindowsFormApplication.

Here is the layout that i want to achieve:

BLUE -> Windows form control

PURPLE -> Canvas, handled differently (Yeah, Windows forms controls too, but not for the same use of it)

I have a problem though, how to render the Canvas in a proper way without using a thread ?

(Look at my other thread here in stackoverflow: https://stackoverflow.com/questions/29463393/access-object-from-other-thread?noredirect=1)

I thought about a timer, but it seemed to be a bad idea for me (Refreshrate).

Ideally a thread would be nice but Windows doesn't like the fact that you want to interact between thread so it's messed up to be polite.

If you know how to achieve that, well, thanks ! :)


texts: Unity 2017.3.of3 Raycast2D randomly misses objects

texts:
2d up down platformer.  Character has 2 Rays(one left one right) going down, when either Ray's hit distance hits between -1 and 1 it should call a function which will change character direction from down to up.  Works 1, 2, 3, 4, sometimes 6, sometimes into the teens times then character goes through the obstacle got placing character over an obstacle and hitting play with no changes gave a different amount of time before falling through the obstacle.  I have tried changing the Time.time in fixedUpdate, placed movement in last update, varying degrees of success, I will post the current version of code, but it has gone through several revisions any ideas accepted.  thanks

[RequireComponent (typeof (BoxCollider2D))]
public class YowiController : MonoBehaviour {

  BoxCollider2D yowiCollider;
  Vector2 rayDir, leftRay, rightRay, rayOrigin;

  public AudioSource jumpSound;

  bool jump;
  bool bounce;

  public float upTime;
  float looseTime;

  float bounceCount = 0;
  float gravity = 3f;
  float bounceHeight = 5f;
  float movementSpeed = 2f;
  float bounceTime = .03f;

  void Start () {
    yowiCollider = GetComponent<BoxCollider2D> ();
    rayDir = new Vector2 (0, -1);
    jump = false;
    bounce = false;
  }

  void Update () {
  }

  private void LateUpdate () {
    movement ();
  }

  void movement () {
    drawRays ();
    if (Input.GetKey (KeyCode.RightArrow)) {
      transform.Translate (Vector2.right * Time.deltaTime * movementSpeed);
    }
    if (Input.GetKey (KeyCode.LeftArrow)) {
      transform.Translate (Vector2.left * Time.deltaTime * movementSpeed);
    }
    if (!bounce) {
      transform.Translate (Vector2.down * Time.deltaTime * gravity);
      gravity += .02f;
    } else {
      Bounce ();
    }
  }

  void Bounce () {
    transform.Translate (Vector2.up * Time.deltaTime * bounceHeight);
    looseTime = bounceTime / 2;
    if (upTime < looseTime) {
      bounceHeight += .01f;
      looseTime--;
    } else {
      bounceHeight -= .01f;
    }
  }

  void drawRays () {
    Bounds bounds = yowiCollider.bounds;
    leftRay = new Vector2 (bounds.min.x, bounds.min.y);
    rightRay = new Vector2 (bounds.max.x, bounds.min.y);
    RaycastHit2D leftHit = Physics2D.Raycast (leftRay, rayDir * -1, .05f, 1 << 9);
    RaycastHit2D rightHit = Physics2D.Raycast (rightRay, rayDir * -1, .05f, 1 << 9);
    if (leftHit || rightHit) {
      RayHit (leftHit, rightHit);
    }
  }

  void RayHit (RaycastHit2D leftHit, RaycastHit2D rightHit) {
    if ((leftHit.distance < 1.1f) && (leftHit.distance > -1.1f)) {
      bounce = true;
      StartCoroutine (Bouncing ());
    } else if (rightHit.distance < 1.1f && rightHit.distance > -1.1f) {
      bounce = true;
      StartCoroutine (Bouncing ());
    } else {
      print ("No Joy");
    }
  }

  IEnumerator Bouncing () {
    yield return new WaitForSeconds (bounceTime);
    bounce = false;
  }
}


texts: Importing FBX model with updated textures into unity creating duplicate textures when using "Extract Textures"

texts: I am trying to figure out the best way to update models, textures and materials. I have a city model (city.fbx) that comes into unity with baked textures and materials from C4D. I bring it in to unity, extract the textures into a local folder called  "Textures" and extract the materials into a local folder called "Materials". Everything is remapped automatically by Unity. Let's say I then update the model using a file syncing program which replaces city.fbx with the same model, but with updated textures. In this case, the textures have been updated to green, where as before they were blue textures. when I extract the textures into the local "Textures" folder, unity creates duplicate textures instead of replacing the old ones. So we now have buildingtexture (the old blue texture) & buildingtexture 1 (a new green texture) - what is the  correct way to import the updated model so as to avoid this?


texts:
How would you go about making ground correction for a platformer but upside down(reversed gravity)? I used this formula: P.Y+=(P.Y-2)%8-1 but the character just keeps bumping up and down like a pogo stick.
By ground correction I mean checking if the player is inside a solid tile while falling and moving him up (or down in my case) until he isn't.
if pd.dy<0 then
pd.f=true
pd.g=false
pd.j=false
if col_map(pd,"up",1) then
pd.f=false
pd.dy=0
pd.g=true
pd.y+=(pd.y-1)%8
end
elseif pd.dy>0 then
pd.j=true
if col_map(pd,"down",1) then
pd.dy=0
end
end


texts: Creating pixel art / animation with flash

texts:
I have a friend that was the one creating graphics for my games. He left the town for some months (work, sigh) and I have tried to get in contact with him but it is impossible right now. Last talk I had with him he explained me that the graphics (2D) he did for my games were all made with flash and also the animations.

I can see why my pal does everything in flash: we develope for several movile platforms with different resolutions and having everything in vector format is nice.

My question is: How is he doing pixel art with flash? I recall he told me he was doing everything with vectors and later exporting to bitmpap, but, is it possible to do this with flash? Can't see how to do the pixel art feeling with vectors. If anyone could help here I would be really greateful.

Thanks in advance.