texts: Processing - implement a first person camera?

texts:
First off, I'm sorry if there are duplicates of this. I did an extensive Google search but was unable to find anything that made sense to me. (I am new to 3D rendering and such.)

I want to make a first person camera that the user can control with the mouse. My current implmentation in Processing looks like this:

PMatrix3D cam;
int oldMouseX=0, oldMouseY=0;
void setup(){
    // ...
    cam = new PMatrix3D();
}
void draw(){
    // ...
    int deltaX=oldMouseX-mouseX;
    int deltaY=oldMouseY-mouseY;
    oldMouseX=mouseX;
    oldMouseY=mouseY;
    cam.rotateY((PI/600)*deltaX);
    cam.rotateX((PI/600)*deltaY);
    PVector x = cam.mult(new PVector(1, 0, 0), new PVector(0, 0, 0));
    PVector y = cam.mult(new PVector(0, 1, 0), new PVector(0, 0, 0));
    PVector d = x.cross(y); d.normalize(); d.mult(R);
    float fov = PI/3.0;
    float cameraZ = (height/2.0) / tan(fov/2.0);
    perspective(fov, float(width)/float(height), cameraZ/10.0, cameraZ*1000.0);
    camera(0, 0, 0, d.x, d.y, d.z, y.x, y.y, y.z);
    // render objects
}

It works well, but there is a problem. When the mouse is moved along the x-axis of the screen, and then the y-axis, or in some way one axis at a time, the camera rolls. I understand that 3D rotation is supposed to work like that, 2 consecutive rotations around 2 axes make a rotation around the third. The problem is that once the camera is in this rolled state, it is difficult to get it to be straight again.

How can I make it so it is easy to point the camera in any direction?
Please explain in easy to understand terms, if possible.

Also, I am a bit confused on

cam.rotateY((PI/600)*deltaX);
cam.rotateX((PI/600)*deltaY);

Before, I had it as

cam.rotateX((PI/600)*deltaX);
cam.rotateY((PI/600)*deltaY);

But that cause the x and y axes to be switched. (i.e., moving the mouse horizontally caused the camera to rotate vertically.) Why is this?


texts:
So recently I have been working on a Legend of Zelda: A Link to the Past clone, and I am wondering how I could handle certain map interactions (like cutting grass, lifting rocks, etc).

The way I am currently doing the tilemap is with 2 PNGs. The first is the "tilemap" where each pixel represents a 16x16 tile and the (red, green) values are the (x, y) coords for the tile in the second PNG (the "tileset"). I am then using the blue channel to store collision data.

Each tile is split into 4 8x8 tiles and represented by a 2 bit value (0 = empty, 1 = Jumpdown point, 2 = unused right now, 3 = blocking). 4 of these 2 bit values make up the full blue channel (1 byte). So collisions work great, and I am moving on to putting interactive units on the level; but I am not sure what a good way is to do it.

I have experimented with spawning an entity for each grass and rock, but there are just WAY to many; FPS just dies even if I confine it to the current "zone" the user is in (for those who remember LTTP it had zones you moved between). It does make a difference that this is a browser-based JavaScript game.

tl;dr: What is a good way to have an interactive map without using full blown entities for each interactive item?


texts: How to get the texture coordinate of a neighbouring pixel for a blur shader?

texts:
I'm still having some trouble to get my head around fragment shaders and doing some image processing on textures. The context is a 2D sprite: a simple texture painted on a quad. All done with OpenGL ES 2.0.

My very basic goal is a simple blur filter using a 3x3 Kernel with average weights: every pixel used is weighed 1/9th and summed up.

Besides many ways to improve the performance of the fragment shader(code below) so far I'm still having some difficulties to find the right texture coordinate for the kernel.

My approach so far is to use the actual size of the quad on the screen on which the texture is painted and pass those two values to the shader. This is done outside the shader and passed as a uniform to the shader program.

glUniform2f(_offset, 1 / spriteWidth, 1 / spriteHeight);

This should result in the step in both directions to calculate a texture coordinate in the 0 to 1 space.

The result is kind of looking good. BUT I am still struggling if this is something that could be done within the shader. Is there a way to get the size of the texture within the fragment shader? If we would be only doing this on a bitmap, I'll just go from pixel to pixel and read the color of the surrounding pixels. I am wondering if my understanding of a fragment shader is quite right: It's run per rendered pixel on the screen. I found some examples for the GLSL to do this but I wasn't able to port it to OpenGL ES, so I had to start from scratch.

For the sake of readability I write a bit more code in hope it's easier to understand the fragment shader:

varying vec2 v_texCoord;
uniform vec2 u_offset;
uniform sampler2D u_texture;

const int size = 3;
const int KernelSize = size * size;

void main()
{
    int i, j;

    vec4 sum = vec4(0.0);
    vec4 intensityOfPixel;
    vec2 texCoordForKernel;

    for (i = 0; i < size; i++)
    {
        for (j = 0; j < size; j++)
        {
            texCoordForKernel = vec2(v_texCoord.x + (float(i) - 1.0) * u_offset.x,
                                     v_texCoord.y + (float(j) - 1.0) * u_offset.y);

            intensityOfPixel = texture2D(u_texture, texCoordForKernel);

            sum += intensityOfPixel * 1.0 / float(KernelSize);
        }
    }

    gl_FragColor = sum;
}

Thanks alot in advance!


texts:
Is there a way to convert the below piece of shader code to shader graph?
I am not sure how to find float2(i, i) in shader graph.
fixed4 frag (v2f input) : SV_Target
            {
                float2 res = _MainTex_TexelSize.xy;
                float i = _offset;

                fixed4 col;
                col.rgb = tex2D( _MainTex, input.uv ).rgb;
                col.rgb += tex2D( _MainTex, input.uv + float2( i, i ) * res ).rgb;
                col.rgb += tex2D( _MainTex, input.uv + float2( i, -i ) * res ).rgb;
                col.rgb += tex2D( _MainTex, input.uv + float2( -i, i ) * res ).rgb;
                col.rgb += tex2D( _MainTex, input.uv + float2( -i, -i ) * res ).rgb;
                col.rgb /= 5.0f;

                return col;
            }


texts:
Ive looked up implementing gravity on several sites. Subtract a constant gravity (9.8 * DeltaTime) from the velocity each frame. My problem is, when implementing it as they say, when walking off a ledge the player will float off, not vertically, just accelerates too slowly as he falls.

World->Gravity = -9.8 * PixelsToMeters;   // PixelsToMeters = 32
CurrentAcceleration = Vector2(0.0f, World->Gravity);
CurrentVelocity = (CurrentAcceleration * DeltaTime) + PrevVelocity;
Vector2 halfATSq = currentAcceleration * 0.5f * Square(DeltaTime);
Vector2 vt = CurrentVelocity * DeltaTime;
CurrentDelta = halfATSq + vt;
CurrentPosition += CurrentDelta;

Now the thing is, with the 1/2at^2 + vt + p calculation, the character does fall about 20 meters in 2 seconds, (I think those are the numbers I used, that was a couple hours ago), so it seems the calculations are right. Ive played quite a few side scrollers and none of them have this floating feel.

So, I tried calculating the gravity based on a TimeInAir variable that multiplies the World->Gravity on the third line, instead of DeltaTime.

CurrentVelocity = Vector2(currentAcceleration.X * DeltaTime, currentAcceleration.Y * TimeInAir) + PrevVelocity;

He no longer floats, he falls as expected. Even jumping looks better. However, now he falls 20 meters in 1 second. Ill deal with this, it is only a game and not reality.

Question is, why is it that this works instead of the original code? Or do I have an error somewhere? Because I have to rework the physics code to get it to look right for everything, instead of just using the basic equations. Is it because its all calculated in pixels? Im wondering if I need to add a full gravity to the velocity on the first frame instead of gravity * DeltaTime? This works for falling off a ledge, but not for jumping.

Im testing these questions as I think of them in my code, and still not getting it. These ideas dont seem to work. Thanks for looking and whatever help or ideas you can give!


texts: How to implement a clipped shadow in 2D?

texts:
I want to create a shadow effect similar to the one found in JoyMasher's Blazing Chrome.

Notice that the shadow clips when you're on a ledge, and projects to the geometry below.

Currently, my shadows are just sprites which I disable when the character is not grounded.

I don't care how JoyMasher did it, I just want to achieve something similar.

How might I achieve an effect similar to the one in Blazing Chrome?

I am working in Godot, but would be fine with an engine-neutral description of a technique.

I have access to all the normal stuff (raycasts, shaders, and so on). That said, I am working in pure 2D, so I can't use any kind of 3D light source emitting downward to achieve the effect.


texts: Which memory is used in D3D12 resources?

texts:
According to MSDN there are three types of memory in D3D12, commited resources, placed resources and reserved resources. I do not understand where they are. Are they in RAM? Are they in VRAM? Are they memory mapped somehow so they are both in RAM and VRAM at (approximately?) the same time?

Realised I might have misunderstood memory mapped memory, perhaps it is just an abstraction for sending things over PCIe, not something that goes to RAM and then somewhere else.


texts: How can I animate a recursive algorithm?

texts:
Say I have a recursive algorithm, for example one that generates a random tree:

// Pseudocode, just a simple algorithm: it isn't perfect.
function generate_branch(angle, length, current_depth, max_depth) {
  var branch = Branch(angle, length); // creates a new branch
  if (current_depth == max_depth) {
    return branch;
  }
  current_depth++;
  // random_int(min, max)
  branch.subbranches[] = generate_branch(random_int(0, angle + random_int(-30, 30)),
                                         random_int(0, 20)
                                         current_depth,
                                         max_depth);
  // ^^^^ recursion
  return branch;
}

var trunk = generate_branch(0, random_int(10), 0, 5);
RenderTree(trunk);

The problem is that this will render the entire tree in one frame. If I want to animate this (i.e. grow the tree over time), how would I do that? What is the best way to do this?

The game uses a game loop.


texts: Do shader compilers typically know not to look up unused texture channels?

texts:
I have a texture that's from the color attachment of an FBO in OpenGL ES 2.0, so I have limited control over the number of channels in the image.

Suppose I only need the color from the R channel of this texture. If I immediately swizzle out the R in the fragment shader like this:

float brightness = texture2D(u_texture, v_texCoord).r;

can I expect the GPU to know not to bother looking up G, B, and A?

I figure this is something that might vary from device to device, depending on the optimizations of the shader compiler, but to me this looks like a very obvious and easy optimization.

