texts: Central logic in entity-component-architectures

texts:
I've build a architecture based on the entity-component-system-idea.
So I got

Components - Just store Data
Systems - Operates isolated on Components
Scripts - Which are just objects from type Script and attached to a ScriptComponent. A ScriptSystem will execute the init() and update() functions on the scripts then.

However, I'm wondering where to place the central game logic since the I have to check a few things about the overall game process, holding the map, counting the points, checks the points if they are enough for the end-screen, etc. ...

Should I create a single entitiy with just such a script attached to it or are there better solutions out there?


texts: How do I expose a field with a generic class to the Inspector?

texts:
I have some utilities implemented as generic classes.

I would like to have fields of these types exposed to the inspector but they appear to not display.

This test code:

[Serializable]
public class TestGenericClass<T>
{
    public string testField;

    public TestGenericClass(T testValue)
    {
        testField = testValue.ToString();
    }
}

[Serializable]
public class TestNormalClass
{
    public string testField;

    public TestNormalClass(string testValue)
    {
        testField = testValue;
    }
}

public class MonoBehaviourClass : MonoBehaviour
{
    public TestGenericClass<string> testGenericClass = new TestGenericClass<string>("generic");
    public TestNormalClass testNormalClass = new TestNormalClass("normal");
}

Produces this result:

As you can see the field for the generic class is missing.

How can I expose a field with a generic class to the inspector?


texts:
I have a scene in my game where you create your own designs by placing static meshes and manipulating their scales, positions, and rotations.

For the rotations I'm using Quaterion.AngleAxis as so:

        if (toolMode == PositioningTool.Rotate)
        {
            switch (grabbedCollider.transform.name)
            {
                case "X":
                    focus.localRotation *= Quaternion.AngleAxis(delta.x * 90 * Time.deltaTime, transform.right);
                    break;
                case "Y":
                    focus.localRotation *= Quaternion.AngleAxis(delta.x * 90 * Time.deltaTime, transform.up);
                    break;
                case "Z":
                    focus.localRotation *= Quaternion.AngleAxis(delta.x * 90 * Time.deltaTime, transform.forward);
                    break;
            }
        }

where delta is the mouse movement for that frame, focus is the object I am manipulating, and transform is the transform component of the ToolArm that the player interacts with. toolarm.position is set to focus.position every frame

my problem arises when I try to do a rotation on my x axis. my other axis will spin 360 and beyond, spinning in circles endlessly. when x axis is used, it only rotates from -90 to 90 (as seen in the unity editor). What am I doing wrong?


texts:
I've got about a year in Java experience, and would like to set up a server and client for an applet game. However, there doesn't appear to be any tutorials out there on anything like I want to use.

I would the server to be able to store an array of x and y coordinates with a player name somehow associated to them, and send them to multiple clients in a short time span. I would like the client implemented in the applet, and be able to request any player's position data.

I'd like to use UDP, because it seems to be the best option for efficient (if less reliable) transmission of data.

If anyone could give me some pointers on how to do such a project, or point me to an appropriate tutorial, I'd certainly appreciate it.


texts:
I'm writing a component-based entity system and one of the components is the entity's state, which dictates how it reacts to game events. In case anyone has experience with implementing states, how granular should they be?

To give you an idea about how granular they are in my case, I have a WalkingLeft state and a WalkingRight state (as opposed to simply a Walking state) and I fear that they might be too granular. What do you think?


texts: Does a game have to explicitly support SLI/Crossfire to take advantage of it?

texts:
This is more of a general curiosity question than a howto question. Just as the title says, do games have to explicitly support SLI/Crossfire to take advantage of multiple graphics cards or are they linked in such a way that you don't need to write extra code?

If explicit support is required, is it common for games to have this support?


texts: Taking MSAA screenshot using D3DX10SaveTextureToFile()

texts:
I have some screenshot code (pasted below) which was working fine until I enabled MSAA. The first time I tried to use this code, it complained that the texture I'm creating needed to match the sample count of the source texture. Fine- my MSAA value is 8 currently, so I set the screenshot texture to a sample count of 8 also.

Now when I try to use the code, it complains:

  ERROR: ID3D10Device::CreateTexture2D: A multisampled Texture2D cannot be bound to certain parts of the graphics pipeline, but must have at least one BindFlags bit set. The following BindFlags bits (0) cannot be set in this case: D3D10_BIND_VERTEX_BUFFER (0), D3D10_BIND_INDEX_BUFFER (0), D3D10_BIND_CONSTANT_BUFFER (0), D3D10_BIND_STREAM_OUTPUT (0)

Note- this happens when I call CreateTexture2D(). However, if I take the hint and try a BindFlag with my created texture (D3D10_BIND_RENDER_TARGET for example) I get the exact same error message when D3DX10SaveTextureToFile() is called.

Here is the code:

ID3D10Resource* pScreen;
mpRenderTargetView->GetResource( &pScreen );

HRESULT hr;

D3D10_TEXTURE2D_DESC texDesc;
texDesc.ArraySize = 1;
texDesc.BindFlags = D3D10_BIND_RENDER_TARGET;
texDesc.CPUAccessFlags = 0;
texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
texDesc.Width = (unsigned int)mWindowSize.x;
texDesc.Height = (unsigned int)mWindowSize.y;
texDesc.MipLevels = 1;
texDesc.MiscFlags = 0;
texDesc.SampleDesc.Count = 8;
texDesc.SampleDesc.Quality = 0;
texDesc.Usage = D3D10_USAGE_DEFAULT;

ID3D10Texture2D *texture;
hr = mpD3DDevice->CreateTexture2D( &texDesc, 0, &texture );
mpD3DDevice->CopyResource( texture, pScreen );

char* filename = "TestFile.dds"

D3DX10SaveTextureToFile( texture, D3DX10_IFF_DDS, filename );
texture->Release();
pScreen->Release();

I should also mention that I've tried various file formats with no success yet. This function has been a real pain in the butt so if there's a better way of doing this, I'd love to know it!


texts:
I am working on a 3D space game using OpenGL and C++ and I am planning to focus on giving the game modern, eye-catching graphics, but the more I think of it the more I realise I don't really know what makes graphics "good". Sure, I can go and play some well known AAA games and bask in the amazingly put together graphics, but I don't really know how the graphics looks good. (this is why I consider games to be an art!)

This is what I can think of now:

High quality textures
High quality models
A good lighting model
Bumpmapping + specularity mapping
High quality UI, if applicable
A wealth of not-overdone posteffects

I'm asking here in the hope of an experienced game developer who has produced games and know how they work inside and out can explain some techniques that warrant a game's graphics to look "good", and some not-well-known quirky tips. That'd be awesome.

Thanks!


texts: Using NDSLib, how to configure video modes to both print text and draw bitmaps on both screens?

texts:
In a NDS application, i'd like print text and draw bitmaps on both top and bottom screens.
I have been able to setup code to either draw bitmaps or just print text to console.

If I try to enable both at the same time i only get garbage. My guess is there is a memory conflict between VRAM banks used by console background (for storing characters sprites) and background buffer used to draw pixels on screen.

My questions is : how should i configure video modes to be able to draw text and bitmaps on top and bottom screen ? If not possible, because there is not enough memory, a solution having only text on top screen is also acceptable.

Here is code :

#include <nds.h>
#include <stdio.h>

int main() {
    PrintConsole top, bottom;

    //1) bitmap init
    videoSetMode(MODE_5_2D);
    videoSetModeSub(MODE_5_2D);
    bgInit(3, BgType_Bmp16, BgSize_B16_256x256, 0, 0);
    bgInitSub(3, BgType_Bmp16, BgSize_B16_256x256, 0, 0);

    //2) console init, incompatible with 1)
    consoleInit(&top, 0, BgType_Text4bpp, BgSize_T_256x256, 0, 0, true, true);
    consoleInit(&bottom, 0, BgType_Text4bpp, BgSize_T_256x256, 0, 0, false, true);

    while (1) {
        swiWaitForVBlank();
        //draw pixels on screens
        for (int y = 0; y < 192; y++) {
            for (int x = 0; x < 256; x++) {
                BG_GFX[x + (y << 8)] = ARGB16(1, x + y, 32, y * x);
                BG_GFX_SUB[x + (y << 8)] = ARGB16(1, 32, y, y * x);
            }
        }
        //print text to console
        consoleSelect(&top);
        printf("top");
        consoleSelect(&bottom);
        printf("bottom");
    }
    return 0;
}


texts: ContactFilter2D does not detect a trigger even with "use triggers" enabled

texts:
I'm Using Unity 2018.3.11f1 and I'm going crazy trying to understand why the "use triggers" variable of the ContactFilter2D is not having any effect and I'm always detecting only the non-trigger colliders.

The problem is just as simple as that: If I use the OverlapCollider trying to detect a collider that is not a trigger it works perfect. However, if that collider is set as trigger the "OverlapCollider" does not detect it even if I set the variable "useTriggers" of the used filter is set to true (and obviously in false the same behavious appears)

Does anyone have any clue about why it happens?

This is the code:

    ContactFilter2D filter = new ContactFilter2D();
    filter.SetLayerMask(GameManager.Instance.interactableLayers);
    filter.useTriggers = true;
    Collider2D[] results = new Collider2D[10];
    int collidersDetected = col.OverlapCollider(filter, results);

Thank you for your help in advance.


texts:
I completed my postgraduate education, and I am interested in starting my own game development company.

I have a team of six members consisting of animators and artists.

I'd like you to suggest all the requirements for starting a new company and suggest whether it would be good for me to start it or not. I have a few game concepts, and I am really passionate about it.


texts: Showing the steps of a level generation process over multiple frames

texts:
I seem to be misunderstanding part of Unity.  I'm generating a maze similar to the one here:  http://journal.stuffwithstuff.com/2014/12/21/rooms-and-mazes/

I put the whole of the generation in Update() and used a bool to ensure it only runs once.  However, right now the whole thing runs before the editor becomes available - it behaves exactly as if I had the whole thing in a Start() section.  Do I need to use coroutines to watch it build out?  In the link above, if you click the first demo box, you can watch the maze place itself and build.  I'd like to be able to see that in the scene view in Unity.  Thoughts?

Edit:

This is my Update() method currently:

void Update()
{
    while (_continue)
    {
      _continue = false;
      Dictionary<String, Tile> _dict = FetchTileList();

      Tile _wall = _dict["Wall"];

      for (int x = 0; x < width; x++)
      {
        for (int y = 0; y < height; y++)
        {
            var _go = Instantiate(_wall.gameObject, new Vector3(x, y, 0), Quaternion.identity);
        }
      }

      _addRooms();

      for (var y = 1; y < height; y += 2) {
        for (var x = 1; x < width; x += 2) {
            Vector2 pos = new Vector2(x, y);
            Rect _rect = new Rect(x, y, 1, 1);
            bool _add = true;

            foreach (var other in _rooms)
            {
                if (_rect.Overlaps(other))
                {
                    _add = false;
                }
            }

            if (_add)
            {
                _growMaze(pos);
            }
        }
      }
   }
}


