texts: Strategy/City Builder browser game - technical details

texts:
I actually have multiple questions into one. Hopefully someone can hit all of them.

I wanted to give a try at a massively multiplayer web based game. Basically, the game would have similarities to Evony, or Eve Online (a much scaled down version). The idea is it would be a mostly real time city builder (like Evony) that allows complex actions between players (like Eve Online but without the graphics and much scaled down). It would sort of be like a database game. I want it to be able to support around 500 people simultaneously online off one server.

However, I have multiple issues that I want to pin down before I actually start writing the code.

Continuous database updating

The database has to be continuously updated on a small time interval to reflect the passage of time in the game verse. Furthermore, the effects of all actions will have to be calculated as well. Right now I'm thinking about using mysql with events using the innoDB engine to do this. Is there a better/faster approach to this?

Continuous graphical updating

Certain details (such as "time till completion" etc when building something) need to be continuously updated on the user interface. I'm thinking about having each page in the user interface continuously make ajax calls for the information. Again, is there a better/faster way?

Thanks


texts: Polishing your game: how much is enough?

texts:
I'm assuming you're an indie developer, doing your own (or getting free/partner-based) artwork. I'm also assuming you have no external pressure driving you forward into new games; you can work on your games as much (or as little) as you want, then move on.

Having said all that, how do you decide how much polish to put in a game?

I'm also assuming you won't fall into the notorious trap of dumping your game half (or less) finished; that you have the discpline to work on it until it's "good (enough)."

I currently have a rough cycle where I develop the core functionality, then content/levels/whatever, then add layers of polish (art, bug-fixes, and usability tweaks) until I get bored. There's always scope to improve, but I don't have a measuring stick telling me that "at this point, your return on polishing is not worth the time/effort you're putting into it."

I'm going to assume this is always worth it if you learn something new (like how to render a glow effect, say).

Also, before you ask, I don't have much of a player base (and not one I can observe, either) to ask them when it's good enough.


texts: For the handling of buildings on a tile-based strategy game, what aproach should I use?

texts:
On a tile-based game of the strategy genre, which allows the player to place buildings over the terrain tiles, there are multiple approaches that can be taken for handling such situation.

The ones that I immediately think about regarding that are:

Create two layers. One for the base tiles (terrain), and
a second for buildings. And, for handling (operations before rendering), iterate them.
Create a single layer, with the tile class having both the
reference to the base (terrain) and the building reference (null if no
building at that tile). And for handling, iterate just one
tile-map, but each iteration will then have to have an
if(building!=null){...} added to it.

EDIT:

As further specification, the situation is that the game will be more focused on management and sandbox (tough combat will still be present), and every building will have many variables that are independent from the other buildings (even of the same type of building). NOTE: You can use the game "Caesar 3" as an example of what I'm going for.

For example, for "housing" buildings, they will have leveling, with a growth (level-up) based on the meeting of the required resources needed for the next level (from "materials", like wheat and wine, to access to specific "infrastructure", like public bathhouses or religious buildings), as well as the handling of such resources (current amount of "material X" stored, max amount of "material X" to be stored, consumption-ratio of "material X").

Another thing is, I don't need to literally render buildings on top of terrain (render both), and actually, I think it's probably a bad thing...So instead, I'm trying to do the handling in a way that will also not do unnecessary rendering. On the rendering loop, the building is rendered when its present, or the terrain otherwise. (This might be a worse approach instead of a better one, tough. Please tell me if so!)

EDIT 2: Please regard the part above as a note. This question is not as related to rendering as it is to handling! I'm beginning to think about removing it.

For my exemple aproaches, both would have a separated logical layer for buildings, as a single building can occupy more than a single tile (a building can be 2x2, 3x3 or 4x8 terrain-tiles, for example).