I'd like to know if I can be reasonably confident that almost all GPUs will make the optimization. This shader is a multiple-texture shader, and I'd hate to get surprised by some percentage of devices running it much slower than what I've tested on. If I cannot, then I may want to take pains to use a different method of generating my image so I can ensure a texture with fewer channels.


texts: How to parent object to empty when looked at

texts: I am making a fps in unity. I have an empty parented to the camera for the gun, and I want to be able to pick up and drop guns found in the scene. Does anyone have a simple c # script that would allow the player to look at the gun on the ground, press a key and have it be parented to the empty? I would also like for the player's old gun to drop on the floor where the one being picked up was and un-parent from the empty when the new gun is picked up. If you want an example I guess you could say it is like halo where you can go around and pick up new guns. I am not looking to make an inventory, just a simple script where you can swap your weapon.


texts: Multiple colored textures vs Color Overlay

texts:
Let's say we're using DirectX 9/10/11. In our game we have a character wearing armor.

The armor has 50 different color variations.
So, if armor is red, the first method would load the red texture from file.
The second method would display the 1 base texture, with a red overlay.

Code wise the overlay armor would just contain an extra flag that would specify color.

Is it faster / more efficient to load different textures in? Or, is it faster / more efficient to color the texture on the fly?

I'm not aware if there is some huge overhead for dropping a tint over a texture...


texts: Interpolate object collision stuck in Unity

texts:
I am working on a very basic test in 2D. The problem I am having is that, when my sprite collides with the ground, it is checking the event too frequently. The sprite stays in limbo, as it doesn't have a chance to leave the ground. By the time it does, the check tells it to turn around, resulting it quickly going up and down. I uploaded an example clip to YouTube.

When contact is made, the sprite needs to change it's Y axis direction. How do I fix this? Please see my code, below:

void Update ()
{
    hitWall = Physics2D.OverlapCircle(wallCheckUp.position, wallCheckRadius, whatIsWall);

    if (hitWall)
    {
        moveUp = !moveUp;
    }

    if (moveUp)
    {
        transform.localScale = new Vector3(-1f, 1f, 1f);
        GetComponent<Rigidbody2D>().velocity
            = new Vector2(speed, GetComponent<Rigidbody2D>().velocity.x);
    }
    else
    {
        transform.localScale = new Vector3(1f, 1f, 1f);
        GetComponent<Rigidbody2D>().velocity
            = new Vector2(-speed, GetComponent<Rigidbody2D>().velocity.x);
    }
}

Here is my object:


texts: What is the best way to make a main menu system?

texts: I know that's it's easy to make buttons that highlight when you move your mouse over them, but when it comes to sub-menus I'm kinda stuck. Anyone got some tips on the best way to have a main menu with sub-menus? (like Singleplayer -> Load Save -> Save 1-5? -> Start game etc.)


texts: Separating physics and game logic from UI code

texts:
I'm working on a simple block-based puzzle game.

The game play consists pretty much of moving blocks around in the game area, so it's a trivial physics simulation. My implementation, however, is in my opinion far from ideal and I'm wondering if you can give me any pointers on how to do it better.

I've split the code up into two areas: Game logic and UI, as I did with a lot of puzzle games:

The game logic is responsible for the general rules of the game (e.g. the formal rule system in chess)
The UI displays the game area and pieces (e.g. chess board and pieces) and is responsible for animations (e.g. animated movement of chess pieces)

The game logic represents the game state as a logical grid, where each unit is one cell's width/height on the grid. So for a grid of width 6, you can move a block of width 2 four times until it collides with the boundary.

The UI takes this grid, and draws it by converting logical sizes into pixel sizes (that is, multiplies it by a constant). However, since the game has hardly any game logic, my game logic layer [1] doesn't have much to do except collision detection. Here's how it works:

Player starts to drag a piece
UI asks game logic for the legal movement area of that piece and lets the player drag it within that area
Player lets go of a piece
UI snaps the piece to the grid (so that it is at a valid logical position)
UI tells game logic the new logical position (via mutator methods, which I'd rather avoid)

I'm not quite happy with that:

I'm writing unit tests for my game logic layer, but not the UI, and it turned out all the tricky code is in the UI: Stopping the piece from colliding with others or the boundary and snapping it to the grid.
I don't like the fact that the UI tells the game logic about the new state, I would rather have it call a movePieceLeft() method or something like that, as in my other games, but I didn't get far with that approach, because the game logic knows nothing about the dragging and snapping that's possible in the UI.

I think the best thing to do would be to get rid of my game logic layer and implement a physics layer instead. I've got a few questions regarding that:

Is such a physics layer common, or is it more typical to have the game logic layer do this?
Would the snapping to grid and piece dragging code belong to the UI or the physics layer?
Would such a physics layer typically work with pixel sizes or with some kind of logical unit, like my game logic layer?
I've seen event-based collision detection in a game's code base once, that is, the player would just drag the piece, the UI would render that obediently and notify the physics system, and the physics system would call a onCollision() method on the piece once a collision is detected. What is more common? This approach or asking for the legal movement area first?

[1] layer is probably not the right word for what I mean, but subsystem sounds overblown and class is misguiding, because each layer can consist of several classes.


texts:
I have a world space canvas in front of the player and I want to shoot a ray towards an enemy (in the direction of the enemy) and create and object where Raycast hits the UI canvas.
I know that the physics engine doesn't interact with UI elements and event system is not the answer for me since it depends on pointer events and their position.
So how can I do this?
If possible, I would like to draw the ray or the line as gizmo to see if it's working.
My Current Code is this:

void OnDrawGizmos()
{
    foreach (AeroplaneAiControl item in GameObject.FindObjectsOfType<AeroplaneAiControl>())
    {
        Gizmos.color = Color.magenta;
        Gizmos.DrawLine(transform.position, item.transform.position);
        Vector3 Direction = transform.position - item.transform.position;
        RaycastHit rch;
        Ray r = new Ray(transform.position, Direction);
        Physics.Raycast(r, out rch);
        if (rch.collider != null)
        {
            Gizmos.color = Color.cyan;
            Gizmos.DrawLine(transform.position, rch.point);
            Gizmos.DrawSphere(rch.point, 0.1f);
        }
    }
}

it draws the magenta line but not the cyan line and no spheres.


texts: Is there a simple way to do true isometric projection with an HTML5 canvas?

texts: Is there a simple way to get a true isometric projection with the HTML5 canvas element?


texts:
I have tried using IEnumerator and Invoke("method",delay_in_seconds).
My first scene is just an image with my studio name on it. I have script that will load the next scene ("Main Menu") 3 seconds after the first scene is loaded.
For this, I tried using IEnumerator and Invoke with 3 seconds delay before calling Application.LoadLevel.

However, on the device, game is launched, unity splash screen is displayed and "Main Menu" scene appears. it looks like the image scene loads while  unity splash screen is displayed and by the time unity screen is completed, the image scene has done executing.

Is there any way to ensure a scene stays on screen before loading the next scene? I could add a button that player should tap to start game. But I don't want to do that.


texts: Quaternion rotation around center, undefined behavior

texts:
Here's my code:

vec4 qx, qy, qz;
mat4 mx, my, mz;

// rotating using quaternions
glm_quat(qx, to_radians(a->rx), 1.0f, 0.0f, 0.0f);
glm_quat(qy, to_radians(a->ry), 0.0f, 1.0f, 0.0f);
glm_quat(qz, to_radians(a->rz), 0.0f, 0.0f, 1.0f);

// turning the quaternions into matrices
glm_quat_mat4(qx, mx);
glm_quat_mat4(qy, my);
glm_quat_mat4(qz, mz);

mat4 trans = {
    1, 0, 0, 0,
    0, 1, 0, 0,
    0, 0, 1, 0,
    0, 0, 0, 1
};

mat4 rot = {
    1, 0, 0, 0,
    0, 1, 0, 0,
    0, 0, 1, 0,
    0, 0, 0, 1
};

mat4 final;

// combining the rotations into one.
glm_mat4_mulN((mat4* []){&mx, &my, &mz}, 3, rot);

// translating the `trans` matrix.
glm_translate(trans, (vec3){ a->x, a->y, a->z });

// finally combining the translation with the rotation into one.
glm_mat4_mul(trans, rot, final);

My desired behavior is that the object rotates around its center, but here is what happens instead:

So , it seems that my object is rotating around some weird other undefined point.
I have no idea why this happens.

Any ideas? Thank you.


texts:
I'm interested in how huge games like The Witcher 3 and Skyrim create and save the open worlds. In my own game I used a system where I stored the map data in a file seperated by commas. For example 'stone' would code for a stone tile, and I just typed in codes for how I wanted my map to appear in the game.

I feel like this was a really innefficient and incorrect way of doing things. But, I couldn't think of a different way to get past the problem.

The creators of skyrim obviously used a level editor, but how did they actually save a map as big as skyrim's world? How is the data stored? Because with something as intricate as an amazing, 3D world, you can't store it like I did by just having codewords for different tiles that are all the same height and width.

How is it done in 2D games as well? For example Ori and the Blind Forest, which does not use a tile-based system. Or, in fact, do they not have files that hold data for the level layouts at all?

Thanks :)


texts:
I want to use the Sprite Atlas in Unity for enhanced rendering performance, but everytime I try to pack sprites into the atlas they appear with severe artifacts.

As you can see, there are blocks of black pixels that appear that aren't supposed to be there. Here is what the gun should look like:

Here are all my settings for the sprites and atlas:

How can I prevent these artifacts from appearing?


texts:
I am throwing a ball using this:

        double v, vx, vy, alpha, t2 = 0;
   if (Keyboard.GetState().IsKeyDown(Keys.Up))
        {
            alpha = MathHelper.ToRadians(60f);
            v = -1230d;
            vy = v * Math.Sin(alpha);
            vx = v * Math.Cos(alpha);

            ball2pos.Y = (float)((vy * t2) + (g * t2 * t2 / 2)) +  graphics.GraphicsDevice.Viewport.Height - ball2.Height;
            ball2pos.X = (float)(-vx * t2);
            t2 = t2 + gameTime.ElapsedGameTime.TotalSeconds; }

It works without a problem. It calculates the throw including the gravitation (g). vx is how much it moves per second on the X,vY the Y accelerration (running against gravity), v the strength of the throw and t2 the current time.

But I want to change the formula to throw the ball to a given destination. Say I want to throw my ball from 60 degrees to a target. How much "strength" do I need for it?

