texts: Collision method only using one item from list

texts:
I've made a temporarily method for collision with all the blocks on the screen. (I used almost the same method in the past, but only for one block at the time.)

So I start in the Sprite class. I use a list named tileCollision and I make a new list in the constructor for the tiles:

public List<Rectangle> tileCollision { get; set; }

public Sprite(GraphicsDevice gd,Texture2D collisionImage, Texture2D textureImage, Vector2 position, Point frameSize, Point currentFrame)
{
    this.collisionImage = collisionImage;
    this.textureImage = textureImage;
    this.position = position;
    this.frameSize = frameSize;
    this.currentFrame = currentFrame;
    depth = 0;
    // the Rectangle list
    tileCollision = new List<Rectangle>();
}

This is the collision method for the Sprite class (NOTE: this class is abstract):

public virtual void Collision (Rectangle collisionRect, List<Rectangle> tileCollision)
{
}

So now we can have a look at the PlayerMovement class, derived from the Sprite class. This is the Collision method (NOTE: the TileSprite class (class for my tiles) also contains a collision rectangle):

public override void Collision(Rectangle collisionRect, List<Rectangle> tileCollision)
{
    foreach (Rectangle rect in tileCollision)
    {
        if (collisionRect.Intersects(rect))
        {

            stopping = true;
            walking = false;

            if (collisionRect.X < rect.X)
            {

                fallingTest = false;
                stopping = true;

                if (left)
                {
                    stopping = false;
                    fallingTest = false;
                }
            }

            if (collisionRect.X > rect.X)
            {

                fallingTest = false;
                stopping = true;

                if (!left)
                {
                    stopping = false;
                    fallingTest = false;
                }
            }

            if (collisionRect.Y <= rect.Y - 50)
            {
                ground = true;
                fallingTest = true;
                stopping = false;

                if (moving)
                {
                    walking = true;
                }
            }

            if (collisionRect.Y >= rect.Y + rect.Height)
            {

                stopping = true;

                if (moving)
                {
                    walking = true;
                }
            }
        }
        if (!collisionRect.Intersects(rect))
        {
            fallingTest = false;
            stopping = false;

            ground = false;

            if (moving)
            {
                walking = true;
            }
        }
    }
}

And finally, this is my SpriteManagerGeneral class (the class where I "connect" everything for sprite handling). The dirt tiles are added to the tileCollision list (NOTE: just for testing):

// childTiles list is not used for collision
tileBase.childTiles.Add(dirt);
tileBase.tileCollision.Add(dirt4.bCollisionRect);
tileBase.childTiles.Add(dirt2);
tileBase.tileCollision.Add(dirt3.bCollisionRect);
tileBase.childTiles.Add(dirt3);
tileBase.tileCollision.Add(dirt2.bCollisionRect);
tileBase.childTiles.Add(dirt4);
tileBase.tileCollision.Add(dirt.bCollisionRect);

My update method for the collision looks like this:

playerBase.children.ForEach(c => c.Collision(player.collisionRect, tileBase.tileCollision));

(playerBase is the base of the player that contains a list (children) with all the body parts in it)

So now my problem: my problem is that my game only uses the collision logic on the LAST item (Rectangle) added to the tileCollision.

You see here that dirt is added as the last item, so the collision will work on this block, but not on the others.

I want it so that the method loops through every item instead of the last item.


texts: How to handle focus on a custom actor in Unreal Engine?

texts:
I created a custom actor, placed it on my scene and selected it.

When I press "F" to focus on it, the camera zoom back very far from the scene, probably because I didn't implement the method supposed to return the bounding box of my actor.

How can I do that?

Update

I implemented a custom component which delegates all drawing functions to an internal ULineBatchComponent member. I unregistered this ULineBatchComponent member. The custom component is not even attached to the actor root component.

But its bounding box is still taken into account when focusing on the actor.

UPBLineBatchComponent.h

UCLASS()
class UPBLineBatchComponent : public UObject
{
    GENERATED_UCLASS_BODY()
public:
    virtual FBoxSphereBounds CalcBounds(const FTransform& LocalToWorld) const;
    void SetTransform(const FTransform &Transform);
    virtual void DrawLine(...);
    virtual void DrawPoint(...);
    void Flush();
    ULineBatchComponent* LineBatchComponent;
    FBox LocalBounds;
};

UPBLineBatchComponent.cpp

UPBLineBatchComponent::UPBLineBatchComponent( const FObjectInitializer& ObjectInitializer )
        : Super( ObjectInitializer )
{
    LineBatchComponent = CreateDefaultSubobject<ULineBatchComponent>(TEXT("LineBatcher"));
    LineBatchComponent->UnregisterComponent();
    LocalBounds = FBox(0);
    LineBatchComponent->Bounds = FBoxSphereBounds(EForceInit::ForceInitToZero);
}

FBoxSphereBounds UPBLineBatchComponent::CalcBounds(const FTransform& LocalToWorld) const
{
    LineBatchComponent->Bounds = FBoxSphereBounds(LocalBounds.TransformBy(LocalToWorld));
    return FBoxSphereBounds(LocalBounds.TransformBy(LocalToWorld));
}

void UPBLineBatchComponent::SetTransform(const FTransform& Transform)
{
    LocalBounds = LocalBounds.TransformBy(Transform);
    LineBatchComponent->Bounds = FBoxSphereBounds(LocalBounds);

    bool bDirty = false;
    for (FBatchedLine& Line : LineBatchComponent->BatchedLines)
    {
        Line.Start = Transform.TransformPosition(Line.Start);
        Line.End = Transform.TransformPosition(Line.End);
        bDirty = true;
    }

    for (FBatchedPoint& Point : LineBatchComponent->BatchedPoints)
    {
        Point.Position = Transform.TransformPosition(Point.Position);
        bDirty = true;
    }

    for (FBatchedMesh& Mesh : LineBatchComponent->BatchedMeshes)
    {
        for (FVector& Vert : Mesh.MeshVerts)
        {
            Vert = Transform.TransformPosition(Vert);
            bDirty = true;
        }
    }

    if (bDirty)
    {
        LineBatchComponent->MarkRenderStateDirty();
    }
}

void UPBLineBatchComponent::DrawLine(const FVector &Start, const FVector &End, const FLinearColor &Color, uint8 DepthPriority, float Thickness, float LifeTime)
{
    LineBatchComponent->DrawLine(Start, End, Color, DepthPriority, Thickness, LifeTime);
    LocalBounds += Start;
    LocalBounds += End;
    LineBatchComponent->Bounds = FBoxSphereBounds(LocalBounds);
}

void UPBLineBatchComponent::DrawPoint(const FVector &Position, const FLinearColor &Color, float PointSize, uint8 DepthPriority, float LifeTime)
{
    LineBatchComponent->DrawPoint(Position, Color, PointSize, DepthPriority, LifeTime);
    LocalBounds += Position;
    LineBatchComponent->Bounds = FBoxSphereBounds(LocalBounds);
}

void UPBLineBatchComponent::Flush()
{
    LineBatchComponent->Flush();
    LocalBounds = FBox(0);
    LineBatchComponent->Bounds = FBoxSphereBounds(EForceInit::ForceInitToZero);
}

Update 2

If I use

LineBatchComponent = NewObject<ULineBatchComponent>();

instead of

LineBatchComponent = CreateDefaultSubobject<ULineBatchComponent>(TEXT("LineBatcher"));

I can focus properly on the actor, but I can't see the lines anymore.


texts: Generating the distance of an intersection through a box from the camera in Unity C#