So, regarding terrain-to-building relation, approach-1 would would go:

  2 iterating loops...

  BUILDINGS-loop: "You are currently iterating me; I am above the
  following terrain-tiles: 1,2,3 and 4; My current resources are: [...]"

  TERRAIN-loop: "(My coords are under a building, render that building instead!)
  || (I'm not under any buildings! Render me!)"

While approach-2 would go:

  1 iterating loop...

  TERRAIN-loop: "If you are searching for the building that was built
  over me, (it's null, render me!) || (its not null, proceed to
  the building's door, over there!)"

  BUILDING: "Terrain x-y sent you to my door? (Sorry, i have already
  been iterated, skip me) || (Hmm, and it seems I have not been iterated
  yet! Alright then! My current resources are: [...]; Render me!)"

Note: The "render" parts are to be considered as just flags to be used by the rendering loop that comes after all handling is done, thus, not as the actual time the rendering happens.

END OF EDIT.

The questions are...

Which is best overall? (why?)
Is either best for a specific matter? (EX: "This uses more
processing, but is less memory-heavy, because...")
And, are there other (better?) approaches?


texts: Unity - Access animation clips/motion of an animator

texts: So I have an animator on my GameObject. I need to change the animation clip/motion of different states in my animator to the one I assign in my EditorGUILayout.ObjectField. Problem is, I have no idea how to access those clips. This is purely Editor Scripting.


texts:
I would like to make an adventure type game functioning similarly to machinarium or broken sword. The only way I can think of doing this is to draw an image as a background on a canvas and use some animated sprites that moves around and responds to touches on the screen.

But having a runnable that keeps re-drawing the canvas seems like a waste of memory to me, especially when it comes to larger images like the background.

I'm pretty new to game development and canvas animations and I was wondering if anyone could point me in the right direction? What would be good training for an adventure type game?


texts: How to allow a 2D game to work with all screen resolutions without only using Unity's Canvas Scaler

texts:
I know there's plenty of questions out there already, however it seems as though there's always an update or change to either the Unity platform, the phone screen sizes, etc.

I'm struggling with trying to get my game to look the same on an iPhone 7+, iPhone 8 (normal) and iPhone X.  I set the canvas to scale with screen size and resolution to 1920 x 1080, match width or height, and ref pixels to 100 as many other posts have recommended.  However the stretching and pulling really makes the game look horrible.

It is a landscape only card game with a few buttons and up to 4 players whose avatars are represented on each corner if all are playing. So I need the background to stretch but I would prefer the card of the avatars to be almost their exact size in terms of ratios as if they were customized for the device. Think of Hearthstone just with 4 players in each corner.

I know games such as Blizzard's Hearthstone has a huge dev team and they're probably developing different views for each resolution, but there has to be a better or more updated solution for small indy teams like mine.

Is there something we need to do with anchors or our canvases to make all of this look better on all popular phone resolutions?  Any help greatly appreciated.


texts: Vulkan PushDescriptorSetTemplates (Can only parts of the UpdateTemplate be updated?)

texts:
I'm exploring the VkDescriptorUpdateTemplate usage and really like the efficiency in coding this versus individual DescriptorSets, except I have one concern. When making an UpdateTemplate for each shader "program" with multiple UBOs, SSBOs, combined image samplers, etc. and attempting to update a single buffer/sampler, I have to update them all based on the template. In reading the specification and googling (not much information on descriptor templates), it isn't clear if there is a way to update only part of the DescriptorTemplate and allow the remainder of the bindings to remain.

Quick Code Example (Updating all three buffer/sampler bindings). This works but in changing the sampler, I have to rebind the other buffers as well.

FDescriptorInfo Sampler(LinearSampler, Tex->ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
FDescriptorInfo Desc[] = {VertexBuffer, CameraBuffer, Sampler};
vkCmdPushDescriptorSetWithTemplateKHR(Vulkan->CommandBuffer, Vulkan->MeshProgram.UpdateTemplate, Vulkan->MeshProgram.Layout, 0, Desc);

If I just want to update the combined image sampler; is there a way to only update the 3rd binding? The example below gives validation errors along with attempting to just pass a single DescriptorInfo as there is no way to tell PushDesctiptor which binding I want to update versus all of them in the template.

FDescriptorInfo Sampler(LinearSampler, Tex->ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
FDescriptorInfo Desc[] = {0, 0, Sampler};
// FDescriptorInfo Desc[] = {Sampler}; // Also tried this but there is no way to tell vkCmdPushDescriptorSetWithTemplate I'm only updating the 3rd binding.
vkCmdPushDescriptorSetWithTemplateKHR(Vulkan->CommandBuffer, Vulkan->MeshProgram.UpdateTemplate, Vulkan->MeshProgram.Layout, 0, Desc);

Is it possible to reduce re-binding/re-pushing other buffers when utilizing the DescriptorSetTemplates?

Thanks in advance for any advice.


texts: Meaning of knots when drawing a NURBS curve?

texts:
I'm using gluNurbsCurve to draw some curves with some control points. I've got the basic setup as described in the red book working correctly and I'm trying to expand on it.
This sample looks like this:

float knots[8] = {0,0,0,0,1,1,1,1};
float pnts[4][3] = { {...},{...},{...},{...} };
GLUnurbsObj *m = gluNewNurbsRenderer();
gluBeginCurve(n);
gluNurbsCurve(n, 8, knots, 3, pnts, 4, GL_MAP1_VERTEX_3)
gluEndCurve(n);

One thing I was wondering about is the meaning of the knots data. How does it affect the result? What other options can I experiment there?
For some reason I could not find any tutorial which properly explains this.


texts: How do you keep the gameplay and music in sync in a rhythm game?

texts:
What's the best way to program a rhythm based game in XNA? (Some sort of game like Dance Dance Revolution) Would you use the built in GameTime? What logic would you use to make sure the game constantly stays in sync to the music? Any tips would be much appreciated!

What I am basically asking is how you would keep the gameplay in sync with the music. For example in DDR how would I correctly sync the arrows to the beat of the music?


texts: I'm currently developing a 3D game with LibGDX, and I'm a bit stuck, and couldn't find any definitive answer. I have a plane, part of a bigger g3db file, to which I'd like to get a normal, to calculate which side of that plane the camera currently is. Is there a method built in to LibGDX to achieve this, or should I calculate the normals from the first three vertices of the plane's mesh?


texts: How do I add an object to the node tree at a specific position

texts:
I'm making a skiing game, and a part of that is programmatically adding snow to the scene in a specific place. It will all be the child of a single node.

I was looking through the Flappy Bird code but when it instances a scene, it only uses the function add_child(). There doesn't seem to be a way to set its position.

Here is the project on github.


texts: Player disappears when it collides with a tagged object

texts:
I am working on a simple game where the goal is to help a Player catch specific objects with a tag "Present".

After taking care of the models, animations I am now working on the collisions and counting UI.

For the collisions, on my Player Controller (I am using the ThridPersonUserController from the player Unity Standard Assets - which simplified the whole animation process), I added the following functions:

    void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.tag == "Present")
        {
            Destroy(gameObject);
            count = count - 1;
            SetCountText();
        }
    }

    void SetCountText()
    {
        countText.text = "Count: " + count.ToString();
        if (count == 0)
        {
            winText.text = "Thanks to you the Christmas will be memorable!";
        }
    }

However, like this, when the Player hits an object with the tag "Present", even though the counting is working properly, the player disappears.

I have tried to change the OnCollisionEnter to an OnTriggerEnter, like this:

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Present"))
        {
            Destroy(gameObject);
            count = count - 1;
            SetCountText();
        }
    }

However when the Player hits the objects with the tag "Present", they don't disappear.

My Player has a Capsule Collider and a Rigidbody.

The objects with the tag "Present" have a Box Collider and a Rigidbody.

Any guidance on how to make my Player stay in scene while removing the other objetcs and reducing the count is appreciated.


texts:
I need to modify the code below to get the penetration depth from the per pixel collision and return it as a Vector2 to later apply it to the character position.
static bool IntersectPixels(Rectangle rectangleA, Color[] dataA,
                            Rectangle rectangleB, Color[] dataB)
{
    // Find the bounds of the rectangle intersection
    int top = Math.Max(rectangleA.Top, rectangleB.Top);
    int bottom = Math.Min(rectangleA.Bottom, rectangleB.Bottom);
    int left = Math.Max(rectangleA.Left, rectangleB.Left);
    int right = Math.Min(rectangleA.Right, rectangleB.Right);

    // Check every point within the intersection bounds
    for (int y = top; y < bottom; y++)
    {
        for (int x = left; x < right; x++)
        {
            // Get the color of both pixels at this point
            Color colorA = dataA[(x - rectangleA.Left) +
                                 (y - rectangleA.Top) * rectangleA.Width];
            Color colorB = dataB[(x - rectangleB.Left) +
                                 (y - rectangleB.Top) * rectangleB.Width];

            // If both pixels are not completely transparent,
            if (colorA.A != 0 && colorB.A != 0)
            {
                // then an intersection has been found
                return true;
            }
        }
    }

    // No intersection found
    return false;
}

Edit: I need something similar to this:
https://github.com/MonoGame/MonoGame.Samples/blob/develop/Platformer2D/Game/RectangleExtensions.cs
The code from the link above is for getting the intersection depth between two rectangles.
Thanks in advance.


texts: how to slide pieces for a slide puzzle game for android(libgdx)

texts:
I want to make a small one-screen game in which the player has to slide pieces of an image until the image is completed. I used texture regions to create the pieces from an image

int numOfTiles_Horizontal = 5;
int numOfTiles_Vertical = 5;

float tile_width = img.getWidth() / numOfTiles_Horizontal;
float tile_height = img.getHeight() / numOfTiles_Vertical;

TextureRegion[][] tiles = new TextureRegion[numOfTiles_Horizontal][numOfTiles_Vertical];
for(int col = 0; col < numOfTiles_Horizontal; col++) {
    for(int row = 0; row < numOfTiles_Vertical; row++){
        tiles[col][row] = new TextureRegion(img, col * tile_width, row * tile_height, tile_width, tile_height);
    }
}

, but I'm unsure about how to allow the player to move the tiles into a blank space as well as making a "blank space" to allow tiles to move.

The game would look like this:

I followed some tutorials for libgdx but cannot find much on achieving this.

I am new to the engine and Android development so any help is appreciated.


texts: RK4, Derivatives, Understanding Game Physics

texts:
Gafferon Games has a great article on RK4 Integration for building physics simulations which can be found here: Integration Basics

Personally my mathematics and physics knowledge could use improvement. I feel comfortable within the realm of vector mathematics, trig, some stats (I've had to use linear line regression formulas for software, etc. ), and basically most things high school level to first year college.

Now to the question, I've read this article, downloaded the associated source and debugged line by line to try and get an understanding of what is happening and still feel like I'm clearly not getting what I'm looking at. I've searched the internet trying to find the "For Dummies" versions, frankly I learn a little differently and staring at formulas all day with the emphasis on memorization isn't going to cut it as I need to understand what is happening so I can be flexible applying it.

So here's what I think I understand so far, but I am hoping someone else can clarify or completely correct me. The RK4 uses a Euler step, then bases that to move forward in time to calculate several more essentially Euler steps(?) and determines using a weighted sum what the best position and velocity is for the next frame?

Furthermore that acceleration method (converted into AS3):

private function acceleration(state:State, time:Number):Number
{
    const k:int = 10;
    const b:int = 1;
    return - k*state.x - b*state.v;
}

takes a constant mass(10) and force(1)? and returns some weird calculation I have no idea why...-mass * position - force * velocity? what?

Then for my last bit of confusion, in the evaluate methods which look like (AS3):

private function evaluateD(initial:State, time:Number, dtime:Number, d:Derivative):Derivative
{
    var state:State = new State();
    state.x = initial.x + d.dx*dtime;
    state.v = initial.v + d.dv*dtime;
    var output:Derivative = new Derivative();
    output.dx = state.v;
    output.dv = acceleration(state, time+dtime);
    return output;
}

We store a new state with the time step, then set a derivative to return...I sort of understand this as it's used in the approximation process, but what is this!:

output.dx = state.v;
output.dv = acceleration(state, time+dtime);

// ok I get we are getting the new velocity since v = a * t, obviously I
// don't what acceleration() is returning though.

We set the derivative output change in position to the states new velocity? Huh?

Lastly this test simulation runs doing this:

var state:State = new State();
state.x = 100;
state.v = 0;

t = 0;
dt = 0.1;

while (Math.abs(state.x)>0.001 || Math.abs(state.v)>0.001)
{
    trace(state.x, state.v);
    integrate(state, t, dt);
    t += dt;
}

So we are setting a new state with a positional value of 100, and a velocity of 0? What is the point of this simulation if we have no velocity...

Anyway, needless to say I'm pretty confused and have drifted off planet Earth. Hoping someone out there can clarify this for me.


texts: Simple way to serialize save game data whilst allowing for future features

texts:
Is there a simple way to 'serialize' the game data of my game, but protected it from being unloadable if I add new fields?  I have all the data in a single class, GameData.java, and I want to avoid having to manually read/write each field from it.  If I serialise it using standard java function, but add new fields to the class, it will render it unserializable.

I'd like to be able to save the class and the reload it from a file, and it use default values for any new fields that are missing from the save file.  XML may be a solution, but is there an existing library to automate the process?

Thanks!


texts: Fitting a rectangle into screen with XNA

texts:
I am drawing a rectangle with primitives in XNA. The width is:

width = GraphicsDevice.Viewport.Width

and the height is

height = GraphicsDevice.Viewport.Height

I am trying to fit this rectangle in the screen (using different screens and devices) but I am not sure where to put the camera on the Z-axis. Sometimes the camera is too close and sometimes to far.

This is what I am using to get the camera distance:

//Height of piramid
float alpha = 0;
float beta = 0;
float gamma = 0;

alpha = (float)Math.Sqrt((width / 2 * width/2) + (height / 2 * height / 2));
beta = height / ((float)Math.Cos(MathHelper.ToRadians(67.5f)) * 2);
gamma = (float)Math.Sqrt(beta*beta - alpha*alpha);

position = new Vector3(0, 0, gamma);

Any idea where to put the camera on the Z-axis?


texts:
Hello I have a game that you can play(duh). When you start the game a loading screen pops up and on the loading screen I display an image of an eye I drew. In paint.net they eye looks perfect but in game it dose not.

Here is the image in paint.net:

Here is the image in game:

I don't understand why the image is all messed up as much. Please help me! Thx.


texts: How do I manage monster tables and item databases in my Android game?

texts:
To learn more about AI during combat, I made a demo in Unity where a player would fight a creature in an arena. I started here because I plan to implement the system I'm working on in another game. In that game, there are a lot of different creatures a player has to fight.

These creatures have a body part set, a move list, an attribute set and a drop table for that type of creature. Currently I'm managing this by a big static class with drop tables, move tables, monster tables and item tables and so on in them. When a creature gets instantiated it copies monster data from that static class and when it dies items in the referenced drop table are instantiated, copying some data from the item table. Whenever a monster performs a move, the necessary information is looked up in that static class.

I could solve monster data by copying the necessary data into the monsters and then dispose of the class, but that leaves no option for items, which are referenced by ID and need to be looked up frequently. Serializing and deserializing the data wouldn't make sense if I would have to load the entire item table or unit attributes every time every time I access them. Keeping the entire game data loaded all the time doesn't sound like the best way to go about managing my data.

My own system is becoming unmanageable. Because I'm targetting Android, I'm also, to a lesser degree, worried that having such a big static class loaded all the time will become a burden once more features are added to the game. I have read this post but didn't find it of much help.

Which ways are there to improve from the current situation?  How could I handle a frequently used item table/database more efficiently. And on the other side, how could I handle a move table and monster table better? How did NetHack do it, for example?


texts: What are some good MMO middleware server packages?

texts:
If you have any experience with any MMO middleware packages and have any positive or negative experiences with them, your feedback will be appreciated.

Specifically I'm looking for server packages.  Price, functionality, speed, and ease of use would all be useful metrics to know about.

For example, doing some preliminary research has led me to some packages like Exit Game's Photon,  RedDwarf Server, and SmartFoxServer.


texts:
I have a shader with acts like a magnifying glass that I downloaded and I have to attach to the camera scene.

My issue with this I want it in the same fixed position as the sprite but being attached to the camera when I changed the screen size for different devices it wonders to the upper right of the screen.

I am completely new to shaders so I and their scripts so I am not sure if this can be done.

private void OnRenderImage(RenderTexture src, RenderTexture dest)
{
    if (mtrl == null || mtrl.shader == null || !mtrl.shader.isSupported)
    {
        enabled = false;
        return;
    }

    if(Input.GetMouseButton(0) || !detectMouseButtonDown)
    {
        mtrl.SetFloat("_Radius", radius);
        mtrl.SetVector("_Mouse", new Vector4(740, 480, 0));
        mtrl.SetFloat("_Distortion", distortion);
        mtrl.SetFloat("_ScaleArea", scaleArea);
        if(isMagnifyingGlass)
        {
            mtrl.EnableKeyword("IS_MAGNIFYING_GLASS");
        }
        else
        {
            mtrl.DisableKeyword("IS_MAGNIFYING_GLASS");
        }
        if(warpType == WarpType.POW)
        {
            mtrl.EnableKeyword("WARP_TYPE_POW");
            mtrl.DisableKeyword("WARP_TYPE_EXP2");
        }
        else
        {
            mtrl.DisableKeyword("WARP_TYPE_POW");
            mtrl.EnableKeyword("WARP_TYPE_EXP2");
        }
        Graphics.Blit(src, dest, mtrl, 0);
    }
    else
    {
        Graphics.Blit(src, dest);
    }
}

Shader:

Shader "Hidden/MagnifyingGlassFisheyeWarpImageEffect"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Cull Off ZWrite Off ZTest Always

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma target 3.0
            #pragma multi_compile WARP_TYPE_POW WARP_TYPE_EXP2
            #pragma multi_compile _ IS_MAGNIFYING_GLASS

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float4 pos : SV_POSITION;
                float4 scrPos : TEXCOORD0;
                float2 uv : TEXCOORD1;
            };

            sampler2D _MainTex;
            float4 _MainTex_TexelSize;

            float2 _Mouse;
            float _Radius;
            float _Distortion;
            float _ScaleArea;

            v2f vert (appdata v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                o.scrPos = ComputeScreenPos(o.pos);
                o.uv = v.uv;
                return o;
            }

            fixed4 frag(v2f i) : SV_Target
            {
                float4 c = 0;
                float2 uv = i.scrPos.xy/i.scrPos.w;
                float2 mousePos = _Mouse.xy / _ScreenParams.xy;
                float wh = _ScreenParams.y / _ScreenParams.x;
                uv.y *= wh;
                mousePos.y *= wh;
                if(length(uv - mousePos) <= _Radius)
                {
                    uv -= mousePos;
#if defined(IS_MAGNIFYING_GLASS)
                    float newLength = _ScaleArea * _Distortion;//_ScaleArea * pow(length(uv) / _Radius,  _Distortion);
#else
#if defined(WARP_TYPE_POW)
                    float newLength = _ScaleArea * pow(length(uv) / _Radius,  _Distortion);
#endif
#if defined(WARP_TYPE_EXP2)
                    float newLength = _ScaleArea * exp2(length(uv) / _Radius * _Distortion);
#endif
#endif
                    uv *= newLength;
                    uv += mousePos;
                }
                uv.y /= wh;

                c = tex2D(_MainTex, uv);
                return c;
            }

            ENDCG
        }
    }
}

