texts: Unity: How can I get realtime image capturing at ~60fps?

texts:
I am writing an application in Unity which will be required to capture an image from a camera every frame (at ~60fps), and send the resultant data to another service running locally.

The issue is, I am aware that capturing the rendered data from the camera can cause massive frame rate drops (as explained in this article) when using the GetPixels() method. The article explains that "GetPixels() blocks for ReadPixels() to complete" and "ReadPixels() blocks while flushing the GPU" which is why the GPU and CPU have to sync up, resulting in a lag.

I have produced a sample project with a script attached which simply outputs frames to a file as a PNG to replicate the functionality of the program I wish to create. I have done my best to implement what is described in the article, namely allowing the GPU to render a frame, then wait a few frames before calling GetPixels() so as not to cause the GPU and CPU to forcefully sync up. However, I really haven't made any progress with it. The project still plays at about 10-15fps.

How can I achieve a realtime capture of 60 frames per second in Unity?

using System;
using System.Collections;
using System.IO;
using UnityEngine;

namespace Assets
{
    public class MyClass: MonoBehaviour
    {
        private const float reportInterval = 0.5f;
        private int screenshotCount = 0;
        private const float maxElapsedSecond = 20;
        private string screenshotsDirectory = "UnityHeadlessRenderingScreenshots";
        public Camera camOV;
        public RenderTexture currentRT;
        private int frameCount = 0;
        private Texture2D resultantImage;

        public void Start()
        {
            camOV.forceIntoRenderTexture = true;
            if (Directory.Exists(screenshotsDirectory))
            {
                Directory.Delete(screenshotsDirectory, true);
            }
            if (!Application.isEditor)
            {
                Directory.CreateDirectory(screenshotsDirectory);
                camOV.targetTexture = currentRT;
            }
        }

        // Update is called once per frame
        public void Update()
        {
            //Taking Screenshots
            frameCount += 1;
            if (frameCount == 1)
            {
                TakeScreenShot();
            }
            else if (frameCount == 3)
            {
                ReadPixelsOut("SS_"+screenshotCount+".png");
            }

            if (frameCount >= 3)
            {
                frameCount = 0;
            }
        }

        public void TakeScreenShot()
        {
            screenshotCount += 1;
            RenderTexture.active = camOV.targetTexture;
            camOV.Render();
            resultantImage = new Texture2D(camOV.targetTexture.width, camOV.targetTexture.height, TextureFormat.RGB24, false);
            resultantImage.ReadPixels(new Rect(0, 0, camOV.targetTexture.width, camOV.targetTexture.height), 0, 0);
            resultantImage.Apply();
        }

        private void ReadPixelsOut(string filename)
        {
            if (resultantImage != null)
            {
                resultantImage.GetPixels();
                RenderTexture.active = currentRT;

                byte[] bytes = resultantImage.EncodeToPNG();
                // save on disk
                var path = screenshotsDirectory + "/" + filename;
                File.WriteAllBytes(path, bytes);

                Destroy(resultantImage);
            }
        }
    }
}

The article implies that it is possible, but I haven't managed to get it to work.

Many thanks in advance for your help.


texts: How can I create delays for sprite animations that work correctly when the application is killed and restored?

texts:
Please see my original question here:

Using System Time to compute delay times that correctly deal with app pauses?

In summary, I am attempting to to introduce a delay (say of 5 seconds or so) before a sprite takes a particular action (say a jump) - but this needs to be preserved when the user pauses the game or the system kills the app and it is re-launched.  I tried to carry out the suggestion in the answer to my previous question (to save the time on app pause and then compare it to current time when resumed to see how long the app was inactive for, then to add this to the time that I check against, but this comes with it's own problems and I'm still not sure of the best approach).

When the app is re-started following the system trashing it to reclaim resources, the time (now correctly adjusted to include time the app was sitting in the background). I reset & compare the time when restoring the bundle. However, it then takes 4 or 5 seconds to re-load everything (this is an OpenGL app, so resources are loaded in onSurfaceCreated which comes after the Bundle is restored) so by the time the game starts, vital seconds have already passed (so, lets say when resuming there should be 4 seconds remaining before a sprite appears, it will still appear instantly).
As mentioned, when the app goes into the background, I'm storing the time and then comparing it to the time when the bundle is restored to get the 'app not active' time - however, what happens in cases when the user (or system) sends the app into the background but the app stays active, and is then re-launched?  the Bundle is then never restored, so I can't grab the restore time to do the comparisons.

So how best to deal with sprite delays which won't break when the app is in the background and not running?  Basically I seem to need a way to have a timer that can be stopped when the app is paused or not active. (The countdown method I described in the original question seems to be the closest thing, ie, just keep a value of say 100 and decrease it each time a game-tic occurs, this would be a lot easier and tidier, however, it would also mean if the game were to ever run slower than 60 ticks per seconds, the delays would be longer), but is there someway I could use 'real' time rather than something anchored to my tics per second that wont' carry on merrily when the game isn't running?

Code for delay based on System time (this is in my game logic update)

//Timer is initially set to 0, so grab time to start timer
if (timer == 0)
timer = System.currentTimeMillis();

//Delay completed? (5 Seconds)
if (System.currentTimeMillis()>Timer+5000){
//Reset for next delay
levelTimer = System.currentTimeMillis();
//Carry out required action here (example, jump or more sprite)
}

Code to reset and re-adjust the timer (currently in onRestoreInstanceState)

timer+=(System.currentTimeMillis()-pauseDuration);


texts: Pro's/Con's of separating game logic and render threads

texts:
Originally, I have thought that it is good practice to separate my game logic (updating) from my rendering thread.  In this threading model, the rendering thread has no limitation on frame rate and simply draws whatever information is currently made available by the updating thread.  On the other hand, the updating thread is monitored, and has a capped frame rate.

I'm led to believe this is BAD and will lead to many coding struggles down the road...

So, I'm wondering what are the POTENTIAL benefits for separating updating from rendering?
Likewise, what are the POTENTIAL benefits gained when keeping the updating and rendering in the same thread?  What are the losses for each method?


texts: How can I create a VBO when I don't yet know how many vertices it will contain?

texts:
I'm trying to convert my 3D block work rendering from immediate mode and display lists to VBOs. I'm having trouble understanding how to properly handle creating the buffers: I really don't know how many vertices, colors, and texture coordinates I'll be passing in until after I've already iterated all of the block faces I expect to render.

How can I create a VBO when I don't know it's size? Every single tutorial/example uses a fixed amount.


texts: An archery's arrow should be a node or particle?

texts: I am using Sprite Kit to do game development. I would like like to design an archery with arrow. Should I use the arrow as one of the node? If so, it is a concern to have too many arrow on the screen, so that the performance will be slower? What do you think?


texts: How to implement glDrawElementsBaseVertex in OpenGL ES 3.0

texts: I want to convert simple OpenGL project to Android native using OpenGL ES3.0, one of the functions which is not implemented is glDrawElementsBaseVertex, I have one VBO which contains many entries inside and known each offset and size, so how can I implement this function by glDrawElements method or is there another way?


texts: Can I use a genetic algorithm for balancing character builds?

texts:
I'm starting to build a online PVP (duel like, one-on-one) game, where there is leveling, skill points, special attacks and all the common stuff. Since I have never done anything like this, I'm still thinking about the math behind the levels/skills/specials balance.

So I thought a good way of testing the best builds/combos, would be to implement a Genetic Algorithm. It'd be like this:

Generate a big group of random characters
Make them fight, level them up accordingly to their victories(more XP)/losses(less XP)
Mate the winners, crossing their builds, to try and make even better characters
Add some more random chars, emulating new players
Repeat the process for some time, or util I find some chars who can beat everyone's butt

I could then play with the math and try to find better balances to make sure that the top x% of chars would be a mix of various build types.

So, is it a good idea, or is there some other, easier method to do the balancing?

Edit: Interesting thoughts in all those answers, still waiting to mark just one as resolved. I can see the problem with the AI implementation, but in my specific case, the AI is pretty straightforward. It'll be based directly on the opponent build and chosen parameters for the duel. (The human player will not have access to those info, so can not foresee the enemy stats and strategy). I've read a topic about testing, and I think I'll starting with simple automated tests and in the future evolve it to a genetic algorithm.


texts: How to render a PNG-file on the screen with SDL?

texts:
I'm coding a 2D platformer in using C++ and SDL2. I've started by coding the GUI, however I'm unsure how to get the menu buttons onto the screen and in the right positions.

How do I load the PNG menu buttons onto the screen in a way that I can adjust them to get them in the right spots?


texts: Microsoft XNA Platformer Example, is the Collsion Detection implemented accurately?

texts:
The example provided by Microsoft seems as if the collision detection (from what I can see) will have a small error. When the user collides with an Unpassable tile, the depth of the intersection is calculated. The smaller of the depth values X and Y is used to fix the position of the user so it no longer collides with the tile. But if the user was travelling diagonally could this result in the user not ending up in precisely the point where the character would first collide with the tile?