texts:
So, I recently saw this fantastic video by Sebastian Lague about planetary generation-
https://www.youtube.com/watch?v=lctXaT9pxA0&t=1100s
And I decided to replicate it, however, on a flat plane, not a sphere.In the video, (at timestamp linked) he uses some mathematical expression to  figure out the distance of the camera's vector through an arbitrary sphere, and uses this to shade the ocean. I can't figure out how to write a similar estimator for an arbitrary rectangular prism. Anyone have any ideas?
EDIT- I have shifted to using surface shaders, but I can't figure out how to compensate for distance in depth-
Shader "Custom/SurfaceDepthShader"
{
    Properties {
        _ColorShallow ("Color Shallow", Color) = (1,1,1,1)
        _ColorDeep ("Color Deep", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.5

        _fadeDepth("Base Alpha", Range(0,1)) = 0.5

        _InvFade ("Soft Factor", Range(0.01,3.0)) = 1.0
    }
    SubShader {
        Tags { "Queue"="Transparent" "RenderType"="Transparent" }
        LOD 200

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Standard vertex:vert alpha:fade nolightmap

        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0

        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
            float4 screenPos;
            float3 worldPos;
            float eyeDepth;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _ColorShallow;
        fixed4 _ColorDeep;

        sampler2D_float _CameraDepthTexture;
        float4 _CameraDepthTexture_TexelSize;

        float _InvFade;
        float _fadeDepth;

        void vert (inout appdata_full v, out Input o)
        {
            UNITY_INITIALIZE_OUTPUT(Input, o);
            COMPUTE_EYEDEPTH(o.eyeDepth);
        }

        void surf (Input IN, inout SurfaceOutputStandard o) {
            // Albedo comes from a texture tinted by color
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _ColorShallow;
            //
            //  smoothness come from slider variables

            o.Smoothness = _Glossiness;

            float rawZ = SAMPLE_DEPTH_TEXTURE_PROJ(_CameraDepthTexture, UNITY_PROJ_COORD(IN.screenPos));
            float sceneZ = LinearEyeDepth(rawZ);
            float partZ = IN.eyeDepth;

            float dist = distance(_WorldSpaceCameraPos, IN.worldPos);

            float fade = 1.0;
            if ( rawZ > 0.0 ) // Make sure the depth texture exists
                fade = saturate(_InvFade * (sceneZ - partZ));

            o.Albedo = lerp(_ColorShallow, _ColorDeep, fade) * c;
            o.Alpha = c.a * fade * _fadeDepth;
        }
        ENDCG
    }
    FallBack "Diffuse"
}
```


texts: minecraft like game server database arhitecture

texts:
Let's say we have a 2d map 500*500 tiles in size. And each tile is editable by players and has many states. So it's 250k tiles.  The game is multiplayer online game.

What would be the best approach from a server database perspective? Store each tile as an object in db with coordinates? Or store them in chunks? Or any other way?


texts: How do I make A* agents avoid other agents?

texts:
I'm implementing a multi agent A* algorithm on a tile map. Agents move only in the X and Y axes. I avoid collisions between them by checking where the others are when calculating paths.

It works fine except the situation where agents have to pass the same tile from different directions. In situations like this, an optimal solution would be for one agent to wait for the other to pass:

Also, if there's no northern corridor, then pathfinding fails.

How could I implement such an algorithm?


texts: Large-Scale 2D worlds with a "world texture" to draw to causing memory issues

texts:
Background:

I've currently implemented a world class where the dimensions are provided in meters and those dimensions are translated to pixel values for an allegro (4.x) memory bitmap to be created so objects can be draw to it. This seemed like a good idea...until I learned the hard way that world dimensions translated to pixel dimensions such that the bitmap created would be upwards of 100,000,000 pixels causes um..."issues" and allegro (4.x) barfs.

Question:

How would I implement large-scale worlds such that they can be any arbitrary size and still have a bitmap/surface/texture to draw to that's small enough to fit into memory along with everything else? Please limit answers to allegro 4.x solutions.


texts: Does ZBrush's ZRemesher set it apart from other software for game models?

texts:
I'm trying to figure out the most efficient way to model game assets as an indie developer. From what I can tell, sculpting is much quicker than manual polygonal modelling for things like characters. However, it requires a retopology step to get the polycount acceptable.

I've seen the following methods of retopology:

Shrinkwrap edge modelling - can take an hour
Tool-assisted shrinkwrap edge modelling - speeds it up a lot, but still a lot of work
Decimate (automatically remove vertices) - instant, but ugly and inefficient end-result
ZRemesher - automatically creates a near-perfect low-poly model

But the part I'm confused about is that ZRemesher came out 4 years ago and other programs are still lacking any similar built-in features. I did find an open-source alternative called "Instant Meshes" which seems to work okay, but not as good as ZRemesher.

Why is this feature still unique to ZBrush after 4 years? Is it a company secret nobody has been able to replicate, or is it not as important of a feature as I think it is? It seems like it can save 10-60 minutes of tedious work for every model. I'd like to use Blender because it's free and I've already gotten familiar with it, but this makes it seem very inferior to ZBrush.


texts: Avoid if statements in DirectX 10 shaders?

texts:
I have heard that if statements should be avoid in shaders, because both parts of the statements will be execute, and than the wrong will be dropped (which harms the performance).

It's still a problem in DirectX 10? Somebody told me, that in it only the right branch will be execute.

For the illustration I have the code:

float y1 = 5; float y2 = 6; float b1 = 2; float b2 = 3;

if(x>0.5){
    x = 10 * y1 + b1;
}else{
    x = 10 * y2 + b2;
}

Is there an other way to make it faster?

If so, how do it?

Both branches looks similar, the only difference is the values of "constants" (y1, y2, b1, b2 are the same for all pixels in Pixel Shader).


texts: Is there a word that describes when too much audio is being play simultaneously?

texts:
In Unity, before I managed sounds properly, if too many accumulated at the same it would become this loud drowned out mega sound (like the speakers got blown out). With proper audio management this is never an issue, but it's funny how many times I see this problem come up in professional level games (notably Demon's Souls and Dark Souls when too many collisions happen with breakable boxes triggering too many sounds to happen at once).

Is there a word that describes that drowned out mega sound that happens when too many sounds are being played at once? Also, what's the process that's happening on the audio technical side when this sound is played, meaning are the sounds just being shoved into one mixer or something?


texts: I was designing the game in that i want to cover the scene with black layer and i want user to see it when he slide the image. Is there any functionality in AndEngine for something like slide to unlock.


texts: How can I get the specific tile in a collision with a Tilemap?

texts:
I am developing a simple platformer, I have three types of tiles right now:

Floor: does nothing on collision.
Bad: makes the player lose the game.
Good: makes the player beat the game.

I am trying to detect the collision with this code I found:

extends RigidBody2D

func _process(delta):
    var tile = get_parent().get_node("TileMap").get_cellv(get_parent().get_node("TileMap").world_to_map(position))
    print(tile)

The tile variable is supposed to contain the identifier of the type of tile the player is touching, but it doesn't, it always returns -1 (No exception or error, just -1).

I believe returning -1 means it isn't touching any tile, but it is.

This is using Godot 3.0 stable.

What am I missing?

Thank you for your patience.


texts: Efficiently rendering lots of the same mesh in Unity3D, but with different colors?

texts:
I'm working on a tile based game, where grass is spreading from tile to tile, so soon lots of grass appear on the board.

Instancing is on, so the FPS is kind of good, even with 300k triangles (1 grass leaf consists of 90 triangles).

BUT: Tiles can be wet and dry on floating scale, which makes the grass leaves turn from green to yellow.

Currently I implemented this simply as such:

var r = originalColor.r + 0.27f * (1f - (ground.Status / 100));
renderer.material.color = new Color(r, originalColor.g, originalColor.b);

Which creates a new material for every grass...

Obviously I can't change the sharedMaterial's color, because that would change all other grass' colors as well.

So how could I efficiently render grass on a big spectrum from yellow to green?

One thing I came up with is that I create only like 100 materials, with 1 percent steps.

= first material is 100% yellow, and the last one is 100% green.

And when a grass turns a bit more green, it doesn't have to create a whole new material with 3.47% green, but instead can use the already created 3% green material.

Any better ideas?

Thanks!


texts: isometric tile - How would I apply effect on only specific part of a sprite?

texts:
How would I apply a mask for pixel shading effect to restrict it only to some part of image? For example I have a height tile:

Now I want to apply the effect only on the tile-shape of this height-tile with some sort of masking:

Therefore, how would I restrict the pixel shading function boundary using masking?


texts: Are there game engines like Unity but for 2D?

texts:
I really like the convenience of unity3d.  The ability to edit the level and see my results in real time are great.  My problem is the idea I want to implement is 2d and uses 2d sprites.  Scaling sprites appears to be a problem for me and all advice I receive says to purchase 150 dollars addons for unity. I love the physics components and the rapid prototyping but I figured that maybe unity is not the tool for the job for this 2d game.

Is there any 2d game engine like unity but for 2d games that would work on the PC and Android?  Or is this something most people code themselves and make?  To me the most important features of Unity3d were its ease to see what was edited and then have it apply instantly.

Thank you. Most searches seemed to give me frameworks and not a large engine suite.


texts: What's the difference between Destroy() and SetActive(false)?

texts: I read about both methods in Unity and wanted to ask about which was the best in efficiency : destroying the object or deactivating it. What is the performance difference?


texts: Is the STL efficient enough for mobile devices?

texts:
When it comes to mobile game development on iOS and Android NDK, some developers write their own C++ containers, while others claim that STL is more than adequate for mobile game development (For example, the author of iPhone 3D Programming uses STL rather than Objective-C in his examples. His defense is that STL is no slower than Objective-C).

Then there are also mobile developers who abandon C++ entirely and develop games entirely (or mostly) in the C language (C89/C90).

What are the benefits and drawbacks of each approach?


texts: How to make a script on a prefab act on a particular scene instance?

texts:
I am building Actionables (Windmill, Coal) on a Planet by hovering the mouse over the Planet and clicking on it.

Actionables are prefabs, which have an Actionable component, with the same setup (at the moment).

Once the player is happy with the location of their Actionable, they click LMB, which activates onClick callback, which is supposed to call Planet.Build(), which adds the Actionable on the Planet permanently (saves it into an internal array).
I also have a "Turn Off" Button, which calls stopBuilding() when clicked, disabling the preview placement.
When stopBuilding() is invoked by the button click, everything works as expected.
I also want to be able to call Planet.stopBuilding() (which, by removing the actionableModel, disables hover preview on the Planet) from Planet.Build(), such that the player does not need to click the Turn Off button described above after building an Actionable.
Inside Actionable prefabs I can only assign other prefabs, but I need them to interact with the scene object. I cannot override the Planet object in Actionable instances, as they are generated on the fly.
How do I access the scene object Planet from Actionable prefab?
Here is my Planet and its stopBuilding method so far:
   public class Planet : MonoBehaviour
   {
       private GameObject actionableModel;

       // ...

       public void stopBuilding()
       {
           // For debugging only
           Planet planet = GameObject.Find("Planet").GetComponent<Planet>();
           Debug.Log(planet.actionableModel);
           Debug.Log(this.actionableModel);

       }
   }

And here is the Actionable component which has a UnityEvent property onClick, which calls stopBuilding() on a click event.
   public class Actionable : MonoBehaviour
   {
       public class OnClick : UnityEvent<GameObject> { }
       public OnClick onClick = new OnClick();

       // ...

       void OnMouseDown()
       {
           onClick.Invoke(gameObject);
       }
   }


texts:
I am creating a real time multiplayer game in Unity 3d. When a game ends I set a static boolean value called "waitingToEndGame" to true. In Update() it waits a few seconds before moving to a new scene like this:

if (waitingToEndGame)
{
    waitTime += Time.deltaTime;
    if (waitTime >= 5f)
    {
        showGameScores = false;
        waitingToEndGame = false;
        if (type == "Multiplayer") MultiplayerController.Instance.LeaveGame();
        GameObject levelManager = GameObject.Find("Level Manager");
        levelManager.GetComponent<LevelManager>().LoadLevel("MainMenu");
    }
    DisableAllMovingObjects();
}

My problem is that even though I am setting the boolean value to true it acts as if it doesn't change and it doesn't make it into the code above to move to the main menu. I even had debug statements printing here as well and they seem to just suddenly stop.


texts: What happened to procedurally generated textures?

texts:
I recall some time ago that procedurally generated textures were becoming a big deal that a lot of people/companies were really interested in with some serious benefits (smaller deployments, potentially faster loading, higher quality, scalable textures, potentially cheaper to produce, etc.).

From what I can tell, the buzz is dead and no games on my radar are using them. What happened?

I was hoping I'd see procedural textures go the way that NaturalMotion's stuff has (slow but steady adoption).


texts: Trouble projecting pixel back to worldspace in PixelShader [DX11]

texts:
For the last two days, I've been trying to get some code working to project pixels back to world space in my pixel shader. Im working on a fairly basic deferred renderer, and I'm using this world space position to calculate distance to a light, so I can calculate the light falloff/intensity.
My first thought was to take the view and projection matrix from the g-buffer pass, multiply them, take the inverse, transpose and then write to the constant buffer.
.cpp file

auto gBufferWorld       = DirectX::XMMatrixIdentity();
auto gbufferTransform   = DirectX::XMMatrixMultiply( gBufferWorld, gBufferView );
gbufferTransform        = DirectX::XMMatrixMultiply( gbufferTransform, gBufferProj );
gbufferTransform        = DirectX::XMMatrixInverse( nullptr, gbufferTransform );

---------------------------------------------------------------------------------------
pixel shader code

float4 pixelWorldPos = float4( input.TexCoord.x * 2.f - 1.f, ( 1.f - input.TexCoord.y ) * 2.f - 1.f, ( depth - nearClip ) / ( farClip - nearClip ), 1.f );

pixelWorldPos = mul( pixelWorldPos, invViewProjMatrix );
pixelWorldPos /= pixelWorldPos.w;

But, I end up getting totally incorrect values. I also tried using just the TexCoords for pixelWorldPos.xy, using the depth value sampled from the gbuffer for pixelWorldPos.z, and still, nothing seems to give me the correct world position.
I also tried using trigonometric functions to achieve this, I dont have the exact code on hand anymore, but it looked something like...
float tanHalfY = tanf( fovY / 2.f );
float tanHalfZ = tanHalfY * aspectRatio;

---- In Pixel Shader ----
float3 dir = normalize( float3( x * tanHalfX, y * tanHalfY, 1.f ) );
float4 pixelWorldPos = mul( float4( dir * depth, 1.f ), invViewMatrix );
pixelWorldPos = normalize( pixelWorldPos );

Of course I could just write an extra GBuffer texture containing each pixels worldspace position, since it would be trivial to compute in the GBuffer pass, but I'm unsure if the extra VRAM consumption is worth it, since I can just calculate in the final lighting pass.
I was hoping someone can point me in the right direction, I really didnt expect to have so much trouble with something that I thought would be so trivial.


texts: Synchronization between game logic thread and rendering thread

texts:
How does one separate game logic and rendering? I know there seem to already be questions on here asking exactly that but the answers are not satisfactory to me.

From what I understand so far the point of separating them into different threads is so that game logic can start running for the next tick immediately instead of waiting for the next vsync where rendering finally returns from the swapbuffer call its been blocking on.

But specifically what data structures are used to prevent race conditions between the game logic thread and the rendering thread. Presumably the rendering thread needs access to various variables to figure out what to draw, but game logic could be updating these same variables.

Is there a de facto standard technique for handling this problem. Maybe like copy the data needed by the rendering thread after every execution of the game logic. Whatever the solution is will the overhead of synchronization or whatever be less than just running everything single threaded?


texts: Subdivided Icosahedron Hex/Pent grid efficient rendering?

texts:
How to performantly display a hex/pent grid on a subdivided icosahedron?

I have a subdivided icosahedron planet used as the "board" for a strategy game. It usually has anywhere between a few thousand and a hundred thousand tiles depending on the size the user inputs to the map generator.

Basically, I cannot brute force this and do a simple bounds and depth check, because of the sheer numbers of tiles.

I am storing the grid in a 2D array for simplicity. I understand that, on a 2D map, you simply do something like the following to draw a hex map:

for(int x = cameraX; x < viewportWidth; x++)
{
    for(int y = cameraY; y < viewportHeight; y++)
    {
        if(x % 2 == 0) //For the 2D array to work properly we have to offset every other row by +1 world coordinate (assuming each tile is 1*1 world coordinates)
           grid[x][y].render(x+tile_width, y);
        else
            grid[x][y].render(x, y);
    }
}

And that to draw a wrap-around world you would check the absolute distance from the camera's position.

Eg:

//This sets up the variable that tells the game what hex tiles to draw.
if(camera.x - viewportWidth < 0)
{
    camera_rX = camera.x - viewportWidth;
    cameraX = grid.length + camera_rX; //We will add this to the cameraX value because the result should be a negative value if the prerequisite if statement is met. The "cameraX" variable is used for viewing calculations, while the "camera.x" variable is used for camera positioning. Err... I think this makes sense.
}


texts: LibGDX - Trying to make a radar-like display

texts:
i have an interesting question about geometry.
I have two or more moving objects outside of my stage's viewport (blue and red circle in the image below), which i want to point at with two arrows on the border of the screen (or better, viewport bounds).
The black dot never moves, because it represents viewport's center.

So, arrows must always point at the objects and must always be "locked" on the border of the screen.

Can someone help me with this?

UPDATE
Following @Stormwind answer, i managed to get a Ray from objects to screen center.
Now my problem is defining the BoundingBox.
I tried declaring it like this:

Vector3 v1 = new Vector3(0, 0, 0)
Vector3 v2 = new Vector3(screen.width, screen.height, 0)
BoundingBox box = new BoundingBox(v1, v2)

and then get the intersection by using the IntersectRayBounds() method,
but behaviour is funny.
I think i missed out something or mistakenly declared the BoundingBox.


texts: Can I develop Linux + Windows games using C#, .NET and OpenGL?

texts:
I want to learn to develop 3D and 2D graphics with either OpenGL or DirectX. I chose OpenGL as it's being used in webGL and works cross-platform.

I already know .NET well, and the C# language just fits my style very well and I feel secure with it.

However, I want to develop a game that works on Windows and Linux. Is this possible to do with the combination of C#, .NET and OpenGL. I know that OpenGL will not be a problem.


texts: Is there a way to create a sky-sphere instead of a skybox in Unity3D?

texts:
In a 3D game, how can I make a sky background seen at the horizon? I tried adding a texture to the skybox but since it's a box it looks horrible.

When I'm not using a texture it's not notable that it is actually a box so it looks better.

I can imagine doing the same with a huge sphere but I imagine there is a proper way of doing it, so I thought I would ask.


texts: Why does creating dynamic bodies in JBox2D freeze my app?

texts:
My game hangs/freezes when I create dynamic bullet objects with Box2D and I don't know why. I am making a game where the main character can shoot bullets by the user tapping on the screen. Each touch event spawns a new FireProjectileEvent that is handled properly by an event queue. So I know my problem is not trying to create a new body while the box2d world is locked. My bullets are then created and managed by an object pool class like this:

public Projectile getProjectile(){
    for(int i=0;i<mProjectiles.size();i++){
        if(!mProjectiles.get(i).isActive){
            return mProjectiles.get(i);
        }
    }

    return mSpriteFactory.createProjectile();

}

mSpriteFactory.createProjectile() leads to the physics component of the Projectile class creating its box2d body. I have narrowed the issue down to this method and it looks like this:

public void create(World world, float x, float y, Vec2 vertices[], boolean dynamic){

    BodyDef bodyDef = new BodyDef();
    if(dynamic){
        bodyDef.type = BodyType.DYNAMIC;
    }else{
        bodyDef.type = BodyType.STATIC;
    }
    bodyDef.position.set(x, y);
    mBody = world.createBody(bodyDef);

    PolygonShape dynamicBox = new PolygonShape();
    dynamicBox.set(vertices, vertices.length);
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = dynamicBox;
    fixtureDef.density = 1.0f;
    fixtureDef.friction = 0.0f;
    mBody.createFixture(fixtureDef);
    mBody.setFixedRotation(true);

}

If the dynamic parameter is set to true my game freezes before crashing, but if it is false, it will create a projectile exactly how I want it just doesn't function properly (because a projectile is not a static object). Why does my program fail when I try to create a dynamic object at runtime but not when I create a static one? I have other dynamic objects (like my main character) that work fine. Any help would be greatly appreciated.

This is a screenshot of a method profile I did:

Especially notable is number 8. I'm just still unsure what I'm doing wrong.

Other notes:
I am using JBox2D 2.1.2.2. (Upgraded from 2.1.2.1 to try to fix this problem)
When the application freezes, if I hit the back button, it appears to move my game backwards by one update tick. Very strange.


texts: How to position objects responsively in SDL?

texts:
I have an SDL window using SDL_WINDOW_FULLSCREEN_DESKTOP (as opposed to SDL_WINDOW_FULLSCREEN, which doesn't work properly)

When I try to place stuff on the screen, it is placed in the wrong location on Fullscreen mode rather than windowed mode. Since fullscreen and windowed seem to have different proportions/placements, I'm wondering what the best way is to accurately place images on the screen in both windowed and fullscreen mode.

I need to "convert" or "adapt" placement from windowed to fullscreen, so it looks right when fullscreen is toggled.


texts: Which things to do in AutoCAD and which in 3ds Max?

texts:
I learned 3ds Max two months ago. I am not perfect in it, but I used it to make a model of a house. I am interested in house architectures. I used to model everything in Max.

I have just started to learn AutoCAD and it has been two weeks. I realized that AutoCAD is very accurate in modelling floor plans, doors, windows, etc.

The teacher told me that every thing from a chair to a pen to a bed, etc., can be modelled in AutoCAD.

Now I am confused as to which is the right way to model house interiors, AutoCAD or Max.

I want to know at what point should I finish things in Autocad and then move to Max?


texts: In Unreal4, Can I use switch case in C++ with FString?

texts:
I'm making XML parsing code with FXmlNode. I want to iterate through GetChildrenNodes(), and use switch-case with FString which is return value of FXmlNode::GetTag(). Is there someway to do that? Or should I use

 if (Tag == TEXT("XX") .. else if (Tag == TEXT("YY"));

Thanks.


texts:
I have a pretty decent experience with tile based 2d games and I would like to try to create a mixed 3d-2d game. To 3d elements will be very simple (ground, walls and water), all other elements will be 2d sprites drawn onto this 3d map. (I am envisioning something similar to Final Fantasy III for iPad, top down view, always the same angle)

Now, here is my question: What are the technical aspects of implementing a 3d tile engine? Are there some good examples on how to do this? Basically I would like to create the maps the same way that I would do in a 2d tile based game.


texts: How to make one-axis tileable simplex noise?

texts:
I made a program that uses perlin noise to generate a height map. It worked very good. Later I changed it to use simplex noise.

What I want to achieve now is that the left edge fits in the right edge, so I want to make it tileable.

I did some research and found this: https://gamedev.stackexchange.com/a/23639/116727.
This formula makes it tileable on every edge but I only want it to be tileable on the left and right edges. Then I found this website: http://www.jgallant.com/procedurally-generating-wrapping-world-maps-in-unity-csharp-part-2/#wrap1. It was just what I needed, with a formula that only tiles on one axis. I the tried to implement it, but I could not get it to work.

Here is my implementation:

//Noise range
double x1 = 0, x2 = 1;
double y1 = 0, y2 = 1;
double dx = x2 - x1;
double dy = y2 - y1;

//Sample noise at smaller intervals
double s = x / xsize;
double t = y / ysize;

// Calculate our 3D coordinates
double nx = x1 + Math.Cos(s * 2 * Math.PI) * dx / (2 * Math.PI);
double ny = y1 + Math.Sin(t * 2 * Math.PI) * dy / (2 * Math.PI);
double nz = t;

float PerlinValue = (float)SimpNoise.Evaluate(nx, ny, nz); //* 2 - 1;

map[x, y] = PerlinValue;

This is the result that I get:

What am I doing wrong? How can I fix this?


texts: Why does my Outlined Diffuse 3 shader seem "detached" at a distance?

texts:
I'm using the Outlined Diffuse 3 shader from Unity and I'm having a problem with it: the outline looks great when the camera is near the object, but at a distance, it looks detached.

From nearby (looks good):

From afar (looks bad; see the shelf and books):

How can I fix this graphical anomaly?


texts: How to profile CPU and GPU performance if I have a monster PC?

texts:
I'm going to upgrade my PC soon. I'm worried that I will no longer spot performance losses in my game because of the better specs.

I can check memory usage easily, but how do I check and debug CPU and GPU usage? I used to rely on the framerate, but I guess that it is not accurate.


texts: Moving an object toward another object on sphere knowing their quaternions

texts:
I have a sphere centered in world origin. On the sphere surface I have two objects and I know their quaternions (rotation around sphere).

Currently my movement works on Vector2 inputs (cannot change distance from sphere surface) concatenating the current movement quaternion to existing quaternion:

 RotationQuaternion *= Quaternion.CreateFromRotationMatrix(
        Matrix.CreateRotationX(-_movementDirection.Y * Speed * deltaSeconds) *
        Matrix.CreateRotationY(_movementDirection.X * Speed * deltaSeconds));

How would I move one object toward another? I have looked into quaternion lerping functionality, but this does not really help, as what I would ideally want is movement direction and apply my own speed and acceleration to it.

Thanks for any help - geometry is not my strongest suite!


texts: What name should I give each difficulty level?

texts: I have a game with 4 difficulty levels (or levels of AI) and I'm wondering what to name them instead of the boring Easy, Normal, Hard, Impossible.


texts:
I would like to use a Wii remote to control my player in my 3D game.

So far I have the arrow keys and mouse to move and look but I want the Wii d-pad to move and accelerometer data to look around.

I have downloaded Unity-Wiimote-1.1 and the demo works fine. In my game I have imported the Unity package for the Wii remote but I'm not sure what script goes where, attached to what, how to call particular functions. They are mostly C# scripts.

There is no documentation with the Unity-Wiimote-1.1 and as I'm a newbie, I'm clueless on what to do.

Or is there a simpler method to getting the Wii remote to be the main controller?


texts: Making NavMeshAgent to look the direction it was moving when it stops

texts:
I'm currently using NavMeshAgent as my player character controlled by keyboard or gamepad input.
Also, I'm flipping my character instead of turning via controlling localScale as below.

        private void FixHeadRotation()
        {
            float dir = (myAgent.velocity.normalized.x > 0) ? 1 : -1;
            transform.localScale = new Vector3(1, 1, dir);
        }

However, since I'm relying on the velocity I'm getting the direction(flip) right when moving, but not when I'm not moving(x should be -1 but 1 since no velocity).

I've noticed the NavMeshAgent has built-in function displaying an arrow gizmo over the agent's head. Perhaps I could use that(don't know how atm)?
or any other suggestions to this?


texts:
So I've been building a game and using the out of the box unity third person controller demo stuff.

I found that even the tiniest of slopes seems to stop the "dude" dead in his tracks.

Is there an easy way to adjust the sensitivity on the scripts somewhere?

I tried messing with the sensitivity options in the input options setup thinking that it might help but it didn't and I don't really want to go messing about in the scripts unless I really have to because i end up complicating my life when I do that.


texts: How do I update this code to hit a moving target from a moving shooter?

texts:
I am working on a game where one spaceship("Origin") can shoot a dumb projectile("Projectile") at another spaceship("Target").
Since the target is moving we will have to lead the target.
The projectile will move at a given speed (to be clear I differentiate between "velocity" which i use when talking about a vector and "speed" when i am talking about the length of said vector).
I am trying to calculate the point where I will have to aim in order to hit the target (assuming it does not change its velocity).
I tried this example.
UPDATED THE CODE
This is part of the "projectile" class that a wrote.
self.targetVessel is the target
self.originVessel is the shooter
this function is called one in the constructor so that self.originVessel.velocity is the starting velocity
self.totalSpeed is the "kick" that the projectile gets from the shooter
    def takeAim (self):
    t = 0

    #self.totalSpeed += math.sqrt(np.dot(self.originVessel.velocity, self.originVessel.velocity))

    posRel = self.pos - self.targetVessel.pos
    velRel = self.originVessel.velocity - self.targetVessel.velocity
    #velRel =  - self.targetVessel.velocity #this hits the target but the speeds don't add up

    a = (np.dot(velRel, velRel))-(self.totalSpeed**2)
    b = 2.0 * (np.dot(velRel,posRel))
    c = np.dot(posRel, posRel)

    disc = (b*b) - (4.0*a*c)

    print("Disc: ", disc)

    if disc < 0:
        print("Target is too fast - no point shooting!")
    else:
        t0 = (-b - math.sqrt(disc)) / (2.0*a)
        t1 = (-b + math.sqrt(disc)) / (2.0*a)

        print("t0: ", t0)
        print("t1: ", t1)

        if t0 < 0:
            t = t1
            print ("Choosing t1")
        elif t1 < 0:
            t = t0
            print ("Choosing t0")
        else:
            if t0 < t1:
                t = t0
                print("Choosing t0")
            else:
                t = t1
                print("Choosing t1")

    shoot = velRel + (posRel / t)
    self.velocity =  shoot + self.targetVessel.velocity
    self.aimPoint = self.targetVessel.pos + self.targetVessel.velocity*t
    targetDirection = self.aimPoint-self.pos
    targetDirection = targetDirection / math.sqrt(np.dot(targetDirection,targetDirection))
    self.velocity = (targetDirection * self.totalSpeed)


texts: Add Objects in LWJGL without using glTranslationf function

texts: It is possible to add an object in LWJGL without using translation function (glTranslatef) ? and if it is possible does this improve somehow performance ?


texts: Monogame / XNA - Is there a limit when drawing at far position (> 1 billion ? = strange behavior)

texts:
So I'm making an "unlimited" 2D Tile-Engine with procedural generation (simple noise based) in Monogame, and I'm loading/unloading Chunck by Chunck as you go along. It's working pretty well now.

Only problem I encounter when I'm positioning my character at a high value like for example int.Maxvalue / 2 (and higher), drawing tiles and every sprites from a high Position becomes all glitchy. Tiles take random sizes with a higher width and height (see pictures).

Drawing tiles :

 spriteBatch.Draw(
   textToDraw,
   new Vector2(i * TILE_SIZE, j * TILE_SIZE),
   new Rectangle(0, 0, TILE_SIZE, TILE_SIZE),
   drawColor,
   0,
   new Vector2(0, 0),
   1f,
   SpriteEffects.None,
   depth
 );

Camera Transform :

public Matrix Transform(GraphicsDevice graphicsDevice)
{
   m_Transform =
     Matrix.CreateTranslation(new Vector3(-m_CameraPosition.X, -m_CameraPosition.Y, 0.0f)) *
     Matrix.CreateTranslation(new Vector3(graphicsDevice.Viewport.Width * 0.5f , graphicsDevice.Viewport.Height * 0.5f , 0.0f)); // on redivise par 0.5 à cause du renderTarget 720x450

   return m_Transform;
}

Begin spriteBatch :

matrix = this.Manager.camera.Transform(this.GraphicsDevice);
spriteBatch.Begin(SpriteSortMode.BackToFront,
    BlendState.AlphaBlend,
    SamplerState.PointClamp,
    null,
    null,
    null,
    matrix
);

Drawing at position x = 1 million, y = 1 million :
Drawing at position x = 1 billion, y = 1 billion:
Red tile is a random tile I draw in another color to be able to get the size. But all the tiles are glitchy.

To isolate the problem as it didn't seem to come from my code, I tested in an Internet XNA sample I modified (From xnagpa.net "Eyes of the Dragons" samples) working with a similar Camera and tile engine. I forced the Camera position to a high value (x = 1 billion, y, 1 billion) and drawing Tiles on the screen at that position. Same problem. So my newb guess is it has to do with calculation of the Matrix, but after that it gets too complicated for me.

Anyone had the problem ? Can confirm it is a limitation of some sort. I don't think it can be fixed, but I'm trying to determine what is the "limit" of my "unlimited world".

Code is from my code base, pictures are from the example I cited and modified


texts: How to efficiently batch blocks and reduce drawcalls in a voxel-like game

texts:
To fully get the benefits of GPU instancing in Unity in a voxel-like game I'm trying to batch as many static blocks as possible (the terrain won't be destructible, and I can't set these blocks to 'static' since I'll later need to assing different properties for each instance)

I see two possible solutions for this kind of problem:

• Creating a prefab for every possible block in my game, and batching togheter blocks with the same material/mesh/uvs

pros: won't need giant textureAtlas for storing albedo textures

cons: certain scenes with many differing terrain blocks may be hard to batch efficiently, and adding a property to every type of block would mean changing every block prefab (a nightmare if I have more than a handful of biomes)

• Creating a single block prefab and offset it's UVs with MaterialBlocks directly in the fragment shader

pros: every scene involving terrain blocks should at least in theory be efficiently batched, a single prefab to describe every type of terrain block

cons: needs a giant texture Atlas, and if it doesn't fits all of the block textures in the game more textures will be needed and I'll be limited in the future in the amount of blocks my game can have (unless I create different materials with different texture bindings, defeating the purpose of this solution), + fragment shader overhead for every type of block in the scene

Am I missing something here? Is there a different approach? If not, which one of the two would you consider the most appropriate in this scenario?


texts: GameMaker Studio 2 - How to place object back beyond X coordinate for looping (warp)?

texts:
I'm making a side-scrolling shooter where I want an object to move from right to left (towards negative X), then, when it's passed out on the left side, jump back to beyond the window width (right side) at a randomly determined Y coordinate (using irandom_range) to loop back into view.
This object is not part of the background as it is meant to obstruct the player's movement (similar to Flappy Bird pipes).
I'm using the Drag'n'Drop interface in Game Maker Studio 2. Currently I have this setup, but the object remains at the right-side window edge, moving randomly up and down each step:


texts: Do you extend Java, to make games, or can you just use JFrame?

texts:
I'm starting to create my own side scroller, in Java. I think I've read that, when you create a game in Java, there is something you can extend your class with, like GamePanel.

Is this true, or can you just use JFrame for your Java games?


texts: Multitexturing depending on given variables?

texts:
I'm having trouble with rendering multiple textures.
Using XNA gamestudio: working with 3D meshes and texturing.
Effect.fx HLSL

I do have a map/level that loads from a heightmap. - This works

I have created an effect.fx file that renders the textures. - This works

Multitexturing shader works to a degree where I hardly can alter the function.

So I can fade from different textures if I pass a height value, would have worked fine if the world was meant to be solid/static, but that's not the case here.

I want to hold certain variables to the vertex/faces and alter them in realtime while the vertexshader and the other drawing components renders it correctly as the variables is being altered.

If I wanted to paint a vertex/face red on a Grass-textured plane then this mentioned vertex/face would then be red.

I'm having a hard time finding the problem.
Wasn't able to make a 2 dimensional for loop within the Pass technique loop
"that just made too much thinking and almost crashed the application"

Have looked trough the source codes for a few example app with no success.

I even bought a book on the subject, but all I've got so far is how to render different textures when the vertex/faces reaches a certain height value on the Y axis.


texts: Batch conversion of PVR to JPEG (or similar)

texts: The command line PVRTexTool works very well for getting textures into a PVR format, but I need a way of going the opposite directions. Does anyone know of a good command line tool (or GUI with a batch mode) that will convert a PowerVR texture to a more common image format (like JPEG or PNG?)


texts: How do I simulate color blindness for accessibility testing?

texts:
Is there an application I can download (or some configuration of Windows, or something) that will let me see how my game will appear to users with different color-blindnesses?

There are already good questions about how to avoid badly-designing your game for colour blindness. There's also a Photoshop filter from VisCheck is a nice idea, except their image-processing upload service is down.

Is there, therefore, a tool I can use to simulate colour blindness and see how things look? Ideally, I would like to try different types (red/green, blue/yellow, mild/severe).

If not, how do other game developers test/avoid this problem, other than ignoring it, or having access to a color-blind person (which I don't)?


texts: Problem if 2 HTC Vive into field of view of emitters?

texts:
I am developing an app for a trade fair that uses the HTC Vive.

Now I am wondering how the HTC Vive syncs with the sensors...I suppose it uses bluetooth, are the sensors "coupled" with the glasses for example with a MAC-Address or sth like that, so another glasses will not work at all, before not configuring it?

I mean, if for any reason another glasses (connected to other computer but powered on) come into the field of view of the emitters, could it be a problem?

Since I have no access at the moment for a second HTC Vive I can't just test it.

If someone has info regarding this it will be very useful.


texts:
I'm trying to figure out how to implement a KD tree.

On page 322 of "Real time collision detection" by Ericson

The text section is included below in case Google book preview doesn't let you see it the time you click the link

text section

Relevant section:

The basic idea behind intersecting a ray or directed line segment with a k-d tree is straightforward.  The line is intersected against the node's splitting plane, and the t value of intersection is computed. If t is within the interval of the line, 0 <= t <= tmax, the line straddles the plane and both children of the tree are recursively descended.  If not, only the side containing the segment origin is recursively visited.

So here's what I have: (open image in new tab if you can't see the lettering)

The logical tree

Here the orange ray is going thru the 3d scene.  The x's represent intersection with a plane.  From the LEFT, the ray hits:

The front face of the scene's enclosing cube,
The (1) splitting plane
The (2.2) splitting plane
The right side of the scene's enclosing cube

But here's what would happen, naively following Ericson's basic description above:

Test against splitting plane (1).  Ray hits splitting plane (1), so left and right children of splitting plane (1) are included in next test.
Test against splitting plane (2.1).  Ray actually hits that plane, (way off to the right) so both children are included in next level of tests.  (This is counter-intuitive - shouldn't only the bottom node be included in subsequent tests)

Can some one describe what happens when the orange ray goes through the scene correctly?


texts: Unity Mirror client scene.local player.connection to client.client owned object not working in client

texts:
U hmm I'm new to mirror networking I just wanna find objects that the local player has authority, but it doesn't work on client, is there a solution to this? Well I could make an object tracking script but that will complicate things.
This question might look like I haven't research anything, truth is I've searched everywhere there is just no documentation for this


texts: Other games that employ mechanics like the game "Diplomacy"

texts:
I'm doing a little bit of research and I'm hoping you can help me track down any games, other than Diplomacy (online version here), that employ all or some of the mechanics in Diplomacy (rules, short form). Examples I'm looking for:

Simultaneous orders given prior to execution of orders

In Diplomacy, players "write down" their moves and execute them "at the same time"

Support, in terms of supporting an attacker or defender "take" a territory.

In Diplomacy, no one unit is stronger than another you need to combine the strength of multiple units to attack other territories.

Rules for how move conflicts are resolved

Example, 2 units move into a space, but only one is allowed, what happens.

I may add to this list later, but these are the primary things I'm looking for. If you need clarification on anything just let me know.

  Note: I tried asking this on GamingSE, but it was shot down. So, I am unsure where else I could post this. Since I am researching this for game development purposes, I assume this post is on topic. Please let me know if this is not the case. Please also feel free to re-categorize this. Thanks!


texts: Box2D No Gravity when moving against wall

texts:
I use Box2D in my current project and I have a problem with the gravity..

You can see my problem here: https://www.youtube.com/watch?v=2_kv9LkKwN4&feature=youtu.be

when i jump normal everything is fine, but when I press against a wall while I jump the body doesn't fall down after I release the move key in the direction of the wall the body falls down.

This is my move code:

public void moveByLinear(float x, float y) {
    linearMovement.set(x, y);

    body.setLinearVelocity(linearMovement);
}

and

moveByLinear(movespeed, getBody().getLinearVelocity().y);

movespeed is 8


texts: Writing Game Engine from scratch with OpenGL

texts:
I want to start writing my game engine from scratch for learning purpose, what is the prerequisites and how to do that, what programming languages and things you recommend me? Also if you have good articles and books on that it will be great. Thanks in advance!

My Programming languages and tools are:

C/C++ is it good to use only C?
Python
OpenGL
Git
GDB

What I want to learn from it:

Core Game Engine
Rendering / Graphics
Game Play/Rules
Input (keyboard/mouse/controllers,
etc)

In Rendering/Graphics:

3D
Shading
Lighting
Texturing


texts: OpenGL orthographic projection rendering quarter of screen

texts:
I'm trying to set up an orthographic projection so I can draw a rectangle using screen coordinates, but even if I draw a rectangle using the width/height of the window, it only fills a quarter of the window. Am I doing something wrong with glOrtho?

Relevant code: (width/height refers to window dimensions)

glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, width, height, 0.0f, -1.0f, 1.0f);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glTranslatef(0.0f, 0.0f, 0.0f);
glBegin(GL_QUADS);
glVertex2i(0, 0);
glVertex2i(width, 0);
glVertex2i(width, height);
glVertex2i(0, height);
glEnd();

Output looks like this:

I am targeting OpenGL 2.1 if that matters.


texts: I wanted to have shadows in my game and thought the way they were implemented in Diablo was good enough. Any hints on how to produce a similar outcome?


texts: OpenGL: Rotating cannon about non-centre position?

texts:
So I have a "cannon" object (basically a long cylinder) and I want to be able to control its angle. The code I have now is:

    glPushMatrix()
    glTranslatef(self.position.x,2.5,self.position.z)
    glRotated(self.tube_angle, 1.0, 0.0, 1.0)
    glScaled(1.0, 0.5, 1.0)
    glCallList(self.tube.gl_list)
    glPopMatrix()

This rotates it around the axis, obviously. I want the bottom to stay in the spot it is (moving object) and just change the angle.


texts: Can I output a text file on build with build details in it?

texts:
We have an issue with organizing our builds. They get copied around and moved so much that it's hard to keep track of what is the newest.

I would like to output a simple text file to the build root (same level as exe) that contains info like the build date and time, platform, etc.

Is this possible from within Unity?  Right now we have no automated build process (CI/CD).

edit: I found onPreprocessBuild() but unfortunately one of our main projects still uses Unity 5.3.6f1, so this will not work. Is there an alternative?


texts:
The problem:
When the player hits the left boundary he stops (this is exactly what I want), when he hits the right boundary. He continues until his rectangle's left boundary meets with the right boundary.

Outcome:
https://www.youtube.com/watch?v=yuJfIWZ_LL0&feature=youtu.be

My Code

public class Player extends GameObject{

BufferedImageLoader loader;
Texture tex = Game.getInstance();
BufferedImage image;
Animation playerWalkLeft;
private HealthBarManager healthBar;
private String username;
private int width;
private ManaBarManager manaBar;

public Player(float x, float y, ObjectID ID) {
    super(x, y, ID, null);
    loader = new BufferedImageLoader();
    playerWalkLeft = new Animation(5,tex.player[10],tex.player[11],tex.player[12],tex.player[13],tex.player[14],tex.player[15],tex.player[17],tex.player[18]);

}

public void tick(LinkedList<GameObject> object) {

    setX(getX()+velX);
    setY(getY()+velY);
    playerWalkLeft.runAnimation();

}

public void render(Graphics g) {

    g.setColor(Color.BLACK);

    FontMetrics fm = g.getFontMetrics(g.getFont());

    if(username != null) width = fm.stringWidth(username);
    if(username != null){
        g.drawString(username,(int) x-width/2+15,(int) y);
    }

    if(velX != 0){
        playerWalkLeft.drawAnimation(g, (int)x, (int)y);
    }else{
        g.drawImage(tex.player[16], (int)x, (int)y,  null);

    }

    g.setColor(Color.PINK);
    g.drawRect((int)x,(int)y,33,48);
    g.drawRect(0,0,(int)Game.getWalkableBounds().getWidth(), (int)Game.getWalkableBounds().getHeight());

}

@SuppressWarnings("unused")
private Image getCurrentImage() {
    return image;
}

public float getX() {
    return x;
}

public float getY() {
    return y;
}

public void setX(float x) {
    Rectangle gameBoundry = Game.getWalkableBounds();
    if(x >= gameBoundry.getMinX() && x <= gameBoundry.getMaxX()){
        this.x = x;
    }

}

public void setY(float y) { //IGNORE THE SetY please.
            this.y = y;
}

public float getVelX() {
    return velX;
}

public void setHealthBar(HealthBarManager healthBar){
    this.healthBar = healthBar;
}

public HealthBarManager getHealthBar(){
    return healthBar;
}

public float getVelY() {
    return velY;
}

public void setVelX(float velX) {
    this.velX = velX;
}

public void setVelY(float velY) {
    this.velY = velY;
}

public ObjectID getID() {
    return ID;
}

public void setUsername(String playerName) {
    this.username = playerName;

}

public String getUsername(){
    return this.username;

}

public void setManaBar(ManaBarManager manaBar) {
    this.manaBar = manaBar;

}

public ManaBarManager getManaBar(){
    return manaBar;
}

public int getLevel(){
    return 1;
}

public boolean isPlayerInsideBoundry(float x, float y){
    Rectangle boundry = Game.getWalkableBounds();

    if(boundry.contains(x,y)){
        return true;
    }

    return false;
}

}

What I've tried:
- Using a method that checks if the game boundary contains player boundary rectangle. This gave me the same result as what the check statement in my setX did.


texts: Is a frame-rate jump in my C++ iPhone game a show stopper and how do I find its cause?

texts:
Every 5-10 minutes there's a noticeable frame-rate hiccup in my game. Other than that my game runs very smoothly - again it's just one quick little jump every 5-10 minutes. Is this something I need to iron out or is it not a big deal?

How can I find what's causing this glitch? Is there a specific instrument I should use?

Here's some additional info:

It happens less on an iPhone 4 compared to a 3GS.
All my game objects use dynamic memory allocation with the default new and delete operators. I'm not using shared pointers. There are no memory leaks.
The game is of the shmup genre.


texts:
Why doesn't this work and how do I fix it/create a different, working loop for this SequenceAction?

public void setLoopingFade(float time)
{
    fadeLoop = Actions.sequence(Actions.fadeOut(time), Actions.fadeIn(time), Actions.run(new Runnable()
        {
            @Override
            public void run()
            {
                fadeLoop.restart();
            }
        }));

    this.addAction(fadeLoop);
}

fadeLoop is a SequenceAction.
I'm adding the SequenceAction to an Actor.

Clarification
Ok, so what I want to do is fade my actor in and out repeatedly. I figured the best way to do this was to create a SequenceAction that I would loop. The looping is what the Runnable is for. However, this method does not work. The fading out and back in happens once and then nothing. Even though the action is still owned by the Actor. I have also tried calling fadeLoop.reset(), however, that does not work either and actually makes the issue worse, because, when calling restart() I can still restart the SequenceAction manually from a different class, but when calling reset() the action loses all functionality.
I have tried adding a boolean functionality that would alert the external class to restart the action, but because the action ends after changing the boolean, it is removed from the actor and despite re-adding the action, it still does not work.


texts: Does using [STAThread] with XNA have any negative implications?

texts:
I'm working on a game in XNA, which has an inbuilt level editor. To facilitate this I want use the FileOpenDialog from Winforms. I followed the instructions as per this answer. This involves setting the [STAThread] attribute on my Program class.

Does using STAThread have any negative implications? Meaning will it cause worse performance or limit me in some way?


texts: Trying to bounce a box with a plane using bullet physics

texts:
I'm trying to simulate a box that bounces with a plane and I'm beginner with bullet physics. I created a plane (box) and and a box that is falling. The problem is the ball is stalled while colliding with the plane and doesn't rotate (no bouncing effect), even if the box is rotated so that it can sharply bounce with the plane. Here is my configuration.

// in update
if (m_pBoxMotionState)
    {
        btTransform transform;
        // get the world transform from our motion state
        m_pBoxMotionState->getWorldTransform(transform);

        btQuaternion quat;
        quat.setEuler(0, 290, 0); //or quat.setEulerZYX depending on the ordering you want
        transform.setRotation(quat);

        XMMATRIX world = btTransform_to_XMMATRIX(transform);
        m_Cube->Draw(world, m_Graphics.getViewMatrix(), m_Graphics.getProjectionMatrix());
    }

// Init
    m_Grid.CreateGrid(360.0f, 360.0f, 50, 50); // width*depth, 360*360
    m_Grid.SetPosition(1, -90, 1);
    m_Cube = GeometricPrimitive::CreateCube(m_Graphics.getContext(), 5.0f, false);

      m_pCollisionConfiguration = new btDefaultCollisionConfiguration();
            // create the dispatcher
            m_pDispatcher = new btCollisionDispatcher(m_pCollisionConfiguration);
            // create the broadphase
            m_pBroadphase = new btDbvtBroadphase();
            // create the constraint solver
            m_pSolver = new btSequentialImpulseConstraintSolver();
            // create the world
            m_pWorld = new btDiscreteDynamicsWorld(m_pDispatcher, m_pBroadphase, m_pSolver, m_pCollisionConfiguration);
            m_pWorld->setGravity(btVector3(0, -10, 0));

            btBoxShape* pBoxShape = new btBoxShape(btVector3(1.0f, 1.0f, 1.0f));
            // give our box an initial position of (0,0,0)
            btTransform transform;
            transform.setIdentity();
            transform.setOrigin(btVector3(0.0f, 50, 0.0f));
            pBoxShape->calculateLocalInertia(4, btVector3(0, 0, 0));
            // create a motion state
            m_pBoxMotionState = new btDefaultMotionState(transform);
            // create the rigid body construction info object, giving it a
            // mass of 1, the motion state, and the shape
            btRigidBody::btRigidBodyConstructionInfo rbInfo(4.0f, m_pBoxMotionState, pBoxShape);
            btRigidBody* pRigidBody = new btRigidBody(rbInfo);
            pGroundShape->calculateLocalInertia(0, btVector3(0, 0, 0));
            btBoxShape* pGroundShape = new btBoxShape(btVector3(360, 1,360));
            btTransform groundShapeTransform;
            groundShapeTransform.setIdentity();
            groundShapeTransform.setOrigin(btVector3(1.0f, -90.0f, 1.0f));

            // create a motion state
            m_pGroundMotionState = new btDefaultMotionState(groundShapeTransform);
            btRigidBody::btRigidBodyConstructionInfo rbGroundInfo(0, m_pGroundMotionState, pGroundShape);
            rbGroundInfo.m_friction = 1.0f;
            rbGroundInfo.m_restitution = 1.0f;
            btRigidBody* pRigidBodyGround = new btRigidBody(rbGroundInfo);

            // inform our world that we just created a new rigid body for
            // it to manage
            m_pWorld->addRigidBody(pRigidBodyGround);
            m_pWorld->addRigidBody(pRigidBody);


texts: XNA/MonoGame Collisions between two boxes don't work as expected

texts:
I have the following problem: I have two GameObjects (one is static, the other is the player). Both of them have one BoundingBox that surrounds them, and a List that contains more BoundingBoxes for a more detailed collision detection.
I use the follwing code when the player moves:

/// <summary>
    /// Checks if this Game Object blocks the specific boundingbox.
    /// </summary>
    /// <param name="box">Box.</param>
    public virtual bool Blocks(BoundingBox box)
    {
        if (BoundingBoxes.Count.Equals(0))
        {
            return !(this.SurroundBox.Contains(box) == ContainmentType.Disjoint);
        }

        bool blocked = false;
        BoundingBoxes.ForEach(b =>
        {
            if (b.Contains(box) != ContainmentType.Disjoint)
                blocked = true;
        });

        return blocked;
    }

    /// <summary>
    /// Checks if this Game Object blocks any of boxes in the specific list of boundingboxes.
    /// </summary>
    /// <param name="boxes">Boxes.</param>
    public virtual bool Blocks(List<BoundingBox> boxes)
    {
        bool blocked = false;
        boxes.ForEach(b =>
        {
            if (this.Blocks(b))
                blocked = true;
        });

        return blocked;
}

If I just use the Surroundboxes, everything works fine. If I start using the Lists, blocked never gets true.
I'm pretty shure my BoundingBoxes aren't the problem (visually they clearly overlap!).
Here's a screenshot, where b is the red boundingbox from the tree and the lightblue is the one from the player. Blue boundingboxes are the surroundingboxes. The right image is just there to demonstrate that the player's boundingbox is also 3D. (In this case each GameObjects List of BoundingBoxes only contains one BoundingBox that is slightly smaller than their SurroundingBox)

Shouldn't  if (b.Contains(box) != ContainmentType.Disjoint) now return true? If not, wheres my mistake?
Any comment/help is appreciated!


texts: Component-based programming with child objects

texts:
I am presently working on a game in Unity3d and have come to a cross road regarding scripting for repetitive child objects.  Should these child objects handle its own scripting for best practice?

For example, I have a parent game object, Game Board, that spawns repetitive child objects, Tiles, on the board.  Right now, I let these child objects handle its own position on the board and its own animation when the tiles move.  However, I can just as easily do this with the parent object's scripting class.

The reason I chose to let the child object do so is because I believe that child objects should be as independent to the parent object as much as possible.  But since these are repetitive child objects, I start to wonder if it is just as easy to do all the scripting in the parent object. This way I decrease the number of class instances in the child objects.

According the component-based programming, which method is recommended?


texts: How to calculate the estimated time of arrival and control signal between two quaternion?

texts:
I'm trying to wrap my head around a control algorithm for a space game. If the user sets a target rotation I want to get a ETA counter and show the engine output. The only input to the system is a max delta angular velocity around the space ship local axis.

I uses Unity engine so I ave access to the quaternion of the rotation and global angular velocity. I can find the delta rotation between the two points as it's dQ = Qstart^-1*Qtarget (from Qstart*dQ=Qtarget).

But how Do I find the engine parameter at that frame and what is the ETA?


texts: Unity build trying to include Editor Scripts

texts:
I'm having a peculiar problem. I'm creating a 2D Unity game using Fungus for cutscenes and the Unity Test Tools for unit testing. The game runs fine in the editor, but when I try and build an executable, I get compilation errors such as "the type or namespace Editor could not be found". All of these errors are coming from scripts in the "Editor" directory of Fungus and "Editor" directories of Fungus dependencies.

Here is what I think the problem is: I've used assembly definitions so that my tests can reference my scripts and so that my scripts can reference Fungus. I think that these assembly definitions are causing Fungus Editor scripts to be compiled into the build.

In summary, here is the directory hierarchy

Assets
  |---> Fungus
  |       |----> Fungus.asmdef
  |---> Scripts
  |       |----> Main.asmdef
  |---> Tests
  |       |----> Tests.asmdef

And the assembly definition dependency graph looks like this:

Tests--->Main---->Fungus

Is anyone an expert on Unity compilation or run into a similar problem that could help me out?


texts: Particle system lifetimes in OpenGL ES 2

texts:
I don't know how to work with my particle's lifetimes. My design is simple: each particle has a position, a speed and a lifetime. At each frame, each particle should update its position like this:

position.y = position.y + INCREMENT * speed.y

However, I'm having difficulties in choosing my INCREMENT. If I set it to some sort of FRAME_COUNT, it looks fine until FRAME_COUNT has to be set back to 0. The effect will be that all particles start over at the same time, which I don't want to happen. I want my particles sort of live "independent" of each other.

That's the reason I need a lifetime, but I don't know how to make use of it. I added a lifetime for each particle in the particle buffer, but I also need an individual increment that's updated on each frame, so that when PARTICLE_INCREMENT = PARTICLE_LIFETIME, each increment goes back to 0.

How can I achieve something like that?


texts: Computing volumetric light effects analytically

texts:
In my previous question I have asked about an effect on how to visualize light spheres. The question resulted in a very nice formulated answer which described pretty well how to achieve this by adding some fog to the scene and using some factor to weight different light samples on the rays from the camera to the scene.

However, since performance was too bad when testing it on the Xbox when taking shadows in account (texCUBElod lookups seem to be expensive) in split-screen multiplayer, I wanted to solve the resulting integral (which is currently approximated by a Riemann's sum) analytically without taking shadows into account.

I could reduce the pixel shader code to some formula, but was unable to solve it. So, I've put up another question on the mathematics stackexchange. It was answered fast, but the responder could not come up with any way I could use to solve this in an efficient way.

The question remains, how the performance could be increased without losing awesomeness of the lighting effect. (It does not have to be physically correct, so, if there are methods to increase performance but take away realism, I would like to hear about them.)

Current pixel shader code


texts: How can I replicate the look and limitations of the Super NES?

texts:
I am looking to produce graphics with the same limitations / look that in the Super Nes era. I am specifically looking for graphics similar to Chrono Trigger / FF6.

It would be a lot easier to do if I had an idea of the resolution / dpi I am supposed to use. I found that the technical specs for the SNES are:

  Progressive: 256 × 224, 512 × 224, 256 × 239, 512 × 239 Interlaced:
  512 × 448, 512 × 478

But even by using these resolutions, it is pointless if I set it at 72dpi, as I will still have possibly very detailed graphics (that is the main thing, I don't want detailed graphics, I want to go pixelated).

I figured it might be related to the sprite size limit, i.e.:

  Sprites can be 8 × 8, 16 × 16, 32 × 32, or 64 × 64 pixels, each using
  one of eight 16-color palettes and tiles from one of two blocks of 256
  in VRAM. Up to 32 sprites and 34 8 × 8 sprite tiles may appear on any
  one line.

This would work for sprites (characters, objects), but what about maps? Are they built entirely from 8x8 tiles? And then, at what resolution is the end result displayed?

It might seem like I am giving the question and answers at the same time, but all of these are suppositions I am making, so could someone confirm or correct them?


texts:
I'm trying to rotate a GameObject that consists of several cubes around its center of gravity on an axis.

When using transform.Rotate(), it rotates around its pivot point (as shown in picture 1) and not its center of gravity as I want (picture 2). How can I achieve this rotation?

Picture 1:

Picture 2:


texts: How can I change width of sprite Dynamically?

texts: I want to change width of sprite dynamically but i can't perform it.!! Here i want to change only my white sprite i want to use these type of facility in my game in using AndEngine I want to display life of player


texts:
Posting this question here rather than SO because of it's relevance with game development.

My dilemma is this: It is currently my summer vacation after my first semester of CompSci and I have learned enough C++ to actually get started in a little more advanced stuff.

I don't want to start games programming yet until I teach myself linear algebra, trigonometry, etc. However, I do want to know the fundamentals, the theory and the methods used in game programming!

I thought I had some decent books in the college library, but they were horribly outdated with books on game programming or game engines or game/graphic (topic here) from the early 90s to 2002.

Knowing the volatile state of computer technology, I figured grabbing knowledge on cutting-edge technology from a decade-old book isn't a good idea. Amazon itself leaves me clueless as to what book I want.

What I don't want:  A platform-dependent book. I'm not out to learn OpenGL, Direct3D or any specific API. I just want to know things like tessellation, how the GPU handles stuff, what goes on under the hood and what kind of raytracing and radiosity methods there are. The basics, the core concepts- those kinds of things.

I hope that's clear! Books, resources are all welcome. Though I much prefer a book over a website!


texts: How do I create a closed beta on Google Play?

texts:
As per suggestion I'm splitting How do I create a closed beta on the App Store? up.

Can I upload the game I'm developing to Google Play as a closed beta, so I could generate a couple of keys/tokens for my testers? I'm hoping to only publish the game for the public after I'm happy with the game as it's offered on Google Play, as a complete user experience which includes the installation process.

If this is not the usual workflow, how should I do it?


texts:
I have tried everything I can think of and all the solutions I could find on forums, but I haven't been able to fix this problem. I have a point light that is shining on several spheres which are casting shadows. The shadows work fine, but they are quite obviously pixelated. How do I get them to be smoother?

These are the settings that I took this screenshot with. I've tried tweaking most of the them, but it's possible I wasn't using the right combination to get the smoother shadows.


texts: How can I maintain a rectangular formation when units are added or removed?

texts:
I've got bots in a rectangular formation with rows and columns. A problem arises when a bot is added or removed from the formation. When this happens, the bots have to rearrange themselves so that the rectangular formation is still roughly the same aspect ratio, and is as rectangular as possible. How to do this?

Some ideas:

When a bot is added or removed, use the new total number of bots and a
desired constant aspect ratio to calculate the new width and height
of the formation that most closely fits that aspect ratio. Then
somehow reshuffle the bots to fit the new dimensions.
When a bot is removed, move the bot that was behind it into it's
place, and continue until you reach the end of the formation. Then
even out the back rank as much as possible by somehow shuffling the bots in
the back rank.
Another idea that's completely different is to mimic the way molecule structures stay together. Make every bot want to be surrounded by four other bots by attracting the four closest bots, and repelling the rest. Repel all bots (including the four) that are too close to ensure separation using inverse square law. You'd also need an additional force to shape of the entire structure. But, this sounds very computationally expensive.

UPDATE: So looking into sarahm's answer, I came up with a good general function that gives good dimensions.

First I solved the below simultaneous equation for width and height, and then rounded the answers.

width/height=aspect ratio of your choice
width*height=number of bots

This gives you the closest integer rectangle to that aspect ratio for your number of bots. The closest rectangle will half the time be a too large, and half the time be a too small (of course sometimes it will be just right but who cares about those). In the cases where the rectangle is a little too large, nothing needs to be done. The back rank will just end up being almost full, which is ideal. In the cases where the rectangle is a little too small, you got problems because that teeny tiny overflow will have to go to its own rank created a rank with only a few bots on it, which doesn't look pretty.  There are also cases where the difference is large (larger than half the width), in which case add or subtract one rank to make the difference small. Then, when the rectangle is too small, add one column to make it just a little bit larger. After doing that it looks like the back rank will always have at least half as many bots as the other ranks.

UPDATE

Once you got the dimensions, compare them to the current dimensions. If the frontage of the new dimension is bigger, for every rank, pop bots from the rank below, and push them onto the current rank until that the number of bots on that rank is equal to the frontage. Continue that algorithm until you get to the back rank. Using this algorithm, bots will move to fit into the new dimension efficiently. After that, I simply push the new old onto the back rank. The algorithm is slightly different for the cases where the new frontage is smaller, but you can figure it out!

There's two more problems next. Deletion, and a more flexible addition method where new bots are not necessarily assigned to the back rank but whichever position is closest to them at the moment they are added.


texts: Best option to narrow a known set of triangles?

texts:
I am building collision detection and response in a custom engine. This routine happens between the moving player, and static entities on the map.

In the first phase, the broad phase I am moving the player and looking for any new AABB to AABB collisions between the player and static entities.

In the second phase, the narrow phase. I then do a swept-spehere to triangle detection. I move the players collision sphere through the triangles in the colliding AABB.This phase can be expensive because the colliding AABB may have complicated geometry with many triangles.

I need to narrow down the set of triangles being detected. Some solutions I have in mind are:

Get the "overlap box" the space where both AABB's overlap in the broad phase.

Then do a pass on all the triangles in the colliding AABB and return just the ones in the overlap box.
My understanding here is I'll have to use a SAT algorithm to detect if the AABB and triangles collide or not and I'll still have to iterate over all the triangles in the colliding AABB. I'm not sure if this is any more performant.
Sort the triangles by distance to the AABB collision

If I sort the triangles by their distance to the AABB collision I will be able to exit from the narrow phase before the entire set of triangles has been processed.
I'm not sure what the performance implications of resorting the triangles each frame would be. I'm thinking not great...
Use a spatial partitioning data structure OctTree or quadTree to narrow down the triangles.

It may be extensive work to build one of these structures together for my engine and populate it with all the entities triangles. I'm not sure if they will give me any improved granularity. Will they be more precise than the AABB overlap?

I wanted to ask for help first before I start building one these solutions and reviewing the performance. Any other ideas are greatly appreciated.


texts: How can I draw the "cone of view" of a camera in a flat 2D minimap?

texts:
I have a 3D world with some model in it (the XZ-plane grid, some gray boxes and a red box). In the upper-left corner I'm trying to draw a minimap that should represents the whole world in 2D (flat). As you can see I already achieved to draw the grid and the boxes just using their scaled position. With the same logic I drew the camera too so here's my question: how can I draw the "cone" of view for this camera? In the image below I just drew a green shape that should explain what I mean better than words (obviously the green one in the image doesn't represent the actual view for this camera, it's just an example).

I'm using LibGDX with a PerspectiveCamera so I got access to all the camera information like the fow, the frustum and so on. Any idea how to implement this?


texts: How to create a smooth rotation with a constant angle?

texts:
I am trying to make a game where the player can only rotate to 4 angles. Something like this

I cannot use Quaternion.Rotatetowards because the player's position is not constant, but I don't have the problem with movement. The problem I am having is that when I use transform.Rotate of 90 degrees it creates a sudden rotation. I would like to have that rotation smooth. I have tried using Slerp but I don't think I quite get the syntax I need to use.

Both Vector3.Slerp, and Quaternion.Slerp interpolate between two different positions, when my player turns I would like him to keep his current position, and only turn his "face" towards the desired position. I would appreciate the help. Thanks.


texts: Unity Android Orientation Bug in Auto Rotate

texts:
I am currently looking for a workaround, or fix, for a Unity bug.

I want to be able to auto-rotate my game, while respecting the Android system settings.

Currently, if you set your Unity Orientation Mode to "Auto Rotation", your application will automatically change its orientation based on the physical's device orientation.  In iOS, if you disable the Screen Rotation in device settings, the auto rotation stops as intended.  In Android, even if you lock your screen orientation, the application will continue to auto rotate.  This is a major bug.

Does anyone know of a workaround, so that my android application will be able to auto-rotate, while still respecting the device system settings?

You can easily reproduce this bug by creating a blank project, setting the orientation mode to "auto rotation" and running it on an android device.


texts: How can I check if player is an operator in Forge?

texts:
In Minecraft Forge, I would like to know if there is any way to find out if a player currently has vanilla "OP" / "Operator" status. I can't find a method that does this on the EntityPlayer Class.

I'd like something like:

EntityPlayer player = (EntityPlayer)sender;
if (player.getOpStatus) {
    [do some stuff]
}


texts: Is it possible to write a game with a HTML5+REST service architecture?

texts:
As a side project I'd like to program a board game similar to Twilight Struggle. For this pet project I'd like to satisfy several non functional requirements:

The core logic must be written in Haskell
If I succeed, I'd like to sell it in platforms like Steam, Google Play and Apple Store.

The Haskell requirement limits me a bit about the range of frameworks to use and the Haskell+SDL2 route doesn't seem very mature when talking about porting to mobile platforms (maybe I'm wrong but I haven't found any easy tutorials on the topic).

So I've thought about an HTML5 Canvas talking to the Haskell core either through REST calls or websockets. The HTML5 canvas will be contained in a Cordova application or similar when in the mobile. What do you think about this approach in terms of:

feasibility
robustness
portability
software engineering
whatever other concern you might have


texts: Why do I get incorrect bounding boxes when I add a cloth component in Unity 2017.3?

texts:
I have a character with a cloth. The cloth is separated into its own mesh, but both the cloth and the character are in the same FBX import. The cloth is correctly skinned to the char so it moves with the animations.

However when I add a cloth component to the cloth, its skinned mesh renderer bounding box shows up very small in the scene view: (see it embedded in the character's waist here)

If I remove the root bone reference from the cloth, the skinned mesh renderer bounding box gets offset from the rendered position of the model:

As you can see something is very wrong here :D The problem is I don't know what, or how to fix it. I suspect that I might have to import the whole fbx in a different way but I'm just a programmer so I have no idea where to start.


texts: Animation Change Delay When Landing On Ground

texts:
I am working on a 2d platformer-like game in Unity. My problem is that when my player character jumps and lands back on the ground, there is a slight delay at times when transitioning to the player idle animation. This is not due to exit time. Instead, upon researching this topic, I found that my real problem lies in the Unity physics loop(FixedUpdate).

FixedUpdate, as the name implies, is called a fixed amount of times, not every frame. My animator relies on a Jumping boolean to tell it whether or not to be in the jumping animation. In my code, the Jumping boolean is set to false when the player lands on the ground. This is handled by OnCollisionEnter2D, which runs on FixedUpdate.

This is were I think my problem lies:

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Ground"))
    {
        _isOnGround = true;
        _animator.SetBool("Jumping", false);
    }
}

I need to know whether or not the player is colliding with the ground, So I setup a tag. I need to find a way to constantly check whether or not I am colliding with the ground, So that I do not see an animation transition delay.

Any Ideas of how I could accomplish this?


texts: I want a variable/field to only be declared when a specific condition is true. I used Compiler Directives. Is the code I wrote valid?

texts:
I want a field I declared (float attackRange) to be only declared when inheriting class set "bool haveLongRangeAttack" is set to true. I wanted to use Compiler Directives for this purpose. Here is the code I wrote;

using UnityEngine;

public abstract class Enemy<T> : MonoBehaviour where T : Enemy<T>
{
    [SerializeField] protected bool haveCloseRangeAttack = false,
                                    haveLongRangeAttack = false;
#if haveLongRangeAttack == true
    [SerializeField] protected float attackRange = 1f;
#endif

    [SerializeField] protected GameObject mainCharacter = null;
    protected GameObject enemy = null;

    protected virtual void ChasePlayer()
    {
        if(haveCloseRangeAttack)
        {
            //...
        }
        else if(haveLongRangeAttack)
        {
            //...
        }
    }
}

I don't know if it is right way to/of do what I want or using Compiler Directives so please review my code and tell me if there is a problem, or if there is a better way.

It was before 6 months when I started writing code, and C was my first language. I am trying to learn new things/concepts and writing at my own style. So there will be another way (maybe more efficient); if there is one, please teach me. I'm working on my own Game Project right now, I'm open to learn new things that will benefit me...

TY for taking time ^.^!

PS:There is no compiler-directives tag in Tags section. Maybe it will be useful to add this tag.


texts: Libgdx: move img from one point to another?

texts:
I'm trying to make an image move towards another point.
I only have the current X/Y and the destination X/Y + Speed.

That's it.

public void Draw(SpriteBatch batch, int goalX, int goalY){
    destX = goalX - posX;
    destY = goalY - posY;

    dist = Math.sqrt(destX * destX + destY * destY);
    destX = destX / dist;
    destY = destY / dist;

    posX += destX * this.speed;
    posY += destY * this.speed;

    batch.draw(img, posX, posY);
}

This is my code, it kinda moves towards the object, but it moves past the object to a certain distance and then starts spazzing out for some reason.

The other point is also moving, just so you know.

Anybody can help me with this?


texts: Elegantly transition from 4-grid to 6-grid and back

texts:
I find in general map creation that I prefer hex grids for natural environments, but square grids for interior and urban/constructed environments.
Is there a smooth or elegant way to transition between these that doesn't require a scene break? Most importantly, is there an intuitive way?
As long as they don't differ too vastly, the ratio of sizes between the two cell types is largely irrelevant to me. I'd also happily use several rows of transitional tiles if their borders can be procedurally determined. I also have no inherent preference for up-point or side-point hexes...
I'd show some things I've already tried, but they are genuinely all varieties of the same eldritch mess...


texts:
I am very new to Unity, and coding in general.
Anyways, I'm trying to load another scene on click, but when I try to do so in the editor, Unity freezes. Also, it, by chance it seems, worked twice when I newly added the script. Not always when I newly add the script, but twice.

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

public class GameMenu : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

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

        if (Input.GetMouseButtonDown(0))
        {
            SceneManager.LoadSceneAsync(sceneName: "Wisp1");
        }

    }
}

Can somebody help?


texts: 2d sprite topples over due to circle collider

texts:
I am completely new to unity nd was trying to create a simple 2d platformer. I a trying to use a box collider and a circle collider for my Player. I am using circle collider because I have heard it helps more accurate collision detection for a player. The problem is that my player topples over when it falls to ground.
Please tell me if there is any fix for my problem.


texts: Floodfilling a texture in HLSL Compute shader

texts:
I have a very large texture which I want to fill with values representing "distance in units from a river tile".
The texture is already seeded with these origin river points (meaning distance/value = 0 in them).
From these points I want to floodfill outwards, incrementing the value with each step from these origin points.
Doing this on the CPU is no problem using a stack or similiar structure but ideally I want to do this in the middle of a Compute shader execution which runs over the entire texture.
I have read this which sound similiar to what I want to do but it mentions there might be a smarter way to do this with Compute shaders - which is what I am using.
Any ideas on how to solve this on compute shaders?


texts: what is the difference between CCSprite and a PhysicsSprite?

texts: I am new to Cocos2D and I've realized that most of the codes written before the Cocos2d update used CCSprites. Recently I realized a lot of more recent codes after the update are using PhysicsSprite. What is the difference? What advantages does one have over the other, if any?


texts: Uniform Block solve padding/alignment for vec3 in CPU struct

texts:
I have a struct on the CPU which I'm sending to a uniform block in my shader. After a bit frustration I finally got it to work. The problem I had was that vec3s are actually treated as 16-bytes, or in other words they need to have padding. So to solve this I added a dummy-float after each vec3 (see below).

I know I could just use vec4, but since I want to treat alpha as a separate component I don't want to type that 4th component for each vector every time. Furthermore, I would have to use swizzling in the shader as well to separate alpha.

Now to the question, is there any nicer/better way to solve the padding problem than having to add an extra float?

// CPU
struct Material
{
public:
    vec3 Emissive; float p1;
    vec3 Ambient; float p2;
    vec3 Diffuse; float p3;
    vec3 Specular;
    float Shininess;
    float Alpha;
};

// Fragment shader
layout(std140) uniform uniMaterial
{
    vec3 Emissive;
    vec3 Ambient;
    vec3 Diffuse;
    vec3 Specular;
    float Shininess;
    float Alpha;
};

Regards, Tobias

My solution:

struct GpuVec3
{
public:
    GpuVec3() {}

    GpuVec3& GpuVec3::operator=(const vec3& other)
    {
        v.x = other.x;
        v.y = other.y;
        v.z = other.z;
        v.w = 1.0f;

        return *this;
    }

    GpuVec3& GpuVec3::operator=(const vec4& other)
    {
        v.x = other.x;
        v.y = other.y;
        v.z = other.z;
        v.w = other.w;

        return *this;
    }

private:
    vec4 v;
};

typedef GpuVec3 GpuVec4;


texts: Getting array of points shaping curve from 2 vector3 points

texts:
What I want is to get path for DoTween method DoPath(), which as a parameter expects array of vectors shaping the direction of the path. I googled some stuff and found out nothing. Just think bezier curve is good idea but i dont even know how it works. Here is an ilustration of my problem

The movement must be curved, don't need linear one.
Thanks in advance


texts: Scene Graph: Does anybody have a real world example?

texts:
I'm trying to wrap my head around how scene graphs work, and how to apply that to my game, in the context of all my game objects, including assets, cameras, units, shaders, etc.

All I can find are massively simplified examples that include planets and rotations. What I'd like is a real world example of a well written scene graph, preferably in C++ and if possible with some form of graphical representation of at least a part of the graph.

Additional information:
I am writing a real time strategy game using C++ and DirectX 11. Any other pointers for advice would be massively helpful. Wrapping my head around a scene graph and how that would relate to design patterns like data locality etc, and how to encapsulate it all in a standardised system is proving very difficult for me. I am extremely, extremely confused.