What would be the formula? I'm not really good at figuring out that and google doesn't give me what I want.
To simplify let's assume that the Y of source and target are the same:

Given: Angle, SourceLocation, TargetLocation, Gravitation

Looking for: Strength


texts: I have a rigged model using an armiture in blender, I was wonder how you could bake the animation as kayframed data so that I could remove the armiture and the model still walks without being rigged.


texts:
I am developing a top down shooter and my singleplayer is pratically finished so now I want to move on to develop multiplayer but I have some questions and I am seeking for some advices.
In my game a match is constituted by a character(two in a multiplayer match) , monsters, projectiles, boosts and spawn points.
Here is my initial solution:
Characters- Send to the game server my character(position, if it´s dead or not,currentHealth,etc) and receive the other player character from the server. Thinking about using UDP because I want real time positions
Monsters- My strategy for this one is having the server randomly choosing one of players´computer to handle the spawn of the monsters .The list of monsters is sent to the server and the other player gets it. Thinking about using TCP because a lost package would imply that the round will have less monsters than it should have
Projectiles- When a player clicks the left button to shoot a projectile, the input is sent to the server. This means that the projectiles list would be instanciated in the server and both players will have to get it from it. 99% sure I will use UDP because a lost projectile wouldn´t have a major impact on the match.
Boosts- Probably the same strategy as the monsters. Pretty sure I will be using TCP because if the boost doesn´t spawn in that round it completely alters the match.
I am looking for critics to the strategies I am planning to implement as well as some advices


texts: Naming a weapon during game development: is using the actual model name in real life against copyright?

texts:
I was planning to name each weapon at the weapon shop and I was wondering if it is safe to use the real name of each weapon and model as well before publishing it via Google Play Store for my created game app? I'm using a freemodel method with ad banner on menu on it, user friendly. I'm making a concept third-person shooter zombie survival game.

I'm checking some other sample of the games, (other than from mobile app) one from the gamer console's classic in PlayStation 1 game Syphon Filter; and the other one from the PC, a popular online FPS game created by Korea called CrossFire. Let's take a comparison's similar of the gun (both gun model name and the model itself) used between these two:

In Syphon Filter, the name of this assault rifle is PK-102. (See gameplay video here) It was based either a model from AK-47, AK-74, or AK-102 assault rifle in metalic like body.
In CrossFire, the name of this assault rifle retained the original name AK-47 along with the model itself. (See video gameplay here.) It assumed they take for a permission to use the original name before using it.

I want to know more further if it is safe to use the model name only but not mentioning the corporation name who created the AK-47. Naming a gun could be striking, same thing naming the actor of the game. If not, probably if it is also okay to name close to the original but at least it's not against the copyright standards.


texts: Can MoonSharp call functions from static classes?

texts:
My question is very simple. I'm using MoonSharp to add Lua scripting to my game. One use case involves calling a static artificial intelligence function from a static class I've implemented in C#. I know you can easily call static functions using MoonSharp, but can those functions be called if the class is static?

I haven't been able to find an answer so far through Google or on this site. My own experimentation with code hasn't been successful either. There are pretty simple workarounds for the problem I'm asking about (like making the AI class not static), but I'd prefer to avoid them.

Thank you :)


texts: Is there an open source rhythm / music game framework?

texts:
I'm trying to build a very simple rhythm game (as a one-off art installation, not a commercial project) demonstrating a novel controller, but I've got an extremely short timeframe to do it in. Are there any open-source rhythm games or frameworks out there that I could use instead of writing such a game from scratch?

I could probably bang the code together in PyGame or Processing over a few days, but any time I can save on programming can be spent instead on the physical build, which would make the overall installation better.  The requirements for the game itself are super simple -- I just need to scroll notes across the screen, register points based on how well the player matches them, and play a song (ducking one of the channels when a note is missed).

The custom controller is Arduino-based, sending its data as bytes over a serial port, so I don't need any fancy DirectX support. Just something that can run with <60ms latency.


texts: LibGDX - Textures rendering at wrong position

texts:
Update 2:

Let me further explain my problem since I think that i didn't make it clear enough:
The Y-coordinates on the bottom of my screen should be 0. Instead it is the height of my screen. That means the "higher" i touch/click the screen the less my y-coordinate gets.
Above that the origin is not inside my screen, atleast not the 0 y-coordinate.

Original post:

I'm currently developing a tower defence game for fun by using LibGDX.
There are places on my map where the player is or is not allowed to put towers on.
So I created different ArrayLists holding rectangles representing a tile on my map. (towerPositions)