Here is what it looks like over the gold selector. It is in the correct position.

Now if I change the screen size for a different device the magnifying effect has shifted to the right


texts: How do I activate a game action when a UI button is held?

texts:
I want to make my button do stuff when the player holds it. In this case, I want to make a grab function: when the button is down the character can grab objects, but if the button is up they do not grab it.
I already have the function using the Standard Assets CrossPlatformInput.
Here is how I have configured my button so far:

Here is my script:
void Update()
{

    Physics2D.queriesStartInColliders = false;
    RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.right * transform.localScale.x, distance, boxMask);

    if (PushKey())
    {
        isGrab = !isGrab;

        if (hit.collider != null && hit.collider.gameObject.tag == "Box" && isGrab)
        {
            box = hit.collider.gameObject;
            box.GetComponent<FixedJoint2D>().connectedBody = this.GetComponent<Rigidbody2D>();
            box.GetComponent<FixedJoint2D>().enabled = true;
            box.GetComponent<Rigidbody2D>().gravityScale = 1;
            box.GetComponent<Rigidbody2D>().mass = 1;

        }
        else if (!isGrab)
        {
            box.GetComponent<FixedJoint2D>().enabled = false;
            box.GetComponent<Rigidbody2D>().gravityScale = 6;
            box.GetComponent<Rigidbody2D>().mass = 6;
        }
    }
}

public bool PushKey()
{
    return CrossPlatformInputManager.GetButtonDown("E");
}

With this function, the first tap on the button means "grab activated" and the second tap means "grab deactivated", like a toggle. Instead, I want the grab to be active as long as the button is held.


texts:
I am trying to filter a category in my ray casting (jBox2D within libGDX), which should return the closest object that does not belong to the category LEVEL0. I've tried a plethora of approaches, but none of them seem to work.

This post, for example, instructed me to do so:

private static class RayCast implements RayCastCallback {
    Fixture f;
    Vector2 point;
    float fraction;

    public RayCast() {
       this.fraction = 1f;
    }

    @Override
    public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) {
       if (fixture.getFilterData().categoryBits == Corpo.LEVEL0)
          return 1f;

       if (fraction <= this.fraction) {
           this.f = fixture;
           this.point = point;
           this.fraction = fraction;
       }
       return 1f;
    }
}

Yet, it ignores the LEVEL0 bodies only sometimes, and sometimes ignores other bodies as well (though it seems to work on most cases, it fails frequently enough to be unacceptable). I've tried a few other solutions, including: returning -1 in the first if (which should mean ignore this collision), return this.fraction always, instead of 1, but nothing works - this, in fact, seems to be a very common problem, as the internet is filled with a variety of workarounds, none of them working for me.

I think my library is updated, or at least is the version that is included in the latest libGDX (which, according to my quick research, is the actual latest).

I've posted this same question here, but I'm not sure about the official forum's activity, so I decided to ask here too, just in case. Whichever website gives the answer first, I shall copy it to the other.


texts: How can I publish a Python game on itch.io as html?

texts:
I'm making a game with Python, using Pygame. I want to publish my game on itch.io so that it's playable in the browser.
Is there a way to do this? If so, how?


texts: Work out the point on an ellipse given centre, radius, and direction vector?

texts:
I have a vector (white line), a centre and a radius along each of the semi-major and semi-minor axes of an ellipse (green line). I need to find the point where the white line intersects the green.

I have tried to work it out using Atan2, Sin and Cos but that doesn't quite work (blue line). It works when parallel to an axis but doesn't otherwise, I have a feeling this is because I am trying to perform the calculation on an ellipse where the horizontal and vertical radii are different.

Vector2 delta = (screenPos - canvasCentre).normalized;
float angle = Mathf.Atan2(delta.y, delta.x);
Vector2 position = canvasCentre + new Vector2(
                Mathf.Cos(angle) * radius.x,
                Mathf.Sin(angle) * radius.y);


texts: How to control multiple characters simultaneously in Unreal Engine 4?

texts:
How do I make two or more characters response to a single user input, in this case a mouse click?

Ideally, I'd like something similar to Baldur's Gate style party control. The only example of multiple character party control I have seen implemented is the BioWare style system.


texts: Why is my enemy hovering in the air when chasing the player?

texts:
In Unity, I have created an enemy AI and applied a script for it to move and chase the player. But when moving, the enemy hovers in the air. My character also does not have a rigid body, he just has character controller and my enemy AI is child object and an empty object as parent object. I added this to do animation. This is my enemy AI script created in C#:

using UnityEngine;
using System.Collections;

public class AdvancedAi : MonoBehaviour

{
    float distance;

    public float lookAtDistance, chaseRange, attackRange, moveSpeed, damping, gravity, attackRepeatTime;
    public Transform target;
    public CharacterController controller;

    private Vector3 moveDirection = Vector3.zero;
    private float attackTime;

    //TODO: add in a function to find controller and to locate and assign the player as the target

    void Start()
    {
        attackTime = Time.time;
    }

    void Update()
    {
        distance = Vector3.Distance(target.position, transform.position);

        if(distance < lookAtDistance)
        {
            LookAt();
        }

        if(distance > lookAtDistance)
        {
            GetComponent<Renderer>().material.color = Color.green;
        }

        if (distance < attackRange)
        {
            AttackPlayer();
        }

        else if (distance < chaseRange)
        {
            ChasePlayer();
        }
    }

    void LookAt()
    {
        GetComponent<Renderer>().material.color = Color.yellow;
        Quaternion rotation = Quaternion.LookRotation(target.position - transform.position);
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
    }

    void ChasePlayer()
    {
        GetComponent<Renderer>().material.color = Color.red;

        moveDirection = transform.forward;
        moveDirection *= moveSpeed;

        moveDirection.y -= gravity * Time.deltaTime; // doesn't seem to work right :(
        controller.Move(moveDirection * Time.deltaTime);
    }

    void AttackPlayer()
    {
        //TODO: Need Attack Animations
        if (Time.time > attackTime)
        {
            Debug.Log("Attack");
            attackTime = Time.time + attackRepeatTime;
        }
    }

    void ApplyDamage()
    {
        chaseRange += 30;
        moveSpeed += 2;
        lookAtDistance += 40;
    }
}


texts:
I have three dynamic Rigidbody2D's, two of them paddles and the other a ball - this ball is also a trigger. If I used OnCollisionEnter before, I understand that the physics engine calculates the collision that should happen based on the position and velocity of the ball and paddle. This created the so called lag problem I had where seemingly two collision results happened. However, now I am using OnTriggerEnter and have a couple questions related to the problem I'm having.

When the ball is level with the paddle on the x-axis and you move up to hit it, the paddle is able to go through the ball but the collision happens from where the ball hit the paddle originally. Why is this? Also, if I print the x position of the ball, the position should be 7.175 but instead it's 7.19996, is there a way to get the actual point of collision? Is this linked to the first question?

Thanks!


texts: Help with open and close UI Menu on background mouse click

texts:
I am trying to make a point and click game in unity 5.2.2.

My problem is that I need to have a UI menu to open, when the player clicks with the left mouse button on the background sprite, and it should close again, when he click on it again. I have created a script, and so far it works like that, but It also closes, when I click on the menu buttons itself, which means that I can't use the menu which opens. Please help me to how I can achive that.

The way the menu should work, is like in the game Game Dev Tycoon, where the player can open and close the menu, when clicking on the game background.

Here is my script, in its current form.

using UnityEngine;
using System.Collections;
/// <summary>
/// This is the main class, for the entire game. The purpose of this class, is to control any gameplay in the game.
/// </summary>
public class GameManagerScript : MonoBehaviour {

public GameObject gameUI;                                           //The actual Game UI

    public void Awake()
    {
        gameUI.SetActive(false);
    }

    // Game Manager Game Loop
    public void Update()
    {
        CheckForKeyInput();
    }

    void CheckForKeyInput()
    {
        //Mouse0 = First mouse button
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            Debug.Log("Mouse0 button fired!");
            gameUI.SetActive(!gameUI.activeSelf);
        }
        //If escape, exit the game
        else if (Input.GetKeyDown(KeyCode.Escape))
        {
            Debug.Log("Application has been exited");
            Application.Quit();
        }
    }
}


texts:
I'm reading the book "Learining XNA 4.0", and I'm in the object oriented disgn part. I'm having a weird problem with the collision of 2 rectangles.