texts: Adjust the Camera Viewport Rect in Unreal Engine

texts: Am new to Unreal Engine. I want to adjust the Camera Viewport  Rect so that the camera will render to half of the screen. This is achieved in Unity by changing the Camera Viewport Rect property. How can we achieve similar stuff Using Unreal Blueprint?


texts:
What is the game all about?

It's a puzzle game. I am using AndEngine to build it on Android platform (currently). I have divided the game into various World, with each World containing various Levels.

What is the Issue?

The purpose of the game is to drag-and-drop the broken pieces into the "drop" area (a.k.a. holder) and form the circle. I've developed the basic 2 levels of the game. This is the third level. Where there are 3 pieces as different objects. I've to drop all 3 pieces into the drop. The issue is how do I know that all the broken pieces have filled the holder? I'm using AndEngine for the first time and have very little idea how this can be done.
Tapping on any broken object would rotate it by 90 degrees. So there can be 4 possible solutions for each of them).

Also, the logic should hold true for any shape, any number of broken pieces, any number of holders.

Below is a picture of level 3. There are 3 pieces named 1, 2 and 3 at different positions. All the pieces must be placed inside the circle.

Ideas that I've thought about

We've thought to solve this using:

Area of the holder is filled -> But how do I programmatically do that?
Take center coordinates of each broken piece and find the distance from the center of the circle. Verify this in all the 4 conditions (all 4 rotations by 90 degree each). -> I'm trying to figure this out.
See if all the broken pieces are used in the holder area -> What if there are more than one holder?

Any technical help or any references would be really great.


texts: Camera follows player but how to stop camera moving when player moves

texts:
The player is moving automatically diagonally down the screen, and I have the camera as a child on the player. I would like the camera to always be following the player (who sometimes slows down / speeds up) as they are automatically moving, but when the player moves left and right, I don't want the whole camera view to shift with this.

I am moving the player with this:

transform.Translate(xSpeed, ySpeed, 0);

And the player can move the character with this:

Vector2 direction = new Vector2(0.2f, 0.67f);

if (Input.GetKeyDown(KeyCode.LeftArrow))
{   //transform stores the position data of the playu
    transform.Translate(direction * -distance);
}

else if (Input.GetKeyDown(KeyCode.RightArrow))
{
    transform.Translate(direction * distance);
}

However when they move with this I would like not for the camera to shift with the movement, but still continue to follow them as they move across the 2D map.

@Hash Buoy I can't add comments yet, but the player is automatically moving at an angle, which the camera follows them. They can move left and right with the arrow keys, and I was just wondering how to stop the camera shifting left and right (also as a 45 degree angle) when they do this


texts: How do music and ambient sound influence gameplay flow?

texts:
I've been thinking about whether music helps or distracts from achieving "flow" when playing a game. Does it enhance or distract from it?

Angry Birds, Temple Run and Doodle Jump seem to achieve great flow without music (or with ambient/percussion-only music). But then again, some games use music but seem to also achieve flow, such as Tiny wings.

Has this been researched? How can I maximise flow with in-game audio?


texts: Multiplayer Implementation, Can I implement it later if I chose to?

texts:
I plan to use XNA to build a game project. I'm not entirely sure at the moment if I want to add multiplayer functionality or not, bearing I have a lot of other problems to solve that I'm still new at. I don't want the project to necessarily get out of hand.

My question is, If I head into my project with no plan to add multiplayer support, is it easy to go backwards (It's usually not) and add the necessary code to capture a multiplayer game?


texts: How to use a normal map for light effects with an AnimatedSrpite?

texts:
I am trying to add light effects with normal map on an AnimatedSprite. I was following that tutorial but with no success.
I am using a Ligth2D, this sprite sheet:

and have created a shader on Material to apply the normal map with this code:
shader_type canvas_item;

uniform sampler2D normal_map;

void fragment(){
    NORMAL = 2.0 * texture(normal_map, UV).rgb - 1.0;
}

Here is the result:

One can observe a light reflection on the left upper of the hourglass, but the light is neither smooth nor consistant.
NB: I have made the spirte sheet myself, feel free to use it.


texts: Why does Unity ignore normals when calculating backfaces?

texts:
Here's some code to generate a square mesh.

Vector3[] vertices = new Vector3[]
{
    new Vector3(x1, y1, z),
    new Vector3(x2, y1, z),
    new Vector3(x2, y2, z),
    new Vector3(x1, y2, z)
};

int[] triangles = new int[]
{
    vertexIndex, vertexIndex + 1, vertexIndex + 2,
    vertexIndex, vertexIndex + 2, vertexIndex + 3
};

Vector3[] normals = new Vector3[]
{
    this.normal, this.normal, this.normal, this.normal
};

The resulting mesh looks like this:

The normals have been set to (0, 0, 1), making the square face in the positive Z direction. I would like them to face in the negative Z direction, so the intuitive solution would be to set the normals to (0, 0, -1), but the result looks like this:

Despite the normals facing the opposite direction, the face's front is still in the positive Z direction. When viewed from the negative Z direction, the square is invisible due to backside culling.

Why do my normals not affect the directionality of the faces?


texts: Trying to run sample AndEngine gles2 code in the simulator throws "java.lang.IllegalArgumentException: No EGLConfig found!", how can I fix this?

texts:
I tried to run a small sample game code in the emulator but it crashed. My LogCat is given here. Can you help me resolve the issue.

02-23 15:18:50.543: D/AndEngine(636): MainActivity.onCreate @(Thread: 'main')
02-23 15:18:50.633: D/dalvikvm(636): Trying to load lib /data/data/com.example.gamegles2demo/lib/libandengine.so 0x40513d70
02-23 15:18:50.633: D/dalvikvm(636): Added shared lib /data/data/com.example.gamegles2demo/lib/libandengine.so 0x40513d70
02-23 15:18:50.633: D/dalvikvm(636): No JNI_OnLoad found in /data/data/com.example.gamegles2demo/lib/libandengine.so 0x40513d70, skipping init
02-23 15:18:50.903: D/AndEngine(636): MainActivity.onResume @(Thread: 'main')
02-23 15:18:50.953: D/AndEngine(636): MainActivity.onPause @(Thread: 'main')
02-23 15:18:50.953: D/AndEngine(636): MainActivity.onDestroy @(Thread: 'main')
02-23 15:18:50.983: D/AndEngine(636): UpdateThread interrupted. Don't worry - this EngineDestroyedException is most likely expected!
02-23 15:18:50.983: D/AndEngine(636): org.andengine.engine.Engine$EngineDestroyedException
02-23 15:18:50.983: D/AndEngine(636):   at org.andengine.engine.Engine.throwOnDestroyed(Engine.java:574)
02-23 15:18:50.983: D/AndEngine(636):   at org.andengine.engine.Engine.onTickUpdate(Engine.java:560)
02-23 15:18:50.983: D/AndEngine(636):   at org.andengine.engine.Engine$UpdateThread.run(Engine.java:820)
02-23 15:18:50.983: D/AndEngine(636): MainActivity.onDestroyResources @(Thread: 'main')
02-23 15:18:50.994: D/AndEngine(636): MainActivity.onGameDestroyed @(Thread: 'main')
02-23 15:18:51.073: D/AndEngine(636): MainActivity.onCreate @(Thread: 'main')
02-23 15:18:51.093: D/AndEngine(636): MainActivity.onResume @(Thread: 'main')
02-23 15:18:51.643: D/libEGL(636): egl.cfg not found, using default config
02-23 15:18:51.653: D/libEGL(636): loaded /system/lib/egl/libGLES_android.so
02-23 15:18:51.803: W/dalvikvm(636): threadid=10: thread exiting with uncaught
exception (group=0x40015560)
02-23 15:18:51.803: E/AndroidRuntime(636): FATAL EXCEPTION: GLThread 13
02-23 15:18:51.803: E/AndroidRuntime(636): java.lang.IllegalArgumentException: No EGLConfig found!
02-23 15:18:51.803: E/AndroidRuntime(636):  at org.andengine.opengl.view.ConfigChooser.chooseConfig(ConfigChooser.java:183)
02-23 15:18:51.803: E/AndroidRuntime(636):  at org.andengine.opengl.view.ConfigChooser.chooseConfig(ConfigChooser.java:157)
02-23 15:18:51.803: E/AndroidRuntime(636):  at android.opengl.GLSurfaceView$EglHelper.start(GLSurfaceView.java:919)
02-23 15:18:51.803: E/AndroidRuntime(636):  at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1264)
02-23 15:18:51.803: E/AndroidRuntime(636):  at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1118)
02-23 15:18:52.294: D/AndEngine(636): MainActivity.onPause @(Thread: 'main')
02-23 15:18:54.404: D/AndEngine(636): MainActivity.onDestroy @(Thread: 'main')
02-23 15:18:54.464: D/AndEngine(636): UpdateThread interrupted. Don't worry - this EngineDestroyedException is most likely expected!
02-23 15:18:54.464: D/AndEngine(636): org.andengine.engine.Engine$EngineDestroyedException
02-23 15:18:54.464: D/AndEngine(636):   at org.andengine.engine.Engine.throwOnDestroyed(Engine.java:574)
02-23 15:18:54.464: D/AndEngine(636):   at org.andengine.engine.Engine.onTickUpdate(Engine.java:560)
02-23 15:18:54.464: D/AndEngine(636):   at org.andengine.engine.Engine$UpdateThread.run(Engine.java:820)
02-23 15:18:54.494: D/AndEngine(636): MainActivity.onDestroyResources @(Thread: 'main')
02-23 15:18:54.494: D/AndEngine(636): MainActivity.onGameDestroyed @(Thread: 'main')


texts:
I have a sprite with an UpdateHandler that can change it's position every 0.1 seconds.

My Question is , given the Sprites current position, how can I move it to another position(like from 10,10 to 250,250).

I found out the rotation angle for my sprite like this:

double alfa = (float) Math.atan2(endY - startY, endX - startX) * 180 / PI;

And an example of moving the position is:

sprite.setPosition(sprite.getCurrentX()+1, sprite.getCurrentY());

This would move my sprite every 0.1 seconds to the right.
I need to make it work between any 2 points.

Thanks!


texts: Procedural dungeon generation. No corridors, color key doors

texts: I am curious how dungeons like the one in Runescape dungeoneering skill are generated. They basicaly have a 10x10 grid. So theres 100 rooms total. There's starting room and exit room. And each one are conected by open doors or doors that require key of some color. Anyone have idea how to generate something like this? I mean how to place doors and keys to make dungeon doable?


texts:
I want to do a game where the map is cell based, like Pokemon, where when you press Left, you move from 210x100 to 209x100.