for(int i = 0; i < map.getLayers().getCount(); i++) {
            curLay = (TiledMapTileLayer) map.getLayers().get(i);

            //For all Cells of current Layer
            for(int k = 0; k < curLay.getWidth(); k++) {
                for(int j = 0; j < curLay.getHeight(); j++) {
                    curCell = curLay.getCell(k, j);

                 //If there is a actual cell
                if(curCell != null) {
                    tileWidth = curLay.getTileWidth();
                    tileHeight = curLay.getTileHeight();
                    xTileKoord = tileWidth*k;
                    yTileKoord = tileHeight*j;

                    switch(curLay.getName()) {

                     //If layer named "TowersAllowed" picked
                    case "TowersAllowed":
                        towerPositions.add(new Rectangle(xTileKoord, yTileKoord,  tileWidth, tileHeight));

// ... AND SO ON

If the player clicks on a "allowed" field later on he has the opportunity to build a tower of his coice via a menu.
Now here is the problem: The towers render, but they render at wrong position. (They appear really random on the map, no certain pattern for me)

for(Rectangle curRect : towerPositions) {
            if(curRect.contains(xCoord, yCoord)) {

                //Using a certain tower in this example (left the menu out
                if(gameControl.createTower("towerXY")) {

                    //RenderObject is just a class holding the Texture and x/y coordinates
                    renderList.add(new RenderObject(new Texture(Gdx.files.internal("TowerXY.png")), curRect.x, curRect.y));
                }
            }
        }

Later on i render it:

game.batch.begin();
    for(int i = 0; i < renderList.size() ; i++) {
        game.batch.draw(renderList.get(i).myTexture, renderList.get(i).x, renderList.get(i).y);
    }
game.batch.end();

regards


texts:
Usually easing equations have 4 parameters:

time
duration
begin point
end point

For example:

public static float EaseOutQuad(float currTime, float begin, float end, float duration)
{
    currTime /= duration;

    return -end * currTime * (currTime - 2f) + begin;
}

Now afaik begin and end point are fixed values.
In my game I have an object oscillating between 2 points on its local X axis. I'm interpolating its position using easing equations, but I would like to be able to modify the end point dynamically avoiding discontinous or abrupt changes.

Is it possible to do this using easing equations or something similar?
Any suggestion?


texts: Adding 2D vector movement with rotation applied

texts:
I am trying to apply a slight sine wave movement to objects that float around the screen to make them a little more interesting. I would like to apply this to the objects so that they oscillate from side to side, not front to back (so the oscillation does not affect their forward velocity).

After reading various threads and tutorials, I have come to the conclusion that I need to create and add vectors, but I simply cannot come up with a solution that works.

This is where I'm at right now, in the object's update method (updated based on comments):

Vector2 oldPosition = new Vector2(spritePos.X, spritePos.Y);

//note: newPosition is initially set in the constructor to spritePos.x/y
Vector2 direction = newPosition - oldPosition;

Vector2 perpendicular = new Vector2(direction.Y, -direction.X);

perpendicular.Normalize();

sinePosAng += 0.1f;
perpendicular.X += 2.5f * (float)Math.Sin(sinePosAng);

spritePos.X += velocity * (float)Math.Cos(radians);
spritePos.Y += velocity * (float)Math.Sin(radians);

spritePos += perpendicular;

newPosition = spritePos;


texts:
So I'm creating a Unity project that has a bunch of buttons (like hundreds) that each do a different thing when pressed.  This is a 3D project and these buttons are also 3D.  I already know how to detect if the player has pressed a button, so I just need to know how to attach an action to one of these buttons.

Should I create a script for each?  From what I've found, it's very memory-expensive and will definitely drop FPS especially for hundreds of buttons.

Should I try to use a UnityEvent?  I don't know if this helps for what I'm doing...?


texts: "Running" against a steep slope on a Box2D Platformer

texts:
Ive seen alot of pages talking about how to emulate a platformer on Box2D, specially about how people dont want to slide down a slope. Well, my problem is different and Im surprised I cant find posts/solutions about it.

The problem happens when I have a very steep slope and I run against it. This is what happens:

Being the square a common platformer hero fixture, since in a Box2D platformer the movement is based on applying impulses or setting the velocity, what happens when I "move" torwards such a slope, its like im pushing against it, which creates a vertical force and therefore the square moves UP (specially since friction is 0 to avoid the "sticking to a wall" thing).

I've solved most of Box2D's non-platformer-proficient issues. This one seems unsolveable.

So, how do I avoid my object to go up a steep slope when pushed against it, and instead slide down since its too steep to be climbed?


texts: Alpha Value at 0 Shows Black for Android Canvas Bitmap

texts:
There have been a few questions similar to this but none seem to give a straight answer. If I am creating a Bitmap from a .png image and want to set a color (i.e. true pink) to transparent, the color turns black instead. I am using get and set pixel methods, iterating through an array of pixel colors.

The method I wish to accomplish this in is as follows:

public Bitmap getFormattedBitmap(Bitmap bm, int newHeight, int newWidth, int r, int g, int b, int a) {
int width = bm.getWidth();
int height = bm.getHeight();
int pixNum = width * height;
int[] pixels = new int[pixNum];
int scaleWidth =  newWidth * width;
int scaleHeight = newHeight * height;

bm.getPixels(pixels, 0, width, 0, 0, width, height);

for(int k = 0; k < height; k++) {
   for(int j = 0; j < width; j++ ) {
        int red   = Color.red(bm.getPixel(j, k));
        int green = Color.green(bm.getPixel(j, k));
        int blue  = Color.blue(bm.getPixel(j, k));
        int alpha = Color.alpha(bm.getPixel(j, k));
        int index = k * width + j;

        if(red == 0 && green == 0 && blue == 0 && alpha == 255) {
            pixels[index] = Color.argb(a, r, g, b);
        }
        else {
            pixels[index] = Color.argb(0, 255, 255, 255);
        }
    }
}

bm.setPixels(pixels, 0, width, 0, 0, width, height);

Bitmap resizedBitmap = Bitmap.createScaledBitmap(bm, scaleWidth, scaleHeight, true);
return resizedBitmap;

}

As you can see, I am using the Color.argb() method to set the alpha to 0, but in reality, it just shows those parts as black on the screen. I recognize bitmaps don't take kindly to alpha channels (unless you configure it to ARGB_8888), but this has me stumped.  It is also interesting to note that I do have SOME control of alpha via the Color.argb() method, it is just if it is too close to 0 it turns black anyway. Something in that method or whatever I am doing does not like full transparency apparently.


texts:
as you might expect, I have got a game in development, including a main character—fortunately…

This character is on the one hand represented by a bunch of Box2D bodies and on the other hand, graphically, by a bunch of SVG-Elements. The character is a floating one, a kind of Hovercraft, basically based on this tutorial, but more sophisticated all in all.

The character can jump, too. To visualize the impulse, which gives the »jump-power« some fire blow out of its very ass straight ahead, what should be animated, during its short visible time.

Question: How to animate that bespoken fire? I could use plain css, or JavaScript, or even SVG-Animation Tags themself, BUT I would like to ask for the preferred weapon of choice, faced to the fact that time is running out (less than 3 days) AND flexibility needed for the customer?

Intentionally I am not posting any code, since I can imagine a solution based on each one of the methods mentioned above, this question is meant to issue the pros and cons, due to time and flexibility.

In this case, all graphics (world, fire, ass, character) are given in SVG and are meant to be displayed as that, whereby the connection between physics and graphics is established by the use of R.U.B.E. I am searching for the most painless way of realization for the ass on fire.

Thanks for reading and
kind regards to the community!


texts:
Is there a data source for 90 and 75 ball bingo tickets? rather than coding to generate the tickets myself just trying to find a source to save me the time.

Many thanks


texts:
This subject, as with any optimisation problem, gets hit on a lot, but I just couldn't find what I (think) I want.

A lot of tutorials, and even SO questions have similar tips; generally covering:

Use GL face culling (the OpenGL function, not the scene logic)
Precalculate anything you can
Use interleaved Vertices
Minimize as many GL calls as possible, batch where appropriate

And possibly a few/many others. I am (for curiosity reasons) rendering 28 million triangles in my application using several vertex buffers. I have tried all the above techniques (to the best of my knowledge), and received almost no performance change.

Whilst I am receiving around 40FPS in my implementation, which is by no means problematic, I am still curious as to where these optimisation 'tips' actually come into use?

My CPU is idling around 20-50% during rendering, therefore I assume I am GPU bound for increasing performance.

Note: I am looking into gDEBugger at the moment

Cross posted at StackOverflow


texts: Simple Tanks game - Client-Server communication approach doubts

texts:
I want to create simple a multiplayer 2D game with tanks ( cooperative ) in C# with .NET.
I also want to keep it simple, because it is only a semester project, and unfortunately i don't have time to learn additional game engines like Unity.

So, can i do it without Unity, XNA or other game engine ?
If yes, here is an architecture/design problem that i am facing:
How should i notify the two players regarding the position of the other player on the map, the position of the bullets and the position of the enemies ?

Should i query the server at 50-100 ms intervals and get a list of JSON messages containing positions and states ( a tank exploded ) ?
Should i send a message from server regarding a bullet let's say, bullet no.1 started from x,y heading on axis y, then in the client, i will draw it until i will receive like an interrupt in case it hits an obstacle ( a tank that was passing by) ?

The first option seems more simpler, but it will kill the server in a real life ( 100000 players ) situation.
The second seems like on overkill and over-engineering from client side.

Any other suggestions ?
Thanks


texts: Authorization in scaling multiplayer game

texts:
I have an architectural problem associated with authorization.

I'm making an MMORPG multiplayer mobile game without separation onto different servers. What I mean by that is that a player from USA could have a mission with someone from China.

Currently I have an authentication microservice that issues JWT tokens. Another types of microservices are game microservices that handles all game logic. By design they would scale to meet the demand.

Every account can have multiple characters created, but only one can be online at the time.

My question is: How can I ensure that only 1 character can be online? Do I attach selected character to JWT? But the player can request another JWT with another character and the previous one would be valid as well until it expires. In this case I would need to look up database with every request, but that defies the purpose of JWT. Should I be using JWT or is there another way authorize players?


texts: Is showing a collision in slow motion computationally relaxing?

texts:
In a lot of racing games (Burnout Paradise, for example) when a collision is about to happen, the game play automatically switches to slow motion and carries on in slow sequence until after the collision is complete.

I always thought this was for the effects. You don't want to miss any part of the collision! But one of my friends recently suggested that this is done to make sure there is not an overwhelming rate of processing required when a collision happens.

Now I think it is actually the other way round. When a collision happens, so many details are shown in slow motion, I am sure there is an overhead on the computing and rendering pipeline.

What is correct?

Does a slow motion scene increase CPU / GPU usage, or decrease it?


texts:
I was starting to develop a 2D game in Java and Android Studio, using SurfaceView. My idea was to make my first engine to understand how game engines work, and also get complete of control over the game flow.

I have had many problems, such as FPS, and handling the stop and resume functions. On the other side, I see many 2D games made with Unity that work very nice.

What does Unity use for 2D rendering on an Android?


texts:
The game I'm developing is close to Pokemon. How should I store the data? I am currently thinking of text files where I save the map and have a corresponding textfile for the trainers and their teams on the "current" screen. However this leaves me with a LOT of textfiles.

At the moment I'm thinking of something like this, however I haven't coded this yet so I can still easily change this.

@Trainer;5;
@Pokemon;12;1;3;4;6;
@Pokemon;13;1;2;5;
@Pokemon;13;1;4;5;
@Pokemon;11;1;3;5;
@Pokemon;16;1;2;7;
@Trainer;3
@Pokemon;13;1;4;5;
@Pokemon;11;1;3;5;
@Pokemon;16;1;2;7;

Where the first column is the "type" of the entry. If the first is Trainer the second is his number of Pokemon. If the first is Pokemon the second is the level, the third the type, the fourth/fifth/sixth the IDs of his attacks. (How should I store the attacks? A seperate textfile where I just store the attacks?)

I am currently finding myself with having such a huge amount of data that I'm starting to wonder wether I should be using a Database instead?

Edit:
Using Java(LWJGL).


texts: Slick2D Tile Based 'Fog of War' Blurring Problem

texts:
I'm working on my first Java Game and I have run into a little problem I'm hoping to get some help with.  I'm using Slick2D displaying a tile based map, and I'd like to know how I can created a "blurred" fog of war.

Here you can see the fog of war covering most of the map, I am rendering the fog by filling a rectangle over each tile who has the property isFog = true.

When the climber goes to a tile isFog sets false, and the map is re-rendered.

I'm looking for a way to create a smoother fog like in this poor paint.net image.

Please let me know what ideas you might have. Thanks!

Apparently I can not post images yet... I will update when I've earned enough reputation.


texts:
First off, I own Unity Pro.

I've been looking in to occluding lights when they aren't being viewed for a while now to improve performance. The main methods I ran in to were using BecameVisible() and testing the camera frustum.

My main problem was that if the player is viewing an area that would be lit by the light, I still want the light to be on.

Currently I'm using a method which checks to see if the lit area is in the camera frustum, but the problem is sometimes lights are in the frustum without actually being visible by the player (e.g. a wall between them and the player). I've tried raycasting to them but you can never get detailed enough for the actual lit area (the best I could figure was using renderer.bounds.extent and renderer.bounds.center to calculate the maximum lit points from the light).

Does anyone know of an easy way in Unity Pro to occlude lights? Or could you tell me a good way to use that camera fulcrum method I was talking about?


texts: How do I implement pixel-exact collision server-side?

texts:
Recently I made a 2D offline game with HTML5 Canvas and JavaScript.  I'm detecting collisions by first checking whether image bounding boxes overlap.  If they do, I check against the bounding boxes, to see if there are any pixels that exist in the same location for both images.

I learned the technique from this tutorial (YouTube).

Now I'm making a multi-player version of the game, in a client-server configuration.  I've decided to have the server handle all physics, including collision.

However, I'm not sure how to implement that. Since the images are drawn client-side, the server cannot access image's data to do the pixel collision tests.  I can make bounding boxes on the server side, but how do I detect pixel collisions?

Tech details: I intend to write the server in node.js, using either CouchDB or MongoDB as my database.


texts:
I have recently read about how to create procedural worlds... but how do I save one?

In games like Terraria or Minecraft users can freely modify the landscape, but that world can't be recreated from the start seed. What techniques are used to save procedural but modifiable worlds?


texts: How to avoid checking the same triangle twice in collision detection with spatial hashing

texts:
I'm implementing a spatial hashing system to speed up my collision detection, but I've run into a problem. Since a triangle can be hashed into multiple buckets, how do I ensure that I don't check the same triangle multiple times?

I've though about having each struct Triangle have a list of pointers to each triangle it has been checked against, as well as a double lastTimeChecked. That way, if the lastTimeChecked was less than the current time, I would know all that data was invalid. This seems inefficient because I am guessing I would have to have this list be a std::vector since I won't know ahead of time how big the list should be.

Then, each time I want to check one triangle against another, I check each triangle's list of triangles it has been checked against to see if either has been checked against the other. Is this the most efficient way to do it?


texts: Volume that encompasses the whole scene?

texts:
I'm thinking that the straight-forward way would be to just iterate through the objects and just find the maximum and minimum coordinates on each axis, but this seems a little bit unoptimal.

Is there a faster, more efficient way of doing this?


texts:
I want to simulate a simple force-acceleration (rather than impulse-velocity) physical world made up entirely of disks and I'm having an irritating problem with my physics.

When two disks collide, I can calculate the changes in velocities quite easily using conservation of momentum and conservation of energy. Since this is going to be a force-based simulation, I need to calculate the forces to apply. I thought I'd use the momentum-impulse equality:

mΔv = FΔt

Sounds simple, except I don't know what to do with time(Δt). So I guess the question boils down to this: how long does the collision take? Or rather, do the two objects stick together for a period of time (Δt)?


texts: sf::Shader not working properly on texture

texts:
I'm having trouble getting my sf::Shader to work on an sf::Texture that I've drawn myself. The vertex shader is pretty standard (I think it's just a copy of the example from SFML's page). The fragment shader is from somewhere in their forums, I'm new to glsl, but my understanding is it takes in a vec3 for the light position (I'm using the mouse position) and then figures the distance to/from the fragment (which comes from the other shader?) and then uses that to determine how light/dark things should be.

It works really well for the rectangle shape I had drawn, but when I try to use the sf::Texture, it shows up regardless of where it is. However -- it does get lighter as the light moves toward it (just not darker/disapear when the light gets farther).

Here is the texture being shown when it shouldn't:
View post on imgur.com

Here is the texture being light really bright when the light gets near it:
View post on imgur.com

Here is my vertex shader:

uniform sampler2D texture;

void main()
{
  // transform the vertex position
  gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;

  // transform the texture coordinates
  gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;

  // forward the vertex color
  gl_FrontColor = gl_Color;
}

And here is my fragment shader:

uniform sampler2D texture;
uniform vec3 light;

void main() {
     float distance = sqrt(pow(gl_FragCoord.x - light.x, 2) +
               pow(gl_FragCoord.y - light.y, 2));

     if(floor(light.x) == floor(gl_FragCoord.x) &&
        floor(light.y) == floor(gl_FragCoord.y))
       distance = 0.1;

     if(distance>light.z)
         distance = light.z;

     vec2 pos = gl_TexCoord[0].xy;

     gl_FragColor = mix(texture2D(texture,pos),
            gl_Color,
            1.0 - (distance/light.z));

}

As for loading/rendering, the shader loads with no error using loadFromFile() and then I create a sf::RenderStates, attaching my shader and setting the parameter "texture" to sf::Shader::CurrentTexture.

The cyan square is just a sf::RectangleShape and the poorly drawn bricks are a png file, loaded to a sf::Texture attached to a sf::Sprite.

The rendering code isn't much:

window.clear();
window.draw(rect, renderState);
window.draw(sprite, renderState);
window.display();

Any help would be much appreciated! If you need any more code / info, let me know.

Thanks!


texts:
I am just starting learning XNA for developing Windows Phone games. I am stumbling accross different sample codes featuring different approaches on handling things.

A question for the experts... or at least for people who already have experiences with that topic:

Does it make more sense to inject instances of SpriteBatch via the constructor of game objects or adding the SpriteBatch object to the GameServices collection and retrieving it from the game objects' constructor like so:

spriteBatch = Game.Services.GetService(typeof(SpriteBatch)) as SpriteBatch;


texts: What is "cold storage" in the context of larger MMOs?

texts: What is a cold storage and what is it used for? I'm not sure if I should use cold storage in my game. I heard it can be used for chat logs, however I'd rather someone here answer all my questions.


texts: How to create a 3D world with 2D sprites similar to Ragnorak online?

texts:
As far as I know Ragnorak Online is a 3D game world with 2D sprites overlayed. I would like to use this style in a game I am making in Unity, so I would like the player to be able to select little square tiles on the terrain.

There are a couple routes I could take such as using a bunch of cubic polygons and linking them together or using one big map. The former approach doesn't seem to make any sense if the world is not flat as polygons wouldn't be reused often. The goal is to break down a 3D polygon into tiles which is hard to wrap my head around.

I believe using something like an interval tree or array would be appropriate to store the rectangle grid, but how would I display a rectangle around the selection the player has his mouse over on the polygon terrain itself?

Here is a screenshot.
Here is a gameplay video.
Here is the camera usage.


texts: OpenGL: Attempt to allocate a texture too big for the current hardware

texts:
I'm getting the following error:

  java.io.IOException: Attempt to allocate a texture to big for the current hardware
    at org.newdawn.slick.opengl.InternalTextureLoader.getTexture(InternalTextureLoader.java:320)
    at org.newdawn.slick.opengl.InternalTextureLoader.getTexture(InternalTextureLoader.java:254)
    at org.newdawn.slick.opengl.InternalTextureLoader.getTexture(InternalTextureLoader.java:200)
    at org.newdawn.slick.opengl.TextureLoader.getTexture(TextureLoader.java:64)
    at org.newdawn.slick.opengl.TextureLoader.getTexture(TextureLoader.java:24)

The image I'm trying to use is 128x128.

System.out.println(GL11.glGetInteger(GL11.GL_MAX_TEXTURE_SIZE));

I get: 32.

32??!! My graphics card is AMD Radeon HD 7970M with 2048 MB GDDR5 RAM, I can run all the latest games in 1080p and 60fps with no problem, and those textures sure as hell doesn't look like they are 32x32 pixels to me!

How can I fix this?

--

Edit: Here's the chaos code I use to init OpenGL:

Display.setDisplayMode(new DisplayMode(500,500));
Display.create();
if (!GLContext.getCapabilities().OpenGL11) {
    throw new Exception("OpenGL 1.1 not supported.");
}
Display.setTitle("Game");
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
GLU.gluPerspective(45, 1, 0.1f, 5000);

Mouse.setGrabbed(true);

glMatrixMode(GL_MODELVIEW);

glLoadIdentity();
glEnable(GL_TEXTURE_2D);
glClearColor(0, 0, 0, 0);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glEnable(GL_POINT_SMOOTH);
glEnable(GL_LINE_SMOOTH);
glEnable(GL_POLYGON_SMOOTH);
glEnable(GL_POLYGON_OFFSET_FILL);

glShadeModel(GL_SMOOTH);

Display is a LWJGL thing, it makes the OpenGL context and the window.

Anyway, I don't think there's anything in the init code that can help me but you never know...


texts: Mapped texture to a gluSphere not wrapping correctly

texts:
I have a 3D sphere rendered using JOGL by means of GLUquadric. I'm trying to add a texture but it is not rendering as correctly.

Does anyone understand why the texture (upper-right of sphere) isnt being wrapped, nor repeated around the rest of the sphere?


texts: differences in UDK map on different installs

texts:
My goal is to create a simple groundplane in UDK (11/2012 version, fresh install) that the user will be able to run around on. My requirements are therefore very basic and I tried to whip something up quickly in the editor. I created a circular (cylinder) plane and applied a material. I added a Blocking Volume, a Lightmass Importance Volume, and a Sky Light. I built everything and get no errors. The map played fine on my system.

I transferred the file to another system with the same version of UDK (also a recent install). When I try to play the map, I plunge to my death. Though I have verified that my player start position is above the ground, I seem to start below the ground looking up at it. What could cause a map that works great on one system have such a positioning issue on another system?

I believe this is a valid question. I'm obviously going to need to systematically test things and I already have tried moving the player start etc. However, I will need to have some idea of what can differ between installs. I'm extremely new to the UDK.

Thanks.


texts: Is deferred rendering/shading possible with OpenGL ES 2.0 ?

texts:
I asked this on StackOverflow, but it might make more sense here:

Has anyone implemented deferred rendering/shading under OpenGL ES 2.0? It doesn't support MRTs, so with only one color buffer, it's not something that can be implemented in the "usual" manner.

Specifically, I'm exploring on iPad, iPhone4 (maaaybe iPhone 3gs), and Android. On the GLESView app on iPad/iPhone4/iPhone3gs, the GL_OES_RGB8_RGBA8 extension is present, and I haven't looked too deeply yet, but with 8bits/channel, this idea is interesting: http://www.gamedev.net/topic/562138-opengl-es-20-and-deferred-shading/

Any other ideas? Is it even worth doing, performance-wise?


texts:
I'm trying to use SDL2 in a panel (VS2015/C++) and cannot find solid examples of how to connect the two. Anyone know how this is done?

I've tried some code found in various places, but no luck yet.  The code below was my latest attempt. I'm using latest version of SDL2.

SDL_Window* sdlWnd = SDL_CreateWindowFrom((void*)mapPanel->Handle);
SDL_SetWindowTitle(sdlWnd, "SDL Window - Set by SDL");
SDL_Surface* s = SDL_GetWindowSurface(sdlWnd);
SDL_FillRect(s, &s->clip_rect, 0xffff00ff);
SDL_UpdateWindowSurface(sdlWnd);
SDL_ShowWindow(sdlWnd);


texts: XNA How to change the sprite texture to white color

texts:
as the title,

how can i do to take the sprite to white color

here is some example,

turn to follows image

and my game planform is XNA now, and developed winphone game

thanks for reading!


texts:
I'm developing a game for Android in Java. I would like to know how a good Enemy class architecture could be implemented.

I've created an abstract class called Enemy. It stores common properties like Health and Animation data. It has methods like LoadContent, Update and Draw.

I want to inherit this class and implement different enemy classes. I want to be able to store all my active enemies in some sort of collection. Then in my Update function of my game loop, I'll do something like:

for each Enemy in Enemies
{
Enemy.Update()
}

And the Update method of the correct child class would be called.

How can this be achieved?


texts:
I am creating a simple game in Pygame for my kids. It involves intersecting random complex curves. Some of the intersections can be coloured in different colours. I have implemented a flood fill algorithm which works well for handling areas created by intersecting complex curves, but is very slow.

Couple of questions:

Is there a built-in flood fill algorithm I should be using (I could not find one) that can handle the above use case?
If not, then outside of algorithm improvements, how could I dramatically speed up a flood fill to make it near instantaneous to the human eye? (I am thinking about going low level but not sure how to go about this)

Flood Fill code:

# replaces all points of same starting colour,
# with a new colour, up to a border with
# different starting colour
def do_flood_fill(surface, x, y, newColor):
    theStack = [(x, y)]
    oldColor = surface.get_at((x,y))    # Get starting colour
    while len(theStack) > 0:
        x, y = theStack.pop()
        if surface.get_at((x,y)) != oldColor:
            continue
        surface.set_at((x,y),newColor)
        # pygame.display.update()   # Show fill - very slow
        theStack.append( (x + 1, y) )  # right
        theStack.append( (x - 1, y) )  # left
        theStack.append( (x, y + 1) )  # down
        theStack.append( (x, y - 1) )  # up


texts: When there are multiple objects of the same type, how do I know which one I am colliding with?

texts:
I'm working on a platformer game using Gamemaker Studio 2. , and currently I'm dealing with implementing platforms:

(Platforms are able to pass through from the bottom, but remains solid when landing on)

It's all working good and well for a single platform, but when I add multiple, then only the lowest placed platforms will work properly. I'm already aware that the problem lies on the second if-statement in the code below.

if (place_meeting(x, y+mySpeed[1], o_platform) &&       //If the player collides with a platform
    mySpeed[1] > 0  )                                   //if the player is falling
{
    if ((y + 29) < o_platform.y)                        //if the player's feets are located higher than a platform
    {
        while !place_meeting(x, y+sign(mySpeed[1]), o_platform)
        {
            y += sign(mySpeed[1]);
        }
        mySpeed[@ 1] = 0;
    }
}

The problem is likely because it's reading information from any platform. but not the higher platform I'm colliding with. So I should need a check to make sure I'm talking about the same object I'm colliding with.

If it was a build-in collision event, I could use the other statement to get the right instance, but currently I'm using place_meeting in a step method to collide, and other would be too broad to use properly. So how would I be able to archieve this?


texts: Have both Cubemaps and TextureArray in a single texture register?

texts:
I want to have both Point Lights, aswell as Spot Lights.
For the Point Lights I have a TextureCubeArray and for the Spot Lights I have a Texture2DArray. Is it possible to combine these two into a single Texture2DArray and treat the Point Light Shadow Maps as Cubemaps, and treat the SpotLight shadow maps as single textures?
I would like to bind only one array instead of multiple ones.


texts: Are there any pathfinding algorithms that would handle different movement types?

texts:
I'm developing a bot for a BattleTech board game simulator http://en.wikipedia.org/wiki/BattleTech, it is turn based.

The board is divided into hexagons, each one has a different terrain type and elevation. You drive a robot which moves over them, to destroy other robots.

I only know Dijkstra and A* pathfinding algorithms, but the problem is that there are 3 types of movements: walk, run and jump several hexagons (each of them have their own rules). Walk and run are almost the same.

The best path could be a combination or each movement type. Here is an example of map http://megamek.info/sites/default/files/isometric_view.png

Do you know a good algorithm for this complex pathfinding or a way to combine A* results for each movement type?


texts:
When the object gets destroyed in my game, I want a touch to continue function after a delay. This is what I tried.

this is the SceneManager class which is attached to the Main Camera

 public bool ttc;
 public void NextLevel()
{
    StartCoroutine(Delay());
}
IEnumerator Delay()
{

    yield return new WaitForSeconds(2);
    print("touch to continue");
    ttc = true;}

My Object class:

   void OnDestroy()
  {
   Camera.main.GetComponent<SceneManager>().NextLevel();
    if (Camera.main.GetComponent<SceneManager>().ttc == true)
    {
        if (Input.GetKeyDown(KeyCode.V))
        {
            Application.LoadLevel("TheGame2");
        }
    }
}

I also tried this:

IEnumerator Delay()
{
    yield return new WaitForSeconds(2);
    print("touch to continue");
    if (Input.GetKeyDown(KeyCode.V))
        {
            Application.LoadLevel("TheGame2");
        }
    }

side note: I will change the 'KeyCode.V' to a mouse button later


texts: Godot: How do I edit the exe icons of other sizes

texts:
I asked this question on  Godot Q & A:

https://godotengine.org/qa/53521/godot-program-icons

Basically, my problem is that I want My executable file's icon to display my own custom icon instead of the default Godot icon. I learned that Windows executables come in bundles and now know that I should include icons of other sizes instead of just one.

How do I do this?

EDIT

My problem is how I do this in Godot, not having found a means to edit the bundles in Godot.


texts:
So... I have a tree object and I have duplicated it to have many trees in the scene. So, I have about 200 trees in the scene. Before duplicating I forgot to add a tree as a prefab. Now, is there anyway to add a tree as prefab and make the other trees behave similarly.

Any Help would be appreciated.
Thanks in Advance!!


texts: How does OnLive work, and is there anything special Game Developers need to do?

texts: The OnLive service works by "cloud rendering", which is very different from the traditional model of "on-premise rendering" that we are all familiar with.  How does this work at a technical level, and is there anything special game developers or artists need to do to optimize their game for the platform?  As a developer, I'm a bit skeptical that everything is as magically working as they seem to suggest.


texts: How many polycount for smartphone hardware starting from 2015?

texts:
I already know that the answer is "depends". Depend if the hardware is low-mid or high hend.
So, I try to re-formulate: is 100K concurrent polycount in a 3d game for smartphone too much ?
How many is it a good compromise ?

Thanks


texts: Is it feasible to playback 4K video in Unity?

texts:
I'm starting work on a 360 VR video player, aimed at mobile devices (iOS/Android Cardboard + GearVR) and I'm evaluating whether it is possible to get video quality from 1080p to 4k in Unity or if I should instead just do the project natively (aka, OpenGL).

I've been trying to find information on the state of video in Unity but I haven't arrived to a clear answer. I'm going to explain the info I'm running on as of now, hopping that someone can add to this or provide an answer or at least show that I am erring on the side of ignorance :)

Assume a video in mp4, H264 at 4K resolution (equirectangular mapping):

OpenGL Approach:

If I were to do this in OpenGL, a (somewhat simplified) workflow would entail decoding each video frame, updating a GL_TEXTURE_2D with the pixel contents, and rendering to a sphere with glCullFace(GL_FRONT) as if it where a regular skybox.

With the above setup, the limiting factors would be:

Does the GPU in my device support 4K textures?  what marketing calls 4k is usually 3840 horizontal, and, an iPhone6 for instance, returns 4096 for glGetIntegerv(GL_MAX_TEXTURE_SIZE,...). So I'd assume the iPhone6 can load textures as big as required for 4K.
Fill rate: i.e.: my iPhone6's GPU might be capable of storing 4K Textures, but it might not be fast enough to fill up a 4K frame buffer at an acceptable frame rate. This unfortunately I think the only way to know is by testing. There is also the added overhead of the Cardboard rendering which means 2 passes per frame.

Unity Approach:

Now for a Unity approach, this is what I did:

Empty scene with a sphere and cardboard camera at the origin.
For the sphere, I created a material based on the Unlit shader with one texture and set the cull face to front.
imported the video and assigned it as the material's texture.

My observations from the above test are:

When importing images, Unity also allows texture sizes of 4096 so 4K should be possible.
Importing a video however, takes a ridiculous amount of time. I believe this is because Unity actually uses Ogg Theora and so it takes forever to transcode to Ogg. As a matter of fact, sometimes I was able to import and sometimes Unity would just stall.
When importing a video, I was not given any mmap, filtering or size options as if I was importing an image. So I'm not really sure what Unity is doing to the video. All I get is a quality / compression slider. The end video is still 3840x1920, which was the original resolution.
The rest of the experiment works ok, as in, yes, the video playbacks in the sphere. But the framerate is not great.

So at this point my conclusions are:

Is it possible to do 4K in Unity? Kind of, In the sense that you can import 4K videos and reproduce them without any external assets.
Is it really 4K quality? Probably not. mp4 is lossy and so is ogg, So I assume my video went a second round of lossy compression when it was transcoded to Ogg.
Is it practical? Not sure. So far, video importing takes an impractical amount of time. Also, 4K in general might be too much for a mobile device rending in stereo, regardless of Unity or doing it straight in OpenGL.


texts: How can I use an HLSL pixel shader to peek at other pixels?

texts:
I think this is like a pixilation shader but I had a hard time trying to find one online, and one that I could manipulate specifically.

I want to create a pixel shader for my monogame project that splits the texture up into blocks. The width and height of the block may or may not match. Then on each block, I want to average out the color of all pixels in the block, and fill it in.

I'm not sure how I would do this in a pixel shader. I can do something like this in code pretty easily but that is because the code scans the entire image at once. A pixel shader though seems to run on each pixel, so I'm not sure how to do that.

I currently have a simple pixel shader where I can plug in code to test. It doesn't do anything right now but return the same color.

#if OPENGL
    #define SV_POSITION POSITION
    #define VS_SHADERMODEL vs_3_0
    #define PS_SHADERMODEL ps_3_0
#else
    #define VS_SHADERMODEL vs_4_0_level_9_1
    #define PS_SHADERMODEL ps_4_0_level_9_1
#endif

// Our texture sampler
texture Texture;
sampler TextureSampler = sampler_state
{
    Texture = <Texture>;
};

// This data comes from the SpriteBatch Vertex Shader
struct VertexShaderOutput
{
    float4 Position : POSITION;
    float4 Color : COLOR0;
    float2 TextureCordinate : TEXCOORD0;
};

// Our Pixel Shader
float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    float4 color = tex2D(TextureSampler, input.TextureCordinate);
    return color;
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile PS_SHADERMODEL PixelShaderFunction();
    }
}


texts: Why does my object instantiation work, but return null?

texts:
For some reason, the LogError runs:

Player clone = Instantiate(player, this.transform.position,
    Quaternion.identity) as Player;

if(!clone) { Debug.LogError("WTF"); }
else       { Debug.Log("WE GOT IT"); }

My object appears, but if I try to do anything with it afterwards  its value is null, and the if(!clone) triggers.

Why is this happening?

The player is a gameobject and is assigned (its my player prefab) and Player is what my prefab is called. I also have a Player.cs script. Is Unity confusing my prefab and script or something?


texts: Changing a sprite and adding a new background layer

texts:
I followed a tutorial to make a Flappy Bird clone. At the end he gives you a premade game so everything works correctly, from jumping to going through pipes, etc.

I want to change the aesthetics though with sprites I made myself. I don't want to change any gameplay, just the sprites. This is easy for the bird, I just selected the asset I wanted and it changed in the scene and game. Easy.

Now, I want to add a building background layer to the back to go along with clouds, stars, and other background elements, and use the parallaxer to make them move. This doesn't work, however. It doesn't show up in the scene or the game when pressing play.

Next I want to make the pipes use a different sprite. So I changed the pipe sprite in the Unity menu to what I wanted, but when I hit play, it's still just pipes.

This is the tutorial project in question and it's free to DL and use, so I shouldn't be having this issue with changing its sprites. Can anyone please talk me through how to get these elements working?

Here is a screenshot of how I've tried making my changes:


texts: Problems with Unity3D Animator controller states

texts:
I have an object (a simple card) equipped with the Rigidbody, Collider and Animator components. In particular, Animator performs two simple clips: Cover and Uncover that rotates the card 180 degrees. The first starting from 0 degrees to 180, the second from 180 to 0.

So the clips should cover or uncover the card. The problem is that the card returns to its original state.

For example, the original state of the card is the "uncovered state" so when I click on it to cover it covers as expected. The I register the state "covered" programmatically. However, immediately after the animation ends, it returns to its original state (uncovered). The card now has an internal (C# variable) state as "covered", but I see it to still be uncovered. When I click it again, will be fired the correct animation clip: "uncover".

What should I do to leave it covered at the first click?

I have uploaded here a short clip that shows the behavior of the card, also below find some screenshots that refer to the various views of the IDE that may have useful information. The video clip is uploaded to Dropbox for the while.

The video of the behavior: Dropbox link

The code of the Flip script:

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

public class Flip : MonoBehaviour {

    private Animator anim;
    private enum cs_e {covered, uncovered};
    private cs_e coveringState;

    // Use this for initialization
    void Start () {
        anim = this.GetComponent<Animator>();
        coveringState = cs_e.uncovered;
    }

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

    }

    private void OnMouseUp()
    {
        Debug.Log("Mouse up");

        if (coveringState == cs_e.uncovered)
        {
            anim.Play("Cover");
            coveringState = cs_e.covered;
        } else {
            anim.Play("Uncover");
            coveringState = cs_e.uncovered;
        }

    }

    private void OnMouseDown()
    {
        Debug.Log("Mouse down");
    }

    private void MouseDrag()
    {
        Debug.Log("Mouse drag");
    }
}

Some screenshots:


texts: Need help finding an old game I want to rewrite/port

texts:
There was this old stick figure game for Windows I played a while back. You, playing as a stick figure, run around on a 2d map with guns and fight other stick figures. You can get power ups, like jetpacks, bigger guns and the like.

It's a very simple game with not much to it. I think it came with a map editor as well.

Google results only provide me with subpar flash games and some Stick War game that clearly isn't it.

I want to write a Linux port and I would like to give it another run before I start that process.

Anyone know what I'm talking about?


texts:
This question is very closely related to a previous question of mine:

Scaling a game view with letterboxes?

My game runs at 480x800 right now but when the screen is smaller or bigger than that I want it to scale up/down the image while maintaining the aspect ratio to fit it as best as it can and then put black letterboxes on the top/bottom or left/right to fill in the left over space if it is of a different aspect ratio. The newly scaled game screen should be centered in the middle of the screen.

I don't know how to go about doing this at all since I want the playfield to be 480x800 because the touch controls use the X and Y coordinates of where the player touches the screen. So I have to figure out how to make it so if the display is centered then the (0,0) coordinate doesnt start in the middle of the letter box but in the top left corner of the playfield where it should be. Also I need to figure out how to make it so when the game is scaled up or down the touch screen controls still work relevant to the new position and scale of the scaled game screen.

I don't know which would be easier, having the game image rendered then scaled up or make it so the gameplay remains the same with object and item positioning but renders a higher resolution image and then have higher resolution image resources rendered on big screens and smaller ones on smaller screens so they're pre-scaled instead of scaled by the hardware or software.

I'm not sure what the best practice is or how to go about doing either method. Please help me out!


texts: Translating ChainShape to world coordinates according to touch drag input

texts:
I'm trying to draw a ChainShape according to touch screen coordinates, however the coordinates are slightly off from my touch coordinates. I translate the chain drawn on the screen to world coordinates but don't think I've done it correctly.

I tried setting the shape's position to the first vertex but it positions it even further from the original touch coordinates. Can someone please help me understand where I'm going wrong?

public class Play implements Screen {
    private static final float TIMESTEP = 1 / 60f;
    private static final int VELOCITYITERATIONS = 8, POSITIONITERATIONS = 3;

    private Box2DDebugRenderer debugRenderer;
    private OrthographicCamera camera;
    private PolygonSpriteBatch batch;
    private World world;

    private List<Float> chain_verts = new ArrayList<Float>();
    private float[] chain;

    @Override
    public void show() {
        world = new World(new Vector2(0f, -9.81f), true);
        debugRenderer = new Box2DDebugRenderer();
        camera = new OrthographicCamera();
        batch  = new PolygonSpriteBatch();

        InputProcessor input_0 = new GestureDetector(new Gesture() {
        }) {
            @Override
            public boolean touchUp(float x, float y, int pointer, int button) {
                if (chain_verts.size() != 0) {
                    chain = new float[chain_verts.size()];
                }

                for (int i = 0; i < chain_verts.size(); i++) {
                    chain[i] = chain_verts.get(i);
                    System.out.print(chain[i] + " ");
                }

                ChainShape chainShape = new ChainShape();
                chainShape.createChain(chain);

                Vector3 mouse = new Vector3();
                camera.unproject(mouse.set(Gdx.input.getX(), Gdx.input.getY(), 0));

                BodyDef bodyDef = new BodyDef();
                bodyDef.type = BodyType.StaticBody;
                bodyDef.position.set(mouse.x , mouse.y);

                FixtureDef fixtureDef = new FixtureDef();
                fixtureDef.shape = chainShape;

                world.createBody(bodyDef).createFixture(fixtureDef);

                chain_verts.clear();
                chainShape.dispose();

                return super.touchUp(x, y, pointer, button);
            }

            @Override
            public boolean touchDragged(float x, float y, int pointer) {
                chain_verts.add(x);
                chain_verts.add(Gdx.graphics.getHeight()-y);
                return super.touchDragged(x, y, pointer);
            }
        };

        Gdx.input.setInputProcessor(input_0);
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        world.step(TIMESTEP, VELOCITYITERATIONS, POSITIONITERATIONS);

        camera.position.set(0, 20, 0);
        camera.update();

        batch.setProjectionMatrix(camera.combined);

        debugRenderer.render(world, camera.combined);
    }

    @Override
    public void resize(int width, int height) {
        camera.viewportWidth = 1200;
        camera.viewportHeight = 800;
    }

    @Override
    public void pause() {}

    @Override
    public void resume() {}

    @Override
    public void hide() {
        dispose();
    }

    @Override
    public void dispose() {
        batch.dispose();
        world.dispose();
        debugRenderer.dispose();
    }
}


texts:
What's the simplest way to fill the background of the screen with a gradient or a texture in Direct3D 10/11?

I'm building a Windows 8 metro app in which the camera never moves and I render some content in D3D, but I need to fill the background with something else than a solid color. Do I need to figure out the size and position of a rectangle and position it in 3D space or can I have some simpler solution?

I don't care about depth at all, I don't use any depth buffer since all my content is sorted back to front, so I could just start by drawing to the background.


texts:
I've been tryin to make My AI follow my A* path in grid. the problem is that is goes off course and doesn't move along the path very well. currently got it to move only  left and up.

how I intended it to work is that the character goes to the centre of the Path cells and repeat until the end.

void AIEnemy::AutoMotion(  Gridspot& grid)
{
    std::pair<int, int> ecn = getNodePosition();

    std::reverse(grid.Path.begin(), grid.Path.end());
    for (auto path : grid.Path)
    {
            if (path.node.first == ecn.first)
            {
                if (rect.getPosition().y != path.rectCenter.y)
                    rect.move(0, -5);
                break;
            }

            if (path.node.first < ecn.first && path.node.second == ecn.second)
            {

                if  (right != path.rectCenter.x )
                    movetoThe(e_left);
                break;
            }

    }
}

Here's how it looks like right now:

here's how it follows the path:

my question is how do I make AI character move on its own and alter its direction toward a goal.


texts: How do I remove 'playerachievementcache.dat' from my GMS project?

texts: I am working with a GameMaker: Studio project that outputs a file called "playerachievementcache.dat". It isn't used for anything, and I can't seem to remove it from my project. Is it possible that this is something the studio automatically includes? Any ideas on how to locate what is creating the file?


texts: [2D] Finding largest possible straight lines around body

texts:
I've got a 2D-map, largely consisting of rectangular tiles, but with some none-rectangular objects mixed in as well (tilted lines on corners for example).

Take this image as an example:

I now need all the largest possible (straight) lines around the two bodies inside that map. There are no additional required attributes to the lines.

In this image, I've marked the lines that I'm trying to find, each one with a different color to make sure there are no confusions:

It's important however, that the algorithm doesn't produce lines inside those two objects, as it would be a waste of resources.

Are there algorithms suited for that or will I have to research an algorithm myself?

By the way, the algorithm will run at loading-time of the game, so it doesn't need to be optimized for runtime-speed. Also, principally, an algorithm that is just able to find the lines around bodies which consist only of square or rectangular tiles would suffice as well.


texts: LIBGdx - Kryonet with an InetSocketAdresse

texts:
I'm trying to implement Kryonet in my game and i'm facing some trouble.
Using the source from the code i develop my server like that :

try {
        this.server = new Server();
        ServerManager.registerClasses(this.server);
        this.server.addListener(new Listener() {

            public void received(Connection connection, Object object) {
                if(object instanceof PositionMessage) {
                    System.out.println("[SERVER] Message from ID : " + connection.getID() + " - " + ((PositionMessage)object).message);
                }
            }

        });
    this.server.bind(port);
    this.server.start();
    System.out.println("Server started on port " + port);
    ServerManager.isLaunched = true;
} catch (IOException e) {
    e.printStackTrace();
    ServerManager.isLaunched = false;
}

And that's how my client is coded :

this.client = new Client();
ServerManager.registerClasses(this.client);
client.start();
client.addListener(new Listener() {

    public void connected (Connection connection) {
        System.out.println("Send");
        PositionMessage pm = new PositionMessage();
        pm.message = "Hi, i'm connected";
        client.sendTCP(pm);
    }

    public void received (Connection connection, Object object) {

    }
});
new Thread("Connect") {
    public void run () {
        try {
            System.out.println("Connecting on " + ipServer + " au port " + port);
            client.connect(5000, ipServer, port);
            System.out.println("I am connected");
            isConnected = true;
        } catch (IOException ex) {
            ex.printStackTrace();
            System.out.println("The server doesn't exist");
            isConnected = false;
        }
    }
}.start();

It works perfectly, the client can connect and the message is send and receive by the server.
But with that code, the problem is that the server is only local and can't be access from the outside (or it is and i'm just bad at it...) so to bypass that i'm not using only a port to create the server, but a InetSocketAdress passing my ip adress.
So i replaced the bind in the server code by this :