I have a list of automateSprite and a Player class both derived from the class Sprite. in the update method im checking if player and the aotomatedSprite rectangles are touching each other, now when I go over the list I have a string called touching that represent the collision.

My problem is the variable touching only changes if the player Sprite touches the last automateSprite in the list.

The code that the book offers for testing is to do Game.Exit() if any collision was found. that work on every automatedSprite in the list, but when I change it to my simple test, it acts like I only check the last item from a list of 4 automatedSprite.

Here is the code:

string touching = "";
public override void Update(GameTime gameTime)
{
    // TODO: Add your update code here
    player.Update(gameTime, Game.Window.ClientBounds);

    foreach (Sprite sprite in spriteList)
    {
        sprite.Update(gameTime, Game.Window.ClientBounds);
        if (sprite.collisionRect.Intersects(player.collisionRect))
            touching = "touching";
        else
            touching = "not touching";
    }

    base.Update(gameTime);
}

public override void Draw(GameTime gameTime)
{
    spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);

    spriteBatch.DrawString(font, touching, Vector2.Zero, Color.Red);

    player.Draw(gameTime, spriteBatch);
    foreach (Sprite sprite in spriteList)
    {
        sprite.Draw(gameTime, spriteBatch);

    }

    spriteBatch.End();
    base.Draw(gameTime);
}

(sorry for my English)


texts: Generating a physics body for 2D Worms-like Terrain

texts:
I wrote a processing sketch that generates hills for a scorched earth clone, like this:

I'm trying to figure out how to make this a physics object in libgdx, but I'm having problems figuring out how to do that.

I thinking about doing this through a ChainShape composed of a vector2 array at each point on the slope.  I've tried running this on an android device through a Box2DDebugRenderer and SpriteBatch, but I can't get anything to show up (although that's another problem).

Does anyone know how to make a physics object like this in box2d?


texts: Using collision.contacts to determine if on a floor

texts:
I'm trying to make my own first-person character (because I get lost in the sea that is Unity's FP character script), and am trying to make it so it detects when it is standing on a floor. I tried using a playerController, but I've found rigidbody is just more malleable.

Anyways, so I think how you'd do it is finding the direction of the contact, and if it isn't straight down, then to keep onGround as false. I'm just not entirely sure the scripting behind this, and several searches have turned up nothing.

Several offered using mutliple colliders, but I would prefer to keep the number of objects, colliders or otherwise, at a minimum, considering there will be a large number of them in the scene as is. I also want something that's easily manipulable so that I can add extra features like climbing up a wall or the like, and I think that measuring the angle to the center is about as simple and easily manipulated as it gets.


texts: Clamp point to triangle for sphere collision

texts:
I'm having some issues clamping a 3d to barycentric triangle. I've searched for some time now and keep seeing the same results, that (u,v,w) should be clamped between 0 and 1. But when I clamp those values, I'm getting very weird results as it saying it's always intersecting. Maybe I'm just clamping the wrong values or what I'm doing wrong.

The issue is that I'm projecting a point on a normal from a given triangle, then testing if the point is inside the triangle, if it is, test if it's inside the sphere. Everything works great except when the sphere center is no longer above/in front of the triangle, so the spheres edge can pass through the edge of the triangle beings that the spheres center is no longer above it. Any help with how I'm supposed to clamp the position inside of the triangle would be much appreciated.

Here is a snippet of the triangle/sphere intersect method:

public boolean CollidesWithMesh(MeshCollider other)
{
    float sphereRadius = gameObject.scale * (bounds.Scale().Max()) / 2f;
    boolean collided = false;
    RawMesh mesh = other.gameObject.meshRenderer.mesh.rawMesh;

    for(int i = 0; i < mesh.triangles.length; i++)
    {
        //Store the verts used in the triangle
        int first = i++;
        Vector3 vert1 = mesh.vertices[(int) mesh.triangles[first]].Add(other.gameObject.position);
        Vector3 vert2 = mesh.vertices[(int) mesh.triangles[i++]].Add(other.gameObject.position);
        Vector3 vert3 = mesh.vertices[(int) mesh.triangles[i]].Add(other.gameObject.position);

        //Project a point along the normal closest to the spheres center
        Vector3 normal = mesh.normals[(int) mesh.triangles[first]];
        float dot = Vector3.Dot(normal, gameObject.position.Subtract(vert1));
        Vector3 d = normal.Multiply(dot);
        Vector3 point = gameObject.position.Subtract(d);

        //If the point is not inside the triangle, continue
        Vector3 v0 = vert3.Subtract(vert1);
        Vector3 v1 = vert2.Subtract(vert1);
        Vector3 v2 = point.Subtract(vert1);
        float dot00 = Vector3.Dot(v0, v0);
        float dot01 = Vector3.Dot(v0, v1);
        float dot02 = Vector3.Dot(v0, v2);
        float dot11 = Vector3.Dot(v1, v1);
        float dot12 = Vector3.Dot(v1, v2);
        float invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
        float u = (dot11 * dot02 - dot01 * dot12) * invDenom;
        float v = (dot00 * dot12 - dot01 * dot02) * invDenom;
        if(!((u >= 0.0) && (v >= 0.0) && (u + v <= 1))) continue;

        //If the sphere does not encapsulates the point, continue
        if(!Contains(point)) continue;

        //Respond to the collision
        Vector3 responseNormal = point.Subtract(gameObject.position).Normalized().Multiply(sphereRadius - (point.Subtract(gameObject.position)).Length());
        Vector3.Subtract(gameObject.position, responseNormal);
        if(normal.y > 0.75) isGrounded = true;
        if(normal.y < -0.75) hitCeiling = true;
        collided = true;
    }
    return collided;
}


texts: How to play many sounds at once in OpenAL

texts:
I'm developing an RTS game and I would like to add sounds to it. My choice has landed on OpenAL. I have plenty of units which from time to time make sounds: fSound.Play(sfx_shoot, location). Sounds often repeat, e.g. when squad of archers shoots arrows, but they are not synced with each other.

My questions are:

What is the common design pattern to play multiple sounds in OpenAL, when some of them are duplicate?
What are the hardware limitations on sounds count and tricks to overcome them?


texts: Efficient method to export a lot of pre-rendered sprites from 3D models

texts:
I have a lot of 3D Characters and I wish to use them in a 2.5D game as Sprites; in doing this I have to render them from a fixed camera angle and since each should have its own atlas file containing animation frames, it's going to be a very time consuming job!
I was thinking to write a python script (models are in Blender format) and let it render the Sprites. Since I don't know Python do you think that it is efficient of me to learn the python first and write the script to do the job for me?
Does anyone have a better idea?

In brief:
I am looking for an efficient method to export pre-rendered sprites from 3D models considering that they all have the same armature with the same animations.


texts: Separation of axis theorem implementation at normals

texts:
This might be more of a math question, but it relates to the development of a simple physics engine I am trying to create.

