texts: Color bands over tile when scaling texture in shader

texts:
I want to have tiles with different sprites on the back.
Initally I thought I will mix two textures together and then apply mixed texture to game object. I thought that should be easy, but google returned discussion about shaders and their superiority.

After reading about shaders  I decided to use shaders instead.

Also I am using rather big sprites and I am scaling them down in shader.
Kind of want to be sure that tiles look good on big screens also.

Also to be sure that game works on smaller screens - I change camera distance when game does not fit in the screen.

Everything is working nice when tile is "near". But when tile is far away it starts to show artifacts over all surface of tile.
It appears that scaling is done not pixel by pixel but in some chunks.

Modified shader code (I commented out mainTex because it does not change anything from "bug" perspective):

Shader "Custom/TwoTextureShader3"

{

    Properties{
        _Color("Color", Color) = (1,1,1,1)
        _MainTex("Main Texture Color (RGB)", 2D) = "white" {}
        _MainTex2("Overlay Texture Color (RGB) Alpha (A)", 2D) = "white" {}
        _Glossiness("Smoothness", Range(0,1)) = 1
        _Metallic("Metallic", Range(0,1)) = 0.2
        _OffsX("Offset X", Range(-2, 2)) = 0
        _OffsY("Offset Y", Range(-2, 2)) = 0
        _Scale("Scale", Range(0, 10)) = 1
    }
        SubShader{
            Tags { "RenderType" = "Transparent"}

            LOD 200
            CGPROGRAM
            // Physically based Standard lighting model, and enable shadows on all light types

            #pragma surface surf Standard alpha fullforwardshadows

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

            sampler2D _MainTex;
            sampler2D _MainTex2;

            fixed _OffsX;
            fixed _OffsY;
            fixed _Scale;

            struct Input {
                float2 uv_MainTex;
                float2 _MainTex2;
            };

            half _Glossiness;
            half _Metallic;
            fixed4 _Color;

            void surf(Input IN, inout SurfaceOutputStandard o) {

                float4 mainTex = tex2D(_MainTex, IN.uv_MainTex);

                fixed2 offsetUV = fixed2(_OffsX, _OffsY);
                float4 overlayTex = tex2D(_MainTex2, IN.uv_MainTex * _Scale + offsetUV);

                half3 mainTexVisible = mainTex.rgb * (1 - overlayTex.a);
                half3 overlayTexVisible = overlayTex.rgb * (overlayTex.a);

                float3 finalColor = (mainTexVisible + overlayTexVisible) * _Color;

                //o.Albedo = finalColor.rgb;
                o.Albedo = overlayTex.rgb;

                o.Metallic = _Metallic;
                o.Smoothness = _Glossiness;
                o.Alpha = max(mainTex.a,overlayTex.a);
                //o.Alpha = 1;
            }
            ENDCG
        }
            FallBack "Diffuse"
}

Tiles looks good when they are near

Tiles looks awfull when they are far away

Currently I am thinking about using two Meshes for single tile, so that game never hints about what is on the back of the tile even when graphics hardware really want to.


texts: Adding smooth round Bézier curve corners in unreal editor?