this.server.bind(socketAdresse, socketAdresse);

With socketAdresse =

ServerManager.socketAdresse = new InetSocketAddress(ipServer, port);

The server is created (at least it seems created, i can't find a way to find if the server is launched, but i have no exception catched. Now for example, if i create a server with my local ip (the same way i was doing without the InetSocketAddress) and the port 2302, the client never connect to the server and i have literally no message. It just tell me that on the client side that the connection was succesfull but the server never receive any information, + when i do a check on the client if it connected, it says "false".

So my problem is that when i don't use a InetSocketAdress, the client can connect fine on my local ip, but i want to be able to host on the web so i use an inetsocketadress but the problem is that a client can't connect to my server and it doesn't give me an error.

Thanks for the help !


texts:
I'm making a platformer in JavaScript and this is the collision detection function that I have

if(obj2.y > obj1.y + obj1.height ||
   obj2.y + obj2.height < obj1.y||
   obj2.x > obj1.x + obj1.width ||
   obj2.x + obj2.width < obj1.x){
    return false;
} else {
    return true;
}

So my question is, how do I tell which side obj1 is colliding with obj2?


texts:
First thing is that I know how to give values to uniforms in OpenGL. Second thing is that it is a question related to optimization and performance.

The habit for changing the uniforms, we preferred is like this:

//Consider that we have shaders having 'aValue' as uniform

//During initialization
GLint loc = glGetUniformLocation(program, "aValue");

//During a loop or when required to change uniform's value
if (loc != -1)
{
   glUniform1f(loc, 0.75);
}

But what if it is like this:

//'program' is a global variable

//Can be anywhere but not after destructing 'program'
void updateUniformf( const char* name, float value )
{
    glUniform1f(glGetUniformLocation(program, name), value);
}

//During a loop or when required to change uniform's value
updateUniformf("aValue", 0.75);

How much would such approach decreases the performance? Or would this approach even affects the performance? It will be appreciable to have some measurements or practical example rather than all theories. Of course, I need to know reasons as well.

Thanks for answering this question!


texts: Is A* efficient even when the obstacles are moving?

texts:
I'm just starting to learn about path-finding and have been looking into the A* algorithm and my main concern is that it all of the examples I have seen show static obstacles that it computes around.

If I have moving obstacles, say other characters for example, moving around as well that the character must find their way around, I'm assuming I'll have to run the algorithm each frame, but I'm worried that will become rather expensive for the hardware to process each frame for each moving actor.

So is A* still efficient enough to use whenever the obstacles are moving too, or is there another method of path-finding that handles moving obstacles more eloquently?


texts:
When I instantiate a ragdoll object, it collapses nicely, but the movement never stops. It wiggles continuously. I'm using CharacterJoint components.
None of the colliders (box and capsule) intersect. They are all spaced by at least a small amount.
I tried playing with angular drag of the colliders, but that seems not to work. There do not seem to be any values in the CharacterJoint that affect this. But I'm probably wrong.
How can I get the physics to stop "wiggling" after a certain threshold?


texts:
I'm sure there has to be a simple answer to this, but frankly I cannot find anything about it anywhere on the internet, so I'm asking here. How do I add a pointer like this hand to the side of the currently selected UI button in my game?

I tried using Unity's built in UI system to do this, using the "sprite swap" feature that changes sprites based on whether or not the button is currently selected. I made an image for my "Play" button, and then an image for when the play button was selected that included a pointer as part of the image, but the image would either resize when the button was selected, or the image was moved to the right to accommodate Unity's centering mechanic on the UI. Perhaps this wasn't so wrong, and I'm just not using the UI system correctly.

Does a feature like this have to be hard coded into the UI design?


texts: How do I let players control which key does what?

texts:
New to coding so this is probably super simple, but I can't find the answer. I'm using Unity 5.4.0 and coding in C#.

Is there a variable for input keys?

I have a game I'm making and it is working good, but I want the players to be able to choose which key does what, but I don't know how to make the key presses changeable. I am using both Input.GetKeyDown(Keycode."KEY") and Input.GetKey(Keycode."KEY").

My question is: is there a variable I can use in place of the keys that I can make changeable by the players?  Like a float, but instead of numbers, it uses key codes.


texts: Why is my game object generated by a custom Unity editor script missing its sprite?

texts:
I have a number of sprites that I generate outside of Unity.  I'd like to automate the process of importing these sprites into Unity as fully-configured game objects.  I'm trying to do this through a Unity editor script, but I'm having some difficulty.  When I run my script, my game object is saved as a .prefab as expected.  However, the Sprite I'm assigning to my game object's SpriteRenderer component is missing:

In my script, I'm assigning my SpriteRenderer's sprite property to a Sprite object that I dynamically create in the script.  Here's the relevant excerpt from my editor script:

GameObject gameObject = new GameObject(fileName);

SpriteRenderer spriteRenderer = gameObject.AddComponent<SpriteRenderer>();

// texture size will be replaced during the LoadImage() call
Texture2D texture = new Texture2D(1, 1);
texture.LoadImage(File.ReadAllBytes(Path.Combine(generatedOutputPath, fileName + ".png")));

spriteRenderer.sprite = Sprite.Create(
    texture,
    new Rect(0.0f, 0.0f, texture.width, texture.height),
    new Vector2(0.0f, 0.0f)
);

PrefabUtility.CreatePrefab("Assets/Prefabs/" + fileName + ".prefab", gameObject);
DestroyImmediate(gameObject);

I can verify through logging that the image path to my .png is correct and that the Texture2D and Sprite objects seem to be instantiated correctly.  For example, I can do this:

// logs "580" as expected
Debug.Log(texture.width);

What am I doing wrong?  How can I save this game object as a .prefab without losing its sprite information?


texts: Interactions between camera and procedural terrain

texts:
QUESTION REWORKED

I need to update every frame camera position along a surface with hills and drops.
In this picture you can see a particle of the surface terrain (just one triangle) and a sphere representing the camera. It is set in a certain point of the surface and has a velocity in the XZ plane.

What I want to do is check the plane sloping and modify the velocity in order to move smoothly on the surface without "entering" in it like if it was a ladder

How should I proceed? I can easily ccess informations like vertex coordinates, surface normale (in that particular triangle) and I think whatever you thinkcould be of help but since I have difficulties in painting on a paper what should I expect I don't know how to approach this problem.

Can someone help me?


texts:
I try to use Physics.CheckSphere to check if a coordonate is empty.
I use three for loop to cycle threw a 2 x Y x 2 chunk. The problem is that it return true if the corner is touching the coordonate

and its actually not even touching it, since I use a 0.5 sphere radius:
if(Physics.CheckSphere(new Vector3(x,y,z), 0.5f) == false)...

(by the way the white cubes you can see on the picture is only to visualize where it detected empty space, they dont have any collider enabled)

and the chunks have a mesh collider, so why is it returning true when its no even touching it ?

if(Input.GetKeyDown("i"))
    {

for(int y = 0; y <= amp + 3; y++)
{
    for(int x = 0; x <= chunkSize - 1; x++)
    {
        for(int z = 0; z <= chunkSize - 1; z++)
        {
            if(Physics.CheckSphere(new Vector3(Mathf.Round(x),Mathf.Round(y),Mathf.Round(z)),0.5f) == false)
            {
                Instantiate(grass,new Vector3(x,y,z), Quaternion.identity);
                dontPlaceHere.Add(new Vector3(x,y,z));
            }
        }
    }
}
}


texts: How can I prevent small numerical advantages from dominating the balance of an encounter?

texts:
I've been tinkering for some time with a game and I'm having a fair amount of trouble with something:

I have two characters, each of whom have attributes (about ten) in a range (between 1 and 20). I want to use these attributes to generate a 'roll' such that the higher roll wins that particular encounter. It's worth noting that the two characters are not damaging/defending each other. They're both rolling to see if they pass what I guess we could call a skill check. They're both rolling to pass/fail against a common value. They do not interact with one another.

However, when one of the characters has even a small numerical advantage, any formula I've come up with results in the ever-so-slightly superior one winning a huge majority of the time. This is undesirable.

I've tried weighting the 'most relevant' attribute for the test at 80% and the sum of the other attributes at 20%. I also tried comparing averages to produce a relative difference and using that to boost the weaker character. Both approaches resulted in the significant advantages I'm trying to remove (for example, if I run the encounter 5,000 times, it quite regularly produces one side winning all 5,000).

Adding a "luck" component only matters, it seems, if it's weighted somehow in favour of the lesser character, and I haven't hit a good balance there.

What approaches can I take to blunt the impact of a small numerical advantage but still preserve and increase that advantage as the relative gap in attributes increases?

Per the request, here are the specifics I have so far. Some things I haven't figured out yet so they remain generalities:

At the moment, the roll is generated as

0.8 * (mainAttribute) + 0.2 (1/3 * subAttA + 1/3 * subAttB * 1/3 subAttC)

At present, this produces numbers in the neighborhood of 4.0. Attributes are randomly generated between specified ranges. The current test uses one character with attributes from 2 to 4, and the opponent between 3 and 5. Predictably, this produce averages close to 3 and 4 respectively.

With this one-point advantage, I'd like to see the stronger of the two win in the area of 55% to 60% of the time, with this scaling up to winning about 80% of the time with an average attribute advantage of 5 or 6, 90% at advantages of 7 or 8, leaving some room for an unlikely win when the gap grows larger. I'd prefer not to ever have guaranteed wins, but perhaps things becoming very unlikely - to the tune of winning 99.5% or 99.6% of the time when the gap gets very large.

The current formula produces a non-random number. Randomness comes from the selection of which attributes are relevant. Not all of the attributes are used for each roll. It's possible for the one with the overall weaker attributes to be stronger in the areas relevant to that roll, and steal a win. But, predictably, it happens rarely.

My next attempt was to weigh their relative strengths, by taking an average of all of each's stats, dividing them against each other, and using that value to give a small boost to the lesser character. This smoothed things out a little, but still had a pronounced tendency to produce things like 5,000 wins for one guy out of 5,000 tries.


texts: How should I add level-specific gameplay code to a level?

texts:
What are best practices to add gameplay, to specific level? I have some event types, and my game logic now looks like. OnEnterSensor is virtual and is different for each level(01,02 ...). Game type platformer and what about other types of games and their logic description.

    virtual bool OnEnterSensor( Entity* sensor, EventArgs* args )
    {
      if (str_equal(sensor->Name(), "button_sensor"))
      {
        door_closed = false;//door_closed internal level variable
      }
      else if (str_equal(sensor->Name(), "door_sensor")) ........ and so on.
    }

Is it good practice to use such kind of code. I'm not sure about this long IF construction when level logic is complex then it becomes large, and hard to read.
Will be glad to hear any recommendations (maybe some in-level events) and other methods to describe level gameplay.


texts: How can I determine the direction of the balls after collision in billiards game?

texts:
I'm making a billiard game and I have two questions:

How do I find the velocity of two balls when they collide with each other and how do I apply it to both balls?

I already know the angles that they're gonna move, I just need to find the velocity that they'll move in those directions.

My game is in 3D, and I'm using Unity. I don't want to use Unity's built-in physics to compute the result in this case, I'd like to know how to compute it myself.