I have been stumped on this for about a week now, and have been unable to find an answer in any of the SAT tutorials. (http://www.metanetsoftware.com/technique/tutorialA.html#toc, http://gamedevelopment.tutsplus.com/tutorials/collision-detection-using-the-separating-axis-theorem--gamedev-169, etc.)

I understand how SAT is supposed to work, however I am little confused on the math. First, I am finding my normals like so:

Block.prototype.findNormals = function () {

        var axisVectors = new Array();
        var vertices = this.Properties.Vertices;
        var keys = Object.keys(vertices)

        for( var i = 0; i < keys.length; i++) {
            var last = {x: 0, y: 0};

            axisVectors.push({xComponent: -(vertices[keys[i]].y - last.y), yComponent: (vertices[keys[i]].x - last.x) });

            last = {x: this.x, y: this.y};
        }

        return axisVectors;
    }

I am then precede to project each vertex of the shapes I am testing on those normals.

The problem occurs, and the part of the math that I am not fully understanding, is when I have a situation like so:

axis = (-5, 6)
vertex = (6, 5)

math.dot(vertex, axis)

This results in 0.

Thus my min value for shape1 is always 0. And this results in a false collision.

Can anyone explain the math a little better?


texts: trapped inside a Graph : Find paths along edges that do not cross any edges

texts:
This is a graph based platformer level and the round shapes are creatures.

I am looking for a path traveling along edges that does not cross other edges(To simulate the creature crawling on the floors and walls).

Here is what the correct path would look like:


texts:
I have been working on a real-time game, and am closing in on the point where I send and receive data. I have previously accomplished this before with a couple other test games, but I have never really learned the correct way to pass data from server to clients efficiently.

My question: What is the best practice for a real time game to pass data? I have my doubts that I should be sending an update every frame (currently running at ~30 fps), but in all honestly I dont know what is best.

Most of the games ive worked on have passed the data instantly when they happen and continue to update every frame. Any suggestions or advice? Ill post more info if needed as well.

Thank you


texts:
I'm trying to make anti-aliasing work inside of OpenGL, here's what I've tried:

glEnable(GL_POINT_SMOOTH);
glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
glEnable(GL_POLYGON_SMOOTH);
glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

But so far none of these have worked.

I have gotten antialiasing to work by enabling it on the control panel for my video card (Catalyst Control Center in my case), but I would like to get it working inside my program instead.

This is what the rendering looks like with 4x antialiasing enabled via the video card control panel:
And this is what it looks like when I do it with my program:

How do I get antialiasing to work?


texts: Draw multiple LINE_LOOPs in one glDrawElements call

texts:
The game I'm working on has OpenGL (2.1) vector graphics, and I need to draw up to 1000 enemies, each of which is composed of between 4 and 100 lines.

Each enemy can be drawn as a single line loop, so one strategy for drawing would be to call glDrawElements(GL_LINE_LOOP, ...) once for each enemy. This results in too many (up to 1000) calls of glDrawElements per frame.

Another strategy would be to separate the line-loops that form each enemy into individual line segments, and call glDrawElements(GL_LINES, ...). This results in a lot of repeated vertices though, which I would like to avoid.

Is there a way to draw multiple line loops in a single call to glDrawElements (or with some other function)? I guess I would need some indicator in the vertex/element array to mark where each line loop ended.


texts:
When I start my game, public AudioSource does not load sound but play a sound.  My code does not have any error.

using UnityEngine;
using System.Collections;

public class random: MonoBehaviour {

    public AudioClip[] gravel;

    void Update()
    {
        if (!GetComponent<AudioSource>().isPlaying){
            GetComponent<AudioSource>().PlayOneShot(gravel[Random.Range(0,gravel.Length-1)]);
        }
    }
}

How can I put my random audio to my audio source.
Video for describle my problem:
In this video play sound twice (because I run my game twice)
In first play I have to attach a file to audio source.
I do not know why my audio source is empty and I have to attach a file to it.
If I can load sound in my audio source I can fix my problem.
I want to play one randomized shot.


texts: What is better: One texture per model or assigning multiple models to one single huge texture?

texts:
If I'm making a low-poly car pack of multiple cars for mobile platforms, should I:

Make a large texture like of 2048x2048 and unwrap all the models to it
Make separate, smaller (256x256) textures for all cars

Will there be a difference in performance? Which way of texturing is preferred? I've never seen any PC game have one large texture for all the cars, instead every car has its own set of textures and materials.


texts: building a game for different resolution phones

texts:
I am starting some tests for building a game on the Android program.
So far everything is working and seems nice.

However I do not understand how to make sure my game looks correct on all phones as they all will have slightly different screen ratios (and even very different on some odd phones)

What I am doing right now is making a view frustum (could also be ortho) which I set to go from -ratio to +ratio (as I have seen on many examples) however this causes my test shape to be stretched and sometimes cut off by the edge of the screen.

I am tilting my phone to landscape to do my tests (a bit extreme) but it should still render correctly if I have done things right.

Should I be scaling by some ratio before drawing or something?

An example would be greatly appreciated.

PS. I am doing a 2D game .


texts: Which consoles support fee-less indie game publishing?

texts: On which consoles can I publish indie games without paying a license fee?


texts:
For an endless runner game such as Subway Surfer, in order to move your character so smoothly in both z-axis and x-axis, which component of the followings is better:

CharacterController or RigidBody?

Can we use both of them together; if so, will it have any effect on the performance of our game?


texts:
Ok, so in my Java2D Game, using swing/awt (I hear it is not the best to combine those), I am trying to finish collisions.

So, the problem is, the "if (player.xvel < 0) { }" and the "if (player.xvel > 0) { }" in the Block class are still being executed even though the player hasn't run into the block horizontally. How can I make it so the code is executed when the player runs/walks into the block horizontally?

My code for the collide function is below, in
Block.java:

    void collide(Player player) {
        Rectangle player_hb = new Rectangle((int) player.x, (int) player.y, (int) player.width, (int) player.height);
        Rectangle block_hb = new Rectangle(x + Display.graphics_panel.WorldX, y, width, height);

        if (player_hb.intersects(block_hb)) {
            Rectangle intersection = (Rectangle) player_hb.createIntersection(block_hb);

            if (player.yvel > 0) {
                player.jumping = false;
                player.y -= intersection.getHeight();
            }
            if (player.yvel < 0) {
                player.yvel = 0;
                player.y += intersection.getHeight();
            }
            /* Execute this code ONLY if player is intersecting a block HORIZONTALLY!! */
            if (player.xvel > 0) {
                System.out.println("You shouldn't see this unless you run into a block!" + i++);
            }
            if (player.xvel < 0) {
                System.out.println("You shouldn't see this unless you run into a block!" + i--);
            }
        }
    }


texts: Relative quaternion rotation (delta rotation) produces unstable results

texts:
Use case: I have a currentRotation quaternion and a targetRotation quaternion and need to calculate the relative rotation between them - as in: what rotation do I need to apply to transform an object with currentRotation so that it has targetRotation.

Common solutions say that the delta rotation can be calculated by qDelta = qFrom.inverse() * qTo, which I use as well and works fine for most cases.

However, I am often running into issues for some specific rotations -
Codepen Example here (I'm using three.js and coffeescript).

While a relative rotation around the z-axis works fine:

qFrom = (new THREE.Quaternion()).setFromAxisAngle new THREE.Vector3(0, 0, 1), 2 * (Math.PI / 6)
qTo = (new THREE.Quaternion()).setFromAxisAngle new THREE.Vector3(0, 0, 1), 5 * (Math.PI / 6)
qExp = (new THREE.Quaternion()).setFromAxisAngle new THREE.Vector3(0, 0, 1), 3 * (Math.PI / 6)
qDelta = calculateRelativeRotation(qFrom, qTo)
qResult = qDelta.clone().multiply(qFrom)

Sane case results (delta):  expected x: 0.0°, y: 0.0°, z: 90.0°, got x: 0.0°, y: 0.0°, z: 90.0°

Sane case results (result): expected x: 0.0°, y: 0.0°, z: 150.0°, got x: 0.0°, y: 0.0°, z: 150.0°

... a more complicated rotation does not work out - the combination of qFrom and qDelta does not result in the expected qTo rotation:

eFrom = new THREE.Euler(0, 170 * dToR, 10 * dToR, 'XYZ')
eTo = new THREE.Euler(0, 170 * dToR, -10 * dToR, 'XYZ')
eExp = new THREE.Euler(0, 0, -20 * dToR, 'XYZ')

Problematic case results (delta): expected x: 0.0°, y: 0.0°, z: -20.0°, got x: 0.0°, y: 0.0°, z: -20.0°

Problematic case results (result): expected x: -180.0°, y: 10.0°, z: 170.0°, got x: 176.5°, y: 9.4°, z: -149.7°

expected result quaternion (qTo): {'_x':-0.086,'_y':0.992,'_z':-0.007,'_w':0.086}
*

actual result quaternion: {'_x':0.257,'_y':0.962,'_z':-0.007,'_w':0.086}

Inverting the calculated delta rotations helps for some cases, but doesn't cover all cases.

What am I missing?


texts: Modding sprites in New Super Mario Bros. DS

texts:
I'm a New Super Mario Bros. DS modder.

My goal is to create a custom sprite over an existing unused sprite.

I checked in on fellow modders and they said theoretically, I could copy another sprite's code to this "new" sprite. They also said they think that the collision manager would be the hardest part.

Does anyone know how I could also copy the other sprite's collision settings to my new sprite?


texts: Is it acceptable to mix simple physics logic with gameplay logic?

texts:
In my 2D game I have a PhysicsEngine class. It currently does two things:

Called every frame to apply global forces on all entities (e.g. gravity).
Called by the CollisionDetector to do the physics part of collision response.

Currently, (almost) all physics-related logic goes through this class (including single-line things like entity.applyImpulse(..)).

My question is, from an OO design perspective: is it okay for an entity to do simple physics logic by itself, or should all physics logic (even simple things) go through classes dedicated to it?

For example: in my game, when spotting a collision the CollisionDetector notifies both entities to take care of gameplay related logic, and the PhysicsEngine to take care of physics related logic. Looks like this:

// on collision between entityA and entityB
entityA.handleCollision(entityB); // take care of gameplay
entityB.handleCollision(entityA); // take care of gameplay
physicsEngine.handleCollision(entityA, entityB); // take care of physics

But what if, for example when a Missile hits something I want to apply an impulse on the hit object? (In addition to the physics that always happens on collisions, in PhysicsEngine).

This is easy to do by simply adding about 3 lines of code to the handleCollision() method in Missile:

public void handleCollision(Entity entity) {
    Vector impulse = entity.getPosition().subtract(this.position);
    impulse.scaleBy(5);
    entity.applyImpulse(impulse);
    explode();
}

However, this would be putting physics logic in a 'gameplay' class. Should the Missile delegate to the PhysicsEngine in some way? Or is it okay that it would contain physics logic?

Another example I encountered in my game, is that when an entity 'fires' a Missile, I want to apply an impulse on the entity to push it backwards. Again, this can be done easily by adding 2-3 lines to the fire() method in the Entity subclass, but I'm not sure it's okay design-wise to mix gameplay and physics logic.

So, is it acceptable to have simple physics logic mixed with the gameplay logic? Or should I always separate the two?

How is this done in 'serious' games?


texts:
Does anyone know when the source code for Doom 3 is to be released?
I've heard a lot of things but nothing conclusive.

Thanks
Adam

Edit any info is appreciated


texts:
I'm trying to build some 2d character with Photoshop and Spine. By now, I have created some of my characters using 16 bit color depth images in Photoshop. Now, I wonder whether I have to use 32 bit or just create everything with 16 bit textures...
How much does it affect my game? Considering a 2D Unity or Flash game.


texts: Delta times and frame lag in the game loop

texts:
Let's say we have a standard gameloop like this, in pseudocode:

while (true) {
    dt = GetDeltaTime();
    Update(dt);
    Render();
}

Here Update(dt) either uses a true variable timestep, or it determines how many cycles of a fixed timestep physics loop to execute based on dt.

Now say we have the common case where we have mostly constant framerate except for infrequent single-frame hiccups, so let's say we have dt values like

1/60, 1/60, 1/60, 1/6, 1/60, 1/60, ...

By the time our GetDeltaTime() detects the larger timestep in the fourth frame, we have already rendered and presented the fourth frame! So one frame will already have been rendered with a wrong (too small) timestep no matter what we do.

So if we now use the larger dt=1/6 to render the fifth frame, my understanding is that we artificially create a second frame where a wrong timestep is used, this time a too large one. I wonder if this problem is acknowledged anywhere. Wouldn't it be better, say, to use the averaged dt over the previous few frames to combat this?

Here are some pictures to illustrate what I mean. I use the example of an object moving along a fixed axis with a constant speed, and using a variable timestepping scheme. The problem is essentially the same with fixed timesteps, though.

The plots have time on the x-axis, and the object position on the y-axis.

Let's say the object moving at 1 unit/s, and framerate is 1 Hz. This is the ideal situation.

Now let's say we have a frame where the time interval is 2 instead of 1. With a classical dt-based scheme, we get this:

So we have one frame where the velocity is perceived too low, and one where it is perceived too high and which corrects for the velocity in the previous frame.

What if we instead, say, always use a constant (or very slowly changing) dt? We get this:

The perceived velocity seems smoother using this approach to me. Of course, the object position is now not the "true" one, but I think humans perceive abrupt changes in velocity more clearly than such small positional offsets. Thoughts?

UPDATE:

At least Ogre can do this: http://ogre.sourcearchive.com/documentation/1.6.4.dfsg1-1/classOgre_1_1Root_1f045bf046a75d65e6ddc71f4ebe0b2c.html So I guess I just got downvoted for people not understanding my question, which is rather frustrating.


texts: Transform the mouse coordinates to the GLSL plane

texts:
I am creating a 2D map editor in C ++ with GLFW. I want move and drag entities with the mouse, but I have a problem, the mouse coords are in the window size range (1200, 720) and the entity is in the GLSL range (100x100 I think), I compare the mouse coord with the 4 entity edges. How can I do this?
PD: Sorry for bad english.
Edit:
There is the code for set position and size to entities:
model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(translate, 0.0f));
model = glm::scale(model, glm::vec3(scale, 1.0f));

And this is the GLSL code:
#version 330

layout (location = 0) in vec2 position;
layout (location = 1) in vec2 textureCoord;

out vec2 TexCoord;

uniform mat4 model;
uniform mat4 projection;
uniform mat4 view;

void main() {
    TexCoord = textureCoord;

    gl_Position = projection * view * model * vec4(position, 1.0, 1.0);
}


texts:
public class Main extends ApplicationAdapter {

SpriteBatch batch;

OrthographicCamera camera;

Stage stage;

Image greyback;
Image circle;

private float width;
private float height;

@Override
public void create () {

    batch = new SpriteBatch();

    camera = new OrthographicCamera();

    stage = new Stage();
    Gdx.input.setInputProcessor(stage);

    greyback = new Image(new Texture("greyback.png"));
    circle = new Image(new Texture("circle.png"));

    width = Gdx.graphics.getWidth();
    height = Gdx.graphics.getHeight();

    greyback.setWidth(width);
    greyback.setHeight(height);

    circle.setPosition(200,200);

    circle.setBounds(200, 200, circle.getWidth(), circle.getHeight());
    circle.setTouchable(Touchable.enabled);
    circle.addListener(new InputListener() {

        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {

            System.out.println("CLICKED");

            return true;

        }

        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {

            System.out.println("REMOVED");

        }

    });

    stage.addActor(greyback);
    stage.addActor(circle);

}

@Override
public void render () {

    stage.draw();

}

}
But, when I click on the circle the touchlistener doesnt fire, why?


texts: "Saving..." dialog isn't shown until after the saving is complete

texts:
I have implemented serialization/de-serialization process in my Unity game where I save/load data from/to XML file.

During the serialization, my game isn't responding until the serialization is finished and this is OK.

What is wrong is that before I call the serialization/de-serialization, I want to show saving/loading panel and show log process, but can't: this panel and all the log information show up only after the serialization/de-serialization is finished.

What I have verified and tried:

The panels hierarchy is correct
During serialization/de-serialization, no error occur
Panels are assigned manually to specified variables
If I comment out the save/load calls and leave only the panel, then the panel is shown
I have also tried to put the thread to sleep but still, nothing happens.

Can anybody can help me? Because I really don't know why this is happening like this.

Here is an snippet of my code:

public void SaveGameClick() {
  SavingPanel.gameObject.SetActive(true); // if I leave only this line and the other line
                                          // commenting the panel shows perfectly
  Debug.Log("Saving..."); // this Saving word shown only when the _savegame.Save() method
                          // finished
  if(_saveGame.Save("save.xml", Seed)) {
    Debug.Log("Saved");
    CyberTeamManagerSubMenu.gameObject.SetActive(false);
    _isShowCyberTeamManagerSubMenu = false;
    SavingPanel.gameObject.SetActive(false);
  } else {
    Debug.Log("Save Error");
    SavingPanel.gameObject.SetActive(false);
  }
}


texts:
This used to be on the physics stack exchange but I was told to put it here:

I'm making a game (with physics) and I have a 3D ball rolling down a flat plane. It moves perfectly fine, but the rotation is messed up. It seems way too fast, and the axis seems to be all wrong. Here's the code that runs every tick (20 times per second). (normal is the normal to the plane, acceleration is gravity vector projected onto the plane, in m/tick2, and velocity is the velocity in m/tick.)

vec3 rotationAxis = normalize(cross(normal, acceleration));
quat newRotation = rotate(oldRotation, length(velocity) / sphereRadius, rotationAxis); // rotate by v/r radians about the rotationAxis

I'm not sure why this doesn't work, since according to angular mechanics, v=rω and ∆θ=v∆t/r (and ∆t=1 since velocity is in meters/tick). Am I doing something wrong? Why is the rotation so much faster than it should be? And is my axis of rotation correct?

Rephrased in a more physics way, is this correct in 3D:

$$\hat{x} = \frac{\hat{N} \times \vec{a}}{|\hat{N} \times \vec{a}|}$$

$$\Delta \theta \textrm{ about } \hat{x} = \frac{v}{r} \Delta t$$

And if it is correct, then what’s wrong with my code?


texts: Would I need to delete unused assets from my Unity packaged build?

texts:
I'm going to make a release for my Unity game.

Does Unity include unused assets in build output? Would removing unused assets from a project reduce build size/Time?

I want to know if Unity packages all the assets to my build (which I would need to delete), or if Unity packages only the assets that are actually used in the game.


texts: Does it matter who does the collision detection?

texts:
I gave an answer to How to decide which GameObject should handle the collision?, and received a lot of negative feedback on it, claiming that it does not matter who does the collision detection. I am not understanding that stance.

For example:

There are 100 bullets and 1 player on the screen. Let's assume brute force collision detection and no optimization such as layers or references.

If the collision detection is done by the bullet, each bullet must detect for collision on 100 different objects. That's 100 x 100 detections, for 10000 detections total.

If the player does the detection, that's 100 detections total, one for each bullet.

Am I mistaken? If so, what am I missing?


texts:
I am a new game developer, and I am making a game in unity. I have button, and the button doesn't work at all.
Also I have a "game object" with a script:
using UnityEngine.SceneManagement;
using UnityEngine;

public class Pause : MonoBehaviour
{
    public GameObject Panel;
    public GameObject PauseButton;
    private bool isopen = false;
    private bool can;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape) && isopen == false && can)
        {
            Pause_();
        }
        else if (Input.GetKeyDown(KeyCode.Escape) && isopen)
        {
            resume();
        }
    }

    public void Can(){
        can = true;
    }

    public void Cannot(){
        can = false;
    }

    public void Pause_()
    {
        isopen = true;
        Panel.SetActive(true);
        PauseButton.SetActive(false);
        Time.timeScale = 0f;
    }

    public void resume()
    {
        isopen = false;
        Time.timeScale = 1f;
        Panel.SetActive(false);
        PauseButton.SetActive(true);
    }

    public void MainMenu()
    {
        isopen = false;
        SceneManager.LoadScene("MainMenu");
    }

    public void Continue_Time()
    {
        Time.timeScale = 1;
    }
}