I'm probably wrong but that's just the way I see it.

   private void HandleCollisions()
        {
            // Get the player's bounding rectangle and find neighboring tiles.
            Rectangle bounds = BoundingRectangle;
            int leftTile = (int)Math.Floor((float)bounds.Left / Tile.Width);
            int rightTile = (int)Math.Ceiling(((float)bounds.Right / Tile.Width)) - 1;
            int topTile = (int)Math.Floor((float)bounds.Top / Tile.Height);
            int bottomTile = (int)Math.Ceiling(((float)bounds.Bottom / Tile.Height)) - 1;

            // Reset flag to search for ground collision.
            isOnGround = false;

            // For each potentially colliding tile,
            for (int y = topTile; y <= bottomTile; ++y)
            {
                for (int x = leftTile; x <= rightTile; ++x)
                {
                    // If this tile is collidable,
                    TileCollision collision = Level.GetCollision(x, y);
                    if (collision != TileCollision.Passable)
                    {
                        // Determine collision depth (with direction) and magnitude.
                        Rectangle tileBounds = Level.GetBounds(x, y);
                        Vector2 depth = RectangleExtensions.GetIntersectionDepth(bounds, tileBounds);
                        if (depth != Vector2.Zero)
                        {
                            float absDepthX = Math.Abs(depth.X);
                            float absDepthY = Math.Abs(depth.Y);

                            // Resolve the collision along the shallow axis.
                            if (absDepthY < absDepthX || collision == TileCollision.Platform)
                            {
                                // If we crossed the top of a tile, we are on the ground.
                                if (previousBottom <= tileBounds.Top)
                                    isOnGround = true;

                                // Ignore platforms, unless we are on the ground.
                                if (collision == TileCollision.Impassable || IsOnGround)
                                {
                                    // Resolve the collision along the Y axis.
                                    Position = new Vector2(Position.X, Position.Y + depth.Y);

                                    // Perform further collisions with the new bounds.
                                    bounds = BoundingRectangle;
                                }
                            }
                            else if (collision == TileCollision.Impassable) // Ignore platforms.
                            {
                                // Resolve the collision along the X axis.
                                Position = new Vector2(Position.X + depth.X, Position.Y);

                                // Perform further collisions with the new bounds.
                                bounds = BoundingRectangle;
                            }
                        }
                    }
                }
            }

            // Save the new bounds bottom.
            previousBottom = bounds.Bottom;
        }


texts: Implementation of finding an index in a 1D array for a triangular grid

texts:
Am using a while loop to find an index within a 1D array, is there an easier, less-time-consuming and/or mathmatical way to find the index?

Consider the next grid:

 4   o
     |\
     | \
     |  \
 3   o---o
     |\  |\
     | \ | \
     |  \|  \
 2   o---o---o
     |\  |\  |\
     | \ | \ | \
     |  \|  \|  \
 1   o---o---o---o
     |\  |\  |\  |\
     | \ | \ | \ | \
     |  \|  \|  \|  \
 0   o---o---o---o---o

     0   1   2   3   4

To find an index in the triangular grid within a 1D array I have the next function:

//int size = 5;
int getindex( int x, int y )
{

    int columnCount = size;
    while( y-- > 0 ) x += columnCount--;

    return x;

}

The array (The numbers within the parenthesis are the coordinates and to simplify your view, in reality the (x,y) is in its whole the data):

pointdata data[ 15 ] = {
    (0,0), (1,0), (2,0), (3,0), (4,0),
    (0,1), (1,1), (2,1), (3,1),
    (0,2), (1,2), (2,2),
    (0,3), (1,3),
    (0,4),
};


texts: Skeletal Mesh Cloth Simulation bug (UDK), unexpected behaviour

texts:
When I try to move to the left (A) the pawn and the cloth move to the left,
and when I move to the right (D) the pawn and the cloth move to the right too...

Why the cloth always goes in same direction than the pawn? I would expect the cloth to go in the opposite direction, like dragged by the pawn.

To anyone who's experienced with pawn with cloth simulation: please help me T_T

Flag model for testing :
Flag bug


texts: Getting one-point-collision object to conform to uneven terrain while keeping constant distance covered

texts:
This is probably best described by image:

I have a character. For floor collision, it uses a single point (the red X). When the character moves, it conforms to the terrain; note how the blue line (its movment per frame) is the same length regardless of the slope.

I have the top three situations working fine. The issue is the bottom one, where the character is crossing over a change in slope. I handle the single-slope case just by rotating the impending movement vector, but obviously that won't work here.

My first instinct was to do something like this:

Measure length to next vertex along first slope.
Subtract length from impending movement vector.
Position impending movement vector at vertex; rotate to match second slope and get resulting position.
Put character at result position.

The problem is that it doesn't seem like this will chain very well if the character has to cross over three or more segments at once (maybe it's moving very fast over round-like terrain).

So basically at this point I'm looking to see if there's an easier solution I'm missing.


texts: Should frame update and network packet sending synchronous or asynchronous?

texts:
I am making a game server that has 60 Update-Per-Second (assume I can most of the time achieve it). In the current model, my main loop does the following tasks in sequence:

Update game logic (position, etc...)
Serialize the data to JSON string
Broadcast the data (through WebSocket) to the clients. Currently the broadcast method is async, that means my server does not stop and wait for the broadcast to finish.

I have 3 questions:

Is it good to send the packages at this frequency?
Should I cap the UPS to 30 instead?
Should I separate the broadcast into another thread, so no matter the UPS of my server, the broadcast will do asynchronous time and depend on the update?

Here is my current code:

public MusicGame(GameRoom room)
{
    this.Room = room;
    this.ConnectedSessions = new List<GameBehavior>();

    this.timer = new Stopwatch();
    this.timer.Start();

    new Thread(() =>
    {
        while (!this.Disposed)
        {
            float delta = (float)this.timer.Elapsed.TotalSeconds;
            if (this.timer.Elapsed.TotalSeconds < MusicGame.FpsLimit)
            {
                Thread.Sleep((int)((MusicGame.FpsLimit - delta) * 1000));
                continue;
            }
            this.timer.Restart();

            delta = Math.Min(DeltaTimeLimit, delta);
            this.Act(delta);
        }
    }).Start();

    this.CurrentScreen = new WaitingScreen(this);
}

public void Act(float delta)
{
    if (this.CurrentScreen != null)
    {
        this.CurrentScreen.Act(delta);
        this.CurrentScreen.SerializeData();

        var data = this.CurrentScreen.SerializedData;
        this.BroadcastGameAsync(data);
    }
}

I am using C# Console Application and WebSocketSharp if it matters.


texts: sample project that mix unityscript and c#

texts:
I like the simplicity of unityscript, at same time I also like the plenty of c# library and open source projects.
I prefer to put my model/controller/logic flow in unityscript using standard unity3d sdk and invoke c# extension library.
Is there any sample project demonstrate how to mix the two scripts in one project?

Your comment welcome


texts: How can I make A* finish faster when the destination is impassable?

texts:
I am making a simple tile-based 2D game, which uses the A* ("A star") pathfinding algorithm. I've got all working right, but I have a  performance problem with the search. Simply put, when I click an impassable tile, the algorithm apparently goes through the entire map to find a route to the impassable tile—even if I'm standing next to it.

How can I circumvent this? I guess I could reduce the pathfinding to the screen area, but maybe I am missing something obvious here?


texts: Can the particle system in Unity select sprites from a spritesheet based on angle?

texts:
I want to create a particle system for gore effects. I have some requirements that don't seem possible with Unity's built-in particle system, but I want to make sure I haven't overlooked something. So the question is, can this (the following) be done with the built-in system or will I need to implement a custom system?
I want the particles to be made of hand-drawn pixel art. The art has specific sprites drawn for the eight cardinal directions. The particle system uses an angle to choose which sprite to use.
For a blood splash effect, the particles are drops of blood. The angle of trajectory is used to select the particle's sprite each frame.
For an explosion of bones, the particles are twirling bones. Each particle has some intrinsic rotation as well as rotational velocity. The angle of the intrinsic rotation is used to select the particle's sprite each frame (independent of the trajectory).


texts: SFML title bar with weird characters when using UTF-8

texts:
(Previously asked at https://stackoverflow.com/questions/4922478/sfml-title-bar-with-weird-characters-when-using-utf-8)

I've just started using SFML and one of the first problems I've come across is some weird characters on the the titlebar whenever I try to use accents or any other extended char.

For instance, I've got:

sf::RenderWindow Ventana(sf::VideoMode(800, 600, 32), "Año nuevóóó");

And the titlebar renders like AÂ+o nuevoA³A³A³

This ONLY HAPPENS if my source code file is enconded in UTF-8. If I change the file encoding to ISO-8859-1, it shows properly. Obviously all of my files use UTF-8, as its the system-wide encoding. I'm using GCC under Ubuntu GNU/Linux.

I've tried using the different utilities in sf::Unicode to adapt the text, but none of them seems to work.


texts: How can I detect when the formations of units are broken? - Unity 2018.2.x

texts:
Sorry if I don't write this properly, this is my first post here.
I am working in Unity 2018.2.xx
 I have an issue where the current solution for checking whether a squad formation is broken. For ease of explanation, it's easier to visualise in 2D space from a top-down perspective.
currently, there is the Squad is tracked by its own class and is an empty game object. the units in the squad have their own unit class and pass data to the Squad controller when needed. i.e on the death of a unit, it tells the squad manager to remove itself from the squad

the Squad formation is tracked in a 2D array and for testing purposes, the squad was formed in a 3*3 square as I tried to display below

o o o
o o o
o o o

what I need, is a way to detect when the squad is split into two, by the player killing/ removing units from the middle.
i.e the squad on the left still has one unit in the middle, and when the unit in the middle column, the unit "breaks" and the remaining  survivors scatter.

o o o    o x o
o x o    o x o
o x o    o x o

Currently, I am checking each column and making sure it isn't the start or end. Then, checking the row to see if there are still units in that column. if not, it runs the splitting functions.

so my question is, is there a better way to do this without going too complex with the approach


texts:
As far as I understand Direct3D 11 I have to specify certain BindFlags in order to use a resource in a specific stage of the pipeline.

From my experience some combinations are more common like BindFlags.RenderTarget | BindFlags.ShaderResource for post processing effects. And I guess it could also be quite handy sometimes to set the ShaderResource flag for DepthStencilBuffers.

So I would like to know what is happening behind the scenes. What is the drawback of simply setting all of them? Would it be a minor performance hit? Or is as bad as an individual copy of the resource for every different flag?


texts: Replacing UI GameObjects with Scriptable Object script

texts:
In my game I'm trying to make a series of mock web pages. To make it easier, I thought I'd make all the webpage UI into Scriptable Objects and have a game manager script determining what content to display on the UI. However, I'm doing a small test that isn't going as planned.

Because the content, style, and layout of each page may be quite different, I decided to make a webpage-styled template and have the content manager switch out scriptable object properties as a GameObject so that it takes everything that will be in the prefab. This doesn't seem to be working and I'm not sure what I'm doing wrong.

For now, I'm just testing this method with a very basic script. It's not changing the main content as a GameObject, though it is doing it on my tab textmesh property. It seems to have an issue with transplanting a prefab into the defined content space, but no errors are popping up. I'd appreciate some advice here.

Web Content Scriptable Object Script:

using UnityEngine;
using UnityEngine.UI;

[CreateAssetMenu]
public class WebContent : ScriptableObject
{
    public string tabTitle; //WebPage Title
    public GameObject canvasContent; //Web Page UI Content I want to change via prefab attached to a  Scriptable Object
}

Content Display Script:

using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class ContentDisplay : MonoBehaviour
{
    public WebContent content;
    public TextMeshProUGUI TabName;
    public GameObject mainContent;

    // Update is called once per frame
    void Update()
    {
        TabName.text = content.tabTitle.ToString(); //This works
        mainContent = content.canvasContent; // This doesn't work

    }
}


texts: Tricks in game mechanics to avoid dealing with network lag compensation?

texts:
Implementing network lag compensation is hard, how to avoid it?

Maybe it's possible to use tricks and build game mechanics in such a way that lag would be percieved as a non critical or even as a natural part of game?

What are those technics and is there any existing games (MMORPG, Strategies, ...) that uses such technics?

UPDATE:

Turn based games don't require lag compensation, but it would be interesting to see approaches for real-time (or just an impression of real-time, the important part - user shouldn't be blocked and forced to wait).