texts:
Unreal Editor offers rectangular and round geometry. It also offers boolean operations. I can make a smooth corner by playing around with cylinder and boolean operations. I really would like to make a Bézier curve corner and I need it done quickly in a lot of places (it's not for looks, I actually need it to affect the gameplay and physics) for the rough draft phase.
I also need it to be customizable. I want to be able to change parameters, essentially playing with the three points of a quadratic bezier.

How could I quickly and effectively add and manipulate round smooth Bézier curve walls / corners in Unreal Editor?


texts: Monogame scale/resizing texture without stretching the borders

texts:
I would like to scale or resize my texture2d but when I do it, the texture border becomes stretched.

Here's an example :

This is my original texture

And this the texture after I change the Scale:

The texture's border becomes stretched compared to the original, and I would like to preserve exactly the same border than the original texture.

Is there a way to re-scale a texture without having it stretched?

If so, could you help me find the best way to do it?


texts: Screen Space - Camera improper scaling on iOS device only

texts:
I've reproduced the issue in a simple setup where I have two canvas's, one overlay and one camera. I put an image under both set to maintain aspect ratio, and set them to use anchors for sizing instead of pixels. On iOS the camera space canvas stretches the image improperly, and the overlay is fine. Both have identical settings, with Canvas Scaler set to screen size and to match width. This only seems to happen on older iOS devices, but my sample size is too small to say that for certain.
I expect both images to maintain aspect ratio on device, but the image under Screen Space - Camera stretches out of aspect ratio. Local Scale on all objects is what I would expect it to be so nothing interesting there.
Has anybody run into this issue before or have any idea what might be causing it?


texts: Show size / dimensions of an object in Unity Inspector

texts:
I want to see the size of the currently selected objects in the Unity Inspector, however I can't seem to find how to add it.
Currently when I select a model in my scene, the Inspector panel shows info about its position, rotation and scale, but not the size of the object.

What I want to achieve is to create a scene so that the objects in this scene have the correct proportions to each other, i.e. if a human has a size of 1.8 'units', an example car should be about 5 units long.


texts:
In my Unity3d game, I want to get the world position that was touched, when I touch a specific object, regardless of all objects that are in front of it.

How would I do that, I only know Camera.ScreenPointToRay(...), but for some reason that does not work properly?

OK - one cannot answer the question with the information I provided.

In order to determin the point, where the Ray hit the object, I used RaycastHit.transform.position (which refers to the Transform object that was hit) as opposed to RaycastHit.point (which refers to the Vector3 in world space, where the RaycastHit happened).


texts:
I'm trying to get my 2D top down shooter to use -some- physics.
I want the player and enemies not be able to exist in the same position, in other words, use collisions.
My first attempt was to use a CharacterController, but I could not get my other game objects to collide with my player, even though I had a RigidBody2D and a BoxCollider2D on them. Obviously, due to using a CharacterController, I was not able to add these components on my player.
Going one step back, I removed the CharacterController, and rather opted to go the Rigidbody2D route. This worked partially. I now get collisions on my player when he walks into other gameobjects (with RB2D and BC2D on them), but there seems to be a "rebound" anomaly occurring; my player moves around after collision.
I've tried playing around with the settings on the RigidBody2D on the player, but it does not seem to have any effect.
This is my PlayerMovement script :
void Update()
{
    HandleRotation();
    HandleMovement();
}

void HandleRotation()
{
    var mousePos = Input.mousePosition;
    mousePos.z = 5.23f;

    var objectPos = Camera.main.WorldToScreenPoint(transform.position);
    mousePos.x -= objectPos.x;
    mousePos.y -= objectPos.y;

    float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
    transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
}

void HandleMovement()
{
    float horizontal = Input.GetAxisRaw(Constants.Axis.Horizontal);
    float vertical = Input.GetAxisRaw(Constants.Axis.Vertical);

    Vector3 direction = new Vector3(horizontal, vertical, 0f).normalized;

    if (direction.magnitude >= 0.1f)
    {
        var speed = (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
            ? mobileController.runningSpeed
            : mobileController.walkingSpeed;
        var moveVector = (direction * speed) + transform.position;
        mobileController.rigidbody2d.MovePosition(moveVector);

        var camPosition = new Vector3(mobileController.transform.position.x, mobileController.transform.position.y, -10);
        cam.position = camPosition;

    }
}

The settings on my Player :

I would like my player to stop dead in his tracks when colliding with another RigidBody2D. Is this possible? And if so, how would I go about doing that?


texts:
I've made a .obj reader in c++ and I've tried rendering some models. I've got the whole concept from here:
https://www.youtube.com/watch?v=KMWUjNE0fYI&list=PLRIWtICgwaX0u7Rf9zkZhLoLuZVfUksDP&index=9

So I've tried to copy the export settings in blender what the guy used in the video (I'm not experienced in modelling so I had troubles because I have a newer version) and I've split every edge so they staied sharp even with the smooth shader. What my model looks like in blender:

I'm not sure if this is a texture or lighting bug. The models that the guy provides in the video work just fine.

Edit:

My drawing code is this:

shader->Enable();
shader->SetUniformMat4f("vw_matrix", viewMatrix);
m_Model->GetVAO().Bind();
m_Model->GetIBO().Bind();
glActiveTexture(GL_TEXTURE0);
m_Texture->Bind();
glDrawElements(GL_TRIANGLES, m_Model->GetIBO().GetCount(), GL_UNSIGNED_INT, 0);
m_Texture->Unbind();
m_Model->GetVAO().Unbind();
m_Model->GetIBO().Unbind();
shader->Disable();

Export settings:

Write Normals
Include UVs
Triangulate faces
Objects as OBJ objects

Edit2:

I've added a pic how the model looks without edge split (above).

My vertex shader:

#version 400 core

in vec3 position;
in vec2 textureCoords;
in vec3 normal;

out vec2 pass_textureCoords;
out vec3 surfaceNormal;
out vec3 toLightVector;

uniform mat4 pr_matrix = mat4(1.0);
uniform mat4 vw_matrix = mat4(1.0);
uniform mat4 ml_matrix = mat4(1.0);
uniform vec3 lightPosition;

void main(void)
{
    vec4 worldPosition = ml_matrix * vec4(position, 1.0);
    gl_Position = pr_matrix * vw_matrix * worldPosition;
    pass_textureCoords = textureCoords;

    surfaceNormal = (ml_matrix * vec4(normal, 0.0)).xyz;
    toLightVector = lightPosition - worldPosition.xyz;
}


texts: Why can't I play 2 animation track at the same time in Timeline for additional Camera?

texts:
I try to move and rotate camera at the same time in timeline. To do this, I added two animation track to camera. One animation track changes position of the camera. And the other one changes rotation of camera. But they are not working at the same time. When I press "preview" button, only rotation of camera changes

This video may help understanding if question is not clear
https://vimeo.com/user133731359/review/517045792/43b6c6ec49


texts: How to design components for tile-based movement in an RPG using ECS

texts:
I'm trying to re-write a small game of mine using ECS mostly for educational purposes and to see if it fits top-down RPG games in the style of Pokemon (gameboy). Since everything is tile based, initially I had a Position component that only holds the position of the player, and a Controller/Input component that, when a movement keypress is detected, starts to change the player's position until it falls into a tile. Then, the Rendering component would render the player based on a vector of clips that simulate the movement.

Thinking that my player should only move in tiles, I thought that it might be better to change the position tile-by tile every time, and then use some sort of interpolation in the Animation or Rendering component to figure out which of the clips to use (left foot forward, right foot forward etc.). This proved to be much less error prone, but now this means that I need to keep the actual position and the "visual" position (the one you can see on the screen). Thinking that logic should be not mixed with rendering, it seems that the "correct" thing would be to not keep the "visual" position in the Position component, but in one of the "front end" components like Animation or Rendering. Which would be the most correct thing to do? By correct meaning the thing that will keep the code truly decoupled in the vein of pure ECS.


texts: Logic that can traverse all possible layouts, but not checking every combination of identical pieces?

texts:
Suppose we have a grid of arbitrary size, which is filled by blocks of various widths and heights. There are many 2x2 blocks (meaning they take a total of 4 cells in the grid) and many 3x3 blocks, as well as some 5x4, 4x5, 2x3, etc.

I was hoping I could set up a program that would look at all possible layouts, and rank them, and find the best one. Simply it would look at all possible positions of these blocks, and see what setup is the best rank. (the rank based on how many of these can be connected by a roadway system of 1x1 road blocks, and how many squares can be left empty after this is done. - wanting to fit the most blocks as possible with the least roads.)

My question, is how should I traverse all the possibilities? I could take all the blocks and try them one at a time, but since all 2x2 blocks are equal, and there are a couple dozen of them, there is no point in trying every combination there, as in the following

AA BBB
AA BBB
 CCBBB
 CCEEE
DD EEE
DD EEE

is exactly the same as

CC EEE
CC EEE
 AAEEE
 AABBB
DD BBB
DD BBB

You notice that there are 2 3x3 blocks and 3 2x2 blocks in my two examples. Based on the model I have now, the computer would try both of these combinations, as well as many others. The problem is that it is going to try every single possible variation of my couple dozen 2x2 blocks. And that is sorely inefficient.

Is there a reasonable way to take out this duplicated work, somehow getting the computer program to treat all 2x2 blocks as equal/identical, instead of one requiring rearranging/swapping of these identical blocks?

Can this be done?

My current pseudo code

blocks = array of all blocks [2x2, 2x2, 2x2, 3x3, 3x3]
iterate(0)
function iterate(i) {
    currentblock = blocks[i]
    for each possible position of currentblocks
        see if there are any more blocks to place, and if there are
            iterate(i+1)
        else
            all blocks are placed, so get the rank
            if the rank is better than thebestrank
                thebestrank = rank
                thebestposition = position
}
at this point, we proceed with thebestposition.


texts: How to change the start position of my 2D game

texts:
I am trying to create a game where you have to move a ball on a platform. At the start of the game, the ball is dropped on the platform and then you can move it around. This is al working, no problems here.

To keep the overview, the ball is centered in the middle of a div. When you move the ball you actually move the platform (giving the illusion the ball moves). This function should stay as it is. The platform is build in javascript as follows:

var levels = [
    [
        [1,1,1,1,1],
        [1,1,1,1,1],
        [1,2,1,1,1]
    ]
];

Where 1 = green tile, 0 = no tile and 2 is a yellow tile.

When loading the level it will generate the first tile (in this case the first 1) in the center of the div, then the next one and the next, etc. Al good so far, but if I change the first 1 tile to a 0 tile (= no tile), it will generate the platform, but since the platform is created in the middle of the div and since 0 is no tile, no tile will be generated and the ball will fall endlessly.

This is no good, I want to have different platforms and not always start with a 1 tile at this position. So I figured to make a "start tile". This is the yellow 2 tile. The idea is that this tile is the tile that always should be shown in the middle of the div at the start of a game, so that the ball always drops on the yellow tile. Therefore the whole platform should be moved at game start/load in order to center the yellow tile.

And this is my problem. How to do this?

I hope my problem is clear. I've also made a fiddle (click the 1 to start the game), so you can try things out

Many thanks

ps so in short:

Ball always drops in middle (must stay this way)
Yellow "start tile" should be moved/centered in the div, so the ball drops on it at game start

pps: The yellow tile can have a different position, it depends on the platform design


texts: HTML5 Quintus button click doesn't work in local

texts:
If you try to run this example http://html5quintus.com/docs/ui.html, you'll be able to click the buttons, but you won't if you download a local copy of the example and click the index file (without using a web server).

I know I need to run the code in a web server and not by just double clicking on the files when I have a .json file, but I can't understand the reason why also the click doesn't work (it does not require resource loading).

Maybe there's a simple modify I can apply to the example code or to the libs to make it work... Any suggestion? Thank you!

EDIT

I don't see any JS error:


texts: How to detect a touch on transparent area of an image in a (libgdx) stage?

texts:
Can some one please help to detect a touch on an image which I am using as an actor in a stage. The image is actually a long diagnol brush which has plenty of transparent area. The problem is when I touche the transparent area of the brush image it is also triggering the clicklistener of the image. I need the click listener should only be called when the finger actually touched the visible image not the area which is empty.

I am using libgdx-0.9.4 libraries. Here is my simple piece of code.

import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.ClickListener;

Image brushImg = new Image(ImageCache.getTexture("brush"));
brushImg.width = mStage.width()*0.75f;
brushImg.height = mStage.height()*0.75f;

brushImg.setClickListener(new ClickListener() {

@Override
public void click(Actor actor, float x, float y) {
    SoundFactory.play("brush");
}


texts: XNA 2D Tile Map zooming to arbitrary point

texts:
I'm working on a game in XNA with a 2D tilemap as the playfield. I'm using a spritebatch with a transformation matrix to provide movement and scaling of the playfield. I'm trying to add a zoom function, so the player can click anywhere on the screen and it will zoom in to that point. The issue is that when I increase or decrease the scale, the "focus" of the zoom is always at the top-left hand corner of the screen.

So unzoomed:

And when zoomed in (note the position of the chequered tile):

What I'd like to happen when the player zooms is that it zooms into the centre of the screen, like so: (I achieved this by moving the playfield around after zooming)

I realise that the way to do this is probably to add or subtract from the X/Y co-ordinates that get fed into the transformation matrix, and probably at a fraction of the scale, but I can't figure this out. Everything I try tends to result in crazy effects while zooming.

Ideally I'd like to be able to set any arbitrary point on the screen, and zoom to that point. Can you help?

The code of the Draw function:

   protected override void Draw(GameTime gameTime)
    {
        Matrix transformMatrix =
           Matrix.CreateTranslation(-baseX, -baseY, 0) *
            Matrix.CreateScale(baseR, baseR, 1) ;

        GraphicsDevice.Clear(Color.CornflowerBlue);

        // "World" spritebatch. Scaling applied.
        spriteBatch.Begin(SpriteSortMode.FrontToBack, null, SamplerState.PointClamp, null, null, null, transformMatrix);

        foreach (Vector3 Square in Squares)
            spriteBatch.Draw(Textures[(int)Square.Z], new Vector2(Square.X, Square.Y), null, Color.White, 0, new Vector2(0, 0), 1, SpriteEffects.None, 0.82f);

        base.Draw(gameTime);

        spriteBatch.End();

        // "UI" spritebatch. No scaling applied.
        spriteBatch.Begin(SpriteSortMode.FrontToBack, null, SamplerState.PointClamp, null, null);
        spriteBatch.Draw(Textures[0], new Vector2(ScreenMidX, ScreenMidY), null, Color.White, 0, new Vector2(0, 0), 1, SpriteEffects.None, 1f);

        SpriteFont aFnt = Content.Load<SpriteFont>("Font1");
        spriteBatch.DrawString(aFnt, "" + baseX, new Vector2(5, 0), Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, 1f);
        spriteBatch.DrawString(aFnt, "" + baseY, new Vector2(100, 0), Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, 1f);
        spriteBatch.End();
    }

Full code available here: https://www.dropbox.com/s/zft5b20st8o7jv7/ZoomTest3.zip

Thanks for any help!


texts: Unity3D - Mesh appears black in parts that it shouldn't

texts:
I have a procedurally-generated mesh that I am generating to use as a terrain. It looks something like this (from above, and it changes slightly every time):

It also looks fine when I view from the z-axis side.

The issue is that when I view it facing the x-axis, it has a black part kind of going through it.

I wouldn't really care about that, but when the player goes into the valley, it seems as if they fall under the black part. They can only see the ground and above them it is all black.

The mesh does have a mesh collider attached, and so the player doesn't fall the way through the mesh - just the "black line". The height of the mesh (on the y-axis) is generated using perlin noise that I multiply by 800 (to increase the waviness), and that is set when I set the vertices. I suspect that this issue has to do with the normals or the uvs not adjusting to the y-axis, but I've messed around with it a lot and nothing seems to help. I currently generate the normals with RecalculateNormals() after I generate the vertices, triangles, and uvs, and calculate the uvs in a for-loop where I take each vertex's x and z axis and divide it by the number of vertices on that axis time the distance between them (to make it between 0 and 1).


texts: Rotation of a point around axis using quaternions

texts:
I have a simple processing program to rotate a point around arbitrary
axis but it stops after a bit. I'm trying to get full rotation of the
point around the axis.

import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.apache.commons.math3.complex.Quaternion;

float ang = 0f;
void setup() {
      size(600, 600, P3D);
}

void draw() {
  fill(255);
  //rect(0, 0, width, height);
  translate(width/2, height/2);
  Vector3D pt = new Vector3D(30, 145, 40);
  Quaternion ptQ = new Quaternion(0, pt.getX(), pt.getY(), pt.getZ());
  Vector3D axis = new Vector3D(50, 50, 50);
  Quaternion q = getQuaternionFromAxisAngle(ang, axis);
  Quaternion r = q.multiply(ptQ).multiply(q.getConjugate());

  stroke(255, 0, 0);
  line(0, 0, 0, (float)r.getQ1(), (float)r.getQ2(), (float)r.getQ3());
  ang += .1;
  println(r.getQ1() + " " + r.getQ2() + " " + r.getQ3());
}

Quaternion getQuaternionFromAxisAngle(float degAng, Vector3D vec) {

  float radAng = radians(degAng/2.0);
  // Here we calculate the sin( theta / 2) once for optimization
  double factor = sin( radAng);

  // Calculate the x, y and z of the quaternion
  double x = vec.getX() * factor;
  double y = vec.getY() * factor;
  double z = vec.getZ() * factor;

  // Calcualte the w value by cos( theta / 2 )
  double w = cos( radAng);
  return (new Quaternion(w, x, y, z)).normalize();
}


texts: How to get this type of movement in LibGDX?

texts:
I want objects in my game to move randomly but always from right side of the screen to the left side. The movement must be as smooth and natural as possible, like they are following a path.
Can i obtain this with the wander steering behavior without having objects going in every direction randomly? (that's what i have right now)


texts:
I'm trying to speed up particles, and one way to do that is by precomputing the texture rotations. What I want to do is load the texture, rotate it and save it to a handle.

How would I go about doing this?

Thanks in advance.


texts: How to pick zoomed objects in an isometric game?

texts:
I´m currently working on an isometric game engine and right now I'm looking for help concerning my zoom function.

On my tilemap there are several objects, some of them are selectable. When a house (texture size 128 x 256) is placed on the map I create an array containing all pixels (= 32768 pixels). Therefore each pixel has an alpha value; I check if the alpha value is bigger than 200 so it seems to be a pixel which belongs to the building. So if the mouse cursor is on this pixel the building will be selected -> PixelCollision.

Now I've already implemented my zooming function which works quite well. I use a scale variable which will change my calculation on drawing all map items.

What I'm looking for right now is a precise way to find out if a zoomed out/in house is selected. My formula works for values like 0.5 (zoomed out) or 2 (zoomed in) but not for values in between.

Here is the code I use for the pixel index:

var pixelIndex = (int)(((yPos / (Scale * Scale)) * width) + (xPos / Scale) + 1);

Example:

Let´s assume my mouse is over pixel coordinate (38, 222) on the original house texture. Using the code above we get the following pixel index:

var pixelIndex = ((222 / (1 * 1)) * 128) + (38 / 1) + 1;
               = (222 * 128) + 39
               = 28416 + 39
               = 28455

If we now zoom out to scale 0.5, the texture size will change to 64 x 128 and the amount of pixels will decrease from 32768 to 8192. Of course also our mouse coordinate changes by the scale to (19, 111). The formula makes it easy to calculate the original pixelIndex using our new coordinates:

var pixelIndex = ((111 / (0.5 * 0.5)) * 64) + (19 / 0.5) + 1;
               = (444 * 64) + 39
               = 28416 + 39
               = 28455

But now comes the problem. If I zoom out just to scale 0.75 it does not work any more. The pixel amount changes from 32768 to 18432 pixels since texture size is 96 x 192. Mouse coordinate is transformed to point (28, 166). The formula gives me a wrong pixelIndex.

var pixelIndex = ((166 / (0.75 * 0.75)) * 96) + (28 / 0.75) + 1;
               = (295.11 * 96) + 38.33
               = 28330.66 + 38.33
               = 28369

Does anyone have a clue what's wrong in my code? Must be the first part (28330.66) which causes the calculation problem.


texts: Texture in model not rendered by BasicEffect

texts:
UPDATE: It is apparently the BasicEffect that is the culprit here. I tried to use another effect (which I coded myself) and then it works!?!? )I kinda like the EnableDefaultLighting, though...)

So this question is now rephrased to: "what in the model exported by Blender can cause BasicEffect to fail to render the texture?".

I have imported this model into Blender and exported it to an .fbx file and imported it into my XNA project. The problem is that the model is pitch black (just as it is in Blender when I look at it in object mode) when drawn in XNA. I have verified that the texture really is there (and that only one iteration is made):

       foreach (var mesh in _model.Meshes)
            foreach (var part in mesh.MeshParts)
                if (part.Effect is BasicEffect)
                {
                    var be = part.Effect as BasicEffect;
                    using ( var stream = File.Create(@"c:\test.jpg") )
                        be.Texture.SaveAsJpeg(stream,2048,2048);
                }

I have followed exactly the same procedure with other models and it has worked. Since the model looks good in Blender and the textures really makes it into XNA... what can be wrong here?

For what it's worth: one difference from what I'm used to is that these textures are not stored inside the .fbx but in a separate subfolder, but the XNA content importer finds them (I get an error if I try to remove them).

UPDATE: it may be important to mention that this model actually has three textures: diffuse, specular and normal maps. However, ONE of them should be projected by the BasicEffect, right?

UPDATE: a screen shot from Blender.


texts: How to improve load times of audio files without loosing too much quality for HTML5 game?

texts:
I'm creating an HTML5 game. We have high fidelity composed music, in the format of wavs and mp3s— some ogg. Game engine we are using is melon JS.

The wav files are generally 3x time size of mp3s, but even loading the mp3s is by far the slowest asset to load on the web game.

I've tried compressing file mp3s at http://www.mp3smaller.com/, @ mp3 Bitrate 32Kbps which resulted in 89% reduction in file size. This significantly improves load time of the game, but it's as though we lost 89% of the quality.

Any recommendations for lossless (or close to) compression services/techniques with significant file downsize but little quality loss?

In images, I know we can take a .png and save as .jpg at lower fidelity, saving about 70-80% in space...but to the eye, it's impossible to tell.


texts: Why does this code work for a stationary object, but not a moving one?

texts:
I use the following chunk of code to make bullets that fire towards the player's ship:
@Override
public void onTimePassed(final TimerHandler pTimerHandler)
{
    pTimerHandler.reset();
    if(spawnBullets){
        for(int i = 0; i < enemies.size(); i++){
            if(enemies.get(i).isShooter()){
                //shoot from this enemy to ship
                final Vector2 v = new Vector2(ship.getX() - enemies.get(i).getSprite().getX(),ship.getY() - enemies.get(i).getSprite().getY());
                v.nor();
                v.mul(BULLET_SPEED);
                createEnemyBullet(enemies.get(i).getSprite().getX(),enemies.get(i).getSprite().getY(), v);
            }
        }
    }
}

This works fine if the enemy is stationary, i.e. just a Sprite with no Body, but when the enemy is moving, my game completely freezes up. Sometimes it will happen immediately (on the first attempt to fire), or sometimes 1 or 2 bullets later.
It gets through this code (a log output after createEnemyBullet works fine), but locks up somewhere before anything else happens. Disabling this section of code makes the problem go away. What could be going wrong?
Edit
Here is createEnemyBullet():
private void createEnemyBullet(float x, float y, Vector2 v){
    //remove old bullet
    if(enemyBullets[enemyBulletCounter] != null){
        makeBulletExplosion(bullets[i].getX(),bullets[i].getY());
        mScene.detachChild(bullets[i]);
        mBulletPhysicsWorld.destroyBody(bulletsPhysical[i]);
        bullets[i] = null;
    }
    //create new bullet
    enemyBullets[enemyBulletCounter] = new AnimatedSprite(x +8, y +8, this.mEnemyBulletTextureRegion); //Nasty magic number, oh well
    enemyBulletsBody[enemyBulletCounter] = PhysicsFactory.createCircleBody(this.mBulletPhysicsWorld, enemyBullets[enemyBulletCounter], BodyType.KinematicBody, BULLET_FIXTURE_DEF);

    enemyBullets[enemyBulletCounter].animate(55);
    enemyBulletsBody[enemyBulletCounter].setLinearVelocity(v);

    this.mBulletPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(enemyBullets[enemyBulletCounter], enemyBulletsBody[enemyBulletCounter], true, true));
    this.mScene.attachChild(enemyBullets[enemyBulletCounter]);
    //update counter
    enemyBulletCounter = enemyBulletCounter < ENEMY_BULLET_MAX -1 ? enemyBulletCounter + 1 : 0;
}


texts:
I'm developing a procedural dungeon generator using pre-built rooms and currently I'm using A* pathing to create corridors to connect one room's door to another room's door.
The problem with this is that the path is very jagged, like this:

whereas I'd prefer it to look like this:

It seems simple enough if only one turn is required, but say it has to connect to the bottom side of the 2nd rectangle, then another turn will be required. Is there any way to do some sort of pathfinding that prefers as straight of lines as possible?


texts: Unity 5: Use Network Simulator, should I?

texts: I am looking to test intelligent prioritisation of a client server game. In my scenario, two clients are connected to the server. I want one client to have a good connection to the server while the others is poor. With my test environment the server and clients are machines within a lab. Can the network simulator within the Network Manager Script do this? Can the network simulator be used on the clients or does it have to be used on the server? Can I, for my situation, have one client use it and bump up the latency or packet loss and then have the other client not use it? I couldn't find anything within Unity's Documentation about this.


texts: How should I define interaction modes in a strategic game?

texts:
I am creating a typical strategic game that gamer can select, deploy and move the game characters (Human mostly) and move or create buildings on its isometric map.

These all are going to be done by gamers gestures obviously, So each time I am handling a tap, pan, swipe or pinch, it is important to know what was the gamer at the middle of or was doing so the new gesture can be handled.

Doing this, I created a global enumerated type including Idle,Select,PanMap and Place and defined a variable with name gameMode to control what the gamer is about to do. for example when the game starts it is valued "Idle" and when gamer touches a building or a character it will be selected only if the gameMode  is Idle and if so gameMode will be changed to Select so the handlePan() method can manage the new gesture and sees if the user is moving the map or a selected building for instant.

When the gamer selects a building and does a pan afterward, the game logic should update the gameMode. When the first touch point of the pan gesture is recieved by handlePan() function, the function will check it against the selected building(currentSelection) to see if the gamer is tended to move the building or it is just a simple map panning, by changing the gameMode to "Place" or "PanMap" and check which gameMode is the case while processing the rest of the touches so they can be handled correctly.

  As I have mentioned above, I have four game modes including idle, select, panmap(while something is selected), place (when gamer is moving something on the map)

Can anyone with strategic experience tell me is this kind of handling user interaction is the best way?

if yes do you think these modes are enough?

Can you tell me what was your modes in case you used this method?

I am using SpriteKit with xcode.


texts: Should a game object class contain the information for how to render it?

texts:
If I have a class called Enemy:
// Simplified version
class Enemy
{
    float xPosition_;
    float yPosition_;
    int hp_;
};

Should this class also contain the information needed to render an enemy?
Like in these two examples:
class Enemy
{
    float xPosition_;
    float yPosition_;
    int hp_;
    Model renderModel_;
};

class Enemy
{
public:
    void drawSelf(Window& window);
private:
    float xPosition_;
    float yPosition_;
    int hp_;
};

Or should the rendering information be inside a special renderEnemy function?
void renderEnemy(const Enemy& enemy)

Which is the better alternative?


texts:
I wrote the script for automatic repetition of texture background. To save it I typed Cmd+S. I dragged and dropped the script to Background in Hierarchy. When hit play button the texture doesn't scale and doesn't repeat itself. What is it that I am doing wrong?

using System.Collections;

public class TiledBackground : MonoBehaviour {

    public int textureSize = 32;

    void start(){
        var newWidth = Mathf.Ceil (Screen.width / (textureSize * PixelPerfectCamera.scale));
        var newHeight = Mathf.Ceil (Screen.height / (textureSize * PixelPerfectCamera.scale));

        transform.localScale = new Vector3(newWidth * textureSize, newHeight * textureSize, 1);

        GetComponent<Renderer>().material.mainTextureScale = new Vector3(newWidth, newHeight, 1);
    }
}

Expected Results:

Results that I'm getting are same as before. Script doesn't seem to work:


texts: Create Adventure Game Scene/Room/Backdrop from Real Photo

texts:
Is there a suitable software or a good tutorial for creating 2D rooms/scenery for adventure games from real photos?

Is it possible to achieve good results by using photos, or the hand-drawn style will always be the best choice?

Thank you!

--- EDIT ---

I want to clarify that I'm particularly interested in the art creation process, not on the environment in which to build games. I'm writing the game in Java for Android, but I don't think it matters.

Also, I'm not trying to decide if the game will have photo realistic rooms or not - I want to achieve 2d pixelated, old-school style background scenes and I wonder if this can be made from photos, because I cannot draw them myself.

For example, can I shoot a scene with my camera and then make it look something like the image in the following link:

PIXEL ART FOREST

I know that I cannot get the same quality as an absolutely hand-drawn pixel, but I'm looking for some decent technology/tutorial/software to make them somewhat similar.


texts:
I am Developing a game in AndEngine Gles2. I have splash scene, loading scene, menu scene and Level1 scene. I am using a Screen Manager to manage all scenes so  I can easily switch between splash, loading and menu scenes.

The level1 scene is also loaded from menu perfectly but a problem occurs when I go back to menu scene on the completion of level. The screen turns black and nothing is shown after that, but the music keeps playing and logcat logs continue. I think the problem is with unloading the resources of Level1 because the switching between other scenes is perfect. I can't give complete code, as it's too long.

I am using bitmapTexture region, Sprites, bodies, physics Word, hud and fixtures etc. Here is my unload method:

unload(){
    setChildrenIgnorUpdate();
    clearChildScene();
    clearEntityModifier();
    clearTouchAreas();
    clearUpdateHandler();
    BitmapTextureManager.getInstance().destroyInstance();
    destroyPhysics();
}


texts:
I'm making a 2d game in which units occupy a dynamic area of the map.

This area will be a rectangular shape like in the following picture. The exact shape will change during gameplay.

How should I draw these shapes?

Should I use a mesh for this? If so, how would I find the vertices of the shapes?

Can I somehow use a "mask" for this? Render a filled rectangular and then subtract those parts which are outside of the shape maybe?

Optional questions: How would I draw a stroke / outline around the whole outer edge of the shape?


texts: Get world object transform relative to another object (potential parent)

texts:
I'm attempting to parent a bullethole decal to a dynamic object. I've figured out how to set the correct position for the bullethole object so that it shows at the correct position of the dynamic object, but once that dynamic object is rotated, parenting new bulletholes are skewed because I'm not compensating for the rotation of the dynamic object (the child object, bullethole decal in this case, is translated relative to the parent, which is why I'm attempting to remove the initial rotation of the parent object to get the actual rotation for the child). I've probably done a terrible job of explaining this...so here is a video of what I'm working on (note that the bulletholes that are added to the barrel before it is moved stay where they should be, and it's only after the barrel is rotated that new bulletholes become skewed)
So I believe I know what needs to happen, I'm just not sure how to go about implementing it. I need to compensate for the rotation of the barrel at the time the bullethole is parented to it, setting the rotation of the bullethole to this value. Possibly an easy question to answer for someone with experience working with quaternions.
if (raycast.hasHit())
{
    auto hitPoint = vel::helpers::functions::bulletToGlmVec3(raycast.m_hitPointWorld);

    bulletObject->currentPositionFromScreen = hitPoint;
    bulletObject->disposeOnNextTick = true;

    auto normal = vel::helpers::functions::bulletToGlmVec3(raycast.m_hitNormalWorld);
    float nrmDot = glm::dot(normal, glm::vec3(0.0f, 1.0f, 0.0f));

    auto bulletHoleAdjustmentValue = this->currentBulletHoleIndex == 0 ? 0.00001f : 0.00001f + (0.00001f * this->currentBulletHoleIndex);
    auto bulletHolePosition = hitPoint + (normal * glm::vec3(bulletHoleAdjustmentValue, bulletHoleAdjustmentValue, bulletHoleAdjustmentValue));

    auto bulletHoleActor = this->bulletHoleQueue.at(this->currentBulletHoleIndex);

    if (this->currentBulletHoleIndex < (this->bulletHoleQueueSize - 1))
        this->currentBulletHoleIndex++;
    else
        this->currentBulletHoleIndex = 0;

    bulletHoleActor->getTransform().setTranslation(bulletHolePosition);

    if (nrmDot < 1.0f && nrmDot > -1.0f)
        bulletHoleActor->getTransform().setRotation(glm::toQuat(glm::transpose(glm::lookAt(hitPoint, bulletHolePosition, glm::vec3(0.0f, 1.0f, 0.0f)))));
    else
        bulletHoleActor->getTransform().setRotation(90.0f, glm::vec3(1.0f, 0.0f, 0.0f));

    bulletHoleActor->setVisible(true);

    // if physics object has a user pointer, parent bullethole actor to the actor which that value represents
    if (raycast.m_collisionObject->getUserPointer() != nullptr)
    {
        auto dynamicActor = (vel::scene::stage::Actor*)raycast.m_collisionObject->getUserPointer();

        bulletHolePosition =  bulletHolePosition - dynamicActor->getTransform().getTranslation();
        bulletHoleActor->getTransform().setTranslation(bulletHolePosition);

        // Was thinking below would work, but it does not for some reason?
        //auto newRotation = bulletHoleActor->getTransform().getRotation() * glm::inverse(dynamicActor->getTransform().getRotation());
        //bulletHoleActor->getTransform().setRotation(newRotation);

        bulletHoleActor->setParentActor(dynamicActor);
    }

}


texts:
I'm trying to make a tile matching game. User can select a pair of tiles from a square grid, and if they match, both are removed from the grid.

Tiles are matched if:

they are of the same type (many types of tiles are in the grid) AND
they can be connected in the grid (either adjacent, or has a clear path of empty spaces between them in the grid)

I would like to scan the grid in advance and find the currently matching pairs (desirably with the path that connects them). Thus I can:

give hint to users if they're stuck in finding a pair
detect a situation when no more pairs can be matched (so the tiles will be reordered)

Ideally during the scan each tile pair of the same type should be taken and checked for matching. Is there any algorithm/technique I can use in here to obtain an optimized approach in finding the connecting paths?
Also, is there anything I should take care of while initializing the grid (currently just random assignment) so as to ensure at least some tiles are adjacent in the beginning (and that I won't have to reorder them too much during the game) ?


texts:
I'm trying to find a way to handle reflections for a breakout clone.

I would upload an image to the post instead of the following paragraph, however i have not yet gained the privilege of that yet.

If the ball intersects the left hand side i want it to bounce off to the left. if the ball intersects the right hand side i want it to bounce off to the right. if the ball intersects the middle section i want it to bounce up the way. i want to learn how to make it bounce in a varying direction dependant on what side of the left, right, or middle section was intersected

I would like to not use three separate rectangles for this, i want to learn how to do it with one.

I use a Vector2 for ball velocity, projVel.

It's position is projPos.

A rectangle for the paddle lightRect.

The reason I use proj.collRect for the beginning of the if is because I cannot use the intersect method with Vector2.

This is my makeshift collision handler at present, which does work but the speed changes to an extent which renders the game unplayable. The speed clamp i have only slightly slows it down i think. i have a variable for projSpeed i cannot clamp that or it will never be able to stop.

if (proj.collRect.Intersects(lightSaber.lightRect))
{
            proj.projPos.Y = lightSaber.lightRect.Y - proj.projTxr.Height;
            proj.projVel.Y *= -1;

    proj.projVel.X = 10 * (proj.projPos.X - lightSaber.lightRect.Center.X) / (lightSaber.lightRect.Center.X);
}

        proj.projVel.X = Math.Max(-4, Math.Min(proj.projVel.X, 4));
        proj.projVel.Y = Math.Max(-4, Math.Min(proj.projVel.Y, 4));

Help me by showing me how I could do this, maybe in the Math. method, or even an alternative to .Intersects so I can use projPos instead of collRect.

I really am not sure where to start, if there is another way I could do it an example would be great.


texts: Soccer national teams uniforms and copyright when developing a soccer game

texts:
I have a project to be accomplished in a distant future about a soccer game.
I´ve read that you can´t feature the actual national teams uniforms without getting permission from FIFA.
Is this only for special designs or for jerseys which are a single colour (most of them) too?
Can you copyright a color? From what I know, most copyright laws don´t allow for a single colour or color combinations to be registered, but maybe in the context of a specific sport and specific teams it is allowed.

PS: thanks, when and if this gets commercially serious, I will seek legal advice.
To be more precise, by presenting a team as Germany with a white shirt and black pants, no logo, no real player names and no real stadiums, do you think that would be considered a copyright infringement?

PS2: the RGB knob approach is what I thought of for teams created by each user. But also though it would be nice to have a special competition which would be a world cup.


texts: Adding newly created objects into a vector inside the object?

texts:
Would some thing like this work?

RawModel::RawModel(GLuint vao, GLsizei count)
    : m_VAO(vao), m_Count(count)
{
    m_RawModels.push_back(this);
}

RawModel::~RawModel()
{
    for (GLuint i = 0; i < m_RawModels.size(); i++)
        delete m_RawModels[i];
}

I am fairly new to the language and I don't know if it would work.


texts:
I'm building a tooltip item like that

I would like to keep this information cached on the client side, avoiding that whenever the information is displayed it's necessary to make a request to the server, but make the cache is not the problem, the problem is that an item can have its attributes modified and the cache on the client side will show wrong information.

My question is, cache is a good idea? if yes what is the best solution?


texts:
I am making my first game in python and I am really stuck at with a physics problem. The game I am trying to make is a copy of the game Breakout. In Breakout, the player controls a "paddle" at the bottom of the screen, which the ball will bounce off of.

I have got the collision to work, but I want the angle between the ball's direction vector and the "paddle" to have an impact on the angle at which the ball leaves the paddle. How can I make this work? I have tried a lot of things, but I can't get it to work.

In these situations I want the angle to be sharper when the ball hit's closer to the edge of the paddle. How can I calculate and make these angles to work?


texts: Looking for good comunication schema in turn-based game with multiple players

texts: based coop game that will need to communicate to the server to handle the game process. Basically I need to be able to invite to the game, progress through turns (one player at a time) and finish in win or loss. Also players could drop off from the game and the game should continue. Is there a known basic schema for this or a set of standards?


texts: How to get the complete width of SKSpriteNode which has many child nodes

texts:
I have a Sprite node with many 6 child nodes. Each are placed one after another in X-axis.
I want to know the complete with of the Sksprite node.

SKSpriteNode *array = [SKSpriteNode node];

[array addChild:box1];
[array addChild:box2];
[array addChild:box3];
[array addChild:box4];
[array addChild:box5];
[array addChild:box6];

array.size.width dosen't get me any size, so how should i get the complete width of array with child nodes..

If i add multiple sprites to NSMutalbleArray then how can i get the width of the complete array.


texts: What is the point of "delta" in this code? Does it reflect a standard thing in game dev?

texts:
I know very little about game programming but would like to learn more. I am trying to understand the code for this game. I am trying to understand why the code is passing a "delta" to Shipcontrols.js, which changes the direction of the ship based on user input.

Basically the game calculates "delta" every loop...

Here is an abbreviated version of the stack that uses delta thru one loop...

var delta = now - this.time;
this.time = now;
this.current.render.call(this.current, delta, this.renderer);

Steps into here...

ctx.manager.add("game", scene, camera, function(delta, renderer)
{
if(delta > 25 && this.objects.lowFPS < 1000) this.objects.lowFPS++;
var dt = delta/16.6;
this.objects.components.shipControls.update(dt);

Steps into here...

bkcore.hexgl.ShipControls.prototype.update = function(dt)
{
var pitchAng;
var yaw;
var roll;
if (undefined != hand){

Which does stuff like this...

if(this.key.forward)
    this.speed += this.thrust * dt;
else

and this...

if(this.key.right)
{
    angularAmount -= this.angularSpeed * dt;

What is the point of delta here? Is it just trying to introduce an element of randomness? The code for this game is very good. Why did this guy use delta?


texts: Dynamic body in Box2D with fixed position

texts:
I need to fix the dynamic body position so that it would not rotate and would not move even if there are other forces, collisions and so on. Let me first explain why I need this.

I have a dynamic body which is the game character. There are non-moving objects that the game character should land on and get some energy as long the character is in contact with those bodies. As these bodies are non-moving it would be natural to make them Static or Kinematic. But in my case I cannot do that, as far as there is another Kinematic body with which all the game items should be collided and on EndCollision event those items should be removed. But in Box2D static and kinematic bodies don't collided with each other. So I have to make my game item on which the character should land Dynamic but still should be sure that it will not move. How should I do this?


texts: I have been making my first game, I have a number of levels I was thinking of making, around 20-30 but I'm not sure if this is too many. Is there a hard and fast rule for number of levels to include in a game?


texts: How can I draw a simple 2D line in XNA without using 3D primitives and shders

texts: I would like to be able to draw arbitary lines in my sprite based 2D XNA game. How can I draw a simple line on screen in XNA without dealing with vertex arrays or shaders.


texts: Make one object rotate to face another object in 2D

texts:
In my 2D project, I have an object that is sometimes above or below another object.

Once the primary object comes in close proximity with the secondary object, I want the object to rotate on the z axis so that the front of the primary object is facing the secondary object.

(Here, following Unity's default setup, the z axis is the axis pointing into the screen)


texts: Creating a queue for BeginInvoke method - loading chunks

texts:
I have a voxel game similar to Minecraft. I have a funciton PushLoadedChunks(Direction) that pushes all of the loaded chunks forward, backward, left, right. This is done with sfd.BeginInvoke(PushLoadedChunks, null, null).

This works great until I fire two of these quickly, which happens if the user goes diagnol. It errors out because two threads are pulled trying to modify the same data, both writing to the same thing because they try to load the same chunks. I wanted to do something like this:

Create one standard thread and a queue to push through. Instead of invoking PushLoadedChunks, I wanted to add it to the queue and have that single thread work through each chunk one after another, proving to be slower performing but more stable code.

I am struggling because Invoke seems to wait for the chunks to return which works, but freezes my player until it is loaded. I need reference in creating a "queue" of sorts, or help setting up a single thread to run each method when they are called and wait until one is finished to do another.

Does anyone have  any advice or resources I could look at to see the best way to complete my task?


texts: There is an understanding like isometric or 2.5D games. As I understand those are the same things. But I could not understand completely what is it. Is it about how the art for the game is drawn? I mean if art is drawn such that you see the game scene from the angle (visible from a top-down perspective or side view [from wiki]) and not perpendicular, is this isometric? Or there are some programming tricks that make game isometric, such as ability of the hero to move in 3 dimensions whereas it actually moves only in 2D like in old Nintendo games (Ninja Turtles or Double Dragon). Please explain this understanding.


texts: How many matrices do i need to represent a rectangular figure and translate it?

texts:
I'm learning math at the moment and i can't really understand the purpose of the matrix.
Yes, i've watched several tutorials out there and reading the book but still confused.

Correct me if i'm wrong.
We need one matrix to represent one point(vertex) on the screen. So to represent a rectangular, we need 3 matrices. Right?


texts: Why the layer must be created from my class and not from layer class

texts:
I am confused about something.
I have the following example:

mainMenu.h

class mainMenu : public Node {
public:
    static Scene* createScene();
    virtual bool init();
    void GoToGameScene(Ref *pSender);
    CREATE_FUNC(mainMenu);

private:
    mainMenu() {};
    ~mainMenu() {};

};

mainMenu.cpp

Scene* mainScene::createScene(){
    auto scene = Scene::create();
    auto layer = mainScene::create();
    scene->addChild(layer);

    return scene;
}

Focus on this part.

auto scene = Scene::create();
auto layer = mainScene::create();

Why do we create layer from mainScene not from Layer

For example: Why we do this:

auto layer = mainScene::create();

If we can do it, like creating a scene

auto layer = Layer::create();


texts: Drawing realistic 2d waves with SDL2 and Rust

texts:
I am making a very simple 2d topdown sailing simulator with Rust and rust-sdl2. I am having a very hard time figuring out how I should implement wave rendering. My current idea is to use a Vec<Spring> and render all of the wave shading on top of these springs. But I have no idea how this rendering should be done. Here is an image which mostly represents the effect I want:

Most questions here are to do with OpenGL which I have no experience with and don't understand at all. Any pseudocode would be particularly helpful!


texts: Move from point a, to point b, and determine the accuracy

texts:
Let's say I have a circle at point a (0,0), and I wish to move it to point b (23,58), whatever, how can I accurately do this with a speed variation if I wanted. (I'm doing this in javascript).

Every attempt I make ends up causing it to shake (as the accuracy is off) someone suggested clamping but I have no idea how to do this or where to even look to figure out how.

Any sources, examples, references, guides, tutorials... that correctly explain it regardless if it's one piece of the puzzle is appreciated.

If it helps, I'm using mouse clicks to determine the position where I should move the object to (Top-Down):

if (char.end.x != char.start.x || char.end.y != char.start.y) {
    char.distance = {};
    char.distance.x = char.end.x - char.start.x;
    char.distance.y = char.end.y - char.start.y;

    char.distance.hypot = Math.sqrt(
        char.distance.x * char.distance.x +
        char.distance.y * char.distance.y
    );

    char.distance.moves = char.distance.hypot / char.speed;
    char.start.x += Math.floor(char.distance.x/char.distance.moves);
    char.start.y += Math.floor(char.distance.y/char.distance.moves);
}


texts: How can I render a 2D image to my screen using Direct X 11?

texts:
I am trying to render an image to my window using Direct X but I don't really want a "3D" world as such, and I don't really want to set up all the vertex/index buffers as I won't need them. I am performing all of my calculations and operations using compute shaders which returns me an image. As the file io is quite a bottleneck, I am looking to just render the image directly to the screen to increase performance. My question is, how would I go about this using Direct X 11? I have looked at some examples already such as rastertek and other questions on SO but they are either over-complicating the matter, or they want a solution to font drawing etc.

At the moment I am able to produce a blank screen using the following code and the screen size is the size of the image retrieved from the GPU. I am looking to draw this entire image to my back buffer or some render target, and then display it.

void Application::Draw()
{
    float ClearColor[4] = { 0.5f, 0.125f, 0.3f, 1.0f };
    context->ClearRenderTargetView(_pRenderTargetView, ClearColor);

    // compute shader operations, retrieve image data from gpu
    // draw image to back buffer/render target then present

    swapChain->Present(0, 0);
}

From Why can't I write to my render targets?, I have tried the solution using

ID3D11Resource * backBufferResource;
_pRenderTargetView->GetResource(&backBufferResource);//backbuffer render target
context->CopyResource(backBufferResource, gpuResource);

This doesn't seem to throw any errors, but it doesn't change the output on the screen. It is mentioned that the back buffer must be the exact same format as the image we're trying to copy to it so this may be the issue. My swap chain desc is as follows

DXGI_SWAP_CHAIN_DESC sd;
ZeroMemory(&sd, sizeof(sd));
sd.BufferCount = 1;
sd.BufferDesc.Width = _WindowWidth;
sd.BufferDesc.Height = _WindowHeight;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;//FORMAT DIFFERENT
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = _hWnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;

and my image format is

DXGI_FORMAT_R32G32B32A32_FLOAT

If I try to change the swap chain format it throws a memory access violation.


texts: colliding 2 moving and rotating sprites in xna 2d

texts: I recently started making a game in windows phone XNA, I have a rocket in the middle that I can rotate and has a thrust to speed up in the direction it is facing and meteors coming out. The point is to survive as long as you can and avoid collision with the meteors. I can't manage to implement the collision between two moving and rotating sprites which are the rocket and a random meteor. I've seen rectangular collision which to me appears bad but maybe I am coding it a bit wrong and the pixel collision is way complicated :/ any help would be appreciated, thanks in advance :)


texts: What Scala-oriented game frameworks exist?

texts:
I'm looking into Scala game development, and wondering if there are any game frameworks oriented towards it, rather than Java.

Java has Slick2D and LWJGL, but they do not take advantage of Scala features.


texts:
I have a "A1" scene, and from there, I want to create a new scene "A2" on button
click and then I want to load the same scene. Creating a scene can be done with,
Scene NewScene = SceneManager.CreateScene("A2");

But this scene is an empty scene and as it is not added in build settings so I used
EditorSceneManager.LoadSceneInPlayMode

which would allow me to load scene without having it in build settings. Till here it is going well but now how do I add the maincamera in this new scene programmatically? I have tried something like
 public void CreateNewScene()
    {
        Scene NewScene = SceneManager.CreateScene("A2");
        EditorSceneManager.LoadSceneAsyncInPlayMode("A2",new LoadSceneParameters {loadSceneMode = LoadSceneMode.Single});
        LoadCamera();
    }

public void LoadCamera()
    {
        Camera camera = gameObject.AddComponent<Camera>();
        Instantiate(camera, new Vector3(0, 0, 0), Quaternion.identity);
    }

after the new scene is loaded.


texts: How to avoid destroying information when scaling

texts:
I'm in the progress of making a simple 3D editor, just for developing skills on 3d graphics.
After implementing some basic tools, I realize that scaling isn't working as I expected.
For example, when you scale down a model to a flat plane along some axis, how is it possible to restore that model when you scale up again on that axis?
Every vertex has been crunched to the same position, so they will all be scaling in the same way, so the model's vertex layout will be lost.
I assume that I need some metadata or "shadow copy" of the model, but I'm not sure.
How can I solve this problem in my editor?


texts: OpenGL to DIRECTX RayCasting and Picking

texts:
Im doing some ray casting and picking from a book that is Open GL. I Get perfect movement on the x and y(I rotated the grid 90 so it would match the x and y. Buy when I try to put it on the the z axis, it is not right

How can I  get this to work in a left handed coordinate system in directx 11?

Here is my code, maybe somneone can help out.

GetPickRay( float sx, float sy, float fov, float width, float height )//sx-sy window coordinates, fov fieldofview, width height size of window
{
    //view cords from NDC,SCREEN
   float vx = (+2.0f*(float)sx/(float) mClientWidth - 1.0f)/P(0,0); //P is projection matrix
    float vy = (-2.0f*(float)sy/(float) mClientHeight + 1.0f)/P(1,1);

    XMFLOAT3 viewPoint2(vx,vy,1.0f);
    XMVECTOR viewPoint = XMLoadFloat3(&viewPoint2);
    XMMATRIX invView = XMMatrixInverse(&XMMatrixDeterminant(V), V);
    XMVECTOR T = XMVector3Transform(viewPoint,invView);

    return T - EYEPOINT;
}

    OnMouseDown(WPARAM btnState, int x, int y)
{
    mLastMousePos.x = x;
    mLastMousePos.y = y;

    XMVECTOR ray = GetPickRay( (float) x, (float) y, 45.0f,(float) mClientWidth,(float)mClientHeight );

    XMFLOAT3 ra;
    XMStoreFloat3(&ra,ray);
    XMFLOAT3 EyePoint;
    XMStoreFloat3(&EyePoint,EYEPOINT);
        // compute intersection with z=0 plane
        float t = -EyePoint.z/ra.z;
        XMVECTOR tt = EYEPOINT + t*ray;
        XMFLOAT3 d;
        XMStoreFloat3(&d,tt);
        moveIT = XMMatrixTranslation(d.x,d.y,d.z);

My up vector for the view matrix is 0,1,0

Thx if someone could point me in the right direction


texts: How to import animation from MotionBuilder to Unity?

texts:
I have an animation (https://i.imgur.com/VZcdgHs.mp4) working in MotionBuilder.
I have tried exporting the whole thing as an FBX, and also have tried exporting as a Motion File.
Either way, when I import it into Unity and set up the Mecanim and Animation Controller and set the animation as the "Entry State" animation... My character moves to one pose and then stays frozen.
Does anyone know how to correctly get an animation from MotionBuilder to animate a character in Unity?


texts: Any learning/studying material for C/C++ that use game programming as learning context out there?

texts:
As most of game programming is done - I read on this very site - in C/C++ I was wondering if there is any learning/studying material for C/C++ that would target specifically game programming.

I am not looking for material about "developing games" or "software architecture for games", but rather for material that uses "game programming" as the CONTEXT for introducing and illustrating C/C++ features, idioms, programming techniques, etc...

With a simile: think to the GOF book on design patterns. There, they used "developing a text-editor" as a context for introducing design patterns, but the book is most definitively not a book about "developing text-editors".

EDIT: The book should contain code examples that are not dependant on proprietary technologies (e.g.: it should use OpenGL rather than DirectX, a dialect of C known to gcc rather than needing a specific commercial compiler, etc...)

Thanks in advance for your time and advice!

PS: My background: I am a programmer with a solid experience in OO scripting languages and only some experience in C and Assembler (on AVR microcontrollers), so I am thinking to mid-to-advanced level material, rather than tutorials for beginners, although it might be interesting to take a look to the latter ones if nothing else is available.


texts: Where to find market research info on adventure games?

texts:
Looks like adventure games are on the rise again. There were several great releases in 2012, including brilliant and highly acclaimed Walking Dead from TellTale.

Is there a market research that proves the new rise of adventure games? Bonus points for revenue estimates and such. I'm particularly interested in mobile games segment, but everything else is of interest as well.


texts: Unity Transform.Position not returning expected position

texts:
So in my scene hierarchy, I have an object laid out like so;
-Level1
--Level2
---Level3
----Level4

My script is attached to the Level1 object. When I try to find the transform.position of Level4 by way of Debug.Log to the console, I get the position of Level1, and so when I change the position of Level4 inside Level3, the data sent to the console doesn't change, still shows the position of Level1.

I do not believe this may be relevant, but what I am doing is an IK rig to move a character's limb. The object for which I am attempting to find the position is nested inside the skeleton of the character. The value returned to me is the position of the prefab placed in the scene. All of the objects (Level1 through Level4) are not explicitly moved, however they inherit their positions from the rotation of their parent.

My code to read the position is as follows:

Debug.Log(object.position);

Where object is already a transform. I have also tried:

Debug.Log(object.transform.position);

But still, all I get is the position of the top level parent.

Thanks for any help.

ADDITION

Ok so to expand on the question, I'll explain exactly what I'm trying to do.
I have the mecanim example and unity 5.0.1f1. I have the Mecanim Example project from the asset store and I'm in the animator controller scene. I have enabled IK pass on my base layer, and have placed my code in the "idle run jump" script, attached to the top level of the game object for the playable character.
I have then attached an empty game object inside the left foot to mark the location of where the left heel meets the floor.
This object is attached in the inspector to a variable in the "idle run jump" script, which then receives the ik pass through the function OnAnimatorIK.
My aim is to get the foot to follow the same position as another object, where leftFoot follows leftFootObj.
My code is as follows;

using UnityEngine;
using System.Collections;

public class pos : MonoBehaviour {

    protected Animator animator;
    public float offset = 0.156f;

    public Transform leftFoot;
    public Transform leftFootObj;

    void OnAnimatorIK() {
        if (animator == null)
            return;

        if (leftFoot != null) {
            Debug.Log(leftFoot.position);
            animator.SetIKPositionWeight(AvatarIKGoal.LeftFoot,1);
            animator.SetIKRotationWeight(AvatarIKGoal.LeftFoot,1);
            animator.SetIKPosition(AvatarIKGoal.LeftFoot,(leftFootObj.position+(Vector3.up*offset)));
            animator.SetIKRotation(AvatarIKGoal.LeftFoot,leftFootObj.rotation);
        }
    }

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

        if(animator.layerCount >= 2)
            animator.SetLayerWeight(1, 1);
    }

}


texts: Finding next experience level using the square root?

texts:
I recently asked this question on how to calculate a level based on experience:

Algorithm for dynamically calculating a level based on experience points?

I am using the following calculation to determine the players level:

decimal experience = 1829;
decimal rawLevel = (decimal)(.06 * Math.Sqrt(experience));
decimal level = Math.Floor(rawLevel);

For my test, 1829 experience points equates to 2.56600857364117M, which I floor to level 2.

My question is, how can I figure out how many points it would take to get to the next level based off of the calculation above?

I know the next level is 3, so I would need to figure out how many points equate to level 3 so that I can find the difference.  What formula would I use, given the constant .06 above?

Update: Solution:

int experience = 150777;
decimal rawLevel = (decimal)(.06 * Math.Sqrt(experience));
decimal level = Math.Floor(rawLevel);
decimal nextPoints = (decimal)Math.Pow((double)(level + 1) / 0.06, 2);


texts: Rotate object relative to camera position

texts:
I am trying to write code that is able to rotate object, based on camera position. So far I ended up with a code posted below. Moving mouse up and down (y input) caused to rotate object in y axis, instead of x. That's why I used cross product.
Achieved result is working not exactly as I expected. Rotation is different for every object, dependent on their pivot. I am not exactly sure how it fix it properly.
public class DragRotate : MonoBehaviour
{
    public Camera camera;
    public float rotationSpeed = 1;

    private void Update ()
    {
        float x = Input.mousePosition.x * rotationSpeed;
        float y = Input.mousePosition.y * rotationSpeed;

        var rot = camera.transform.TransformDirection (new Vector3 (x, y));
        rot = Vector3.Cross(rot, camera.transform.forward);

        transform.rotation *= Quaternion.Euler (rot);
    }
}

This script will be primarily used with one axis rotation, this feature is not implemented in code yet, but it's shown in the use case.
According to attachment, I want to rotate selected cube (visible pivot is set to global). It's worth to say, that in this examples padlock has always same position and rotation, the only thing that changes is position and rotation of the camera:

a) Swipe from bottom to top - negative rotation on X axis.b) Top
to    bottom positive on X axis.  c) Other axes should be locked,
but for    example swipe from right bottom to left top should rotate
like    example a), but taking into consideration only y (vertical)
input.
This should behave exactly like example 1, but taking camera rotation into account. So 1a is 1b, 1b is 1a etc.
Swipe from left to right should result in 1a rotation, swipe from right to left should result in 1b rotation. Bottom to top or top to bottom should have no effect at all.


texts: Saving and Loading File to Application.persistentDataPat not working on Android device

texts:
I am trying to save data and load data on the project i am working on, but i cant seem to get it work in an Android device it works fine on Unity when i play it, not sure what i am missing or done wrong here is the following code i use to save and load data.

using System.Collections;
 using System;
 using System.Runtime.Serialization.Formatters.Binary;
 using System.IO;

public class PlayerInfo : MonoBehaviour {

 public static PlayerInfo playerData;
 public int gameCoins;

 void OnDisable()
 {
     BinaryFormatter bf = new BinaryFormatter ();
     FileStream file = File.Create (Application.persistentDataPath + "playerinfo.dat");

     PlayerData data = new PlayerData ();
     data.gameCoins = gameCoins;

     bf.Serialize (file, data);
     file.Close ();
 }

 void OnEnable()
 {
     BinaryFormatter bf = new BinaryFormatter ();
     FileStream file = File.Open (Application.persistentDataPath + "playerinfo.dat", FileMode.Open);
     PlayerData data = (PlayerData)bf.Deserialize (file);
     file.Close ();

     gameCoins = data.gameCoins;

 }

 }
 [Serializable]
 class PlayerData
 {
     public int gameCoins;
 }

Anyone can give me an idea of what i need to do or look at i will be very much appreciated, and many thanks in advance for taking the time to help.


texts: What sort of things can cause a whole system to appear to hang for 100s-1000s of milliseconds?

texts:
I am working on a Windows game and while rendering, some computers will experience intermittent pauses ("hitches" for lack of a better term). When profiled they appear in seemingly random places in the code. Eventually I noticed that it wasn't just my process that was affected, but (seemingly) every process on the system. All of the threads in my application hitch at once. The CPU utilization drops during these hitches and it appears as if most processes make no progress.

This leads me to believe this may be an Operating System or Driver issue, but it only occurs while playing the game (and only on some systems). What sort of operations might the operating system be doing that would require the kernel to pause all user threads and block. Some kind of I/O? At first I thought of paging but my impression is that would only affect a single process, no?

Some systems in use: Windows, DirectX (3d), nVidia cards (unknown if replicates on ATI), using overlapped io for streaming


texts:
Possible Duplicate:
  Good resources for learning about game architecture?

I know that game architecture can vary greatly, especially with the type of game being built, but I know that there are a lot of similarities too.

I feel like I am on the cusp of really having a good grasp on game architecture, but I feel like something is missing. Maybe it's something obvious. So, I want to know, is there a resource out there that is the be-all-end-all guide to 2D game programming concepts, patters and architecture?

Edit:  I'm mostly interested in building platformers and shmups and the like. So, if the resources are related to those types of games, even better.


texts: script execution order on changing scene

texts:
In script execution order , i set A start first before B , and B start first before C .

So normally the script execution order should be A -> B -> C

C is already loaded on scene 1 without the help of other script .

B will be added by C on scene 1 and A will be added by B on scene 2 , and C will be added again by A on scene 2.

The gameobject in which B is attached won't be destroyed when changing scene , or in simple term , DontDestroyOnLoad() .

When Scene 1 loaded , C will load B , B will request scene change , which mean C will be destroyed afterward .After scene change , B will load A , then A will load C . B will request Application.Quit after 50 frame since it's loaded.

So if player start from scene 1 , is the script execution order has changed ? and how is script execution order from start until Application.Quit ? Please explain with details this problem almost made me lose my brian clels .


texts: How can I pass a std::vector to my shader?

texts:
I have a Vector3f type which has x, y, and z properties. I have a std::vector of these vertices which describe my terrain.

I would like to pass these values to a vertex shader through a uniform variable, but all the OpenGL functions expect GLfloat *. Which is the best way to this? I would like to avoid conversions if possible.


texts: Is Flash development for Android below 2.2 feasible?

texts:
Apparently you need to install AIR in your mobile to use Flash apps, and AIR requires Android 2.2 while my Milestone is a feeble 2.1.update1.

There is seriously no Flash lite or other alternative?


texts:
I would like to have a VR camera (for the player) but also have another camera (spectator).
I am using Unity 2019.4.8f1 on the Universal Render Pipeline
I have only been able to find outdated articles:
https://blogs.unity3d.com/2017/12/12/spectating-vr/
https://unity3d.college/2017/05/08/unity3d-spectator-mode-vr/
https://forum.unity.com/threads/using-a-second-cam-while-still-rendering-the-vr-camera-for-the-vr-headset.659434/
Thanks!


texts:
I'm thinking of using cocos2d 2.0 for my next project and am wanting to know if it's possible to have a shader that renders to a texture and that texture be input into another shader?

I have a few effects that need this capability, but haven't been able to find anything that says you can do this.


texts: How do I resolve a sphere-triangle collision in a given direction?

texts:
I am trying my hand at game physics.

I understand that the basic way to pull back a sphere when it collided is to negate the penetration distance:

// If collided...
// `distance`: distance form triangle face; a negative number
// `normal`  : triangle face, in vec3
// `position`: sphere center, in vec3
position.x -= normal.x * distance;
position.y -= normal.y * distance;
position.z -= normal.z * distance;

But I don't want to change y coordinate, while the player is on the ground like this (side view):

How can I calculate the expected translation?

I have these values:

penetration distance, as a negative number (shown in blue)
triangle face normal, as a vec3 (shown in red)
triangle vertices, as 3 vec3s

and

sphere radius, as a number
sphere center, as a vec3

Answers in any programing language are welcome!

updated Jul 17, 2014

I found a hint. It's difficult to explain, I will attach 2 more figures.
It seems, dashed lines in following figures are the translation value what I need, I guess.

and in another case


texts: Including slick2d or slick-util in maven build?

texts:
I'm converting a project to lwjgl and trying to use slick-util as well. There's no slick-util maven repo anywhere (nor slick2d itself anymore). I've included local dependancies before using

    <dependency>
        <groupId>org.newdawn</groupId>
        <artifactId>slick</artifactId>
        <version>237</version>
        <scope>system</scope>
        <systemPath>${project.basedir}/lib/slick-util.jar</systemPath>
    </dependency>

The maven package process runs without issue, but when I try to run the jar, it errors out with a ClassNotFoundException. There's no mention of slick-util in the manifest and I can't find out how to make my game load that jar properly.

Side question: how do I ensure when I distribute my applications, the game properly installs these libraries?


texts: How do you repeat 2D tiles in Java code when you go out of range?

texts:
I am looking up tutorials on how to make 2D games, and I can just copy and paste their code but I would rather know what it means and how to do it.

Suppose you have a 2D game window that has a map width of 64, how do you actually repeat the tiles when you go out of range when scrolling?

In this render method what line of code is actually allowing the game to repeat the tiles when you go out of range?

From the below code this line stands out to me:

int tileIndex = (xTile &(MAP_WIDTH_MASK)) + (yTile &(MAP_WIDTH_MASK))* MAP_WIDTH;

As this line gives you the X and Y coordinates of which tile you are on, it seems like the bitwise & operator is repeating the tiles, please correct me if I am wrong and also explain to me what the & operator is doing?

Code Example:

 public static final int MAP_WIDTH= 64;
 public static final int MAP_WIDTH_MASK= MAP_WIDTH - 1;
 public static final int PIXEL_SIZE= 8;
 public static final int PIXEL_SIZE_MASK= MAP_WIDTH - 1;
 public int[] tiles = new int[MAP_WIDTH*MAP_WIDTH];
 public int[] colours = new int[MAP_WIDTH*MAP_WIDTH*4];
 public int xOffset = 0;
 public int yOffset = 0;

 public void render(int[] pixels, int offset, int row) {
        for(int yTile = (0 + yOffset) >> 3; yTile<=(height + yOffset) >> 3; yTile++) {
            int yMin = (yTile * PIXEL_SIZE) - yOffset;
            int yMax = yMin + PIXEL_SIZE;
            if (yMin<0) yMin=0;
            if (yMax>height) yMax = height;
            for(int xTile = (0 + xOffset) >> 3; xTile<=(width + xOffset) >> 3; xTile++) {
                int xMin = (xTile * PIXEL_SIZE) - xOffset;
                int xMax = xMin + PIXEL_SIZE;
                if(xMin<0) xMin=0;
                if (xMax>width) xMax = width;
                int tileIndex = (xTile &(MAP_WIDTH_MASK)) + (yTile &(MAP_WIDTH_MASK))* MAP_WIDTH;
                for (int y = yMin; y < yMax; y++){
                    int sheetPixel = ((y + yOffset) & PIXEL_SIZE_MASK)*sheet.width + ((xMin + xOffset)& PIXEL_SIZE_MASK);
                    int tilePixel = offset + xMin + y * row;
                    for(int x = xMin; x< xMax; x++) {
                        int colour = tileIndex * 4 + sheet.pixels[sheetPixel++];
                        pixels[tilePixel++] = colours[colour];
                    }
                }
            }
        }
```


texts: How can I support PlayStation 3 controllers in my Java game?

texts: Is there a way to interpret the input from a PlayStation 3 controller, and use it in a Windows and MacOS program that I am writing in Java? I have been looking at SDL and OIS, but they aren't coded in Java, so I would have to write a Java wrapper.


texts:
Im trying to implement an Event System for a game, where there are classes that can fire or handle an event wheter or not they implement these interfaces:

public interface IGameEvent<T> where T : EventArgs
{
     event EventHandler<T> OnEvent;
}

public interface IGameHandler<T> where T : EventArgs
{
    void OnEvent(object sender, T e);
}

everything looked great until i realized that no class can implement more than 1 IGameEvent because it would cause duplicate declaration,

Here is an example:

public class Event
{
    public KeyPressEvent OnKeyPress;
    public UpdateEvent OnUpdate;

    public void AddHadler<T>(IGameEvent<T> eEvent , IGameHandler<T> eHandler) where  T : EventArgs
    {
        eEvent.OnEvent += eHandler.OnEvent;
    }

    public void RemoveHandler<T>(IGameEvent<T> eEvent, IGameHandler<T> eHandler) where T : EventArgs
    {
        eEvent.OnEvent -= eHandler.OnEvent;
    }
}

KeyPressEvent:

public class KeyPressEvent : IGameEvent<KeyPressEvent.KeyPressedEventArgs>
{
    public class KeyPressedEventArgs : EventArgs
    {
        public KeyPressedEventArgs(Keys key)
        {
            Key = key;
        }

        public Keys Key { get; private set; }
    }

    public event EventHandler<KeyPressedEventArgs> OnEvent;

    private void OnCheckForKeyPressed()  //Example
    {
        if (OnEvent != null)
            OnEvent(this, new KeyPressedEventArgs(Keys.Space));
    }
}

Would be better to manually store the suscribers in a list in the EventSystem ?

How slower or faster than this approach that would be?

Thanks!


texts: Unity Rigidbody sitting on top of another Rigidbody does not move with the Rigidbody its sitting on

texts:
I have a mesh with a rigid body that moves back and forth like a platform. Other rigidbodies fall onto the upper surface of this cube. The problem I have is that when the platform rigid body moves the other rigid bodies stay in the position they landed in, they do not move with the cube. Everything else physics wise works.

I have tried adding a physicsmaterial to both the platform and the rigidbodies falling onto the platform but this made no difference.

I do no want to tether them to each other because I want them to fall off when they are pushed by other objects.

The platform is moved back and forth using the RigidBody.MovePosition function.


texts: How to quickly calculate the sight area in a 2D tiled game?

texts:
I have a matrix of tiles, on some of that tiles there are objects. I want to calculate which tiles are visible to player, and which are not, and I need to do it quite efficiently (so it would compute fast enough even when I have a big matrices (100x100) and lots of objects).

I tried to do it with Bresenham's line algorithm, but it was slow. Also, it gave me some errors:

----XXX-        ----X**-     ----XXX-
-@------        -@------     -@------
----XXX-        ----X**-     ----XXX-
(raw version)   (Besenham)   (correct, since tunnel walls are
                              still visible at distance)

(@ is the player, X is obstacle, * is invisible, - is visible)

I'm sure this can be done - after all, we have NetHack, Zangband, and they all dealt with this problem somehow :)

What algorithm can you recommend for this?

For my needs, I'll define visible like this: tile is visible when at least a part (e.g. corner) of the tile can be connected to center of player tile with a straight line which does not intersect any of obstacles.


texts: Get angle in radians given a point on a circle

texts:
I'm working on a dial that rotates around a circle.

This dial should lets you mousemove anywhere in a circle to adjust the position of the dial to a point on the circle with the same angle as the click. For example, from the dial above if you clicked the spot shown in pink below I'd move the dial above that point but on the circle.

I know how to get the position of a point on a circle given a radius and an angle (in radians). That's this formula:

x = Cos(angle) * radius + CenterX;
y = Sin(angle) * radius + CenterY;

However, I am looking to do somewhat of the opposite -- I've got a click point, which I want to turn into a point on a circle (where the control knob goes). I'm trying to use this point (and a given radius) to figure out the angle in radians for it, so that I can place the control knob on the circle at the same angle.

Is there a handy formula I can use to accomplish this?


texts: Does all box2d bodies have collision detection?

texts:
What I want to know is if both b2-static and dynamic bodies have automatic collision detection.

And how do I tell box2D what it should do when it collides with a specific body?


texts: LibGDX - why are the shapes from my ShapeRenderer resizing with my viewport?

texts:
I have created a class called Node which I would like to (currently) contain a single Actor (later I will be adding additional actors, but for now I'm sticking with just one).  The actor is called "body" and is just a container for the position/size of the "Node" actor.

I have also created a Label which I am drawing with a custom font file.

What I am having issues with is that when I RESIZE my app window (on desktop, I'm not currently using Android or any other targets), the LABEL works just fine (stays the same size on my screen), but the Node gets resized with the main window.  That is, if I make the window twice as wide, the square stretches to be twice as wide as it was before.  Why is this?  The coordinates I am using work exactly as I expect UNTIL I resize the screen.  Is there something else I have to do in the resize() method?

App class:

public class App implements ApplicationListener {
    private Stage stage;
    private ShapeRenderer shapeRenderer;

    @Override public void pause() {}
    @Override public void resume() {}

    @Override
    public void create() {
        stage = new Stage(new ScreenViewport());

        shapeRenderer = new ShapeRenderer();

        //  FONT stuff  //  https://github.com/libgdx/libgdx/wiki/Gdx-freetype
        FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/arial.ttf"));
        FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
        parameter.color= Color.ORANGE;
        parameter.size = 24;

        BitmapFont arialFont = generator.generateFont(parameter);
        generator.dispose();

        Skin skin = new Skin();

        Label.LabelStyle labelStyle = new Label.LabelStyle();
        labelStyle.font=arialFont;
        skin.add("default", labelStyle);

        Label label = new Label("DOOT", skin);
        label.setX(110.5f);
        label.setY(110.5f);

        stage.addActor(label);

        stage.addActor(new Node(shapeRenderer));
    }

    @Override
    public void resize(int width, int height) {
        // See below for what true means.
        stage.getViewport().update(width, height, true);
        shapeRenderer.updateMatrices();
        System.out.println(""+width+"x"+height);
    }

    @Override
    public void render(){//} {
        Gdx.gl.glClearColor(0.3f, 0.3f, 0.3f, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        stage.act(delta);
        stage.draw();
    }

    @Override
    public void dispose() {
        stage.dispose();
    }
}

Node class:

public class Node extends Group {
    private Actor body;
    private ShapeRenderer shapeRenderer;

    public Node(ShapeRenderer sr) {
        body = new Actor();
        body.setBounds(10.0f, 10.0f, 100.0f, 100.0f);
        shapeRenderer = sr;
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        super.draw(batch, parentAlpha);

        shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
        shapeRenderer.box(body.getX(), body.getY(), 0.0f, body.getWidth(), body.getHeight(), 0.0f);
        shapeRenderer.end();
    }
}


texts: How do I persist the states of distant objects?

texts:
How would one manage the state of static living things like trees in a large sandbox world? Trees in Minecraft, for example: They grow even when the player is far away.

One way is to save them with a timestamp as they go "out of range" and stop updating them in the usual way. Then re-instate them with a sensible state by running an update with a delta time of the time elapsed since that saved time.

I'm planning a new prototype but this has me a bit stumped.


texts: Should I have an upper limit to the number of update cycles per second in a JS game?

texts:
I'm making a JavaScript game engine for fun and one thing I noticed was that my laptop runs super hot with the simplest game mechanics and that my game is doing about 600 updates per second.

The graphics is already capped at 60 fps, but I'm wondering if I should limit the update cycles so my processor doesn't get owned on the simplest games.

I think the answer is yes, it is just that I've never heard of anyone doing this before, so I wanted others opinions.


texts: How to figure out a users earnt exp based upon calculating the difference by user and player by x?

texts:
How would I figure out a users earnt EXP based upon calculating the difference by user and player by x using this format?

If the user is 60 levels less than me, I would get 0 exp (as that's just bullying).

If the user is within 21 and 59 levels less than me, I would get 1 exp.

If the user is less than 20 levels of mine, I would get 2 exp.

If the user is the equal level they would get 3 exp, however if the user is within my level, and 20 above me I would get 4 exp.

If they were between 21 and 40 levels above me I would get 5 exp

If they were 41 and 60 levels above me I would get get 6 exp

and if they were 61+ levels above me I would get 7 exp

So I'm looking to do something like this -

How would it structure if I wanted to make it (player being me, and the user is the opponent)

if( $PLAYER->level is more than 60 of $USERS->level )
{
$earn = 0;
}
elseif( $PLAYER->level is between 21 and 59 more than $USERS->level )
{
$earn = 1;
}
elseif( $PLAYER->level is between 1 and 20 more than $USERS->level )
{
$earn = 2;
}
elseif( $PLAYER->level == $USERS->level )
{
$earn = 3;
}

I know in SQL they have a between operator, but I cannot seem to find a a PHP one and/or figure out a solution to display what I intend to do above.

Is it possible to do what I intend? Or do I need to find a new solution?


texts: SceneManager.GetActiveScene(); return -1 when Debugging active scene in editor

texts:
I'm trying to use the new SceneManagement since Application.LoadLevel is obscelete and I've read that we need to put it like this.

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

public class UI : MonoBehaviour {

    private Scene activeScene = SceneManager.GetActiveScene();

    // Use this for initialization
    void Start () {
        Debug.Log (activeScene.name);
    }

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

    }

    public void restartLevel(){
        SceneManager.LoadScene (activeScene.buildIndex);
    }
}

The Debug.Log show "-1" and it should be "0" and throw this error in console

Scene '' (-1) couldn't be loaded because it has not been added to the build settings or the AssetBundle has not been loaded.

The Scene is added in the build setting too by the way.

Seems that it can't return me the good index and even with the activeScene.name, still returns NULL. I miss how Application.LoadLevel was easier and more robust that this new way...


texts: is GameObject.Find() a bad idea even for one frame?

texts:
as I searched GameObject.Find and GameObject.FindwithTag are heavy to work with and for reall projects its better to find repalcements.

for a NPC that get instantiated in game it first needs to find player character. for this issue I only can use GameObject.find() .

for a scene with lots of objects maybe its heavy for even one frame if there is lots of objects in the scene. is there any way to set the researching object in head of hierarchi and the NPC to only get that?


texts: Easy Method to Change Color on UI Elements

texts:
This isn't a language-specific thing as far as I'm concerned.  I was wondering what may be a quick way to change the COLOR of a certain on-screen element such as a button and its associated text.

I would assume there is a trick to making a graphics engine so maybe individuals pixels or groups of sprites can have their colors easily shifted.  A lot of game interface buttons and such have this so you know when an event like a click has occurred.

Any pseudo code would be helpful and I am working in Android (not XML fluff), but again, this probably is not a very specific question, just an inquiry on how to go about this.


texts: Biome Transition in a Grid & Borderless World

texts:
I have a universe: a list of "Systems", each with their own center, type and radius.

A small part of such a universe could look like this:

Systems:

Can be very close to a different system, e.g. overlap
Can be inside another, much bigger system
Can be very far away from any other systems
Spawn system specific entities and particles inside the system radius
Have some properties like background color

So far so good. However, the player can fly around freely, inside and outside of systems, in real time.

How do I interpolate and determine things like the background color now, depending on camera position?

E.g. if you are halfway between a green and a red system you should see a background halfway between red and green, or if you are inside a lilac system near the center and at the border of a green system you should get a mostly lilac background etc.


texts: Eliminate delay between looping XNA songs?

texts: I'm making a game with XNA and trying to get some background music to loop correctly. Because the file is an MP3 of about 30 seconds in length, I instantiated it as a Song. I want it to loop perfectly, but even when I set the MediaPlayer.IsRepeating property to true, there is always a delay of about one second before the song starts up again. Is there any way to eliminate this delay such that the song loops instantly, so it can play more fluently?


texts:
I have started using Lua as a scripting language for my game engine. It works perfectly for things like input, audio etc. However, I'm now trying to bind my entity component system functions which make heavy use of templates.

For example, getting a component of an entity in c++ would look like this:

uint32 entity = 1;
Transform &transform = registry.get<Transform>(entity);

and adding a component to an entity:

registry.add<Velocity>(entity, 0.0f, 0.0f);

From what I can tell, Lua cannot handle templated functions - I would have to bind a new function for each component e.g getTransformComponent(entity). This obviously isn't great and becomes a huge pain for the end user. I've had a look around and can't find anything that is particually helpful for my problem. I see a few people suggesting things like getComponent("Transform") but I don't see how this would be implemented in c++ as my components are PODs, no base 'Component' class?


texts:
I'm trying to make smooth following camera using this algorithm:

camera.position.add((pos.x - camera.position.x) * 1.2f * deltaTime, (pos.y - camera.position.y) * 1.2f * deltaTime, 0);

It works fine(camera movements are smooth), but when I move the player appears this artifacts:

Player move() function:

moveX(SPEED  * deltaTime);

protected void moveX (float amount) {
        float newX = pos.x + amount;
        if (!map.doesRectCollideWithMap(newX, pos.y, getWidth(), getHeight()))
            pos.x = newX;
    }


texts:
When using a Client-Server model, it's necessary for those two parts to communicate data back and forth. There is one specific area that I've been thinking about and unsure about. That being putting certain information in a main update packet, that is sent every n milliseconds, or send it once when it happens. An example would be a turn-based strategy game. When one player's turn ends, and the next player's turn starts, you could send one packet to notify the clients of the change, or every n milliseconds, tell the client whose turn it is and it can determine when it changes. These are the pros I see to these approaches:

Inside Update Packet:

Harder to become desynced if packets are lost, whereas if sent as an
individual packet and the client fails to receive it, could create
big desync issues.

Individual Packet:

Sends less data between the server and client since it only sends it
once, instead of every n milliseconds.

I'm fairly new to game design, so I'm not sure if there is a general consensus about the proper way to do this. There may also be another solution that I haven't thought of. Any input would be great.