And that also doesn't work.
P.S I have 3 canvases.
I look forward to see an answer.


texts: Script executes fine but randomly crashes with NullRefferenceExpectation

texts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Zombie_Spawn : MonoBehaviour
{
    public float timer = 0.0f;
    public bool m_spawn = false;
    public GameObject m_Zombie;
    Vector2 pos;

    void Update()
    {
        if (m_spawn == true)
        {
            timer += Time.deltaTime;
            if (timer > 2.0f)
            {
                pos = Camera.current.ViewportToWorldPoint(new Vector2(1f, 0.135f)); //this executes fine but will Null out randomly
                Instantiate(m_Zombie, pos, Quaternion.identity);
                timer = 0;
            }
        }
        else
        {
            timer = 0f;
        }
    }
}


texts: How would I translate screen coordinates to Isometric coordinates?

texts:
I have a function isoToScreen(x, y) that converts Isometric coordinates to Screen coordinates.

var tileW = 16;
var tileH = 16;

var isoToScreen = function(x, y) {
    var posX = (x - y) * tileW;
    var posY = (x + y) * tileH / 2;

    return [posX, posY];
};

But how would I make a function that converts screen coordinates back to Isometric coordinates?

var pos = screenToIso(16, 8);
pos[0] = 1; // Iso X
pos[1] = 0; // Iso Y


texts: Why do FPS games often automatically reload?

texts:
Was pointed here by Arqade's Meta

On every first-person-shooter game I've played I've noticed that the 'automatically reload when empty' game mechanic is always used:

I've always found it annoying, and so do many others:

Any way to turn off automatic reloading? - GameFAQs
Auto-reloading or manual reloading
Rid of Auto Reload
Auto reload, please (and interruptable reloads)

and many more results.

Is there a particular reason why this specific game mechanic is extremely common in first-person-shooter games?

A couple of possible reasons why:

Makes it easy for new players
Using the same mechanics as other games makes it easier to learn your way around the game


texts: Accessing C++ class members with LuaPlus

texts:
I've implemented LuaPlus in my engine eventmanager successfully and really like the flexibility I gained. But I'm still not exactly where I want to be, because I can't link my c++ classes to a Lua class.

For example, I have a Actor class in C++, and I want to be able to create the same class in Lua and gain access to members with LuaPlus, but I can't figure how I can achieve that.

Is this actually LuaPlus built-in functionality, or do I have to write my own interface that exchanges data tables between C++ and Lua?

My current approach would be to fire an event in Lua that creates an new actor class in C++ code, and transfer its ID and the data I need to back to Lua. When I modify the data I send the modifications back to C++ code again, but I actually thought there's something in LuaPlus that exposes this functionality already.


texts:
I'm trying to write a shader that doesn't blend additively etc etc. I'd like to take whichever of the source or destination colours is brighter and use that and BlendOp Max seemed like the tool for the job.

However, as you can see below, the shadow of one light seems to be occluding the other, which doesn't match up with how I understand BlendOp Max is supposed to work:

Unity Docs
NVidia
OpenGL

Could anyone clarify where I'm going wrong or provide an alternative?

Interestingly, Blend One One is working fine, however, BlendOp Add (along with all the other BlendOps apart from the 'logical' ones) are creating the same issue.

Update

Shader Code:

Shader "Lantern/Flat Pullup" {
Properties {
    _LitTex ("Lit (RGB)", 2D) = "white" {}
    _UnlitTex ("Unlit (RGB)", 2D) = "white" {}
    _Pullup ("Pull up Point", Range(0,1)) = 0.7
    _BlendSize ("Blend Size", Float) = 0.3
}
SubShader {
    Pass{
        Tags { "LightMode" = "ForwardBase" }
        LOD 200

        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #include "UnityCG.cginc"

        uniform sampler2D _UnlitTex;
        uniform float4 _UnlitTex_ST;
        uniform sampler2D _LitTex;
        uniform float4 _LitTex_ST;
        uniform float _Pullup;
        uniform float _BlendSize;

        uniform float4 _LightColor0;

        struct VI {
            float4 vertex : POSITION;
            float4 tex : TEXCOORD0;
        };

        struct V2F {
            float4 pos : SV_POSITION;
            float4 tex : TEXCOORD0;
            float4 posWorld : TEXCOORD1;
        };

        V2F vert(VI v){
            V2F o;
            o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
            o.tex = v.tex;
            o.posWorld = mul(_Object2World, v.vertex);
            return o;
        }

        float4 frag(V2F i) : COLOR {
            float3 flatReflection = _LightColor0.xyz *
                (1 / length(_WorldSpaceLightPos0.xyz - i.posWorld.xyz));

            return lerp(
                tex2D(_UnlitTex, i.tex.xy * _UnlitTex_ST.xy + _UnlitTex_ST.zw),
                tex2D(_LitTex, i.tex.xy * _LitTex_ST.xy + _LitTex_ST.zw),
                clamp((length(flatReflection) - _Pullup + _BlendSize) / (2 * _BlendSize), 0, 1)
            );

        }

        ENDCG
    }

    Pass{
        Tags{"LightMode" = "ForwardAdd"}
        //Blend One One
        BlendOp Max
        LOD 200
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #include "UnityCG.cginc"

        uniform sampler2D _UnlitTex;
        uniform float4 _UnlitTex_ST;
        uniform sampler2D _LitTex;
        uniform float4 _LitTex_ST;
        uniform float _Pullup;
        uniform float _BlendSize;

        uniform float4 _LightColor0;

        struct VI {
            float4 vertex : POSITION;
            float4 tex : TEXCOORD0;
        };

        struct V2F {
            float4 pos : SV_POSITION;
            float4 tex : TEXCOORD0;
            float4 posWorld : TEXCOORD1;
        };

        V2F vert(VI v){
            V2F o;
            o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
            o.tex = v.tex;
            o.posWorld = mul(_Object2World, v.vertex);
            return o;
        }

        float4 frag(V2F i) : COLOR {
            float3 flatReflection = _LightColor0.xyz *
                (1 / length(_WorldSpaceLightPos0.xyz - i.posWorld.xyz));
            return lerp(
                float4(0,0,0,1),
                tex2D(_LitTex, i.tex.xy * _LitTex_ST.xy + _LitTex_ST.zw),
                clamp((length(flatReflection) - _Pullup + _BlendSize) / (2 * _BlendSize), 0, 1)
            );
        }
        ENDCG

    }
}
FallBack "Diffuse"
}

Update 2

The same plane and lights rendered using Unity's standard shader, for illustrative purposes.


texts: How do we make online games deterministic?

texts:
I am trying to understand how networking in games work as I am trying to make an online game myself. I can't grasp how it is possible to synchronize the players, in order to make the game deterministic. I found an article saying this:

  in order to ensure that the game plays out identically on all machines it is necessary to wait until all player’s commands for that turn are received before simulating that turn. This means that each player in the game has latency equal to the most lagged player.

This makes sense and I also came to the same conclusion after hours of drawing graphs with various scenarios. However, there are some games where one player can have 500ms delay, and another player could have 40ms delay. In this case, how is the game deterministic ?

Lets name players with 40ms, 500ms delay: Player40, Player500

Lets say that Player40, shoots Player500 with an instant laser shot at T1 = 0ms. Exactly 40ms after the Player40 actually clicked with his mouse to shoot (so T2 = 40ms), The "laser shooting event" registered on the server and returned "ok, you can execute laser shoot" to Player40. So, the shot is being applied on Player40's machine and on his screen he sees that he killed Player500, and the corpse is lying on (x1,y1,z1).

Meanwhile, what happened on Player500's machine, was that Player500 was running straight. A few moments later he sees a laser a few feet behind him, he dies even though the laser didn't hit him, and his corpse is lying on (x2,y2,z2).

Since this scenario never happens in some games, does this mean that those games are deterministic ? How is something like this possible, without forcing all players to get a delay equal to the delay of the most lagging player ?


texts:
I am working on isometric tilemap in Unity 2019.4.8f1.
In the Tile Palette panel, the selection is always 1 block away. Please see this screenshot:

In the screenshot, apparently I selected an empty tile, but in fact I am select the green tile with flowers. How come? Every selection is one tile away. The same issue happens in the Tilemap selection mode too. I have to select the adjacent tile in order to select the tile I want.
How do I fix it? It's quite annoying.
UPDATE I have added the settings of Grid, Tilemap as well as the import settings of the tile sprite sheet below.

UPDATE 2 Changed the Pivot in Sprite Editor to Bottom Center
Recreated the Tile Palette, and it looks like hovering 0.5 unit up.


texts:
I want to create a polyline which should be quite smooth for my game. A point is following moving on the line, but can accelerate/brake and has to get slower in corners.