The main reason for me to avoid lag compensation is simplicity.


texts: Wraparound world with wraparound horizontally physics implementation in Unity

texts:
What is the best way to implement a wraparound world with wraparound horizontally physics in Unity?

That means that if I have an object and move it so that a part of it sticks off to right (so that the camera does not see it) I would like the part of the object to be shown on left. The same goes for the left side.

The best (even though I do not like it at all) implementation I was able to find is to have three objects. One of them is visible for the camera and two others become visible when the middle object goes off the camera.

Any other ideas on this?

Here is my explanation with images of what I want to happen:

Thank you.


texts:
I'm trying to rearrange my layers in Unity but I can't seem to drag them. When I try to do this I'm in edit layers under the heading sorting layers and I click on the = symbol and try to drag it but it won't move. I also tried restarting Unity twice but it won't resolve the problem.

Could someone help me with this?


texts: Unity Performance: Recycling Pooled Objects OR Re-Instantiating?

texts:
Re-using pre-instantiated objects in a pool.
Destroying then re-instantiating objects in a pool.

Both pools are limited.

When creating loads of objects which is better for performance?


texts: Which Kinect package for PC takes care of motion tracking too?

texts:
I am aware that there are opensource drivers for interfacing Kinect with the PC. My question is - the drivers at OpenKinect seems to provide only the images and depth data (from the reading of their wiki and API). It seems that you need to provide your own imaging solution.

My question is - is there any all-in-one package, with samples/sources that not only grab images from Kinect, but also do the imaging/motion detection for you?


texts:
I have a small shader that does the following things:

(First cgprogram block)

Copy the current mesh and scales it along the normals
Assign a color to the inflated mesh
Draw the inflated mesh

(Second cgprogram block)

Assign a color to the original mesh
Draw the original mesh

In-game you can only see the inflated mesh because the smaller one gets inglobated.

Is there a way to re-order the rendering order, by drawing first the inflated mesh and then the original mesh, resulting in a sort of outline effect?

What I tried

Setting Cull Front on the inflated mesh and Cull Back on the original mesh

I copied this approach from an outline shader. Unfortunately it leads to other problems such as bad intersecting between inflated mesh in-game.
Changing the Queue in the shader between the two CGPROGRAM blocks

I set the first CGPROGRAM block on "Queue" = "Geometry-10" and the second on "Queue" = "Geometry+0" but.. no effect.

Is there a way to obtain the desired effect? Thanks in advance.

Here are some images to make the question a bit clearer:

Current wireframe situation

Original mesh inside, inflated mesh outside

Current shaded situation

Desired outcome

Inflated mesh set on Cull Front

This is the aforementioned problems between intersecting meshes. The inflated meshes have z-fighting going on.


texts: Physics Simulation - Pushing an object with user control

texts:
I'm working on a 2D game engine using C, SDL and OpenGL. Have worked out basic graphics, physics, and broad phase collision detection. I am trying to realistically simulate "pushing" objects around. I have gotten halfway there, but it doesn't feel right. I've implemented the impulse calculation found here to change linear and angular velocity. I want the blocks to have weight to them, and to slow the player down.

Consider this video. The leftmost block is player controlled. This is how my simulation feels right now.

Is there a relevant mathematical formula for this?


texts: Raycast against a mesh without using a mesh collider?

texts: I have a complicated mesh that doesn't need to have anything to do with physics. However, I need to be able to detect said mesh with a raycast from a point. I have several hundred of these objects that regularly get moved around and rescaled, so a mesh collider is way too computationally expensive - especially since I don't need any form of collision detection other than this raycast. However, the mesh is human-shaped, and is thus irregular enough that I can't just use lots of primitives, nor can I just check if the mouse point is within a specified area (since the area is far too complex to manually specify). Turning the mesh collider off when it's not relevant works a little, but the act of turning the collider on and off is ALSO computationally expensive enough to cause noticeable frame drops. What component or settings can I use in order to raycast a mesh without all the slowdown of a mesh collider?


texts: Unity: OnTrigger detection issue with Child of Prefab

texts:
I'm trying to make a set of tiles on the floor of my 3d world visible only when the Player is nearby them. This will work as single tile prefabs. Just not if I set them within an empty parent gameobject... which is what I really need, ideally, for the sake of game performance.