Like this:

    void Update()
    {
        var x = Input.GetAxis("Horizontal");
        var z = Input.GetAxis("Vertical");

        if (x == 0 && z == 0)
        {
            return;
        }

        if (x > 0)
        {
            x = 1;
        } else if (x < 0)
        {
            x = -1;
        }

        if (z > 0)
        {
            z = 1;
        } else if (z < 0)
        {
            z = -1;
        }

        transform.Translate(
            x,
            0f,
            z,
            Space.World
        );
    }

But with this approach, when you quick press and release the left, the Update is executed many times and you go from 210 to 203 easily.

How can I move from 210 to 209 in 0,5 seconds and don't allow other movement until the current movement has finished?


texts: Monogame resizing GraphicsDeviceControl in WindowsForms?

texts:
I'm currently working on a custom Map editor using Windows Forms.

I have a class inheriting from GraphicsDeviceControl (called MapDisplay) that I'm using so that I may use spritebatch to draw the map onto the form. I have this map display control inside of a split panel on my form, and it adjusts its size depending on the size of the map that's loaded. Currently I use mapDisplay.Width and mapDisplay.Height to change it's size, then use mapDisplay.Invalidate() so it redraws.

The problem comes when the width or height of the map display gets above a certain amount, it goes blue and stops working. How do I stop this from happening?

Cheers!


texts: What is the best way to exploit multicores when making multithread games?

texts:
Many people suggest to write a program, and then start optimizing it. But I think that when it's coming to multithreading with multicore, a little think ahead is required.
I've read about using threads, and experienced it myself during some courses at the university (still a student).

The big question is simple, but a bit abstract:

  What thread related steps in game design do I need to take, before implementation?

Now trying to be more specific. Let's say, as an example, that I'm making a small board game  (like Monopoly) that I want to be multithreaded.
My goal Is that this multithreaded game will exploit the best of the multicore system, lets say 4-6 cores (like in i7 processors).

My answer to this question at the moment is, one thread for each of these four basic components:

GUI
User Input / Output
AI (computer rival)
Other game related calculations (like shortest path from A to B, or level up status change)

I'm not an expert (yet!), and I'm sure there are better answers out there.
Any suggestion, answer, different approach will be helpful.

Some thoughts:
Maybe splitting the main database is a good way.. (or total disaster.. )


texts: What is a good flat file format for storing a 2D tile map that can grow infinitely in any direction?

texts:
I am creating a simple map engine that will automatically expand in any direction with procedurally-generated content as needed.

What is a good way to store map data, anchored at a 0,0 origin so that a rectangular subset of map data can be loaded quickly and efficiently from any point on the map?

I have an idea that maybe I should chunkify the map into distinct sectors and then use some sort of header format to identify where in the file a specific sector is stored. Is this a good technique or are there better, more efficient techniques that I can look at?


texts: Numerical stability in continuous physics simulation

texts:
Pretty much all of the game development I have been involved with runs afoul of simulating a physical world in discrete time steps. This is of course very simple, but hardly elegant (not to mention mathematically inaccurate). It also has severe disadvantages when large values are involved (either very large speeds, or very large time intervals).

I'm trying to make a continuous physics simulation, just for learning, which goes like this:

time = get_time()
while true do
    new_time = get_time()
    update_world(new_time - time)
    render()
    time = new_time
end

And update_world() is a continuous physical simulation. Meaning that for example, for an accelerated object, instead of doing

object.x = object.x + object.vx * timestep
object.vx = object.vx + object.ax * timestep -- timestep is fixed

I'm doing something like

object.x = object.x + object.vx * deltatime + object.ax * ((deltatime ^ 2) / 2)
object.vx = object.vx + object.ax * deltatime

However, I'm having a hard time with the numerical stability of my solutions, especially for very large time intervals (think of simulating a physical world for hundreds of thousands of virtual years). Depending on the framerate, I get wildly different solutions.

How can I improve the numerical stability of my continuous physical simulations?


texts: How can I display only the new state of the grid?