In the end I want to set up some stats (good acceleration, low topspeed, "good" cornering") and simulate the time it has taken to go from start to finish (drawning it to the player would be just a bonus). Yes, this will be some sort of a racing simulation.

I'm quite new to this style of games and I have no idea to do that. I don't even know how to create such a polyline I can easily use.

I don't want a finished algorithm but rather some hints in the right direction. I thought about using the angle of the corner to determine the speed, but that's not really much. I want to implement the time simulation in python, outputting the movement with html/javascript.

How would I start implementing such a mechanism?


texts: Will the same Flash game business model work for HTML5 games?

texts:
One of the best ways to earn money with Flash games is by making sponsorship deals. The developer puts the sponsor's logo and a link to their site in the game and lets the game spread around the web. The sponsor gains money from the ads and the extra traffic to their website. Alternatively, they site-lock their game to their website (usually for a short period of time) so that people who want to play the game go to their website. It's true that one can remove the site-lock with some effort by decompiling the swf, but it's usually not done as it's not worth the effort and not legitimate. Another significant part of the Flash business model is to put advertisements in-game. There are other ways of earning money with Flash games, but from what I know, these two are the most prevalent ones.

Since HTML5 is necessarily open source, it makes me wonder if this model would still work for HTML5. Even if you obfuscate your js, it's much easier than Flash to copy the game, so maybe it's worth the effort for someone to copy the game to their (illegitimate) site. If you add your sponsor's logo and link or advertisements, it might be worth the effort to remove them for their site, something that I think is much harder to do with Flash games. Perhaps even the illegitimate site could claim that their site is better because there are no in-game ads. There's still the legitimacy barrier, but I wonder if it's strong enough.

Let's put aside all game development technical restrictions regarding HTML5 for this question (suppose for a moment that HTML5 works just as well as Flash for games). I have two very similar (pair of) questions. The first is, would the Flash business model work with HTML5? What changes to it would be helpful for HTML5 games? The second question is, what about the big picture for HTML5 games? Is adapting the Flash model really the best solution, or is there a better model for the HTML5 games world to "turn"?


texts: Is there a better alternative to Timers to increment speed?

texts:
I'm making a chaser game in flash, where you would press an arrow key and the player would move in that direction then stop on another point on a grid, as the enemy does the same and chases the player. To make the movement smooth, I have a timer moving the player one pixel each repetition (50 times to stay on the grid points), having the delay get smaller every 30 frames to speed up. But after the delay gets to 0 and can't go any lower, the player can't get faster. What is a better alternative to use to continue going faster?

            var playerTimer:Timer=new Timer(40,50);
            playerTimer.addEventListener(TimerEvent.TIMER,playerMoveTrigger);
            var pStatus:String="";
            stage.addEventListener(KeyboardEvent.KEY_DOWN,playerMove);
            function playerMove(e:KeyboardEvent):void
                {
                if((player.x+15)%50==0&&(player.y+15)%50==0)//ensures player is on grid before moving
                {
                    switch(e.keyCode)
                        {
                            case Keyboard.DOWN:
                            pStatus="down";
                            break;

                            case Keyboard.UP:
                            pStatus="up";
                            break;

                            case Keyboard.LEFT:
                            pStatus="left";
                            break;

                            case Keyboard.RIGHT:
                            pStatus="right";
                            break;
                        }
                }
                playerTimer.start()
                }
                playerTimer.addEventListener(TimerEvent.TIMER_COMPLETE,resetTimerP);
                function resetTimerP(e:TimerEvent){playerTimer.reset();}

            function playerMoveTrigger(e:TimerEvent)
            {blockMove(player,pStatus);}
            var offSet:int=0;
            function blockMove(block:Shape,dir:String)
                {   offSet=(block.height==30)?15:10;
                    switch(dir)
                        {
                            case "down":
                            if(block.y+offSet<150){block.y+=1;}
                            break;

                            case "up":
                            if(block.y+offSet>50){block.y-=1;}
                            break;

                            case "left":
                            if(block.x+offSet>50){block.x-=1;}
                            break;

                            case "right":
                            if(block.x+offSet<150){block.x+=1;}
                            break;
                        }
                }


texts: How does Direct3D know if a constant buffer is for the vertex or pixel shader?

texts:
I have a question about constant buffers in directX 11.  They really confuse me and after searching on google most sites simply supply sample code without explaining how it works.  I am probably overlooking something but, as of now, they appear to me to work by sheer magic.  Say I have two constant buffers in an hlsl file:

struct Light
{
    float3 dir;
    float4 ambient;
    float4 diffuse;
};

cbuffer cbPerFram
{
    Light light;
};

cbuffer cbPerObject
{
    float4x4 WVP;
    float4x4 World;
};

And I create an equivalent buffer in my C++ program like so:

//Create the buffer to send to the cbuffer in effect file
D3D11_BUFFER_DESC cbbd;
ZeroMemory(&cbbd, sizeof(D3D11_BUFFER_DESC));

cbbd.Usage = D3D11_USAGE_DEFAULT;
//cbPerObject is a struct with same layout as cbPerObject in HLSL file
cbbd.ByteWidth = sizeof(cbPerObject);
cbbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbbd.CPUAccessFlags = 0;
cbbd.MiscFlags = 0;

hr = d3d11Device->CreateBuffer(&cbbd, NULL, &cbPerObjectBuffer);
//Create the buffer to send to the cbuffer per frame in effect file
ZeroMemory(&cbbd, sizeof(D3D11_BUFFER_DESC));

cbbd.Usage = D3D11_USAGE_DEFAULT;
//cbPerFrame is struct with same layout as in cbPerFrame in effect file
cbbd.ByteWidth = sizeof(cbPerFrame);
cbbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbbd.CPUAccessFlags = 0;
cbbd.MiscFlags = 0;

And then I update one like this:

d3d11DevCon->UpdateSubresource( cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0 );
d3d11DevCon->VSSetConstantBuffers( 0, 1, &cbPerObjectBuffer );
hr = d3d11Device->CreateBuffer(&cbbd, NULL, &cbPerFrameBuffer);

How does directX know which constant buffers in my shader are going to be used for VS and which for PS and which buffers in my codes correspond to which buffers in my hlsl?  For example I call VSSetConstantBuffers above and pass the arguments and it automatically knows to throw that stuff in the per object buffer as opposed to trying to put it in the perFrame buffer. As far as I can tell when creating cbPerObjectBuffer, I never explicitly bound it to the cbPerObject buffer in my hlsl.  Is slot number dependent on the order the buffers appear in hlsl?  The only way I can figure is that the data structures simply define an interface to the buffer memory on the card and it is up to the programmer to use the correct one.  For example, I COULD attempt to use cbPerFrame in my vertex shader and indeed the same data can be accessed that way but in order to get correct results you would have to access it using offsets into the light object.  Does what I am asking make any sense? lol


texts: How to Play YouTube Videos Within Asset Store for Unity

texts: On every computer I've ever tried to use Unity, the Asset Store seems incapable of showing the YouTube video previews of assets. It always claims my "browser" does not currently recognize any of the video formats available and recommends I click for a visit to a FAQ about HTML5 video. I would expect this to be built into Unity, yet it seems not to be. I can't find anything online about what the deal is. So how do I get the videos to work within the Asset Store within Unity??


texts: How to make a gui button follow a path after a touch?

texts:
I would like a button in my gui menu to follow a specific path if we selected it, I am wondering how I could do it: if we touch the button, then it can only move on the specific path, it is an arc such as this path :

Would you know how to achieve this?
I am using Unity, but I think the theory should be the same for other software/language ?

Thanks for your help

__

EDIT:

here is the code for the bezier curve in unity : Where should I put the script?

using UnityEngine;
using System.Collections;

public class DrawBezierHandle extends Editor {

    public Transform startT;
    public Transform endT;

    function Start(){
        startT = GameObject.Find("start").GetComponent("Transform") as Transform;
        endT = GameObject.Find("end").GetComponent("Transform") as Transform;
    }

    function OnSceneGUI() {

        var width : float = HandleUtility.GetHandleSize(Vector3.zero) * 0.1;
        Handles.DrawBezier(startT.position,
                        endT.position,
                        startT.position * 5 * Vector.up,
                        endT.position * 5 * Vector.up,
                        Color.red,
                        null,
                        width);
    }
}


texts:
I have two GameObjects set down. One is named Spawn Point, and it is set at the beginning of my level, and Death Point, set down at about 0,-40,0. My code tries to see if the character is below the Death Point area and moves the player to the spawn point. I feel that the answer is so simple, that I could look it up, but I looked it up, and I didn't see it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class death : MonoBehaviour
{
    public GameObject spawnPoint;
    public GameObject deathPoint;
    // Start is called before the first frame update

    // Update is called once per frame
    void Update()
    {
       Vector3 playerPos = transform.position;
        if(playerPos.y < deathPoint.transform.position.y) {
            transform.position = spawnPoint.transform.position;
        }
    }
}

A big thank you in adavance.


texts: How can I insert and remove blocks quickly in a Minecraft-style world?

texts:
I currently have volume data for the world stored as an array of booleans.  I then check each empty block and if it has non-empty neighbors the faces get drawn.  This prevents me from sending a bunch of faces to the graphics card using OpenGL.

I'm now working on inserting and removing blocks but I'm not sure how to do this quickly.  It is simple enough to change the volume data but I don't want to recompute all the vertices from the volume data each time someone inserts or removes a block.  It occurred to me just to add the block to the vertex buffer at the end of the existing vertex data but then I don't have a good way of destroying it as I have no way to correlate between the volume and vertex buffer data.

Any thoughts on how I can fix the mess I'm in?


texts:
I have been learning a new method of programming. I have been programming many years and am recently finding out there is a better method in general via abstract classes.

My question is how to convert a small section of my code so i can understand how this works entirely. So far i could only figure out how to do 1 part:

public abstract class Water
{
    public abstract string GetString(double AmountToAdd);
}

public class AddTotalWater : Water
{
    public double TotalWater;

    public override string GetString(double AmountToAdd)
    {
        TotalWater += AmountToAdd;
        if (TotalWater > 999999)
            return TotalWater.ToString(Globals.ScientificNotationFormatter);
        else
            return TotalWater.ToString();
    }
}

and use it with:

TotalWater.text = AddTotalWater.GetString(amountToAdd);

I would just like some guidance to learn how to do this fully.
Is this the proper way to do this to begin with?

This is the nested nightmare I have currently that i want to convert:

public void DetermineWaterValues()
    {
        if (Time.deltaTime < TotalWaterProductionTime)
        {
            double tempWaterTime = waterCounter += Time.deltaTime;
            if (tempWaterTime > TotalWaterProductionTime)
            {
                tempWaterTime = TotalWaterProductionTime;
                waterCounter = 0;
                WaterProgressBar.fillAmount = 0;
                TotalWater.text = AddTotalWater.GetString(amountToAdd);
            }
            else
            {
                if (TotalWaterProductionTime >= 0.1)
                    WaterProgressBar.fillAmount = (float)(tempWaterTime / TotalWaterProductionTime);
                else
                    WaterProgressBar.fillAmount = 1;
            }
        }
        else
        {
            WaterProgressBar.fillAmount = 1;
            TotalWater.text = AddTotalWater.GetString(amountToAdd);
        }
    }

It's quite complicated to figure out how to do this properly.
This is the way i did it for over 10 years heh...


texts: How can I get visually accurate collision normals with sphere collisions?

texts:
I'm solving simple 3D sphere collisions by checking the sphere for overlap with a mesh, finding the nearest point on that mesh's surface to the center of the sphere, and then resolving the collision by moving the sphere out of the mesh using the normal and the penetration distance.

To find the normal, I'm using the normalized vector from the nearest point on the mesh to the center of the sphere.

Now I'm trying to resolve a collision where the sphere has overlapped more than one collider. How I'm currently solving it is by iterating through all the meshes and checking to see if the last correction solved the collision.

In the scenario shown in the bottom image, this can cause a problem when trying to determine a collision normal. The two collisions return two different normals, as they should (Though, Depending on which collision was resolved first, the correction from the right box would solve the collision with the left box, in which case there would only be one normal).

Now, mathematically, that all makes sense, but visually causes a problem. If I'm trying to determine a single normal to, say, bounce the ball off the surface create by those two meshes, any normal that takes both collision normals into effect would be inaccurate. Visually, one would expect the collision normal to be straight op, but since one of the collision normals is at an angle, I would need to somehow determine that that is a sort of "false" normal.

The solution that comes to mind is to order the collision checks by their distance from the sphere, thereby ensuring that, in that scenario, the angled normal never even comes into play. Is this an accurate way to do this, or would that cause other problems I'm not seeing?


texts:
I've had this question for some time now, but never got around to asking it. Why can't games be easily adapted to VR? I understand some games in which animations change viewpoint would nauseate the gamer, but in games like CSGO, where the only thing that would be difficult might be scoping in and head bob, why can't games simply go through some predetermined algorithm to split the view for VR, and add in code for VR headset control and VR controllers? I assume there is some reason, but I can't think why.

Thanks for any help.


texts: how to reset etsa function GetJoystickNames in unity?

texts:
the problem is that if I connect a command the array
GetJoystickNames increases an index but if you disconnect it does not reduce the index and continues counting as if it were connected


texts: suggestion for a “strategy game” like platform to test AI algorithm

texts:
I wrote a piece of tricky AI algorithms that simulates animals living in an environment and their food seeking, interacting with each other and especially learning new patterns of lifestyle.

now I want to add some graphics to it. so instead of a form with colored dots I would see a 3d environment with different objects moving on it, just like an strategy game.

my code is in VB.net and it uses lots of advanced oop techniques and dynamic nested classes. so changing code to another platform like python, c++ or java is not and option for me. also I am not a trained graphic programmer so which graphic platform I get is what I use as graphic output. If I could only have source of a simple strategy game it would be enough for me.

also any link to opensource .Net strategy games or any source code that can hemlp me in this concept is appreciated.


texts: How to create a component that is a child of another component?

texts:
I have several objects in my game that all have an customEvent component. I have three different types of customEvent, customEventA, customEventB, customEventC. At some point, I want to enable this customEvent component, but I don't know if its type A, B, or C.

What I want to do is just reference GetComponent<customEvent>().enabled = true and then it will automatically enable whatever type is actually attached to the GameObject.

What I am trying to do is similar to how Collider component works. You can have a BoxCollider, SphereCollider, PolyCollider, etc. and can refernce it by saying GetComponent<Collider>().

How can I achieve this?


texts: Rotation of Rectangle along Y-axis transformed to parallelogram

texts:
After the rotation of a rectangular view along the Y-axis, about its center, transformed into parallelogram, how do I get the rotated parallelogram coordinates?

By Y-axis, I mean perpendicular to the device screen.

Rotated rectangle:

Original rectangle:

Not using the openGl, ViewProperty animator is used!


texts: How can I make a custom editor that creates/deletes game object clones around a given point

texts:
I have been manually creating and deleting clones of my game objects that I arrange in a circle around a given point. Each of the objects is rotated making each object the same angle apart from the others as seen in the image below.

My objects range from 2 to 10. Doing this manually is very cumbersome, especially when changes have to made. How can I create a unity custom editor that allows me to specify a number of game object clones I want to create around a specified anchor point? Additionally, adjusting the number of clones should dynamically create/delete clones and reposition/rerotate them.


texts:
I'm playing with orbits in a simple 2-d game where a ship flies around in space and is attracted to massive things. The ship's velocity is stored in a vector and acceleration is applied to it every frame as appropriate given Newton's law of universal gravitation. The point masses don't move (there's only 1 right now) so I would expect an elliptical orbit.

Instead, I see this:

I've tried with nearly circular orbits, and I've tried making the masses vastly different (a factor of a million) but I always get this rotated orbit.

Here's some (D) code, for context:

void accelerate(Vector delta)
{
    velocity = velocity + delta; // Velocity is a member of the ship class.
}

// This function is called every frame with the fixed mass. It's a
// method of the ship's.
void fall(Well well)
{
    // f=(m1 * m2)/(r**2)
    // a=f/m
    // Ship mass is 1, so a = f.
    float mass = 1;
    Vector delta = well.position - loc;
    float rSquared = delta.magSquared;
    float force = well.mass/rSquared;
    accelerate(delta * force * mass);
}


texts: To use Apple's game servers, do I need to enroll in the Apple Developer program?

texts: I am developing a multiplayer iPhone game. To use the Apple game servers, do I need to register for the Apple Developer program?


texts: How can I make a rectangle to an irregular shape?

texts:
I used masking for breaking an image into the below pattern. Now that it's broken into different pieces I need to make a rectangle of each piece. I need to drag the broken pieces and adjust to the correct position so I can reconstruct the image. To drag and put at the right position I need to make the pieces rectangles but I am not getting the idea of how to make rectangles out of these irregular shapes. How can I make rectangles for manipulating these pieces?

This is a follow up to my previous question.