Once I put them inside the empty parent gameobject, OnTrigger stops working or even registering (debug.log doesn't show anything).

Does anyone know the correct way to access and switch the MeshRenderer on/off via OnTrigger (or OnCollision might be even better... I've tried and same issue) when I have a LevelManager that loads all my game objects at runtime? The Level Manager instantiates a prefab (clone), which has an empty gameobject that's holding the tiles as children?

Code I've tried and that's not working so far:

public class CubeVis : MonoBehaviour
{

    // Use this for initialization
    void Start()
    {

    }

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

    }

    private void OnTriggerEnter(Collider other)
    {
        Debug.Log("hit");
        if (other.gameObject.CompareTag("Cube"))
        {
            Debug.Log("hittt");
            //other.gameObject.GetComponentInParent<MeshRenderer>().enabled = true;
           // other.gameObject.GetComponentInChildren<MeshRenderer>().enabled = true;
            //other.gameObject.GetComponent<MeshRenderer>().enabled = true;

        }
    }

Inspector/Hierarchy info as requested:


texts: AR Foundation video player in Unity without Vuforia

texts:
I am trying to follow this mini tutorial and I can detect an image and replace it with my 3D object. The object is an AR Session Origin tracked image prefab, but when I try to add a Video Player instead, nothing happens.
I was using Unity 2019.2 and got an error when trying to put the video player on the object, then searched about it and Unity fixed that issue on 2019.3.
I am now using 2019.3 and don't get the error anymore, but there is also nothing on the screen when the image is detected.


texts: How to achieve cavalier projection using OpenGL fixed pipeline?

texts:
I want to make a quick demo program showing a cube, or a user loaded model, rotating in screen rendered with one of three projections: perspective, isometric and cavalier.

Using the fixed pipeline, how can I build a projection matrix for cavalier projection?

I think I can start with the orthographic projection matrix and then tweak the values, by eye, until I get the z of the vertices go to the right and up as farther the z is. I want the lines parallel to the z axis rendered as vertical lines 45 degrees rotated to the right.


texts: Is there any ways to fade mesh particles like color over lifetime method with addictive shader. I have little to no understandings of shader coding, and fade rendering issue kicks in even with vertex color shader. Any idea guys?


texts:
So Small problem. I'm able to rotate my camera around my player AND rotate the player when the camera moves around it, but the controls don't seem to move with it. Example: W moves forward. If I look right then W should move forward in that direction. It doesn't, instead it will go left (the forward as it was before).

[SerializeField] GameObject GameCamera;

private void PlayerRotateWithCamera()
    {
        Quaternion CharacterRotation = GameCamera.transform.rotation;

        transform.rotation = CharacterRotation;
    }

private void FixedUpdate()
{
    PlayerRotateWithCamera();
    MovePlayer();
}

I only think the player is rotating cause it looks like it is, but if you look at the move tool the axis dont seem to move with the Player

Just in case my movement isn't getting along with the rotation:

private void MovePlayer()
    {
        moveHorizontal = Input.GetAxis("Horizontal");
        moveVertical = Input.GetAxis("Vertical");

        // more realistic ball movement
        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
        rb.AddForce(movement * moveSpeed);
    }

I also have Tool handle rotation set to global because it's a ball, and well, those axis obvious go crazy while rolling around.

Any help at all would really be appreciated!


texts: Why can't I reference "targetVelocity" variable to this script?

texts:
Recently, I implemented a shooting system for my 2D game but this system has a problem. The problem is that when the player is facing left, the bullets are still being shoot to the right. For fixing this, I need to access a Vector2 named targetVelocity to check whether the player is facing right or not. targetVelocity  is defined in another script called PhysicsObject that is specifically for the player physics and the player script inherits from it (the variable was protected but I changed it to public). I just don't know how to reference this in my Bullet script and I don't want to add the player script to the bullet.  Also, I've read the past questions and answers that were similar to this but I haven't found the answer yet because this is a different case. Thanks in advance.
This is my Bullet script and I want to somehow reference targetVelocity.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bullet : MonoBehaviour
{
    [SerializeField] float speed;
    [SerializeField] float lifeTime;

    public GameObject destroyEffect;

    private void Start()
    {
        Invoke("DestroyBullet", lifeTime);
    }

    private void Update()
    {
        transform.Translate(Vector2.right * speed * Time.deltaTime);
    }

    void DestroyBullet()
    {
        Instantiate(destroyEffect, transform.position, Quaternion.identity);
        Destroy(gameObject);
    }

}

Here is the weapon script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Weapon : MonoBehaviour
{
    public GameObject bullet;
    public Transform firePoint;

    private float timeBtwShots;
    public float startTimeBtwShots;

    private void Update()
    {
        if (timeBtwShots <= 0)
        {
            if (Input.GetButton("Fire1"))
            {
                Instantiate(bullet, firePoint.position, transform.rotation);
                timeBtwShots = startTimeBtwShots;
            }
        }
        else
        {
            timeBtwShots -= Time.deltaTime;
        }
    }
}

This is the player script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewPlayer : PhysicsObject
{
    [Header("Attributes")]
    [SerializeField] private float jumpPower = 10;
    [SerializeField] private float maxSpeed = 1;

    //Singleton instantation
    private static NewPlayer instance;
    public static NewPlayer Instance
    {
        get
        {
            if (instance == null) instance = GameObject.FindObjectOfType<NewPlayer>();
            return instance;
        }
    }

    // Update is called once per frame
    void Update()
    {
        targetVelocity = new Vector2(Input.GetAxis("Horizontal") * maxSpeed, 0);
        //If the player presses "Jump" and we're grounded, set the velocity to a jump power value
        if (Input.GetButtonDown("Jump") && grounded)
        {
            velocity.y = jumpPower;
        }
        //Flip the player's localScale.x if the move speed is greater than .01 or less than -.01
        if (targetVelocity.x < -.01)
        {
            transform.localScale = new Vector2(-1, 1);
        }
        else if (targetVelocity.x > .01)
        {
            transform.localScale = new Vector2(1, 1);
        }
}
}


texts:
I'm creating a rotation for my sun to move, however it quickly extends to Infinity before going into NaN. I thought that taking advantage of the Matrix4f would make this much easier but it does as previously stated. Ideally should have the sun rotate around the sunCenter. Why is it doing this and how would I fix it?

private Vector3f getSunPosition() {
    double rotation = (time / DAY_LENGTH) * 360;
    Matrix4f matrix = new Matrix4f();

    Vector3f pos = sun.getPosition();
    matrix.m03 = pos.x;
    matrix.m13 = pos.y;
    matrix.m23 = pos.z;

    Matrix4f.rotate((float) Math.toRadians(rotation), sunCenter, matrix, matrix);

    return new Vector3f(matrix.m03, matrix.m13, matrix.m23);
}

I had it print out the Vector3f and rotation. The rotation looks a bit odd at first, however I can fix that another time.

Vector3f[1.0, 1.0, 1.0] 0.0
Vector3f[288375.56, 0.18377686, 287549.88] 79.41000366210938
Vector3f[1.96323607E11, -125296.0, 1.96323607E11] 158.82000732421875
Vector3f[1.05730567E17, 0.0, 1.05730567E17] 238.23001098632812
Vector3f[5.5935644E22, 0.0, 5.5935644E22] 240.02999877929688
Vector3f[2.9050322E28, 0.0, 2.9050322E28] 241.8300018310547
Vector3f[1.4801178E34, 0.0, 1.4801178E34] 243.6300048828125
Vector3f[Infinity, 0.0, Infinity] 243.8400115966797
Vector3f[Infinity, NaN, Infinity] 244.04998779296875
Vector3f[NaN, NaN, NaN] 244.25999450683594
Vector3f[NaN, NaN, NaN] 244.41000366210938
Vector3f[NaN, NaN, NaN] 244.55999755859375


texts: What is the recommended reading list for a very experienced s/w developer, with no MMORPG experience, who wants to design an MMORPG?


texts: Problem With Smooth Animation In C++/SDL/OpenGL

texts:
I been working in the animation of a 2D platformer game in C++/SDL/OpenGL, and my team and I reach the point where we need to establish that every animation of the player (Walking, Running, etc..) needs a different framerate for our concept, but I use as a guideline the Game  Programming All In One as a example for the smooth animation, and in the book recommend have variables that limits the movement and the changes of frames.

To clarify what I mean I have in my Sprite class these parameters:

std::vector< Vector2f > delayMovementSprite;
std::vector< int > frameDelayPerAnimation;
GLfloat countX, countY;

Where the vector delayMovementSprite contains all the values for the differents animations and countX increment in every frame until it's equal or greater than the value that correspond in the vector delayMovementSprite.

Something like this:

void Sprite::movePosXWithSpeed()
{
  playerMoveInX = false || playerMoveInX;

  countX++;
  if ( countX > delayMovementSprite.at(getCurrentState()).x )
  {
    countX = 0;
    if ( handlerAnimation->getAnimationDirection() == SpriteData::RIGHT )
    {
      if ( position.x + getSpeedX() + width < 6368.f )
      {
        position.x += getSpeedX();
        playerMoveInX = true;
        return;
      }
    }

    else if ( position.x + getSpeedX() + width  > 0 )
    {
      position.x += getSpeedX();
      playerMoveInX = true;
      return;
    }
    playerMoveInX = false;
  }
}

And for the frames I have a class Animation which handles the following information:

Uint32 frameRate, oldTime;
int frameDelay;
int frameCount;

And in the function that animates I do the following, much like the MoveX in Sprite:

int Animation::animate()
{
  if( oldTime + frameRate > SDL_GetTicks() )
  {
    return -1;
  }

  oldTime += frameRate;
  frameCount++;

  if ( frameCount > frameDelay )
  {
    animationAlreadyEnd = false;
    frameCount = 0;
    currentFrame += incrementFrame;

    if( currentFrame > maxFrames)
    {
      animationAlreadyEnd = true;
      currentFrame = returnFrame;
    }
  }

  return currentFrame;
}

I got working all that and everything executes apparently fine, but in some points of the game the animation doesn't look really smooth when in other points it is.

I leave the video of the "gameplay" so everyone could see what I mean.

http://www.youtube.com/watch?v=uoxKEYzwkcQ

I currently using during the execution of the game a general Timer in 60 FPS.

If anyone needs more information, don't hesitate in ask.

Thanks a lot for the help.


texts: Balancing players between air/land fields in a PvP match

texts:
Background:
In my game there are two teams per PvP match, and those two teams are further divided into air/land fields. Each team has 12 players on the ground and 6 patrolling the sky. The goal of the game is for the air/land units to work together to win the match. Players are matchmade into games randomly, without taking into account skill/field preference/etc (the short explanation is that we don't have control over this).
The problem:
If I allow complete freedom in choosing fields, I might end up with no players in the sky or vice versa on one or both teams. If I don't give players a choice, they won't be happy when they aren't assigned to the field of their preference. Overall I imagine the fields would balance out on their own if they're equally enjoyable, but there's little room for error there -- if either field gets a bad first impression, it'll be difficult to recover from. I want to ensure there are some constraints in place to prevent death by conjecture.
I thought of adding 1 or 2 landing pads at either team's base, and that way players who wanted to play the land field could land, and players who wanted to play the air field could take a parked aircraft on the landing pad. This could breed tension between players where more than 2 players are competing for landing pads though.
What are some approaches I can take to resolve this, which avoid forcing player behavior as much as possible, but still ensure gameplay is predictable and reliable? Specifically I'm looking for what key issues an answer takes into account and how it resolves them. If you're drawing experience from something that's already been put into practice and already has tangible results, those results would be a wonderful addition to your answer.


texts: How to implement click-to-move in a 2D game?

texts:
Currently I am learning how to use XNA by making a 2D Game. So far I am doing okay, but I want to implement a click-to-move instead of using the keys to walk around but I haven't found any samples around and I am sort of clueless on how to approach it.
I know that XNA works well for xbox controls and keyboard but I haven't seen anything related to mouse interaction at all also I dont really mind about xbox since I am not aiming for anything else other then a PC game.
So what I am looking for is how the click-to-move is implemented, and if the mouse icon displayed in game is also supported by the xna framework or if you have to make it yourself in order to make the current tile glow or display that the mouse is there or something like that.

UPDATE:
Moving with the mouse is not quite the same, you have to consider obstacles as well at least in my case of what i am planning...
For example i want the clicks to be considered as straight walking forcing the user to navigate himself on the map instead of auto-navigating the user per click so if he clicks past a wall for example it will walk to the wall and stop instead of finding the route to the other side if there is one... another doubt that comes to my mind using the getstate of X and Y for example on a scrolling window will it actually recognize where the mouse is or there will be the need of world-to-screen calculation to disclose where is point B that was clicked by the user ?


texts: Procedural terrain generation in cylindrical (2D) world

texts:
I'm fairly new to procedural terrain generation. I know that to generate terrain you would use different calculations with the x and y axis (also z if you have one).

But what if you want to generated random terrain on a 2D world that loops around itself? By that I mean a world in which you enter the right side upon leaving the left side (or the other way around). It should also be generated on the fly and not all at once.

One solution I can think of is to just generate ocean along the border, but that is not what I'm looking for. I also seem to remember that Civilization generated such types of worlds, but I'm not quite sure how that worked, it's been quite some time since I played that game.

So how exactly can one generate such a continuous world?


texts: How to navigate through google Map in unity

texts:
I am working on loading the google map and navigating through the map.

I have loaded the google map which shows the current location in unity.

Now I need to show the direction from Place A to Place B.How Can I implement this in unity


texts: Difference between Unity's [Command] and [Server]

texts: [Command] and [Server] functions both run on the server and can also be called by a local player but what is the difference between them?


texts:
I´m currently trying to develop a Game, which uses Component based Entities.
The problem I`m facing right now is how to mask my Components and retrieve them from the Entities.
At the Moment i use a enumeration which has ab entry for each Component. Entities define then masks based on which Components they have associated. When I query for a Component i pass the correspoding enumeration value.

Here is a basic example to show how my Code works:

class Component
{
    public:
        enum Type
        {
            A       = (1u << 0),
            B       = (1u << 1)
        };
        virtual TypeBit() = 0;
};

class Entity
{
    public:
        shared_ptr<Component> GetComponent(Component::Type type);
        unsigned int TypeMask();
    private:
        std::list<shared_ptr<Component>> _components;
}

What I like i my approach is the simplicity of the Bitmasks with logic operations, i.e. to see if a System is interested in an Entity.
The problem I have is, that, everytime when I add a new Component I have to add a new enumeration value. This adds potential for errors which is why I would prefer a more generic solution.


texts:
I have a simple WebGL canvas, where I'm attempting to render a texture on a square. When working with textures as local files, all is fine. But when I try to load a texture from the web, I get a black canvas.

Please see this fiddle for a demo. I have made the shaders and JavaScript very simple.


texts:
So, I'm having some issues with lighting in my Unity game.  I had implemented torches, which seem to be working fine, but I have a creature (gelatinous cube) that I've put spot lights facing to give it a "glow".  The reflected and refracted light ends up having two issues:

the light abruptly ends at the edge of floor tiles, and
depending on the position, the light sometimes goes from it's blue color to a reddish color.

I have a short (11 second) video here:  http://www.labyrintheer.com/wp-content/uploads/2016/11/Nov-17-2016-21-07-57.mp4 so that you can see what I'm talking about.  I've tried changing global lighting settings and playing with the settings on the spot lights, but nothing seems to resolve the issue.

Still images for anyone hesitant to click the video link:

Hard falloff:

Reddish color:

Using a single point light inside the cube, instead:

You can see it on the wall in the upper right and the floor at the top a bit.  The upload seems to have lowered the quality a bit, but you can still see it.  The single light makes it a little bit better, but there's still complete falloff.


texts: Loading sound in XNA without the Content Pipeline

texts:
I'm working on a "Game Maker"-type of application for Windows where the user imports his own assets to be used in the game. I need to be able to load this content at runtime on the engine side.

However I don't want the user to have to install anything more than the XNA runtime, so calling the content pipeline at runtime is out.

For images I'm doing fine using Texture2D.FromStream.

I've also noticed that XNA 4.0 added a FromStream method to the SoundEffect class but it only accepts PCM wave files.

I'd like to support more than wave files though, at least MP3.

Any recommendations? Perhaps some C# library that would do the decoding to PCM wave format.


texts: Dynamic rigidbody and kinetic with simplectic integration for trajectories [2d]

texts:
Okay, I have the following situation:

I want to launch a GameObject into orbit of a planet and using the dynamic rigidbody everything is working as I want. I simulate gravity and as it hits the surface again it bounces around nicely using the Box2D system.

However, I want to calculate the trajectory and visualise it on screen. I thought about it and came up with two solutions, but I run into some problems:

1 Simplectic integration for the trajectory

I simulate the trajectory using simplectic integration. However, as can be expected, the results are different for the dynamic rigidbody movement and the simplectic integration. This became very obvious when I launched two identical objects and simulated one dynamically and the other one simplectic. The code is as follows (all in FixedUpdate):

if (rb.isKinematic)
{
    velocity += forces / mass * Time.fixedDeltaTime;
    Vector2 newPosition = (Vector2)transform.position + velocity * Time.fixedDeltaTime;
    rb.MovePosition(newPosition);
}
else
{
    rb.AddForce(forces);
}

The simplectic / kinematic one is slower than the dynamic one. Weird.

2 Use Physics2D.simulate

According to https://docs.unity3d.com/ScriptReference/Physics2D.Simulate.html I can simulate it via code. However, this means that I have to set everything that is not to be simulated as disabled and simulate it for a given amount of time to calculate the trajectory. Not really what I was looking for, because I want to have a live trajectory update

3 Full simplectic
That seems to be easy, but I want to have realistic collisions and bounces. Don't want to reinvent the wheel when Box2D should be sufficient.

4 Simplectic for simple movement, dynamic at collision
This seems to be the logical candidate, but don't know if it is clever. Had no time to implement this yet, but should not be that difficult. Feels a bit icky...

So, question?

My questions are:

Can I reduce or eliminate the offset from solution 1?
If not, what whould be the most logical solution and / or am I missing one?

EDIT
It was asked how I calculate the forces. This is simply Newton's law with squared distance:

public Vector2 CalculateForce(GameObject a, GameObject b) {
    // AUComponent is an interface type I have... not very special in itself.
    float mA = a.GetComponent<AUComponent>().Mass;
    float mB = b.GetComponent<AUComponent>().Mass;

    Vector2 r = b.transform.position - a.transform.position;
    return gravityConstant * mA * mB / r.sqrMagnitude * r.normalized;
}

However, the ever increasing offset is also happening with a constant force applied in a direction.

The masses of the AUComponent are equal to those of the RigidBody.


texts: Is it possible to create 3d games with good performance in java?

texts: Recently i use Javafx 8 for creating small 2D games , but i think it can't manage memory and other things very well .I see Jmonkey jmonkeyengine as a game engine for Java and i see some videos of their project in YouTube. Now i want to know it is possible to create a good game with good performance and graphic with Jmonkey or other game engines writtent in java? Is it possible to deal with GPU buffers in Java?


texts: Need help thinking of a way to code a text parser

texts:
Apologies if this has been asked before, or if it is a bit too simple for this forum.
I'm new to C++ and as one of my first projects I have decided to try a textual adventure. Step 1: the text parser.
Note that I am aware that there are libraries out there that will make this for you, but I want to code it from scratch to learn what is going on :)

So! I've gotten to the point where I add the user's input to a vector, so that I can handle each word individually. However, I cannot for the life of me figure out a "handler" that does not hard-code everything.
I want to create a map through which to associate the string, for example "Go", to the relative action handler.
Something like this:

map<string, ActionHandler> actionMap;

actionMap["Go", GoActionHandler];

GoActionHandler would be a struct of ActionHandler type, and I would put in ActionHandler or the general messages/actions/reactions, and then in GoActionHandler I'd elaborate on the possible "Go" actions.
But, one thing at a time... The code above does not compile, as ActionHandler is not a "type".
Considering that for now I am just focusing on having a (scalable!) program that reacts differently based on the word entered, could someone help me by showing me real code? I've found online people making examples in pseudocode, but I'm to big of a noob to then know how to execute what they are talking about, even though I understand the logic.

So could anyone dumb this down and point me in the right direction? How do I include in my main() a way to call a struct/function based on the a string contained in a vector? (eg. string "Go" in vector[0]?)


texts: How to update libgdx scene2d Label text dynamically?

texts:
I display a BitmapFont on the screen, update its text and the font is updated dynamically on the screen as well.
I seem to fail to do the same with a scene2d Label added as actor to a Stage.
The act(delta) and draw() methods are being called in the render() method.
My code basically looks as follows:

public void init() {
    Label label = new Label(text, labelStyle);
    stage.addActor(label);
}

public void update() {
    updateText(text);
}

@Override
public void resize(int width, int height) {
    /* do some resizing */
    label.setPosition(newPositionX, newPositionY);
}

@Override
public void render(float delta) {
    /* do some rendering */
    stage.act(delta);
    stage.draw();
    update();
}

Do I need to do anything other than setting the Label text, adding it to the Stage as actor, and then updating the text elsewhere? The label displays its original text, though the text updating works fine.

Thanks.


texts: Box collisions between vehicles in traffic pattern

texts:
I'm working on a traffic simulator. Right now, I have ways to manage 4-way stop intersections and a solution for efficiently determining which vehicles are colliding with one another. All vehicles operate independently of each other and will overlap/ignore any vehicles they pass.

I'm looking to build a way to resolve collisions between vehicles such that a Vehicle will follow the Vehicle in front of it. If a Vehicle stops at an intersection, any Vehicles that follow thereafter should stop and wait as well.

Below are the relevant components I already implemented:

TileGrid containing road segments.
TravelGraph graph of waypoints for Vehicles to travel along the TileGrid.
CollisionTracker for efficiently determining which vehicles are colliding, i.e. O(1) lookup for get_collisions(<vehicle_id>) -> List[<vehicle_ids>]
Intersection for determining which vehicles are waiting at an intersection and determining which Vehicles may pass through it.

The only seemingly-viable algorithm right now is:

Calculate velocities and position of all vehicles after tick
Determine which vehicles are in a collision
Determine which vehicles are in a "collision group" (e.g. if A collides with B, collides with C, then (A, B, C) are in a group)
Determine the order of the vehicles in each group based on their velocities (e.g. if A, B, and C are moving to the right and C is the rightmost, followed by B, followed by A, then the order is [C, B, A]).
Recalculate the positions of all vehicles, in order from front to back (e.g. C, B, A) such that they reside adjacent to, but not touching the Vehicle in front of them.

Problems with this solution:

This requires a lot of recalculations. If there's a line of n vehicles waiting on a light, I'd effectively compute 2*n positions per tick in addition to all other overhead for establishing groups, order, etc.
If the vehicles are following each other around a turn, the logic for finding the "vehicle order" becomes more complex, adding on to the computations per tick.

Ideally moving the vehicles would require n calculations per tick.

I'm open to any/all suggestions here. I've tried building my code as modular as possible, so I'll happily rewrite large parts of it if there's a better architecture to solve this problem.

Below is the visual representation of the TileGrid (black), TileGraph (purple), and Vehicles (circles).


texts: How to make card movement behave like those in Hearthstone and Eternal CCG?

texts:
I'm trying to achieve the same effect that cards in Hearthstone and Eternal CCG does, for example, cards behave as they were a type of "crane", when the cards move, their body is tilted towards the direction they are moving, making it behave like a "crane".

Does anyone have any idea whatsoever on how I could achieve this? I'm trying to do everything manually, e.g., get the card position, detect if the card is moving left or right, change the card Y axis to achieve the tilt effect relative to the direction the card is moving, clamping the value so it doesn't over-rotate, etc., etc.

I would really appreciate and would LOVE to know how I could be doing this. Do I need to create an animation and play after giving it the direction? I don't know you help me out please!


texts:
These are my Vector2's that I am using for this function.

public Vector2 position = new Vector2();
public Vector2 velocity = new Vector2();
public Vector2 movement = new Vector2();
public Vector2 direction = new Vector2();

Here is the function that I use to move the position vector along an angle. setLocation() just sets the new location of the image.

public void move(float delta, float degrees) {
    position.set(image.getX() + image.getWidth() / 2, image.getY() + image.getHeight() / 2);
    direction.set((float) Math.cos(degrees), (float) Math.sin(degrees)).nor();
    velocity.set(direction).scl(speed);
    movement.set(velocity).scl(delta);
    position.add(movement);
    setLocation(position.x, position.y); // Sets location of image
}

I get a lot of different angles with this, just not the correct angles. How should I change this function to move a Vector2 along an angle using the Vector2 class from com.badlogic.gdx.math.Vector2 within the LibGDX library?

I found this answer, but not sure how to implement it.

Update: I figured out part of the issue. Should convert degrees to radians. However, the angle of 0 degrees is towards the right. Is there any way to fix this? As I shouldn't have to add 90 to degrees in order to have correct heading. New code is below

public void move(float delta, float degrees) {
    degrees += 90; // Set degrees to correct heading, shouldn't have to do this
    position.set(image.getX() + image.getWidth() / 2, image.getY() + image.getHeight() / 2);
    direction.set(MathUtils.cos(degrees * MathUtils.degreesToRadians), MathUtils.sin(degrees * MathUtils.degreesToRadians)).nor();
    velocity.set(direction).scl(speed);
    movement.set(velocity).scl(delta);
    position.add(movement);
    setLocation(position.x, position.y);
}


texts: Diamond shaped selection on a staggered iso map

texts:
I have a staggered isometric tile map and want to do a selection that aligns with the diamond shape of the tiles.

This is what I mean:

So I got two points on screen and their map cell coordinates. How do I iterate over all tiles that are within the selection?

What I got to help with this is a method that gets the neighboring tiles.


texts: How to avoid texture bleeding in a texture atlas?

texts:
In my game there is a Minecraft-like terrain made out of cubes. I generate a vertex buffer from the voxel data and use a texture atlas for looks of different blocks:

The problem is that the texture of distant cubes interpolates with adjacent tiles in the texture atlas. That results in lines of wrong colors between cubes (you may need to view the screenshot below at its full size to see the graphical flaws):

For now I use these interpolation settings but I tried every combination and even GL_NEAREST without mipmapping doesn't provide better results.

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

I also tried added an offset in the texture coordinates to pick a slightly smaller area of the tile but since the unwanted effect depends on the distance to the camera this cannot solve the problem completely. At far distances the stripes occur anyway.

How can I solve this texture bleeding? Since using a texture atlas is popular technique there might be a common approach. Sadly, for some reasons explained in the comments, I cannot change to different textures or texture arrays.


texts: Updating a gameobject position that needs to be consistent across all players' games

texts: I am creating a real time multiplayer game in Unity 3d using Google Player Services that has a ball that the players will interact with. I'm not particularly sure how I will update the ball's position on all of the games though. I have each player sending updates for their positions and all of that but with the ball being interacted with by all players I'm not sure how to figure out who's update of the ball position I should take.


texts: Is it possible to create custom functions in Twine 2's Harlowe format?

texts:
I'm starting to learn Twine and I'm putting together a little framework for making a game.

I'd like to be able to store functions or procedures somehow so that I can use them over and over again without having to write the whole thing each time.

Example[Something like this]: (set: $incrementItemsAmount to (set: _item's amount to it + 1))

I've looked at lambda macros, but they look like they're more for looped procedures.


texts: Should I check all the collisions in the game world?

texts:
I'm developing a 2D game engine and right now I'm designing the collision system.

I've read about space partitioning and quad trees, and I understand that only the objects that are in the user's view need to be drawn and checked for collision.

All the objects, regardless whether or not whether are in the user's view, need to updated, but what's happen if an object out off the user's view collide with another object? I mean:

Should I check all the collisions in game world, even if the objects are not in view?


texts:
It is always said that the polygon amount of a single modell must be as little as possible when it comes to realtime simulations such as computer games. (Or at least lower than when rendering a movie)
I am fully aware that this must be done in order to save performance. But aside from that information i cannot find why huge polygon amounts must be avoided.

(In Short: I know that polygons eat performance. I want to know why they eat performance)

So my question would be:
What happens when a frame is rendered? The polygons are surely somehow processed in the graphicard. What happens there?.
If possible i would like to have some links to sites containig this information.


texts: How can i run my .LÖVE game directly from the lua interpreter?

texts:
I've just started with LOVE and LUA , i'm interested in LOVE because i want to  play around with something different from my dayjob(i'm a webdeveloper) and since it uses LUA and is interpreted , i though it would be a great way to try out the API.

but i couldn't find how to run my .LÖVE game directly from the lua interpreter? i'm finding it bothersome to package the game each time i make a little test with the API.


texts: Java: Exported JAR file doesn't load images

texts:
I am using Netbeans to create my game. The images do seem to load when I run it in Netbeans. However, the built jar file only leaves me with a blank screen.

This is how I call the images in my game.

public Image playerSprite = playerSprite = Toolkit.getDefaultToolkit().getImage("sprites\\spritesL.png");

I put all image resources in a folder called sprites, and I declared it as a Source in the Project Properties. In addition, the image files does appear in the root directory of the JAR file, but cannot seem to access it.


texts: In OpenGL, is it a bad idea to "combine" immediate mode and retained mode for the sake of GUIs?

texts:
Suppose I have a 3D scene being drawn with glDrawArrays(...) and I want to render something simple, like a 2D overlay. Would it be a bad idea to use immediate mode for such a thing, instead of setting up a 2D renderer with retained mode?

Example:

void Draw()
{
    // Draw the 3D scene:
    // *does stuff*
    glDrawArrays(...);
    // *some other stuff*

    // Setup a quad with immediate mode (for something like a vignette overlay)
    glBegin(GL_QUADS);
    glTexCoord2f(...); glVertex2f(...);
    glEnd();
}


texts:
I want to create a simple Flash game. Let's say, it's about soccer hooligans. I would need the characters to walk around the isometric landscape, drink, fight or whatever it is they do.

Now, how do I create those characters? I imagine it could be possible just to draw a separate movie clip for every action for 8 different directions (will 8 be enough?). But this seems like a little bit of work, to say the least.

Some people recommend creating and animating the models in some 3D editor (3DS Max, for instance). This looks better. But, how do I use them? There's no 'native' 3D in Flash (yet). And I don't really feel like being involved with one of the flash 3D engines (some have overly sophisticated APIs, others have bugs, the rest are not maintained anymore).

I could pre-render the animations to frame sequences and then just download them, right? But that makes a HUGE chunk of data.

Any thoughts or advices?


texts: OpenGL ES 2 - Developing snowfall particle system

texts:
I've recently begun OpenGL ES 2 and I'm trying to implement a snowfall (on Android), but I'm not sure what's the best approach. I would like to develop it myself rather than use a library. It really helps a lot in understanding OpenGL.

What I'm doing at the moment is: I have an array of, say, 1000 particles, each with its own lifetime (=number of frames it will live). It works fine if a particle "dies" and starts all over when it already left the screen, but if it is still on the screen and it has to die, the user will notice that the particle suddenly disappeared. The problem is very noticeable if this happens very often. I need a way to kill a particle only when it left the screen.

Is there a way to improve my approach or maybe I should change it completely?


texts: Getting distance between point of an object and another object in Unity

texts:
First, I'd like to apologize because this is a very basic and repetitive question, but I am completely new to game development.

I understand that I can find a distance between two objects using:

float dist = Vector3.Distance(other.position, transform.position);

However, how can I find the distance between a point of one object to other object?

For instance let's say my object is this sphere

Now, how can I return an array that says that there are no objects to the left (null), in the front there is an object at 1, and to the right there is an object at 0.5?

Thank you for your patience and understanding


texts: It possible to render a true quad (without triangles) using OpenGL?

texts: Is it possible to render a "true" quad in OpenGL? By that I mean a square which is not made out of two triangles.


texts: How would I add keyframes to my animation clip from another object in Unity?

texts: I am creating an FPS game which will have many weapons that have their own animations. I will need to access keyframes of the character's position, rotation, and scale, how will I do that? I can only add keyframes from the object I'm animating, or, I can only add keyframes from a child object.


texts: How to increase drag sensitivity while dragging distance is less than a certain value

texts:
I built a inventory hotbar wheel for mobile controls. The wheel can be accessed if I put my finger on a specific "hitbox" on the right side of the screen and drag left. The result looks like this.

I haven't added in item icons and such, but the black stain things are going to be the outlines of the items, and there will be item icons in the middle of them. As you can see, the larger, darker outline is the active item (the one that will be used/equipped from the inventory). I have coded the script for the inventory so that the active item will be 3 slots away from the right side of the screen.
This is the script
public class Quick_Acces_Slider : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
{
public Image quickAccessSlider;
public Canvas canvas;

public float slotDistance;
public float[] slotPosition;
public float trueOffset;
public float offset;

public float canvasWidth;

public Vector2 originalPosition;
public Vector2 position;

public float slideDistance;
public float slideCap;

public float scrollSpeed;

// Start is called before the first frame update
void Start()
{
    canvasWidth = canvas.GetComponent<RectTransform>().rect.width;
}

public void OnPointerDown(PointerEventData drag)
{
    originalPosition = drag.position;

    slotPosition = new float[quickAccessSlider.transform.childCount];
    slotDistance = 1f / (slotPosition.Length);

    offset = trueOffset * slotDistance;

    for (int i = 0; i < slotPosition.Length; i++)
    {
        slotPosition[i] = ((i * slotDistance) + (slotDistance/2)) + offset;

        if (quickAccessSlider.transform.GetChild(i).gameObject.activeInHierarchy)
        {
            slideCap = slotPosition[i];
        }
    }

    OnDrag(drag);
}

public void OnDrag(PointerEventData drag)
{
    position = originalPosition - drag.position;

    slideDistance = Mathf.Clamp(((position.x / canvasWidth) * 2f), 0f, slideCap);

    for (int i = 0; i < slotPosition.Length; i++)
    {
         //Scale active objects, change color, etc
    }

    quickAccessSlider.rectTransform.anchoredPosition = new Vector2(slideDistance * -quickAccessSlider.rectTransform.rect.width, quickAccessSlider.rectTransform.anchoredPosition.y);
    }
}

public void OnPointerUp(PointerEventData release)
{
    Array.Clear(slotPosition, 0, slotPosition.Length);
    originalPosition = Vector2.zero;
    position = Vector2.zero;
    slideDistance = 0;
}

}
The inventory slider is set up so that there is a rectangular panel, with the item slots as its children, and the pivot point of the panel is the right side of the screen, as such:

Essentially, right now, because I have the offset value which makes the active object the one that is 3 slots from the right side, I actually have to swipe a certain amount before I can get to the first active item.
I want to make it so that the slider is more sensitive to drag while the slide distance is less than the offset value, so that I don't have to drag as mush to get to the active item. I also want the effect to work in the reverse scenario, where I am trying to stow the slider (dragging toward the right of the screen).
I've tried a few methods such as where I tweak the slideDistance while it is less than the offset, or where I try to Lerp the slideDistance value to the offset value, but none of them seem to work due to a few reasons.
The main reasons my solutions didn't work was because the slideDistance value needs to be equal to the offset value once I'm done tweaking the value/it is not longer less than the offset value to prevent jittery movement, and because I need the increased sensitivity to work both ways, when dragging left and also dragging right.


texts: How to make pathways/corridors in a randomly generated dungeon?

texts: I am trying to make a random dungeon generator using Unity. I have been able to setup the rooms properly and connect them to each other using a minimum spanning tree algorithm. I have attached an image below where you can see what I have so far. The next step will be to create pathways/corridors to connect the rooms together but I am having difficulty understanding how I am supposed to go about it. I want the corridors to be straight or form an 'L' shape when connecting to each other. So I was wondering if anyone could help me out with this. Any help is appreciated.


texts: Closest circle intersection within a triangle

texts:
(Context: I use a Delaunay triangulation for pathfinding, and have circular points of interest, of varying sizes, being randomly placed around the map. Units need to be able to determine the closest such point of interest to path to, using a Dijkstra search across the triangulation.)
Given a triangle, and a set of circles which overlap or intersect it, I'm trying to find the closest circle to a given point within the triangle.
My first thought was to just take the distance from the point to each circle center, minus the radius. But there are some cases where that does not give the correct result. See the following image:

Measuring from point P within the triangle, to circles A and B. Using only the radius of each circle, as with d1 and d2, would result in circle A being considered closest. However, the closest edge of circle A used to measure d1 is outside of the triangle. Staying within the triangle, the closest edge from point P to circle A would be d3, which is much further away than d2, indicating that circle B is actually closest within the triangle.
Is there a method for determining this difference, finding d3 for circles where d1 would be outside the triangle? How do you determine the intersection point between circle A and the triangle?


texts: Can frequent state changes decrease rendering performance?

texts:
Can frequent texture and shader binding decrease rendering performance?

"Frequent" binding example:

for object
   for material in object
      render part of object using that material

"Low count" binding example:

for material
   for object in material
      render part of object using that material

I'm planning to use an octree later and with this "low count" method of rendering it can drastically increase memory consumption. So is it good idea?


texts: Choosing a draw call when not reusing vertex data

texts:
Up until now I've always used glDrawElements, and have my vertex and index buffers bound. From what I've read, glDrawElements is generally the way to go, and it works fine. However, I'm starting a new project and am questioning whether this is still the best fit.

For the current project, I'm recomposing a 2D scene from scratch every frame. The player's character runs around, and I only draw the part of the world that is visible, generating 2D quads from the map tiles and building the vertex/index buffers.

Given that (from my understanding) glDrawElements works best when you upload your VBOs and make multiple draw calls against them, wouldn't it be better to use something else in this case, such as glDrawArrays? I've generally read that glDrawArrays is slower, but given that I'm having to push the vertex data every frame anyway, that might not be true here.

I don't want to switch draw calls and assume I made the right choice when I could in fact be using it improperly to begin with, invalidating any performance improvements I see.


texts: I made a library that enables client-server communication using both TCP and UDP protocols. When game developers on the #gamedev IRC channel (Freenode) knew that, they totally refused the idea. They recommended RUDP instead of TCP. Should I remove the TCP communication and use RUDP instead?


texts: Communication in an entity-component through public variables or public member functions

texts:
I am currently coding my own ECS to get a deeper understanding of how such an engine works. I am currently putting together systems. I am aware that there is no right answer to my question as there are a lot of flavors of ECS. Probably I should say that I try to avoid an event queue at the moment. So I only want to do synchronous and direct communication.

Please note that this is the basis and preparation for my systems and event system for asynchronous communication.

How do you guys concept your components? Are you offering public variables directly accessed by the systems or do you communicate through public member functions?

Public variable

class AIComponent : public IComponent{
  public:
    bool m_LeftPressed = bool();
}

Public member function

class AIComponent : public IComponent{
  private:
    bool m_LeftPressed = bool();

  public:
    bool leftPressed();
}


texts: libGDX: Why doesn't Gdx.input.isKeyJustPressed() work?

texts:
I'm trying to use the method Gdx.input.isKeyJustPressed() to check if the Android BACK button was just pressed. I don't want to use the Gdx.input.isKeyPressed method to avoid multiple calls. Here is my code:

public void handleInput() {
    if(Gdx.input.isKeyJustPressed(Input.Keys.BACK)) {
         // show previous screen...
    }
}

public void update(float dt) {
    handleInput();
}

But unfortunately this doesn't work. Any ideas?


texts: Good book/resource recommendation for HTML5 mobile game development?

texts:
The problem: I am taking an existing, 5 year old, html based MMORTS game and "HTML5-ing" it, "AJAX-ing" it and most importantly, optimizing for mobile devices like iPhone, android etc. For these devices, the application will be packaged as a downloadable app that is a wrapper for a browser which actually shows the game..

The Question
Looking for a good book, or books, or in-depth articles that would help me learn:

what tools I have in iOS, andriod applications for optimizing an html based game. things like caching of images, etc
what kind of connectivity, or interactivity I can expect between the html/javascript pages and the wrapper - can I play sounds in the wrapper by triggering them from javascript? etc
tip and tricks to optimize html/html5 & Javascript application to run well on mobile devices
ETC :)

Any recommendations would be greatly appreciated!!


texts: Orbiting multiple objects evenly around a changing radius

texts:
I have multiple objects (circles) and I want to place them in a circle, with even distance between each one, and have them orbit the center of the screen.

If I remove one object, I want the orbit radius to reduce and the other circles, as a result, end up getting closer and closing the circle again.

Below are some images to help explain what I'm trying to achieve.

A. is the objects evenly distributed around the center.

B. is after destroying one of the objects, the "circle of objects" need to close in and evenly distribute the objects once again.

C. is just after another object has been destroyed.

I know that the solution is some "basic" math, but it's been a while, and I'm super rusty.

Thanks for the help, if anything further is needed please let me know!!

Cheers!

o7


texts: Moving Objects Relatively With Their Parent Object [Gamemaker]

texts:
I have an object type, oFur, instances of which are generated in a random distribution over the sprite area of a parent object, oFurArea.

However, I would like the oFurArea to change its image_xscale and image_yscale dynamically, as well as its y position. This is easy to do, but I would also like all of the oFur instances to move with their parent (i.e. change their own 'y' values), whilst maintaining their relative positions on the parent object.

Either I'm having a brain-fart, or I cannot work out how to do this. Any help would be appreciated.


texts:
If I want to create a game in which I use sources from another game that has copyright is illegal. But what if I use screenshots from a 3D game to make another 2D game (something like a questionnaire)? Or what if I use the 3D models from the first game, render them with a program like cinema4D or blender in 2D and use them in the 2D game? And if it is illegal please explain me why and what laws of copyright would apply in that case.

I know that observing how a game works or any software for that matter and then reverse engineering it is legal so doing the same thing with resources from a game is legal. That's why I wanted to make clear my question is not related to reverse engineering.


texts:
I'm stitching together the workings of a component based game engine, and as such have been deeply reading into many aspects of both game engine architecture and a fair amount of opinionated theory of different programming styles / do's and dont's. Etc.

Currently, I really like the idea of treating components like little data structures and having larger sub-systems handle this data appropriately. Thus the "GameObject" is more of a GUID that ties in these struct-based components into a loosely defined object with various properties.

So my question, or well current delima is how to store these various components and I seem to have two competing ideas.

The easy way to handle storing these components, is to have each sub-system double as a factory class which creates and stores the component into a hash table which the sub-system maintains. So the Renderer would have a method that could produce and store a Renderable component given a GUID and some input parameters. Whenever a object or object component is removed from game each sub-system could be messaged and that sub-system could then delete the corresponding component without trouble.

In addition to that, components of the same type are grouped together and since these components are all the same size this makes for a pretty damn clean memory management. I see no problem using std::vector or a hash table of some sort to contain these elements.

The issue I have with this approach is that it fragments a (all) "GameObject's" significantly. Suddenly the position component of a given object is located miles away from the physical component. This seems like a performance nightmare, looking up any other component becomes a cache-miss, etc. Which brings me to option #2...

The other approach I've come up with is to keep the factory part of the sub-systems. Renderer would still produce Renderables, but Renderer would not be responsible for storing the component, instead it would be given a location to write the component struct to as an input parameter by a dedicated system, like a memory manager.

The advantage here is components belonging to a particular GUID could be grouped together in contiguous memory (at least in theory), providing a chance that the needed date for another component (say Physical wants to alter the Position component) may already exist in the processors cache due to the effects of cache-lines.

The (massive) disadvantage that I see in doing this is managing the necessary memory to group these differently sized components together, that sounds like a nightmare to me.

So what I wish to ask is, what do you guys think? Is there a really smart third option I haven't thought of, or am I crazy for even caring about cache-misses? In that case, is the easy way just the correct way, etc, etc.

Thanks, -Cody


texts:
Continuing my exploration of raycasting, I am very confused about how the correction of the fisheye effect works.

Looking at the screenshot below from the tutorial at permadi.com, the way I understand the cause of the fisheye effect is that the rays that are cast are distances from the player, rather than the distances perpendicular to the screen (or camera plane) which is what really needs to be displayed. The distance perpendicular to the screen then, in my world, should simply be the distance of Y coordinates (Py - Dy) assuming that the player is facing straight upwards.

Continuing the tutorial, this is exactly how it seems to be according to the below screenshot. From my point of view, the "distorted distance" below is the same as the distance PD calculated above, and what's labelled the "correct distance" below should be the same as Py - Dy. Yet, this clearly isn't the case according to the tutorial. My question is, WHY is this not the same? How could it not be? What am I understanding and visualizing wrong here?

UPDATE: Here's another perspective. The tutorial at lodev.org has another way of handling the fisheye effect which confuses me in the same way. This one relies on distance vectors more than angles and calculates the perpendicular distance to the wall according to the below formulas where mapX is the position of the player, rayPosX is the position of the wall that has been hit by a ray, and rayDirX is the direction of the ray (along with its Y counterparts of course). (1-stepX)/2 is simply a way of adding 1 if the ray is on the left side of the field of view. By the same logic as in the above tutorial, the perpendicular distance is simply mapX - rayPosX in my world. Why does rayDirX need to be divided to it?

//Calculate distance projected on camera direction (oblique distance will give fisheye effect!)
if (side == 0)
      perpWallDist = fabs((mapX - rayPosX + (1 - stepX) / 2) / rayDirX);
else
      perpWallDist = fabs((mapY - rayPosY + (1 - stepY) / 2) / rayDirY);


texts:
I want to limit the joint angle of my character.
I have just one issue i can't get the value of the joint limits of the human
-i search about max, min angle of each joint in x and y but i can't get them-
can someone give me them.


texts: Triangle-triangle continuous collision detection

texts:
I am making a 3D game engine and I use continuous collision detection. I am using Sphere-Trees to cull primitive collision checks to a minimum. However, I'd like to perform continuous triangle-to-triangle collision checking.

How does continuous triangle-triangle collision detection work, assuming triangles with linear velocities?


texts:
I have a texture with R32G32B32 floats.  I create this texture in-program on D3D11, using DXGI_FORMAT_R32G32B32_FLOAT. Now I need to see the texture data for debug purposes, but it will not save to anything but dds, showing the error in debug output, "Can't find matching WIC format, please save this file to a DDS".

So, I write it to DDS but I can't open it now!  The DirectX texture tool says "An error occurred trying to open that file".

I know the texture is working because I can read it in the GPU and the colors seem correct.

How can I view an R32G32B32 texture in an image viewer?


texts: Too much animation work for 2d characters. Creating 2d character animations by prerendering an animated 3d model?

texts:
I've read a bit about creating assets for games and the consensus seems to be that 2D is cheaper than 3D in all aspects with the exception of character animation. That's caused by the need of redrawing every frame of an animation versus simply animating the skeleton of a model.

The cheapest solution seems to be making all the assets with lots of animations as 3d models and prerendering them to create sprite sheets, and leave the background and everything else that has few animations traditionally drawn.

How do I do it, what tools would be appropriate, whats the process and workflow? How does the pipeline for this work? Where could I learn more about doing something like this?

On the other hand, I'm afraid that such an approach greatly limits the available customisation of my characters - wouldnt such a thing mean that each combination of gear needs to have its own spritesheet? Doesnt that pump up my game size and memory footprint and slow it down due to slow disk access?

How viable is putting a 3d model in a isometric view 2d environment? Would that be a solution to the "lots of sprites" problem, if it exists? How would I go about that in Unity? Where could I learn about that approach?

I've looked at this question but it did'nt really help me, the answers are just vaugue suggestions, I want solutions and resources to learn how to implement those solutions.

EDIT:
I'll elaborate on why that question isnt the same as mine, because some of the commenters didnt get it. That post refers to a game called hero academy that has little to do with the isometric game I'm talking about - that one has a grid, does not use the 8 directions, does not adress the customisation of a character via gear etc. All in all it's totally another beast. As for my question, think Diablo II.

Out of the answers I found there it seemed like the answer referring to project zomboid might be on the right track for me, but I had doubts about the customisation and tons of sprites. So what am I asking here? Does the "project zomboid method" fit my needs (trying it out only to find out it doesnt work would be a waste of time) and if it does, how do I do that in Unity. Why didnt i phrase the question that way in the first place? To avoid the XY problem. Hope this clarifies well enough.


texts: How do I recognize squares, rectangles ... (like in TwoDots)?

texts:
I currently working on a small mobile game. Not a clone of TwoDots(!) but I need to recognize patterns like they do and I use the game as an example. How the game works? Players have to connect dots. Players can only connect a dot to its direct neighbor in the grid. So the next dot has to be left, right, above or below. Dots can only be added once to a sequence. Connecting a dot to one that is already part of the sequence closes the sequence.

See here http://youtu.be/8RDm6wQ9QbM?t=1m41s (just the next 20 seconds)

What I want to know is when a player connects dots, are there any enclosed dots?

My idea was to store the players touch directions (next to the dots and their position in the grid). For the blue square this would mean {1,2,3,4} if you start from the bottom left and connect counterclockwise. Then I could simply check the number of directions in the array (=4). From my grid I know that the start-dot is [3|3] and the end-dot is also [3|3]. This means it has to be a square and there is nothing enclosed because it is the smallest possible rectangle/square.

The problem starts with bigger squares e.g. the purple one. Starting from the bottom left and connect counterclockwise again there would be the following sequence {1,1,1,2,2,2,3,3,3,4,4,4}. How do I know that this is a square/rectangle or some strange stuff and furthermore how do I know if there are any dots inside?

I can count all directions (3x1, 3x2, 3x3, 3x4) and see that all directions appear 3 times. It has 12 directions. 12 is divisible by 4 so it could be a square. But sadly 12 directions doesn't have to be a square nor a rectangle because [1,2,1,2,1,2,3,3,3,4,4,4] would also close the pattern with the the same amount for each direction.

Well... the green one really makes my brain hurt. Green is definitely not a rectangle nor a square. I know that there might be any dots enclosed because there are more than 4 directions stored in the array and the start- and end-dot are the same but how do I get the three question marks? Same goes for the blue dots which are enclosed by the purple square.

I am totally lost here and I think... or better I hope I am overthinking/missing something here.

Thanks for your help!
proudcastle

Some Possible Squares:
4x OO |8x OOO |12x OOOO |16x OOOOO |20x... 24x... etc.
   OO |   O?O |    O??O |    O???O |
      |   OOO |    O??O |    O???O |
      |       |    OOOO |    O???O |
                        |    OOOOO |

Some Non-Square Rectangles:
6x OOO OO |8x OOO OOOO OO |10x OOOO OOOOO OO |12x OOOOO OOOOOO OO etc.
   OOO OO |   O?O OOOO OO |    O??O OOOOO OO |    O???O OOOOOO OO
       OO |   OOO      OO |    OOOO       OO |    OOOOO        OO
          |            OO |               OO |                 OO
                          |               OO |                 OO
                                             |                 OO

Some Strange Stuff
10x OOOOO   OOO  OOOO  OO   OOOO |12x  OOOOO  OOOO   ...
      O?O  OO?O  O?OO  OO   OOOO |     O??OO  O??OO
      OOO  OOOO  OOO   OOO   OO  |     OOOO   OOOOO
                       OOO       |


texts: How can I accurately simulate orbits in Unity?

texts:
I would like to create a space simulation with realistic gravity.

This means planets in 3d space which act as central gravity sources and multiple objects which are attracted by those planets gravity so that they orbit them in physically correct orbits (like in Kerbal Space Program, for example).

How can I implement such gravity sources with C# script?


texts: Legal issues around using real players names and team emblems in an open source game

texts:
I'm writing a sports management simulation game. Like most sport management games, it makes heavy use of statistics. I would like to use real players, teams and league names.

i) Am I running the risk of getting into legal battles if I should use the real names?
ii) Also what about team colours and emblems etc?

Update
Much thanks for all the input!


texts: Frog-Lilypad Animation: Animate Unity2D Tilemap based on Player position

texts:
I'm developing my first Unity game, involving a frog jumping on lilypads. As the frog leaves a lilypad, I would like it to sink beneath the surface. Here's what I have currently, with the lilypads as static tiles:

What would be the easiest way to do this? I know how to make an animation, but I'm not sure how to get each LilypadTile to be aware of the player's position, and trigger the animation/state change as the player leaves the LilypadTile. I don't even think Tiles have an Update() function, so am I approaching this correctly? Should I instead make my lilypads be Sprites?

Are there any good written references or example documentation regarding common Unity workflows/organization? I'm tired of watching long YouTube videos for each piece of information I need.


texts: I currently have an image processing application that outputs processed images post pixel shaders have been applied. However, using the examples I've found on the internet, the colors are flip to BGRA when RGBA is expected. I currently work around this with by post export processing to get the desired RGBA format. I was hoping someone else has dealt with this and has a solution that does not require post processing to correct the format.


texts: Unity: How to import a SINGLE animation for an existing character?

texts:
The Holy Grail of animation solutions (for me). Right now, if I want to append a new animation for an existing character, I don't immediately know what to do. I assume I need to bring the same FBX into the Assets folder with the new animation, copy the animation, drag that onto my previous prefab, and delete the new FBX.  But that is such a pain!

I already have a VERY complicated animation tree that is executed via a script and some animation events. How can I quickly save and import a new animation into Unity, made with Blender?


texts:
I'm developing a 2D Platform game, I have a 2D camera, some backgrounds, and everything is working good. Now I want to implement parallax scrolling to give the illusion of depth in my game, but i can't imagine how to make my different layers of background to move (most correctly, be rendered by the camera) with a different speed from each other).

In brief this is my game structure:

I have 3 layers of backgrounds: the first is the road level, where the player runs; the second is the intermediate; the third are some mountains very distant (in my mind). Everyone of these layers is created with seamless textures and organized with the tilemap technique, with every texture positioned one after the other. Of course I make the spritebatch draw only the visible ones.

The camera is a rectangle that follows player movements and goes just horizzontaly.

Since layers aren't moving, but only the camera is moving, I don't know how to make a background scroll with a different speed from another!