texts:
I am making a console based snake game. I am able to move the snake using grids that show up successively on the console. I want to animate the snake using always the same grid.

    static void Main(string[] args)
    {
        char[,] board = new char[17, 17];
        int count = 5;
        for (int i = 0; i <= 16;             {
            for (int j = 0; j <= 16; j++)
            {
                board[i, j] = '.';
            }
        }
        while (count < 11)
        {
            board[8, count] = '*';
            board[8, count + 1] = '*';
            board[8, count + 2] = '*';
            board[8, count + 3] = '*';
            board[8, count + 4] = '*';
            board[8, count + 5] = '*';
            board[8, count + 6] = '*';

            for (int i = 0; i <= 16; i++)
            {
                for (int j = 0; j <= 16; j++)
                {
                    Console.Write(board[i, j]);
                }
                Console.WriteLine();
            }
            count++;
        }
    }


texts: Having issues with pong physics, is my approach wrong?

texts:
I've been working on a pong clone, i've made games in the past but they have all been very hacky. This time I was trying to go for a better approach in terms of using OOP or patterns. So far the games not posed many issues, I am however having problems thinking about the collision system and ball physics. In my main loop the collision code is as follows:

if (ball->Y < 0)
{
    ball->direction = -ball->direction;

    if (ball->ballSpeed < 700)
    {
        ball->ballSpeed += 25;
    }
}

if ((ball->X + ball->width > player2->X)
    && (ball->X + ball->velocityX) + (ball->width) < player2->X + player2->width
    && (ball->Y + ball->velocityY) + (ball->height) > player2->Y
    && (ball->Y + ball->velocityY) + (ball->height) < player2->Y + player2->height)
{
    ball->direction -= 70;

    if (ball->ballSpeed < 700)
    {
        ball->ballSpeed += 25;
    }
}

if ((ball->X + ball->width) > player1->X
    && (ball->X + ball->velocityX) + (ball->width) < player1->X + player1->width
    && (ball->Y + ball->velocityY) + (ball->height) > player1->Y
    && (ball->Y + ball->velocityY) + (ball->height) < player1->Y + player1->height)
{
    ball->direction += 70;
    if (ball->ballSpeed < 700)
    {
        ball->ballSpeed += 25;
    }
}

The program checks the points of the objects rect's to see if they have passed any of the paddles and then applies changes to the balls public variables. Here is the ball update code:

if(move)
{
velocityX = int(cos((direction + 0.0) * M_PI / 180.0) * (ballSpeed *deltaTime));
velocityY = int(sin((direction + 0.0) * M_PI / 180.0) * (ballSpeed *deltaTime));

    rect.x += velocityX;
    rect.y += velocityY;
}

X = rect.x;
Y = rect.y;
width = rect.w;
height = rect.h;

This PARTIALLY works however the ball goes in weird directions sometimes, on top of that the ball can actually go through the bottom portion of the paddle (it seems that from the bottom of the paddle, there is a gap the ball can exactly fit through). Really the physics of the ball just seem weird and not fluid at all. I'm not brilliant at maths so I don't really know of any other way to go about this. Help would be greatly appreciated.


texts: Handling localization strings in a performant game engine c++

texts:
I'm wondering what's the approach for handling localization in a modern game engine. Typically I'd reference a string that would serve as a tag (say: AURA_POISON_CLOUD) in the code and then later in my UI I'd look it up in the language of my choice.

Considering that strapping a full-on string to my gameplay Status struct (ECS architecture) seems a bit inefficient, I could hash the string and then in my UI I would have to first get the original string and then do the localization look up. How would you handle the hashing though when it needs to be reversible? By definition it seems impossible, so an alternative would be two dictionaries: strings=>ints and ints=>strings for the reverse lookup. Is there something I'm missing here?

How do you approach this problem in your games?


texts:
I'm currently developing a 2D Plattformer in Unity. And now I'm stuggling with the Character Controller. I know there are a lot of usefull tips for 2D Plattformer Controller in a Mario or Donkey Kong way of Controlling, which are great, but they don't fit my type of 2D Plattformer. My Levels have a similar concept to those in Ori and the Blind Forest and I wanted to have a similar kind of Movement. So does Anybody know how they achieved this kind Character Movement?

For those unfamiliar with Ori and the Blind Forest Control:

In Mario and Donkey Kong the Levels are very horizontal and you run from left to right. The Ground is sometimes interrupted and you have to jump on several Plattforms to reach the next part of the Ground. The Environment like Ground, Plattforms, Walls are mostly boxes.

in Ori and the Blind there is no run from left to right. The Levels go in all Directions. The Environment is more realistic so you have to slide down curvy Walls and no disappearance of the Ground. Also Plattforms are very rare. So instead of jumping through the Level you have to climb through.

I don't know if that Description is enough so here is some Gameplay.

EDIT:
I tried .addForce() for every Movement, but this had a weird Slipping Effect. After releasing a button the Charracter slips a few Meters until it finally stops. So I'm currently manipulating the rigidbody.velocity directly for normal horizontal Movement and addForce for the rest like jumping or dashing.

But I have a lot trouble with Sliding along Walls. As mentioned above the Walls are curvy so just cancelling out horizontal Movement and apply some Vertical Force with rb.velocitiy doesn't work. The Character have to follow along the Wall shape. Thus I added a Force towards the Wall, which pressed the Character to the Wall. But this doesn't work very well with my jumping.


texts:
Running Ubuntu 11.04, SDL 1.2 trying to pickup mouse wheel up/down movement with this (stripped down) code:

int main( int argc, char **argv )
{
    SDL_MouseButtonEvent *mousebutton = NULL;

    while ( !done )
    {
        if(mousebutton != NULL && mousebutton->button == SDL_BUTTON_LEFT)
            yrot += 0.75f;
        else if(mousebutton != NULL && mousebutton->button == SDL_BUTTON_RIGHT)
            yrot -= 0.75f;
        else if(mousebutton != NULL && mousebutton->button == SDL_BUTTON_WHEELUP){
            xrot += 0.75f;
        }else if(mousebutton != NULL && mousebutton->button == SDL_BUTTON_WHEELDOWN){
            xrot -= 0.75f;
        }

        while ( SDL_PollEvent( &event ) )
        {
            switch( event.type )
            {
                case SDL_MOUSEBUTTONDOWN:
                    mousebutton = &event.button;
                    break;
                case SDL_MOUSEBUTTONUP:
                    mousebutton = NULL;
                    break;
                default:
                    break;
             }
        }
    }
    return 0;
}

strange thing is, scrolling with the mouse button does nothing, but if I hold down a mouse button or two and then move the mouse it hits the SDL_BUTTON_WHEEL code occasionally.  This honestly reeks of a pointer issue, which would make sense since I've been spoiled with C# for the past couple years, but I am just not seeing it.

How do i correctly find mouse scroll events in SDL?


texts: How to make an expanding radial search in Unity?

texts:
I am currently working on a City Builder Game and I often come across the problem of having to decide wich location to use.

Examples:

The citizen has a job and needs a home. There are several buildings with open slots.
The citizen is at a positon and is hungry. There are several restaurants on the map.

How can I choose the right building to go to?
I don't really wan't to check the distance for each, because there could potentially be hundreds of buildings and that decision problem occurs quite often.

I also don't care for the optimal solution, any nearby result is fine.

Currently all buildings register them self in a LinkedList. When searching for something I'd start at the beginning and the first occurrence that was 'good enough' would be returned.
Citizen now drive across the map for something that was right next to them if the one far away was built earlier in the game.

Any suggestions?


texts: Questions about the details of implementing a component-based entity system

texts:
I started reading about component-based entities, and overall it seems like a good idea, but many of it seems to skip over a lot of details and not give many real examples, so there are things that don't really make sense to me. Note that I'm also mainly talking about the architecture where components only hold data and act as keys that trigger systems to be run for that entity, but this still mostly applies with each component having an update method that's called by the entity.

When to think if it, many entities have things in common (like, for example, enemies with collision and physics), plus behavior that's specific to only that one kind of entity. Do I need to create lots of systems that are only good for one kind of entity, and are not at all generic/reusable?
How should components interact with each other? I heard of using message queues, but that seems like it would be slow, plus how would I stop it from queueing messages that will never be read? Or is just setting fields in the component (to be checked by the other system) considered good?
What's the best way to handle collision detection? A system that checks for collisions and sends events/stores the colliding objects in a component?  Would just giving the world/entity manager a method (that would freely be used by different systems) to find colliding entities that have a certain component be a good idea? Or is there another way?
How to handle animations changing based on events? if I have a component telling the animation component to switch to a certain animation, doesn't that make it so that the component can't be used with a different animation?
In 2D, how would drawing order be handled? Especially if there are multiple kinds of drawing systems?
With OOP you can store a reference to an object in another object, and call methods on it. How would the equivalent be done with an entity/component system, considering entities are not guaranteed to have certain components?

So how are these issues normally solved? Or am I thinking about this completely the wrong way?


texts: Drawing from an ArrayList drawing same image repeatedly (Slick2D)

texts:
This is the game I'm working on.

I isolated the problem into this class.

public class Runa extends BasicGame {
int startTime, tracker;
public ArrayList<Circle> circ = new ArrayList<Circle>();
public int[] a = new int[]{
        15, 16, 17, 18, 19, 32, 36, 40, 45, 46, 55, 56, 57, 58, 63, 65, 68, 70, 72, 74, 79, 80, 81, 82, 86, 94, 95, 96, 97, 98, 99,
        100, 101, 102, 103, 104, 105, 117, 120, 122, 126, 128, 129, 130, 131, 133, 138, 139, 140, 142, 149, 151, 155, 156,
        158, 164, 166, 172, 174, 180, 182, 184, 188, 189};
public ArrayList<Integer> aList = new ArrayList<Integer>();
public Runa(String title) {
    super(title);
}

@Override
public void init(GameContainer c) throws SlickException {
    startTime = 0;
    tracker = 0;
    //this just transfers the hard coded values into an arraylist
    for(int i = 0; i<a.length;i++){
        aList.add(a[i]);
    }
}
@Override
public void update(GameContainer c, int d) throws SlickException {
    //this calculates the rhythm of the game
    startTime+=d;
    if(startTime>((60/(calcBPM(195.8,89)))*1000)){
        startTime=0;
        tracker++;
    }

    //this adds a new circle every time the current beat (tracker) reaches a beat on the aList
    if(aList.indexOf(tracker)>0)
        circ.add(new Circle(50,50,50));
    //this should just move one circle at a time, meaning I thought that only one circle would be added above, and move it down 4 px
    for(Circle circle: circ)
        circle.setCenterY(circle.getCenterY()+4);
}

@Override
public void render(GameContainer c, Graphics g) throws SlickException {
    //draws each circle in the arraylist
    g.setColor(Color.red);
    for(Circle circle: circ)
        g.draw(circle);
}
//calculates the bpm
public double calcBPM(double d, int numSecs){
    return d*60/numSecs;
}
public static void main(String[]args) throws SlickException{
    new AppGameContainer(new Runa("Test"),680, 480, false).start();
}

}

Why is it doing that weird stretch thing? Is that because I'm using an arraylist?


texts: TitleSafeRegion isn't available on XNA 4?

texts:
I'm following the book Microsoft XNA Game Studio Creators Guide v2. and there is a snippet in the book that is used to return a Rectangle that represents the safe area you can draw without the fear of 'drawing' outside the screen.

Except in my IDE Visual Studio 2010, that method doesn't show up in intellisense and in fact doesn't show up anywhere.

Here is the snippet:

private void UpdateAsteroid(GameTime gameTime)
{
    // time between frames
    float timeLapse = (float)gameTime.ElapsedGameTime.Milliseconds;
    if (move == true)
    { // asteroid centered at the middle of the image
        Rectangle safeArea = TitleSafeRegion(rockWidth/2, rockHeight/2);

      // asteroid right edge exceeds right window edge
    if (rockPosition.X > safeArea.Right){
        rockPosition.X = safeArea.Right; // move it back
        rockSpeed *= -1.0f; // reverse direction
    }
// asteroid left edge precedes the left window edge
else if (rockPosition.X - rockCenter.X < 0){
rockPosition.X = rockCenter.X; // move it back
rockSpeed *= -1.0f; // reverse direction
}
// asteroid within window bounds so update rockPosition
else
rockPosition.X += rockSpeed * timeLapse;
// Scale radians by time between frames so rotation is uniform
// rate on all systems. Cap between 0 & 2PI for full rotation.
const float SCALE = 50.0f;
rockRotation += rockRotationSpeed * timeLapse/SCALE;
rockRotation = rockRotation % (MathHelper.Pi * 2.0f);
}
}


texts: How to calculate a vector for multi-axis rotations from sphere coordinates?

texts:
I'm working on a SceneKit project in iOS, trying to rotate a sphere (representing a planet) so that a point at a given longitude/latitude coordinate is facing "forward" (i.e. that point moves to the {0,0} position).  So for example, we're looking at Earth's {0,0} point, off the coast of Africa, but I need to know what rotation vector would have us looking at {37,-122}, aka San Francisco.  Ideally, the planet would remain "naturally" oriented, with north remaining generally "up" from our perspective, but that's flexible.

I've got the animation working and I can rotate to a given longitude OR latitude using SCNVector4, but as soon as I try to rotate to a given longitude AND latitude, it gets wildly messed up.  So I've been doing some research, and I've found some resources that seem to do exactly what I need, but to be honest they're a bit beyond me.  I'm a complete newbie in the world of trigonometry and matrices, and it seems there's no way around this problem without them.

Can anyone help me understand how these concepts can take long/lat coordinates, and calculate a rotation vector?  A method for creating a SCNVector4 would be perfect, but even just help with calculating the components individually would be greatly appreciated!


texts: Convert rotation from Right handed System to left handed

texts:
I have Euler angles from a right handed system that I am trying to convert to a left handed system. All  the information that I have read online says that to convert it simply multiply the axis and the angle in the correct order and it should work. In other words, Z * Y * X. When I do this what I see in Maya, and in engine still do not match up.

This is what I have so far:

static Quaternion ConvertToRightHand(Vector3 Euler)
{
    Quaternion x = Quaternion.AngleAxis(-Euler.x, Vector3.right);
    Quaternion y = Quaternion.AngleAxis(Euler.y, Vector3.up);
    Quaternion z = Quaternion.AngleAxis(Euler.z, Vector3.forward);
    return (z * y * x);
}

Keeping the -Euler.x helps keep the object pointing up correctly, but when I pass ( 0,0,0) to face in the -z, it faces in the +z. Help :/


texts: Quick way to approximate a truncated gaussian distribution?

texts:
I'm doing some procgen stuff and I need a truncated gaussian distribution. Basically, I need a way to get the same thing as this:

import random
def truncated_gaussian(mean, deviation, min, max):
    while True:
        val = random.gauss(mean, deviation)
        if min < val < max: return val

except without so much wasted effort. It looks like this is a pretty complicated thing to do properly, but I don't need statistics-grade perfect randomness, just a video-game-grade approximation.

Anyone know a trick to make this work?


texts:
I have been pulling my hair out trying to make an object in cocos 2d that is a CCSprite (with an image) and a CCLabelBMFont.

I tried making a CCNode object and I tried making a custom CCSprite object but none of it worked!

Can someone show me how to do this?

Thanks.


texts: How can I fix my project after upgrading to Unity 2019 / .NET 4.x?

texts:
My Unity version was about a year out of date. After upgrading it to Unity 2019.1.5f1 through the Unity Hub, my project started throwing hundreds of errors. The most prominent one seemed to be:

Feature `out variable declaration' cannot be used because it is not part of the C# 4.0 language specification

How can I fix my project so that it runs again?


texts:
I'm a freelance game designer, and I can't afford to hire someone to do skyboxes for me.

However, I am unable to do them my self.

Let's say I have a texture that can be tiled on four sides...

If I put that very texture on each side of the skybox.. It just comes out looking like a cube.

I'd like to know how exactly I need to "warp" a texture, so that when applied to a cube on all four sides, it looks spherical.

Thanks! -- G


texts: How to distinguish between full/partially intersecting Collider2D?

texts:
I'm using Unity 5 to make 2D game.

I have a screen (gray), arena (green) and player-controlled object (yellow) that can be moved across the screen with mouse before placement:

There is no Rigidbody2D attached to arena or object.

Is it possible to check whether the object is fully inside the arena or partially inside it using built-in Unity physics API?

I know that it can be easily calculated in this case, but I want to know, is it ever possible.


texts:
I want to allow a user to redeem a token every X time (i.e. 24 hours). Once they redeem it, they must wait X time again before redeeming the next item. This ensures that users must visit the app daily to continue gaining tokens.

I'm not sure how to work with clock differences between machines. What if

Server B:      9:03:41
User A tablet: 9:03.59
Server C:      9:05:23

(assume they all have the same date and all are AM)

User A's tablet makes a request and server B response with "Token available". The user then tries to immediately redeem the token, but server C responses with "Sorry, token not yet available." This would obviously be annoying to the user.

I could potentially handle this on the server. If the server says a token is available, then set a flag that actually guarantees that it is available.

But what if I want to actually let the user know how much time is left before they receive their next token. If all the servers have a different clock time, then all requests for time left would return a slightly different time.

I don't think I could rely on client time, since the user may play with different devices.

How could I handle this?


texts:
So I started learning java sometime ago and now I am understanding packages.

My main goal is to do minecraft modding. Can someone with modding experience please tell me how hard(or easy) minecraft modding is? And how much time will it take for me to get to a level when I can start modding?


texts:
I am trying to optimise some of my rendering to get is useable on lower end machines (in my case a 2GHz i5 laptop with a GT 520M).

A quick investigation showed that the GPU isnt actually getting to 100%, but both CPU cores are. While most of this is non-rendering stuff (which I can likely make faster), I was surprised to find the piece of code below is apparently using 10% (20% of a core).

void RenderStaticTerrain()
    SetShadersInputLayoutConstantsEtc();
    for region in regionsInView: //about 20
        region->SetVertexAndIndexBuffer()
        for texture in regoin->UsedTextures(): //around 100
            d3dContext->SetAsShaderResource(texture);
            d3dContext->DrawIndexed(...);

I used the Windows Performance Analyzer sample based profiling and that points at some AMD or Nvidia DLL's as being where the CPU spends its time, largely I believe within the DrawIndexed (found via QueryPerformanceCounter. The sampling results seemed to dump the dll time just in RenderStaticTerrain itself).

The textures, buffers, etc are all immutable usage so don't see anything obvious to consume CPU there like moving vertices about or anything like that.

Two idea I have which (both of which look like some work) is texture arrays and using a few very large textures containing the others. However I am not sure how viable either of those are, and if it would actually make any performance difference.

For texture arrays it seems I can have upto 2048 which is plenty. However I am not sure if the GPU is going happy with what seems to me like effectively random access via a vertex buffer field. The major problem  however is it appears all the textures need to have the same size, while most of mine are in the 32x32 to 128x128 range, with some even larger ones.

Another idea was to pack them into some really big textures, but this always seems to cause problems with mip-mapping and texture filtering, since even if I repeat each textures border pixel a few times, a few mip levels down and I have one pixel in the small texture being made from pixels of unrelated textures.

Not sure what other options there are. I am still not really sure why that loop uses much CPU at all.

The current code is only D3D11 targeting D3D11 hardware, but I do plan to support older hardware and OpenGL.


texts: Creating custom editors for components with custom classes

texts:
Let's say that I have the following Component

using UnityEngine;
using System.Collections;

public class TestPlayer : MonoBehaviour {

    public int health = 0;
    public int maxHealth = 100;

}

It is cool, but the editor could look better. So  I wrote this Custom Editor

using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(TestPlayer))]
public class TestPlayerEditor : Editor {

    private SerializedProperty health;
    private SerializedProperty maxHealth;

    private void OnEnable() {
        health    = serializedObject.FindProperty("health");
        maxHealth = serializedObject.FindProperty("maxHealth");
    }

    public override void OnInspectorGUI() {
        serializedObject.UpdateIfDirtyOrScript();

        EditorGUILayout.IntSlider(health, 0, maxHealth.intValue, "Health");

        EditorGUI.indentLevel++;
        EditorGUILayout.PropertyField(maxHealth, new GUIContent("Max Health"));
        EditorGUI.indentLevel--;

        serializedObject.ApplyModifiedProperties();
    }
}

Great. Now the Editor looks much better

But now turns out that because I am getting more properties of my Player with a similar pattern, I want to refactor it...

using UnityEngine;
using System.Collections;

public class TestPlayer : MonoBehaviour {

    public FillingProperty hp;
    public FillingProperty stamina;

}

[System.Serializable]
public class FillingProperty {
    public int val;
    public int max;
}

How could I write now the Custom Editor script, so that the inspect shows me the same interface as before, but for every FillableProperty I wish to add?


texts: How to animate a character from a sprite sheet?

texts:
I'm making an online game, and I had been using a blank square as the character until recently. Now I want to add a real, animated character.

I downloaded a free sprite sheet which has 12 (3x4) character sprites.

What is the general method to animate the character?

I see why having all the character animations in one file can be useful, but I don't understand how it would be done. I don't want code or anything, I just want to know how you normally use the sprite sheet to animate a character so I code it afterwards.


texts:
I want to map a 2d picture onto an arbitrary 2d quadrilateral, for the purpose of particle system. To do that, I split the picture into two triangles, and then linearly interpolated  u,v along the triangle edges, using the following code:

struct tlerp {
  double x,i;
  double u,v;
  double ui,vi;
} tlerp;

void tlerp_init(tlerp *l
                      , double first_step, double steps
                      , double sx, double ex
                      , double su, double eu
                      , double sv, double ev) {
  l->i  = (ex - sx) / steps;
  l->ui = (eu - su) / steps;
  l->vi = (ev - sv) / steps;
  l->x = sx + first_step*l->i;
  l->u = su + first_step*l->ui;
  l->v = sv + first_step*l->vi;
}

void tlerp_advance(tlerp *l) {
  l->x += l->i;
  l->u += l->ui;
  l->v += l->vi;
}

But the result is garbled. My guess is that linear interpolation can't be used here, because the space inside quadrilateral is obviously non-linear (on the attached picture it gets more compressed the closer it gets to the top). Is there some way to make it linear again?

As always, I'm not using an OpenGL/DirectX, so can't use any built-in solution.


texts: How to make the bullet stop accurately when destination is reached?

texts:
In the below code, is the method I use to move a bullet to its destination and stop when bullet is near to destination. But the problem is the bullet is stopping not accurately, sometimes there's a small offset or span or sometimes is accurate depends on the angle.

public Vector2 getVelocity(Vector2 currentPosition, Vector2 targetPosition) {
    Vector2 targetDirection = targetPosition.cpy().sub(currentPosition);
    return targetDirection
            .nor();
}

final float SPEED = 6;
float pos = bulletPosition.len();
float des = bullet.destination.len();
float tol = Constants.TIME_STEP * SPEED;

if(MathUtils.isEqual(pos,des, tol)) {
    body.setLinearVelocity(0,0);
} else {
    body.setLinearVelocity(getVelocity(bulletPosition, destination).scl(SPEED));
}

[SOLVED]

if(MathUtils.isEqual(pos, des, tol)) {
     // quick & dirty way
     body.setTransform(destination, angle);
     // better way
     ...
}


texts: How legal would it be to use some elements of the Half Life universe in my non comercial, indie game?

texts: I'm planning to make a simple, HTML5 game, that would use some elements of the Half Life universe. Basically, it would be a 2D Portal clone, but it would have it's own story, and portals would be different, along with the mechanics of making and using them. Also, how far can I go with this? If possible, I'd like to have Gman, a character from Half Life, walk by a few times, and maybe even use some of the sounds from Half Life or Portal. It's also important to note that I wouldn't be making any kind of profit.


texts: Where is better to do shaders, vfx, uv-mapping and coloring?

texts:
Well i understand that 3DS-Max is mainly for modeling and Unity is mainly for programming and logic, but where is it better to do shaders, vfx, uv-mapping/painting and coloring?

for example i worked a little bit in Blender and it has modifiers, but also Unity has materials and similar stuff.

What let's say "imade a model in 3ds max, now where should i do the art and texturing, should i continue with 3ds or should i do it in blender? OR it doesn't matter where?"


texts: What does maximum normalized frictional force mean in this tutorial?

texts: I tried following this tutorial: https://nccastaff.bournemouth.ac.uk/jmacey/MastersProjects/MSc12/Srisuchat/Thesis.pdf, but in page 19 I ran onto a problem - I don't understand the step 4. It is also not explained before. Could somebody explain what is it and what values may be used?


texts:
i would like to start this topic for programs to counter-attack link text.

I am not aware of a big list but with everyone's help i hope to make this a fine topic.

Posting format:

NAME: nProtect GameGuard

GAME TYPE: any type of game

Website: http://global.nprotect.com/product/gg.php

FEATURES?

Protect the users' PC from fast
evolving hacking technologies and
viruses.
Real-time protection, diagnose
various patterns latest hacking tools
that can harm games, but also memory
debugging prevention technology will
be applied, completely blocking
hacking tools through real-time
hacking tool monitoring and blocking
function.
Blocks hacking attacks through memory
scan
Blocks online outflow of personal
information


texts: Creating an asset library accessible from all classes

texts:
The idea of what I'm trying to do is to create a class that will automatically pull in all of the assets needed using the ConstructorHelpers and store them in a library with IDs. Then from there, any class that includes the asset library should be able to access the library and the objects within.

So far I have created an empty C++ class and added all of the backend needed, and I've used the GameModeBase to instatiate the class as a static variable, however I can't include the asset library elsewhere and use it.

I have thought about creating an actor class and just plopping it into the world, but I really don't like the idea of that and would prefer something more robust.

I've tried searching for a way to do it online, but I can't seem to find it, does anyone know of a solution?

Below is the code I am using to create a singleton class and it will not compile, giving me an LNK2001 error

unresolved external symbol "private: static class AssetLibrary* AssetLibrary::Instance"

.h

static class UE4Testing_API AssetLibrary {
public:
    static AssetLibrary* GetInstance();

private:
    static AssetLibrary* Instance;

    AssetLibrary();
    ~AssetLibrary();
};

.cpp

AssetLibrary* AssetLibrary::GetInstance() {
    if(!Instance) {
        Instance = new AssetLibrary();
    }

    return AssetLibrary::Instance;
}

AssetLibrary::AssetLibrary() {

}

AssetLibrary::~AssetLibrary() {
    delete Instance;
}

Regards,


texts: How do I calculate the motion of 2 massive bodies in space?

texts:
I'm writing code simulating the 2-dimensional motion of two massive bodies with gravitational fields.

The bodies' masses are known and I have a gravitational force equation.
I know from that force I can get a differential equation for coordinates.
I know that I once I solve this equation I will get the coordinates.
I will need to make up some initial position and some initial velocity.

I'd like to end up with a numeric solver for the ordinal differential equation for coordinates to get the formulas that I can write in code. Could someone break down how from laws and initial conditions we get to the formulas that calculate x and y at time t?


texts: How should I distribute the values of equipment stats when I know the average value?

texts:
I am making a Diablo-like game and I want to randomly generate the stats of the loot that gets dropped.  I'll use "damage per second" as an example.  I've filled a spreadsheet with two columns of numbers.  The first column is the level, the second column is the average damage per second.  So when you look at a row of the spreadsheet it'll say something like, "at level 50, the average damage per second should be 100".  From here there are many branches I could take:

Decide that the range values are not weighted.  In which case, all you have to do is find a range below and above the average and randomly generate numbers in that range.  For example, I'll arbitrarily decide that 20% is a good number and then the random range goes from 80 to 120.  AFAIK, as long as that same % is added and subtracted to the number, then it should average out to 100.
Decide that the range values are weighted.  In this case, I want the higher stats to be more rare than the lower stats.  So if the range were between 10 to 20, it would be more common to get a 10 than a 20.  But, I think that there are other unknowns I have to solve first.  Like, I probably need to figure out how I want the numbers weighted.  I know how to set up weighted random values.  But I don't know how to guarantee the average of the values is the number I want.  How would I figure that out?

1) Seems way easier to code and balance.  But I'm wondering if it's a poor choice for a loot system.  If all the popular games out there use this, that's good enough for me and I'd consider that an answer.

On the other hand, if they use something like 2), I'd like to figure out how I can use the average as input to get the weighted range as output.

And if there's a 3) I haven't thought of that most games use, I'd like to hear about that.


texts: Can i release a game in steam with free assets?

texts:
I'm making a game with unity, and i'm planing release the game in steam as FREE. I'm using free assets from unity asset store, and also i'm using free assets models from another sites. I always see if the 3d models are free. I'm no using models like Batman, that have rights from DC. But for example i use a model of door or a stair.

My question is, can i publish my game in steam, or another place, without care about someone someone processing me because i use his 3d models, that is free?


texts: How to loop through functions dependent on previous function?

texts:
In Unity, I need to generate a series of platforms in a specific order for a sidescroller I am working on. The issue is that the generation of the next platform is dependent of the previous platform meaning I can not generate the next platform before the previous platform is made. In this case I cannot predict where the next platform will be at since its length is based off randomized parameters. Also I the generation function is based off of multiple scripts so it has to go through multiple scripts before the generation is complete.

I am currently using a Bool function to wait for the completion of the generation but I do not think this is the appropriate way to go about this. What would be an appropriator structure for calling multiple functions dependent on the previous call?

This function is used to call the functions to generate the platform

    public void GeneratePlatformSequence ()
{
//For loop to
    for (int i = 0; i < TerrainSequence.Count; i++) {
        bool isComplete = TerrainSequence [i].Transition (TerrainSequence [i+1], new Vector3(50*1,0,0));
    }
}

Abstract class for Platform Generation

public abstract class TerrainMesh : MonoBehaviour {

    public abstract bool Transition(TerrainMesh CurrPlatform, Vector3 LastPosition);

}

One of the mesh generation classes I use to create the platform

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

public class GroundTerrain : TerrainMesh {

    public override bool Transition(TerrainMesh CurrPlatform, Vector3 LastPosition) {
        bool isStepComplete =   GroundTransition(CurrPlatform, LastPosition);
        return isStepComplete;
    }

    public bool GroundTransition (TerrainMesh CurrPlatform, Vector3 LastPosition){
        if (CurrPlatform is WaterTerrain) {
            print ("Generating WaterTerrain");
//Here is where I generate the Actual mesh for the platform.
            bool GeneratedMesh = MeshGenerate ();
            return GeneratedMesh ;
        }

        return false;
    }

}


texts:
I'm trying to programmatically generate vertices and indices for a torus. I found this piece of code somewhere, and it looks like it works, but I'm not certain it is correct.

With my little knowledge of trigonometry, I figured out how the vertex generation part works, but I'm stuck at the index buffer part (though I know what the modulus operator is used for).

Does the code work correctly? Can anyone explain what it does to generate the correct indices?

I tried to output the index buffer and noticed there's a triangle with indices (10,10,10), which is weird and makes me think this may be wrong. Plus the UVs look weird for the last 'slice' of the torus, as in this pic.

int sides = 10, cs_sides = 40;
float radius = 3.5 * 10.0;
float cs_radius = 0.75 * 10.0;

numVertices = sides * cs_sides;
Vertices = malloc(sizeof(Vertex) * numVertices);

numIndices = (2 * ((sides+1) * cs_sides) + cs_sides);
Indices = malloc(sizeof(GLushort) * numIndices);

int angleincs = 360/sides;
int cs_angleincs = 360/cs_sides;
float currentradius, zval;

//calculating the vertex array
for (int j=0, m=0; j<360; j+=cs_angleincs, m++)
{
    currentradius = radius + (cs_radius * cosf(j * D_TO_R ));
    zval = cs_radius * sinf(j * D_TO_R );

    int index = (m*sides);
    for (int i=0, n=0; i<360; i+=angleincs, n++)
    {
        Vertices[index + n].Position[0] = currentradius * cosf(i * D_TO_R ); // x
        Vertices[index + n].Position[1] = currentradius * sinf(i * D_TO_R ); // y
        Vertices[index + n].Position[2] = zval;                              // z

        Vertices[index + n].Color[0] = 1.0;
        Vertices[index + n].Color[1] = 0.0;
        Vertices[index + n].Color[2] = 0.0;
        Vertices[index + n].Color[3] = 1.0;

        float u = (float)i/sides;
        float v = ((float)j + u)/cs_sides;

        Vertices[index + n].TexCoord[0] = u;
        Vertices[index + n].TexCoord[1] = v;
    }
}

// cs_sides = 40
// sides = 10

int i=0, n=0;
//calculating the index array
for (;i<cs_sides; i++) {
    for (int j=0; j<sides; j++) {
        Indices[n++] = i * sides + j;
        Indices[n++] = ((i+1) % cs_sides) * sides + j;
    }

    Indices[n++] = i * sides;
    Indices[n++] = ((i+1)%cs_sides) * sides;
    Indices[n++] = ((i+1)%cs_sides) * sides;
}


texts: Project 3D points to a plane, then project their bounding box back to 3D

texts:
I have a table in 3D space, represented by a plane.

I want to project arbitary points representing an object (cup, toy, etc) onto that table, run 2D principal components analysis to get an oriented bounding box (https://www.sciencedirect.com/topics/computer-science/oriented-bounding-box)

This gives me 2D oriented bounding boxes (defined by 8 corner points) that lie along the table plane. Now, I want to project these points back to 3D somehow so I can get 3D bounding boxes that are aligned with the plane.

The projection from 3D to 2D plane is not invertible.. so how do I do this?


texts:
I'm a web developer with over 12 years of experience and I'm moving my first steps in game development in the latest days. Specifically I'm playing with Unity and trying to understand how it works and how can I realize a 2d platform game. Currently I created a character that can be controlled with the keyboard (it moves to right, left and can jump), so far it seems more easy than I was expecting and despite I never used C# before I'm already quite comfortable. My first big concerning is about sprites and how can I create combined sprites or use an image as a repeated background.
For example, let's imagine that I have a png of a brick and that I want to use it to create a wall, that can be of a variable width and height. How can I achieve that? With html/css I would simply create a class like this:

.wall {
    background: url(brick.png);
}

and by applying that class to any html element it will render a repeated background by adapting it to its container no matter how large or tall is it. In unity/C# what should I do?

So far I tried to create a new material and applied it to a cube object but the result is that the image gets stretched and sucks.
I saw some example that creates N sprites programmatically by adding them one after another, but I wonder about the performance implications of this technique... for example if I have to repeat the brick 100 times I have to create 100 objects, it seems unfeasible to me!
What I want to achieve is the most flexible, simple and performant way to create "shapes" with repeated background.


texts: Unity 5 How Do I Set Text of Text Component of Input Field

texts:
How do I set the text of the new Input Field's Built In Text UI Object in Unity 5+?

 myInputFieldText.text = "Text Value I Want";

The code above does not work to set the text inside of a InputField's Text. Thanks


texts:
I'm trying to make an agent patrol around a maze. The maze is proceduraly generated and consists of many rooms connected with doors. The problem occurs when the agent reaches a door. I wrote a script where if the agent gets near a door, the door opens, but the results are bad because the doors are walkable, so the navmesh doesn't consider them as obstacles and the agent gets stuck if the door opens and gets in its way.

I've been looking everywhere on the internet, but haven't found a solution.
If anyone has an idea or a way to make this work, I'll be very thankful.


texts: How do I avoid floating point indeterminism when implementing lockstep?

texts:
I am working on a multiplayer RTS game in Java. It uses lockstep for networking, which requires that both computers can deterministically.

These are the 2 closest/more viable approaches I could come up with- but both have issues:

The first is to just use int and long for all my player positions and stuff, and get any use of floating point math totally out of the game model. I like this concept- but the problem is what happens when I need a square root, or a cosine? I would have to basically make an entire math library!
I also found that I can use the strictfp modifier and StrictMath class to do deterministic math with doubles... Which I could see using this to create deterministic math within my games model. It would be very prone to bugs as it would be very easy to accidentally go outside of the "strict" scope though.

Also I cant seem to figure out if serializing a float or double causes it to lose its determinism. I'm using Kryo/Kryonet right now, but I cant seem to find any information on if it is deterministic with floats or not (I cant seem to find any information on the built in java serialization either, or any other serialization library)

Does anyone have any suggestions on how I could tackle this problem?


texts: How to translate swipe gestures into rotations?

texts:
I am making a snake game. I want to rotate my snake in the direction specified by swiping on the screen, the directions are limited to orthogonals (90 degree increments). It's an android game.

Can someone provide me with an algorithm to rotate a snake given its current rotation, and a swipe direction? As it rotates at 90 degrees correctly but not always in the direction specified by swipe.


texts: Algoritm for scaling an 3D model with fixed edges

texts:
I am looking for an algorithm that allows me to scale a 3D model with certain fixed edges. For example scaling up a window should have the frame remain a fixed width while the length of the frame pieces increases or a kitchen sink should have the tap remain at a fixed size while the rest increases.

Note that in the example it's a 2D model while in reality it's a 3D model, scaling can also happen along certain axis (so only scaling over the Z-axis, rather than over all axis at the same time).

Performance is of minor concern(it's a small part of the loading sequence to which I can allocate an extra thread) so a c#/pseudocode solution is acceptable, it doesn't have to be implementable as a shader.

So far I was thinking about some kind of energy formulation/graph based system but I cannot get that to work with possible with death ends in the model. I looked for scientific papers on the issue but couldn't find the right paper (I vaguely remember there being one I learned about in university).

edit:
it should also be able to handle situations like this:
 where the parts that shouldn't scale are intermixed with the geometry of the object, this could also (in you don't want all of this to focus on architecture) be something like the eyes of an animal.

Lastly there is also the possibility of some edges being fixed and others (in the same face) not being fixed, I was hoping to solve this like so:


texts: Is there a gl*TexStorage* equivalent to glCompressedTexImage*

texts:
I have been using glTexImage functions to create textures and then heard of glTexStorage* that is supposed to be better and is introduced in the latest standards.

But the problem is that I can't seem to find an equivalent to glCompressedTexImage2D(...) in terms of gl*TexStorage.

I've only found 2 references on an IRC chat to these supposedly equivalent functions while searching. (here and here)

Do these equivalent functions even exist ? And if they don't, why don't they exist ?

Thanks for any help


texts: How can I calculate normals using a vertex and index buffer?

texts: Is it possible to calculate normals using the positions in a vertex buffer and index buffer? Would someone show pseudocode for the algorithm?


texts: How should I update vectors, et cetera, in a time-based fashion?

texts:
I'm trying to write something I believe is straightforward but wanted to check that I'm doing it right.

All I want is to update the position of a 2D sprite based an acceleration and velocity. I'm using time based modelling so I have time deltas at my disposal. My current approach looks a little like this:

int rotDuration = btnRight.GetDuration() - btnLeft.GetDuration();
ship.Facing += (ANGULAR_VELOCITY * (rotDuration)); //angular displacement (rads?)

Rise::Vector2D forwardDir(sin(ship.Facing), cos(ship.Facing));
Rise::Vector2D finalVelocity = ship.Velocity + (elapsedTime * btnAcc.GetDuration() * MAX_ACC * forwardDir);
ship.Position += finalVelocity;

Hopefully that's pretty straightforward. I get the duration that rotation was occurring for, then multiply this by the speed I wish to allow my ships to rotate. For the velocity, I applied the equation from here. I'm very unsure as to why it says to scale the whole thing by max acceleration, though...

Does this look correct and will it produce the sort of rotation you would expect? For context I'm simulating space- or ice-like inertia.


texts: How can I edit collisions in Unreal Engine?

texts: I made a concave house model. When I import it to Unreal Engine it generates a simple box collision that covers the full mesh. I need a collision that only covers the walls. How can I generate one or edit the collision? (I'm using Maya.)


texts: Elements of a widget blueprint do not appear if I click on simulate

texts:
I made a widget that contains 2 minimaps and 2 texts related to a character's variables.

When I click the play button (Selected Viewport) everything happens fine:

Focus where I circled in pink.

It turns out that when I click the Simulate button, these two texts do not appear, but the minimaps do:

I did a test by first clicking the play button (Selected Viewport) and then I ejected the character (which for me is the same thing as simulating, except without closing and opening the game) and the texts appeared, so my problem is only when I'm done start simulating.

I would like to know how to make these 2 texts appear even if I click on simulate instead of play.


texts: Are SDL games trivially portable from Linux to Windows?

texts:
I have a small game made with SDL2 and I want to port it to Windows. Would I hav eto write a lot of #ifdefs to port it or will the very same code work on Windows and Linux? Or is it more complicated?

Sorry if these are silly questions. I couldn't find existing resources on porting SDL games between desktop systems and I've never done this before!


texts: Blending textures together, texture fade over / fade in

texts:
What is the best way to render a texture overlapping effect?

Like in this example:

I want either the grass to fade in to the snow texture, or the other way around. No rough edges. Somehow make them blend over. So the grass has a bit of snow or the snow has a bit of grass How is this possible during runtime? If that's possible.

I don't render this by using the SpriteBatch, since the ground isn't rectangles (they can be moved).

This is the way I render each shape (each one of those squares):

// LoadTexture
// Apply EffectPass

device.DrawUserIndexedPrimitives<VertexPositionNormalTexture>
(
    PrimitiveType.TriangleList,
    render.Item.Points, // Array of VertexPositionNormalTexture
    0,
    render.Item.Points.Length,
    render.Item.Indexes, // Array of int indexes (triangulation)
    0,
    render.Item.Indexes.Length / 3,
    VertexPositionNormalTexture.VertexDeclaration
);


texts: How should a circuit or power system (like redstone in Minecraft) be implemented

texts:
I want to implement a power-system like the redstone system in minecraft.

I have n power sources and m cables. If I disconnect the power source or a cable the circuit should turn off.

How do I avoid circles?
If each cable with the status "on" powers the nearby cables I can create infinite circles where there is no power source involved (see image). Plus site is that it runs in T=m

I could send power burst through the graph starting at every power source and in each update call I turn every cable off. Problem is it runs in T=n*m.

Is there a best practice? In Minecraft the redstone system was very slow so I think I overlooked something.

EDIT: The system should work without a distance based decay.


texts: How do I prevent receiving data from the network from dropping rendering frames in a multiplayer game?

texts:
I'm building an HTML5 massively multiplayer online game. I've been working on this project for awhile, but am having some trouble sorting through a couple of performance issues.

Since this is a multiplayer game, information is sent to and received from the network. When a client needs to know about new entities on the screen, the server must stream this data.

Unfortunately, one big problem I'm having right now is that sometimes either a) a lot of data needs to be streamed or b) lots of small pieces of data are streamed in a short amount of time. Both scenarios currently cause the client to drop rendering frames as the client spends its time receiving packets and processing the data.

What is the best way to prevent the networking data from causing frame rate problems? I am particularly interested in approaches to this kind of system that minimize frame drop issues, though suggestions tailored to my specific situation are welcome.

Update: To elaborate on the type of information sent in my particular case, my client does minimal interpolation and receives updates anytime the state of an entity changes on the server. The client also receives large packets with the entire state of an entity the first time the client needs to know about that entity.


texts:
In Valve's software Hammer (Counter-Strike Global Offensive SDK Hammer software, for reference), I have created several props that I plan to have players jump on. However, players pass right through this prop.

How can I make it so that a prop is solid, and so that players can't walk right through the prop? Also, the prop is a static prop.


texts: How to Make Different Instances of an Object Have Different Sprites

texts:
In Game Maker, I am trying to make it so that three instances of an object have three different sprites. Using DnD, what would be the optimal way to do this? If it helps, the three instances are different sizes and are in separate, fixed places.

EDIT: I have added the following, and it gives an error that the global variable has not been set.


texts:
I have the next issue when a object is suspended in the air far enough of the ground.

How the algorithm works:

It checks if the coordinates in the light view matrix of this cascade are inside the the actual cascade's view ([0,1] interval).
If it is inside, it checks the depth to see if it is in shadow and finish.
If it is not, it checks the next cascade.

The coordinate that it is checking is actually inside this shadow cascade, but the cube lands just partially in this shadow cascade, and for this reason the surface is cut and you can see the floor that is at the other side of the cube, which is the floor that is checking to draw or not the shadow, producing this artifact.

Is it any way to solve it? I tried checking if the next cascade has lower depth but it cause other problems and artifacts that are even worse because of the glur effect and the lower precision of the next cascade.

It just happen with distant flying objects or high objects, anything else it works great.


texts: How do I calculate forces from a cinematic rigidbody?

texts:
Imagine a game with an astronaut that is directly controlled by a players pose. If the player now rotates their arm from the waist to the head, a rotation of the whole body in the opposite direction would be the result. Alternatively think about a sprinter which is controlled by the players pose. The player extends one of their legs. What would be the resulting force to the ground or velocity of the sprinter?
How do I calculate the resulting force to the whole body?
For the sake of specifity, you can assume Unity with rigidbody physics, but I'm having a problem of understanding if a rigidbody game engine can even be used to inversely calculate forces from pose changes of a kinematic character.


texts: How to calculate tangents in beam data to fit given trajectory

texts:
I'm currently trying to create a trajectory effect (in UE 4.25.1) similar to one from the last of us:

I have created a beam with niagara, which lets me determine the starting point of the beam, endpoint and the tangents for both of them:

I am happy with the look of it, but I don't understand the math behind the tangent values. My goal is to make the line overlap the actual trajectory of the projectile (arrow), which is calculated in a BluePrint.
Most examples I found online either just use the Debug-Line from the Predict Projectile Path by Trace Channel, which looks rather bad or they spawn some kind of mesh every x interval on the trajectory line, which is not the kind of indicator I want to create.
Right now, the arrow is being shot from a starting point (bow) with a given velocity and a direction (camera angle). Unreal then calculates the drop of the arrow according to gravity and velocity.
So, the starting position of the beam would be the same as the starting position of the arrow and the angle/rotation would be equal, as well. I can also determine the endpoint for the beam (endposition of the arrow).
However I don't understand how I could calculate the required tangents for the beam to represent the trajectory of the arrow (dropping)? I am new to UE and math is not my strongest point to say the least. Is this even possible with the way I set things up?


texts: How should I store world data in a 2D grid sandbox game?

texts:
I'm just a beginner game developer and working on my own first project (beyond copying other games for learning skills).

Because I really like sandbox games (like Minecraft, Rimworld, Terraria etc..), I am trying to make a 2D grid-based sandbox game.

For now I am building a plan for my game's base architecture, and I'm having an issue managing world data (for more specifically, handling Block/Tile Data).

In a sandbox game, you can easily place or remove some blocks (or tiles) as you like.
So you need to store it in some kind of storage and sort it so that you can access these blocks easily.

So I thought I should make an Array that holds pointers to Tile Class instances, and the index in the array corresponds to the grid's index. I started writing code based on this idea.

But here is the problem: since not every tile's size is 1x1, some may take 2x3 blocks. If i just put this object's pointer in the array, there are 6 identical pointers stored in single array.

I think that may not the best way to handle tile data.

I thought there might be some way to handle tile data better than to just put a pointer in array.

So how should my game handle multi-grid-cell sized block (or tile) data?


texts: How to Handle Lighting from a 3D Game Engine with a Roguelike Game using Shadowcasting

texts:
Normally the shadowcasting will, from the player position, set a brightness amount to each relevant tile. Yet I'm making a roguelike with a 3D map, and Unity has lighting.

Currently I have the player piece with a point light, and game objects that haven't been seen yet are set to inactive. but it doesn't have the same effect.

Has anyone resolved this situation?  Any suggestions?

Addendum:
Screen shots:

I somewhat like the effect as it is in the screenshots; I'd like to be able to control the amount of light in each 'tile' if possible.


texts: What are "distance fields" and how are they applicable to collision detection?

texts:
I was looking at some efficient methods for collision detection in a scene with both static and dynamic objects when I came across "distance fields."

I tried to search and understand this concept, but I could only find papers written in very complex language. Can someone explain in easy words what distance fields are and how can they be used for collision detection?


texts:
I currently have a fairly decent framework for a side-view strategy-ish game built around libgdx. While I may have reinvented the wheel a couple of times, I believe I've done the vast majority with tools already existing in libgdx parts properly: camera, viewport, sprites, etc.

One thing I've not used at all is Scene2D, as I've simply not had a need for it (yet). Drawing the sprites at their positions is more than enough. The terrain is procedurally generated pixel art that is drawn beforehand.

Now I've come to the point where I need to implement some fairly basic UI-systems. Nothing out of the ordinary: A few buttons to click, and an area with additional info.

I haven't decided entirely on which approach to use when implementing the UI, but in the meantime I'm going with a fairly simple approach:
When everything else is drawn, I reset the projectionmatrix so that everything drawn after that never moves with the world:

    Matrix4 uiMatrix = camera.combined.cpy();
    uiMatrix.setToOrtho2D(0,0,viewport.getWorldWidth(), viewport.getWorldHeight());
    batch.setProjectionMatrix(uiMatrix);
    // Then draw the UI

This works fine, except when the aspect ratio changes and/or when the window resizes. Therefore I would like to find a more scalable way.

Is Scene2D the way to go? It currently looks like the only reasonable way of getting an UI that works well with resizing the screen and panning around.

The info I find on how to implement it either assumes a complete rewrite to use actors instead of sprites, or doesn't scale well at all.


texts: Unity 5 2D drawing sprites programmatically

texts: How can I draw sprites in Unity 5 programmatically ? I am looking for something similar to spriteBatch.Draw() in XNA. The results I get when I search about it are either outdated http://wiki.unity3d.com/index.php?title=SpriteManager (this was written in 2012), or they are done using the unity interface. All I can find is a Sprite class in UnityEngine.dll. Is this what I need ? How would the drawing work ? I really don't get it.


texts: How to decide which GameObject should handle the collision?

texts:
In any collision, there are two GameObjects involved right? What I want to know is, How do I decide which object should contain my OnCollision*?

As an example, let's suppose I have a Player object and a Spike object. My first thought is to put a script on the player that contains some code like this:

OnCollisionEnter(Collision coll) {
    if (coll.gameObject.compareTag("Spike")) {
        Destroy(gameObject);
    }
}

Of course, the exact same functionality can be achieved by instead having a script on the Spike object that contains code like this:

OnCollisionEnter(Collision coll) {
    if (coll.gameObject.compareTag("Player")) {
        Destroy(coll.gameObject);
    }
}

Whilst both are valid, it made more sense to me to have the script on the Player because, in this case, when the collision happens, an action is being performed on the Player.

However, what's making me doubt this is that in future you may want to add more objects that will kill the Player on collision, such as an Enemy, Lava, Laser Beam, etc. These objects will likely have different tags. So then the script on the Player would become:

OnCollisionEnter(Collision coll) {
    GameObject other = coll.gameObject;
    if (other.compareTag("Spike") || other.compareTag("Lava") || other.compareTag("Enemy")) {
        Destroy(gameObject);
    }
}

Whereas, in the case where the script was on the Spike, all you would have to do is add that same script to all the other objects that can kill the Player and name the script something like KillPlayerOnContact.

Also, if you have a a collision between the Player and an Enemy, then you likely want to perform an action on both. So in that case, which object should handle the collision? Or should both handle the collision and perform different actions?

I have never built a game of any reasonable size before and I'm wondering if the code can become messy and difficult to maintain as it grows if you get this sort of thing wrong in the beginning. Or maybe all ways are valid and it doesn't really matter?

Any insight is much appreciated! Thank you for your time :)


texts: Surface shader ignores lighting in vertexLit path

texts:
I want to use a surface shader in VertexLit(not Forward) rendering path. I caused a problem that the compiled shader completely ingnores lighting from the light sources on the scene.
Here's the code:

Shader "Custom" {
    Properties {
        _MainTex ("Base (RGB)", 2D) = "white" {}
    }
    SubShader {
        Tags { "LightMode" = "Vertex" }
        LOD 200

        Lighting On

        CGPROGRAM
        #pragma surface surf Lambert
        #pragma target 3.0

        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
        };

        void surf (Input IN, inout SurfaceOutput o) {
            half4 c = tex2D (_MainTex, IN.uv_MainTex);
            o.Albedo = c.rgb;
            o.Alpha = c.a;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

I really need this shader to work. Please help me.


texts: Unity character vibrates during idle animation

texts:
My player character vibrates in his idle pose for some reason. He has 3 animations (IdleState, WalkState, RunState) and the latter 2 run smoothly, but when I don't provide directional inputs and he enters his idle state, he looks like he had 100 espresso shots!

43 second video demo here: https://youtu.be/QuHPrkjx-T4

I am not using a blend tree for the moment and the animation used for IdleState was exported with only a single frame (frame 1) from Blender. Unity's FBX import panel has the animation listed as playing from frame 0 to 1.  I have tried many different configurations for this animation in the importer, including looping, not looping, matching pose, setting animation length to 0.  None of that fixed the jitters (the latter nullified the animation). I have restructured my scripts but have not found a solution for this yet.

My character uses 2 scripts, one to control movement, and another to control animation.

This one controls movement:

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

public class PlayerController : MonoBehaviour {

    private float charSpeed;
    public float walkSpeed;
    private float runSpeed;
    public float jumpForce;
    public CharacterController controller;
    public float gravityScale;
    private Rigidbody rb;

    public static Vector3 moveDirection;

    // Start is called before the first frame update
    void Start() {
        controller = GetComponent<CharacterController>();
        rb = GetComponent<Rigidbody>();
        charSpeed = walkSpeed;
        runSpeed = walkSpeed * 2;

    }

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

        if (Input.GetButton("Fire3"))
        {
            charSpeed = runSpeed;
        }
        else {
            charSpeed = walkSpeed;
             }

        // Declare movement vector
        moveDirection = new Vector3(Input.GetAxis("Horizontal") * charSpeed,
            moveDirection.y,
            Input.GetAxis("Vertical") * charSpeed);

        // Set y-axis movement conditions (jumping, grounded, free-fall)
        if (Input.GetButton("Jump") && controller.isGrounded){
            moveDirection.y = jumpForce;
        }
        else if (!controller.isGrounded)
        {
            moveDirection.y = moveDirection.y + Physics.gravity.y * gravityScale * Time.deltaTime;
        }
        else
        {
            moveDirection.y = 0;
        }

        // rotated 45 deg to align controls to camera instead of world space:
        Vector3 rotated = Quaternion.Euler(0,-45,0) * moveDirection;
        controller.Move(rotated * Time.deltaTime);

        Vector3 lookDir = new Vector3(rotated.x, 0, rotated.z);

        if (lookDir != Vector3.zero)
        {
            transform.rotation = Quaternion.LookRotation(lookDir);
        }
    }
}

...and this one plays the animations:

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

public class CharacterAnimator : MonoBehaviour
{

    private Rigidbody rb;
    Animator animator;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        animator = GetComponent<Animator>();

    }

    void FixedUpdate() // was Update(), no change
    {
        if (Input.GetAxis("Horizontal") == 0 && Input.GetAxis("Vertical") == 0)
        {
            animator.Play("IdleState");
        }
        else
        {
            if (Input.GetButton("Fire3"))
            {
                animator.Play("RunState");
            }
            else
            {
                animator.Play("WalkState");
            }
        }
    }
}

What is causing this jittery idle state bug?


texts:
Im making a soccer game where you basically have to shoot the ball to the goal and the ball goes to where you touch the screen.
Im having an issue with the ball though, when the ball spawns on the player it goes directly to the top left corner of the screen, without even touching the screen. This might be really easy but I cant seem to find the solution

Here's the code:

Ball class

public void shootToward(float targetX, float targetY) {

    velocity.set(targetX - position.x, targetY - position.y);
}

public void update(float deltaTime) {

    position.add(velocity.x * deltaTime, velocity.y * deltaTime);
    velocity.scl(1 - (1f * deltaTime));
}

Game class

public void create () {

    cam = new OrthographicCamera();
    cam.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    batch = new SpriteBatch();
    batch.setProjectionMatrix(cam.combined);

    player = new Sprite(player1);
    player.setX(MathUtils.random(Gdx.graphics.getWidth()));
    player.setY(MathUtils.random(Gdx.graphics.getHeight() / 2));

    b.position.set(player.getX(), player.getY());

}

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

    b.update(Gdx.graphics.getDeltaTime());

    batch.begin();
    batch.draw(bg, 0, 0);
    batch.draw(goal1, Gdx.graphics.getWidth()/4-20, Gdx.graphics.getHeight() - 180, 420, 130);
    if (!Gdx.input.isTouched()) {
        batch.draw(bs, b.position.x, b.position.y);
        b.shootToward(Gdx.input.getX(), Gdx.graphics.getHeight() - Gdx.input.getY());
    }
    player.draw(batch);
    batch.end();
}

Thanks in advance.


texts: LibGDX - Executing 2 different touchDown events in the same method

texts:
On the bottom left of my screen is a circle with an Arrow and on the bottom right is a circle with a gun. If the player is in jetpack mode and the Arrow "button" is clicked he flies like flappy bird (touch down = push him upwards, touch up = he falls down) - if the player is in jump mode he simply jumps.

My problem is I can't seem to fly the jetpack upwards AND shoot a bullet at the same time (i.e. the case where I'm tapping both the Arrow and the Gun). Is there some sort of trick I can use here?

My touchDown() method is in a class Controller looks like this:

@Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        int tapY = Gdx.graphics.getHeight() - screenY;
        //true if the arrow (bottom left) is tapped
        arrowClicked = inRange(upArrowSprite, screenX, tapY);
        //true if the gun (bottom right) is tapped
        gunClicked = inRange(gunSprite, screenX, tapY);

        // if arrow is pressed and player isn't in jetpack mode, make him jump
        if (arrowClicked) {
            if (!(player.getState() == ObjectState.JETPACK_MODE)) {
                player.setState(ObjectState.JUMPING);
                player.jump();
            // if the player is in jetpack mode, accelerate him upwards every time arrow is tapped
            } else {
            player.setTouchedDownFlying(true); // set boolean to be true
            player.setState(ObjectState.JETPACK_MODE);
        }
        }
        //if the gun is tapped (bot right), shoot a bullet
        if (gunClicked) {
            player.shoot();
            }
        return true;
    }

these are the relevant methods in Player:

public void update() {
    moveBy(xSpeed, -gravity);
    ...
    if(touchedDownFlying) {
        jetPackFly();
    }
    ...
}

public void setTouchedDownFlying(boolean bool) {
    touchedDownFlying = bool;
}

public void jetpackFly() {
        setySpeed(getySpeed() + flyAcceleration);
}

public void shoot() {
        Bullet i = new Bullet(this);
        bullets.add(i);
}

Any help is highly appreciated, thank you :)


texts: Using unity app how to read the asset in android SDCard?

texts:
I am trying to read one file from my android sd card from my unity application, but its not reading.

using the asset bundle i have exported my file and kept in my android device sd card  and i am trying to fetch it and show into my scene.

Here is the code i have used for this:

public string URL;
public string URLAndroid = Application.persistentDataPath+/cube.unity3d;
public string AssetName;

private string path;

IEnumerator Start() {

    //path = System.IO.Path.Combine (Application.persistentDataPath, "/cube.unity3d");

    // Download the file from the URL. It will not be saved in the Cache
    using (WWW www = WWW.LoadFromCacheOrDownload(URLAndroid, 1)) {
        yield return www;

        if (www.error != null)
            throw new Exception("WWW download had an error:" + www.error);

        AssetBundle bundle = www.assetBundle;

        if (AssetName == "")
            Instantiate(bundle.mainAsset);
        else
            Instantiate(bundle.LoadAsset(AssetName));

        // Unload the AssetBundles compressed contents to conserve memory
        bundle.Unload(false);

    } // memory is freed from the web stream (www.Dispose() gets called implicitly)
}

Here i have used the URLAndroid as a normal downloading method and  ihave tried to fethch the model using system.io method but its not happening.
I have created the corresponding folder in my android device and kept my assets eventhough its not happening.

Plesae help me to solve this issue.