texts: How do I find the rotation point given a touch anchor, new position and new rotation?

texts:
I've got an Cocos2d layer which anchorPoint, position and rotation (according to http://www.qcmat.com/understanding-anchorpoint-in-cocos2d/) vary when the pinch zoom gestures. Everything works fine.

I've also added smoothness, so the layer will stop gently when it is 'thrown away' by a one finger gesture. The layer will also stop zooming in a gentle way when the 2nd finger is released (if it is released during movement). I've also succeeded with smooth rotation, so the layer continues rotation around touch1 when touch2 is released (if touch2 described an orbit around1).

My problem is that the rotation functionality is not generic. For instance, I've problems with the case where touch1 and touch2 is on the opposite side of the center point, and follows a path on a circle circumference. The layer will then rotate around the centre point. That works fine until the fingers are released, but my algorithm is not robust enough to find out that it shall continue the rotation around said center point.

Question: How do I in a generic way find the point of rotation, and the rotation speed around that point, for a layer using sampled data containing anchorPoint, position and rotation for the last 0.1(?) seconds?

The example above is only one use case. You can also think about the case where touch1 follows the arc from (1, 0) to (0, 1) meanwhile touch2 follows the arc from (2, 0) to (0, 2). That will result in a rotation around (0, 0). I want to detect that movement, and continue the rotation around (0, 0) if the touches are released at the same time.


texts: How to get the maximum installed version of DirectX?

texts:
Okay, So I would like my engine to detect weather or not it can use DirectX 10, if it can't it defaults to DirectX 9.0c but, the function DirectXSetupGetVersion() will only return Versions 5 through 9. Could someone point me to what could tell me the device capabilities?
Thank you for your time.


texts:
Below I've an image of my current scene, and two images of what I want to achieve. Now the question is, how can I visualize objects in low light, as you can see the current scene isn't that attractive however the pic from kentucky route zero is soul capturing, so what should I do? Any type of guidance will be appreciated c:

Current Scene:

Required Output:


texts: Best way to handle tick-based resource generation in an online multiplayer strategy game

texts:
I'm building an online multiplayer strategy game. The game has no offline mode and requires syncing up to a server. Part of this game is constructing buildings which will generate resources each second. These resources would be generated whether the player is online or offline.

If this was a purely offline game, this would be easy: get the delta between when the app was closed and when it was opened again and multiply by resources per second and just fast forward everything.

Since it's an online game, and other players can be affected by the resources an offline user has, these calculations have to occur on the backend.

My question is: if I have 10,000 players, each with 20 buildings generating resources on a per second basis, how on earth should I handle 200,000 things all at once and syncing to a database?


texts: Drawn frustum does not match with glm::perspective

texts:
I am working on a personal project and I got a 3d viewport with moving camera working nicely. Now I am working on being able to freeze the time and switch to a debug camera and move in the game freely. In order to do so I also wish to see where the original camera is and what the frustum is. I started by creating at the origin the camera shape and compute the proper frustum.

The camera frustum is the result of a vertical angle of view of 30 degree, near plane 100, far plane 5000. (no particular reason behind those value).

Those values are the exact same of the flying camera so I would expect if i put the camera at the origin, pointing in the same direction (-z), the frustum should match the screen size.

Unluckily that doesnt happen here is the result I get:

If in the frustum point calculation I scale the fov by 2.75~ I get the right size, no idea if that number has a specific meaning. I am quite sure the frustum is correct, I say that because if I do  atan(plane-width/2 / near) I get half the fov*window ratio. Same for far plane, which is correct. That lead me to think it might be a problem just in the visualization.

I use glm to compute both look at and perspective:

mat4 Camera3dPivot::get_world_view_matrix() const
{
    //just computing and returning the camera
    mat4 look = lookAt(m_pos , m_pivot, vec3(0.0,1.0,0.0));
    return look;
}

mat4 Camera3dPivot::get_projection_matrix() const
{
    //computing perspective

    mat4 temp44= perspective(m_fov,((float)m_width/(float)m_height),m_near,m_far);
    //flipping the perspective to avoid upside down effect
    temp44[0][0] *=  -1.0f ;
    temp44[1][1] *=  -1.0f ;
    return temp44;
}

After that the MVP matrix is nothing more that proj * lookM.

view_to_proj_matrix = projection_matrix* model_to_view_matrix;

So far the camera worked really nicely, no glitches or artefact I am aware of, so I am quite confidant in the code both cpu and shader.
(shaders are the most basic one you can imagine, i can post them if needed).

This is how I compute the frustum:

Camera3dPivot* cam = (Camera3dPivot*)m_cam;
float angle = cam->get_fov()* (M_PI / 180.0);

float near =cam->get_near_plane();
float hnear = 2.0f*tanf(angle / 2) *near;
float wnear = hnear * cam->get_ratio();

float far = cam->get_far_plane()*0.9;
float hfar = 2.0f*tanf(angle / 2) * far;
float wfar= hfar * cam->get_ratio();

float hnearhalf = hnear / 2.0;
float wnearhalf = wnear / 2.0;

float hfarhalf = hfar / 2.0;
float wfarhalf = wfar / 2.0;

There is only one camera in the scene. The flying one, the drawn camera is just a not transformed drawn of the flying camera.

I went through the code several time checking the data and everything is fine and makes sense, from the angles, to the aspect ratio of the viewport etc.

So I am starting to think I am actually missing something, also because it has to work, since if I replicate the same exact scenario in maya the frustum matches the viewport. Although I might try to see if maya gives me the points of the frustum and compare them with mine.

Any help on the matter is appreciated.
PS: this is the tuorial i looked at for the frustum calculation:
http://zach.in.tu-clausthal.de/teaching/cg_literatur/lighthouse3d_view_frustum_culling/
PPS: I am also sure i am inputting the right angle, glm::perspective I feed degrees , tanf I feed radians, you can see the conversion in the frustum code.


texts: How can I morph between images in real time?

texts:
So, I need to be able to make a picture slowly transition into another picture, not as a transparency fade, but as a morph.
And I need that in real time.

More on "morphs":
When you outline two areas in two separate images which are supposed to turn into each other over a number of animation frames; and then their colors and outlines slowly blend until one image becomes another.
That is what I need.
I was initially hesitant to ask this, because I was under the impression that it has traditionally been a brutal algorithm to force your computer to perform.


texts:
I have a stationary cube in my scene that I'm orbiting a camera around. I have my MainCamera nested under a GameObject that I'm calling 'OrbitalCamera'.

I setup the script so that a click (or tap) and drag will rotate the camera around the object in space so it feels like you're rotating the cube (ie: if I click the top of a face on the cube, and pull down, I'm rotating the X value) but you'll actually be rotating the camera.

For the most part, my script works. However, after rotating the Y so much, the camera is upside down and the X gets inverted. Here's my script:

public class OrbitalCamera : MonoBehaviour {
    public bool cameraEnabled;

    [SerializeField] private float touchSensitivity;
    [SerializeField] private float scrollSensitivity;
    [SerializeField] private float orbitDampening;

    protected Transform xFormCamera;
    protected Transform xFormParent;
    protected Vector3 localRotation;
    protected float cameraDistance;

    void Start () {
        cameraEnabled = true;
        xFormCamera = transform;
        xFormParent = transform.parent;
        cameraDistance = transform.position.z * -1;
    }

    void LateUpdate () {
    if (cameraEnabled) {
            // TODO:: FIX PROBLEM WHERE WHEN CAMERA IS ROTATED TO BE UPSIDEDOWN, CONTROLS GET INVERSED
            if (Input.GetMouseButton(0)) {
                if (Input.GetAxis("Mouse X") != 0 || Input.GetAxis("Mouse Y") != 0) {
                    localRotation.x += Input.GetAxis("Mouse X") * touchSensitivity;
                    localRotation.y -= Input.GetAxis("Mouse Y") * touchSensitivity;
                }
            }
        }

        Quaternion qt = Quaternion.Euler(localRotation.y, localRotation.x, 0);
        xFormParent.rotation = Quaternion.Lerp(xFormParent.rotation, qt, Time.deltaTime * orbitDampening);
    }
}

Is there a good method to achieve this type of 360 camera? I'd like dragging from right to left to always move the camera left and dragging left to right to always move the camera right -- no matter how the camera is oriented.


texts: How can I make iPhone apps (games) on Windows?

texts:
I want to start making iPhone games, but sadly I'm a Windows geek.. Is there a way to make good profesional iPhone games without Xcode/owning a Mac computer?

If not, what do you recommend, a Mac Mini?

Thanks in advance!


texts: How can i create 700,000 cubes, memory usage get to 91% and above it?

texts:
var key = thisKv.Key;
                foreach (var thisValue in thisKv.Value)
                {
                    GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
                    cube.transform.parent = emptygameobject.transform;
                    var renderer = cube.GetComponent<MeshRenderer>();
                    renderer.material = textMaterial;
                    cube.transform.position = new Vector3(-thisValue.Y, 0, thisValue.X);
                }

thisKv.Value Value contain over 700000
And then when it's creating the cubes:

GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);

And make the loop very fast my memory usage of the pc get to 91% and more and i need to shut down the unity editor.

Is there any other way to handle so much cubes ?


texts: Workflow for accountable file transfers between freelancer and developer

texts:
I'm an indie game developer and I often hire freelancers for artwork. We sign an agreement to basically state that I'd get ownership of the resources they produce.
I'm a fairly picky person when it comes to formalities in these agreements, and I can't find a good system to document file transfers between freelancer and client. What I'm looking for is:
A way to track a relationship between their email account and mine, and document file exchanges, like a "timeline":

Freelancer uploaded X file at 16:50 UTC+03:00, [download button]
Freelancer uploaded Y file at 17:43 UTC+03:00, [download button]
Client uploaded Z file at 18:35 UTC+03:00, [download button]

And files are permanently kept in the timeline for documentation purposes - it should be impossible to delete an entry (unless both parties agree to delete it). The point of such structure is to "vouch" that this person transferred a file at some point and neither party can deny it.

Technically, e-mail attachments do exactly this. However, if it is a relatively large file, Gmail will ask them to upload to Google Drive. The problem with this is that Drive lets them keep ownership of the file (so if they delete it, I cannot get it back unless I had downloaded it); we would lose the whole "record" thing as there will be no guarantee that the file that I have is in fact the file that they uploaded.
How we've worked with a few freelancers in the past is that they will transfer a bulk of files (zip) to us using whatever convenient method, and then, in written, state that they have produced and transferred a zip with some MD5 hash. So if it is ever necessary to prove that such a file was given to me by a freelancer, we'd just compute its hash. However that's understandably inconvenient.


texts: My Character objects are complex, how should I organize their structure?

texts: I'm using Monogame to make a fighter.  I have created an abstract Character class that has basic character functionality such as HP, meter, update boilerplate and such, and will be overridden as each specific character to include parameters specific to said character.  The abstract Character class has a Move subclass that has mostly static functionality and takes in a delegate that handles its effects.  The problem here is that most of this functionality is static and, to me, doesn't seem to need instantiating, but because the move delegate requires, at the very least, a reference to the instance of the Character that owns it (so that it can work its arbitrary effects on the character, the opponent, the environment, w/e) it seems like it needs to be instantiated, which means feeding a move in (or its delegate) as a parameter for every move I want to give a character, which is going to get very messy very fast.  What should I do about this?


texts: Tile map collision is not working properly


texts:
I have a character in a basic platformer game and am having trouble.

Whenever my character stands over two tiles on a tilemap and appears to be directly colliding with them the character's is_on_floor variable toggles constantly between true and false, messing with my jump physics. Standing on a non-tilemap object.

My collisions have been checked and are fitted to each object. my tiles are at a 24 * 25 in size.

edit

I have recently been working with sloping tiles and have encountered a similar problem after having changed my collision box into a capsule.

How do I fix this and what is causing this?


texts:
I am using the following code to rotate entities to look at points.

glm::vec3 forwardVector = glm::normalize(point - position);
float dot = glm::dot(glm::vec3(0.0f, 0.0f, 1.0f), forwardVector);

float rotationAngle = (float)acos(dot);
glm::vec3 rotationAxis = glm::normalize(glm::cross(glm::vec3(0.0f, 0.0f, 1.0f), forwardVector));
rotation = glm::normalize(glm::quat(rotationAxis * rotationAngle));

This works fine for my usual entities. However, when I use this on my Camera entity, I get a black screen. If I flip the subtraction in the first line, so that I take the forward vector to be the direction from the point to my camera's position, then my camera works but naturally my entities rotate to look in the opposite direction of the point.

I compute the transformation matrix for the camera and then take the inverse to be the View Matrix, which I pass to my OpenGL shaders:

glm::mat4 viewMatrix = glm::inverse(
    cameraTransform->GetTransformationMatrix()
);

The orthographic projection matrix is created using glm::ortho.

What's going wrong?


texts: Is there a way to convert built unity games back into a project

texts:
I accidentally deleted my game.
I had been working on it for about 2 months and I accidentally deleted it while cleaning up my files. I am so smh. I have a ton of builds of the game though and since the game and all its scripts was converted to a file. Would I be able to un-pack said build back into a unity project? I am not that cut about the game because I didn't like it but I did spend a lot of time on it. Oh yeah and also its a school assignment...
Please help.


texts:
I am currently using OpenCV to track the face of a person.

With this I extract the feature points and calculate the objects heads pose by applying the "solvePnP" function.

This function gives me a translation vector and a rotation vector.

I can later apply this to a camera in Unity so that it rotates around the object simulating the face moving around.

This works fairly well, and the head moves as the user moves his head however it is very jaggy.

I figured that smoothing the translation vector would be as easy as calculating the average of the current and previous points.

But I am having a hard time smoothing the rotation vector.

The data comes as a vector (here are some consecutive examples):

[2.918782807448489; 0.1896564461354077; -0.2327480775908206]

[2.922645604179207; 0.1834802203843292; -0.1842765118011375]

[-3.339417618845302; -0.2022563569884805; 0.1950620807331237]

[2.884993823241512; 0.1935712993426144; -0.2426539399793146]

[-3.341933025273495; -0.2062648239738171; 0.2609849753763552]

Which I would like to "smoothen". The opencv documents state the following about this vector:

  Output rotation vector (see "Rodrigues") that, together with tvec,
  brings points from the model coordinate system to the camera
  coordinate system.

I've tried adding the previous plus the current rotation vector and then normalizing it and even though it seems a lot more stable it flickers between being upside down and not.

http://answers.unity3d.com/questions/437111/calculate-vector-exactly-between-2-vectors.html

Does anyone know what am I doing wrong?


texts: Use large image individually, or in TextureAtlas?

texts:
Does it make any sense to include a large image (with dimensions of say 1920x1080) in a TextureAtlas and then use it with libgdx for example?

Or should I rather use it individually and include the .png file into the assets folder as it is?

Thank you.


texts: UnityEditor.SyncVS.SyncSolution putting wrong language version in generated files

texts: I'm working on getting our Unity projects building in bamboo for our build server. We have a cli step that runs through the Unity commands for creating a build. It works fine on several projects, but for some reason this particular project I'm working on I'm getting an error that states I need to use c# version 7.2 or newer. If I log in to the build server and open the .csproj files in notepad and check the language version, it's setting them to 7.0. However, if I deactivate the cli step so that the build job only clones the project, then manually log in and open unity and go through the process so it generates the .csproj files, then check them, the language version is set to 8.0. The project works fine locally on my own pc. And it works when setup manually on the build server pc, but when ran through the cli step, it generates them at an earlier c# version. This leads me to believe there is a problem with the UnityEditor.SyncVS.SyncSolution step in my commands. I'm just not sure what it could be, or why it's behaving differently for this project as opposed to other projects that are using the same code base (where the problem is said to occur), same Unity version, same build server, etc. Anyone else experience this issue or have any thoughts on a solution?


texts: How do I use CC_CALLBACK for external classes in Cocos2dx v3.2?

texts:
I've been having problems with using 'CC_CALLBACK_#' (i.e. CC_CALLBACK_0, CC_CALLBACK_1). It works alright if I am using it to call a function from the class (Using 'GameScene' class for this example) itself like

CC_CALLBACK_0(GameScene::gamePause,this)

However I am unable to use it to call functions from other classes (i.e. 'SettingsScene') that have been included like

CC_CALLBACK_1(SettingsScene::bgmControl,this)

I can use the SettingScene CC_CALLBACK code just fine in the SettingsScene class.

In cocos2dx v2, 'menu_selector' did not have any issues calling functions from other classes so I was wondering if anyone could tell me how to do it in v3.2? I really don't want to resort to copying the functions from other classes into the class I want to call it from :(

Thank you so much!


texts: How to retrieve the coordinates of an animated object?

texts:
On Unity, I created a script in C # to animate a cube.
I am trying to create a script in C # which, once the animated object and in support of a key of the keyboard (for example F) returns to me the coordinates of the object at the moment when I pressed F

Can you give me this script?

Thank you for your help


texts: "Occlusion culling data is out of date. Please rebake" - No scene specified, Unity 5.6.2

texts:
I've inherited a Unity project with hundreds of scenes. When I try to build it for consoles/mobile I get 11 errors saying "Occlusion culling data is out of date. Please rebake" and the build fails. Double clicking on these errors takes me nowhere, and no scenes are specified. It is my understanding that I can only bake occlusion culling by opening the scene manually and hitting the bake button. Due to the size of this project, that would take many hours. The game runs fine from within the editor, but simply won't export to consoles.

How can I do any of the following:

Automatically rebuild all occlusion culling information.
Find which scenes are out of date.
Disable occlusion culling project wide, letting me at least get a build onto dev-kits out for further evaluation.

Thanks for any help at all.


texts: Does Phaser Arcade.Body velocity include deltaTime or not?

texts:
I want to move my character along the x axis with constantly speed. I thought move depends on frame rate. So, technically I should write

sprite.body.velocity.x = speed * deltaTime

where deltaTime = game.time.elapsedMS / 1000;

But if I'm doing that - my character moves vvvvverrry slooow, even if speed = 1000.

But if I'm writing

sprite.body.velocity.x = speed

it works fine. My fps = 60;

Phaser Documentation
says:

  velocity - The velocity, or rate of change in speed of
  the Body. Measured in pixels per second.

no deltatime....

and all demos do not have deltatime

http://phaser.io/examples/v2/arcade-physics/platformer-basics

http://phaser.io/examples/v2/arcade-physics/asteroids-movement

etc.

So, I don't understand: shoud I calculate deltaTime or just use velocity.x?


texts:
This thread directly concerns lightmap generation; however, indirectly, the rasterization of polygons by the GPU.

I am currently generating lightmaps using a pixel shader. To the shader I send 3 lightmap UV coordinates per mesh face. Those UV coordinates are directly rendered onto a lightmap texture( by setting the lightmap as the render target ). The vertex shader looks like this:

// ---------------------------------------------------------------
// Vertex Declaration
// ---------------------------------------------------------------
struct VS_INPUT_Std
{
    float4 Position : POSITION0;
    float3 Normal : NORMAL0;
    float2 tUV : TEXCOORD0; // diffuse UV coordinates
    float2 lUV : TEXCOORD1; // lightmap UV coordinates
};
//--------------------------------------------------------------//
// LightMap Pass
//--------------------------------------------------------------//
PS_INPUT_Std LightMapPass_Vertex_Shader( VS_INPUT_Std Input )
{
    PS_INPUT_Std Output = ( PS_INPUT_Std )0;

    Output.Position = float4( ( Input.lUV.x * 2 ) - 1, ( Input.lUV.y * -2 ) + 1, 0, 1 );
    Output.Normal = mul( Input.Normal, mW );
    Output.Pos3 = mul( Input.Position, mW );
    Output.tUV = Input.tUV;
    Output.lUV = Input.lUV;
    return Output;
}

The pixel shader returns a color based on light contribution. The result of the lightmap generation for this test mesh looks like this:

The light for this scene is floating in the center of the room...

The problem is that the lightmap has 'cracks' due to the rasterization of polygons by the GPU. It appears as though that for a given face lightmap pixels are not included during rasterization because their pixel centers do not fall within the bounds of the face's UV coordinates despite the fact that the face overlaps those pixels. As a result a black( unset ) pixel is rendered and effectively blackens the diffuse color of the mesh during texture modulation. Here is a screenshot:

Here is a screenshot of an auxiliary window which shows both the lightmap and a selected mesh face. This is generated by rendering the UV coordinates of the mesh face over a screen quad of the lightmap:

As you can see, the mesh face( green ) extends beyond the pixels rendered during generation of the lightmap. It seems as though those pixels were excluded during rasterization. Most of the problem faces are narrow in dimension. I thought that I could fix this by increasing the size of the lightmap, however, this doesn't always work...

Here is the entire lightmap:

Can I change a rasterization state to allow pixels under certain conditions?

EDIT: Lightmap and Deferred Shading Cube Pics


texts:
I'm working on a game using Haxe + Flambe but I'm having a hard time making the UI part of it (main screen, level selection, etc).

And I began to think... is there another way?

I would love to have something like Flash, I mean, WYSIWYG like to make the UI. Just because I don't want to spend my time coding the screens until they look like what's on my mind.

So the questions are:

How do people work?

Is there something visual to make the UI for games that'll be programmed on Haxe (it doesn't matter if using OpenFL, Flambe or other)?


texts: Independent HTML5 Physics Game: Any Feedback?

texts:
I've been independently developing a physics-based HTML5 game. I haven't used any libraries or engines; all the code, including the physics, is my own. It is free for a while on the Chrome Web Store and I was hoping that I could get some feedback on it. You can get it for Chrome here: https://chrome.google.com/webstore/detail/dbnmkpcomailjochphnmfklofkmgenci.
 I know this is not a normal question, but I'm happy for answers to be abstracted/generalized for broader use. Im asking here because I don't know anyone else personally who does this stuff. Any thoughts, comments or ideas you might have would be greatly appreciated!

The physics system is written in JavaScript and works by setting up the differential equations of motion (plus a few conditions) and evaluating them numerically using the Euler method. The graphics are done through the HTML5 canvas and the music is done through the audio element. (Said music is in the public domain by the way). You can see the code by going to VIew>View Source in Chrome.


texts:
I was wondering if anyone could shed any light on whats going wrong with my additive blending here, I think I'm nearly there, currently my outcome is black squares. I have tried using both the formula's on this website here https://love2d.org/wiki/BlendMode_Formulas to try and get my desired outcome and it doesn't seem to be working.

This is the equation I have in my notes and what I have found online.
Final.Red = Bitmap.Red + Viewport.Red
Similar for green and blue, RGB range is [0-1] or [0-255]

The colors I am using are 255 RGBA format.

void SpritePlotterForm::DrawSpriteAdd( int X, int Y, Bitmap^ SrcBitmap )
{

    int FinalViewPortRed;
    int FinalViewPortGreen;
    int FinalViewPortBlue;
    int FinalViewPortAlpha;
    for (int x = 0; x < SrcBitmap->Width; x++)
    {
        for (int y = 0; y < SrcBitmap->Height; y++)
        {
          if (SrcBitmap->GetPixel(x, y).A >= 0)
          {
                // resets to avoid corruptionj of image
                FinalViewPortRed = (SrcBitmap->GetPixel(x, y).R + GetViewportPixel(x+ X, y + Y).R)/255;
                FinalViewPortGreen = (SrcBitmap->GetPixel(x, y).G + GetViewportPixel(x + X, y + Y).G) / 255;
                FinalViewPortBlue = (SrcBitmap->GetPixel(x, y).B + GetViewportPixel(x + X, y + Y).B) / 255;
                Color ResultColour = Color::FromArgb(FinalViewPortRed, FinalViewPortGreen, FinalViewPortBlue);
                SetViewportPixel(X + x, Y + y, ResultColour);

          }
       }
    }

}

I think the error is to do with how I am handling my alpha values, but I have tried multiple algorithms and either, end up darkening the image, creating a whole black square, or a whole transparent square, or worst is it gets an out of bounds issue.

Image to be blended

the result  I get from this algorithm (run twice, those are two seperate flames there)

Desired outcome


texts: Rotate object Up/Down/Left/Right in any orientation

texts:
I'm rendering model at the origin with a fixed camera looking at it positioned on the z axis.

I want to be able to rotate the model up/down and left/right. Currently I have 2 variables, HorizontalRotation and VerticalRotation. When calculating the world matrix I rotate about the Y axis by HorizontalRotation and about the X axis by VerticalRotation.

The ..Rotation variables are controlled by pressing up/down/left/right arrow keys.

The problem I'm having is that the rotations are happening relative to the object.

Lets say it's a model of the world. Pressing Up a bit would let me look at the north pole.
Currently when i press right the earth spins infront of the camera on its axis; I'm still looking at the north pole.

How can i get it so that no matter what rotations are currently applied i can always rotate my model relative to the camera/world axis?


texts: How do I use Sprite in libgdx ashley ecs framework?

texts:
In the libgdx ashley wiki there's an example of Position and Velocity components, which is pretty easy to understand. My problem now is I don't know how do I integrate Sprite class as Component. In below example, If I use it like this the PositionComponent will be thrown away? because sprite has x and y fields. Also I want to use the method of Sprite setOriginCenter(), in that case do I still need to create another component which is OriginComponent? or completely leave it to SpriteComponent?. Do you think it's recommended to use this class (Sprite) in ECS framework?

class SpriteComponent implements Component {

    Sprite sprite;

}


texts: Moving non-local player from local player with Mirror Networking

texts: i am using mirror networking which is based on UNet. I can move non local objects easly by assigning their authority to the local player and move them, but i can't assign/remove authority for other player's in the game, therefore i can't directly change their velocity. Any ideas how can i change other non local player's velocity from local player ?


texts:
I have in place a cell-based lighting system that works basically like this: (Not my actual code)

    //Light moves up
    for (int x = 0; x < width; x += 1)
    {
        for (int y = 0; y < height; y += 1)
        {
            light[x,y] = light[x,y+1] - amount;
        }
    }

    //Light moves down
    for (int x = width; x < 0; x -= 1)
    {
        for (int y = height; y < 0; y -= 1)
        {
            light[x,y] = light[x,y-1] - amount;
        }
    }

    //Light moves left
    for (int x = 0; x < width; x += 1)
    {
        for (int y = 0; y < height; y += 1)
        {
            light[x,y] = light[x+1,y] - amount;
        }
    }

    //Light moves right
    for (int x = width; x < 0; x -= 1)
    {
        for (int y = height; y < 0; y -= 1)
        {
            light[x,y] = light[x-1,y] - amount;
        }
    }

The variable amount is determined in each for() loop by if there is a block at x,y.

This should make it so that light darkens faster if there is a block at the position, but the light shows up looking like this:

Light shine out sides oddly

Light is in a tunnel, as you can see the top and bottom blocks are solid but they are not being lit up

Verical tunnel, but it seems to work correctly

Up and down dont seem to work quite right

I should also mention that changing the order of the passes changes in which direction the light propagates incorrectly. For example, if I change the order from up,down,left,right as shown above to left,right,up,down, the light is spread correctly in a horizontal tunnel and incorrectly in a vertical tunnel.

SO MY QUESTION IS: What is wrong with my code that creates this obvious miscalculation?

If you need to see more code or explanation or screenshots, I'll be happy to provide.


texts:
Sorry guys! I am super new to this, and I'm trying to teach myself Unity. I have a very small knowledge of Maya from a 3d modeling course I took a year ago in college, and have made a very simple object and animated it using keyframes (2 keyframes to be exact) in maya, but I can't seem to figure out how to get that animation into Unity.

I've been playing around with this for hours now, and all the tutorials and such I find online are for really complex objects like people, and they have joints and stuff going on. Are joints required for an animation to work in Unity?

I've saved my maya file into my assets folder, but I don't see any animations in the import settings in Unity.

Here is my object:

And it animates to this position:


texts: How can I programmatically change a sprite's pivot without it affecting a game objects current position and rotation?

texts: Because of the complexity of positions, I am using the centre pivot for my game objects sprite. Can I possibly change the pivot without it affecting the game objects current position and rotation? or in other words, can I change the pivot while the sprite remains unchanged visibly? I would preferably like to do this using c# script.


texts: Spline type to achieve a specific result

texts:
Is there a type of spline which can produce (approximately) the following result given the specified points indicated. I want to be able to specify how curved the corners are from the "centre points" so that I get "very square" corners to "very round" corners. Sorry about my shakey hand ! Points along a line should produce (roughly) a linear curve.

I found quite a few questions and answers online about this but they all seem to be B-spline related, and don't (I think) quite capture my constraints. If anybody knows what I'm looking for, direction to an online reference/article would be great.

My points always appear on an integer lattice (grid), and are always equally spaced.

I'm looking for something low complexity, but which I can pass a value, say t in [0,1] and returns the (x,y) position of the curve at that time. I realise I could probably build a function like this piece-wise, but wondered if there is a ready made spline solution (piece-wise equation) which could achieve the same result.

Maybe B-splines or NURBS are the answer, but maybe they are heavy on computation too...

Given Sirisian's answer below, I suddenly realised how Bezier curves work. Wow they really are a clever idea!

Everything seems centred around a single t value, e.g.

l1(t) = a+t(b-a)
l2(t) = b+t(c-b))
m(t)  = l1(t)+t(l2(t)-l1(t))

We can expand m to simplify if necessary.

I think B-Splines give a nice result, e.g. see below. It also has the advantage of not being restricted to a uniform grid. Not sure about speed of computation yet though...


texts: How often to save player's state in persistent online games?

texts:
In online games, people prefer to log on and off whenever they want. Usually, their game achievements are seamlessly saved, on the server. That is not that difficult to achieve, but I am wondering how can be done in an efficient way that makes sense and will scale.

Does it make sense to save the player's coordinates and state with every time they send it? My node.js server can do that easily without blocking a response, and I want to employ a Mongo database, but maybe it's more appropriate to do that once a second and in a server-wide event, collecting all at once?


texts: Getting the edge-cells in a list of cells on a 2d grid, and knowing which neighbor is missing

texts:
I create a "circle" on my 2d-grid using this code:
public List<Cell> GetSurroundingCellsCircle(Coord originCoord, int distance)
{
    List<Cell> matches = new List<Cell>();
    int EX = distance + coord.x;
    int EY = distance + coord.z;
    int SQ = distance * distance;

    for (int x = coord.x - distance; x <= EX; x++)
    {
        for (int z = coord.z - distance; z <= EY; z++)
        {
            int c = x - coord.x;
            int d = z - coord.z;

            if ((c * c + d * d) < SQ)
            {
                Cell cell = GetCell(new Coord(x, z));
                if (cell != null)
                    matches.Add(cell);
            }
        }
    }

    return matches;
}

This code works fine and returns a list of cells that together create a circle-shape. Now I want to get all the edge-cells of this circle, and not only that, but I also need to know which side of the edge-cell that has no neighbor, so I know where to draw the line. I want a result that looks like this red line:

I wrote this code that would work for a square (it just finds the max/min of X/Z and draws a sphere there, but as you can see in my image, its missing the "rounding" cells:

int maxX = 0, maxZ = 0, minX = 0, minZ = 0;

        for (int i = 0; i < cells.Count; i++)
        {
            int cX = cells[i].coord.x;
            int cZ = cells[i].coord.z;

            if (i == 0)
            {
                minX = cX;
                minZ = cZ;
            }
            else
            {
                if (cX < minX)
                    minX = cX;

                if (cZ < minZ)
                    minZ = cZ;
            }

            if (cX > maxX)
                maxX = cX;

            if (cZ > maxZ)
                maxZ = cZ;
        }

        for (int i = 0; i < cells.Count; i++)
        {
            int cX = cells[i].coord.x;
            int cZ = cells[i].coord.z;

            if (cX == maxX || cZ == maxZ || cX == minX || cZ == minZ)
            {
                Gizmos.DrawSphere(
                    new Vector3((cells[i].coord.x * GridBase.WORLD_CELL_SIZE) + GridBase.WORLD_CELL_OFFSET,
                    1,
                    (cells[i].coord.z * GridBase.WORLD_CELL_SIZE) + GridBase.WORLD_CELL_OFFSET),
                    1);
            }
        }


texts:
Box2D marks stable range of object size is 0.1M ~ 10M. This specifies object size range. How about space size? If I make an 1M object at (1000.0f,1000.0f) position? Is it can be stable? Or should I assume spatial range is also limited same with object size?

PS. Maybe the resolution limit is defined because of limit of floating-point operations. I believe there's also some limitation on spatial range, but I couldn't figure out specific range myself.


texts: What structure is best used to model maps for games like Bard's Tale / Dungeon Hack?

texts:
I would like to create or use an existing JavaScript engine to build a game in the spirit of Dungeon Hack, Eye of the Beholder and older Might & Magic games. Going off my memory playing these games there could be 6 different bitmaps to each cube, and each side may have an additional decoration or other game object overlay.

How should I model these maps in code?


texts: As seen, the texture is not adjusted to the sphere. I tried to change alignment, but it still displays multiple sides. How can I fix this?


texts: Raycasting with a selection rectangle box

texts:
I'm currently making a level editor for my game and want to implement a selection tool to make it easier to select multiple voxels at once.
My question is what the most efficient way is to get all the selected objects?
Do I just unproject the starting position and end position of the selection rectangle and create a bounding box that I then can use for intersection checking or is there a better way?

EDIT: Since I can't rotate a bounding box I need to find another way. I just need a way to find out if the bounding box of a voxel is inside the box that is formed by the four points of the selection.


texts:
I have different vertex layouts I'm using to render things in DirectX and as of now I've just used the same vertex layout for every mesh I load in. But now I want to have the vertex layout change according to the mesh loaded in. If the mesh has a normal map I would like to have an vertex layout with tangents so I can render with the normal map. If I don't I would like to have an vertex layout without tangents to save me some time on my rendering. Right now in my mesh class I have...

std::vector<Vertex::PosNormalTexTan> vertices;

where PosNormalTexTan is the vertex layout. Then I have...

void Construct(ID3D11Device* device, UINT vCount, std::vector<Vertex::PosNormalTexTan> vertices, std::vector<UINT> indices);

Called when constructing the mesh. I would like the possibility of using

std::vector<Vertex::Basic32> vertices;

How could I do this without creating an overload for every vertex layout?


texts: Ground contact point for animated character sprites in an isometric game?

texts:
I'm working on an isometric game. I have the 3D pre-rendered sprites for directions per state (walking/running, etc.) per frame. Now I need to know where a particular character stands on the ground to have it synchronized. But this "ground contact point" (GCP) changes from frame to frame, and is basically (slightly) different for every combination. At this moment I have some rough average, but sprite wiggles a bit during animation. It's rendered correctly (1024x768), but cropping of the frames even though it correctly removes empty borders, it also removes the "offset" information, which is no longer there. So I basically need to remove empty borders while taking into account all the frames in all the animations. So the character in the sprite animation is still stabilized, but unneeded space is removed.

Example:

Is there any software that does it, or is there some technique to do it?


texts: How can I create a shader that will reproduce this lighting effect on terrain?

texts:
Notice the way in which the major light source in each image reflects off the ground, as a function of the distance between the light source and the viewer (?).

Is this a (bumped) specular map? The effect is seen all over in World of Warcraft; I specifically remember it on the snow in Dun Morogh, and on the shores of Darrowmere lake. Looking directly toward the sun is required. The effect is also commonly on the surface of water in RL and in CG. Specifically, I want to build the effect where the reflection is more intense on the ground surface closer to the light source, and falls off as it approaches the viewer.


texts:
I am working with the 3D model and I am using the Scene Kit for rendering and Model I/O for loading the obj file. It works perfectly fine for the small size of obj. But now I have 250MB of file and when It starts loading it takes too much memory and lower end devices are crashing.

How can I read this obj files that is used by the scene kit or any alternate way to read this file? Below is the line of code I used for reading obj file:

MDLAsset *asset = [[MDLAsset alloc]  initWithURL:mapURL];
MDLMesh *object = (MDLMesh*)[asset objectAtIndex:0];

Is there any alternative way to load large obj files?


texts: Which isometric angles can be mirrored (and otherwise transformed) for optimization?

texts:
I am working on a basic isometric game, and am struggling to find the correct mirrors.

Mirror can be any form of transform.

I have managed to get SE out of SW, by scaling the sprite on X axis by -1. Same applies for NE angle.

Something is bugging me, that I should be able to also mirror N to S, but I cannot manage to pull this one off.

Am I just too sleepy and trying to do the impossible, or a basic -1 scale on Y axis is not enough?

What are the common used mirror table for optimizing 8 angle (N, NE, E, SE, S, SW, W, NW) isometric sprites?


texts: LWJGL—How to Animate Sprites from a Sprite Sheet Using Certain Keys?

texts: I'm talking here about walking animations and such for a 16-bit RPG. I have a simple sprite sheet that contains walking animations for all directions (up, left, down, and right), but I'm having trouble getting LWJGL to animate them—how would I do it?


texts: Determine if AI can traverse a given spline

texts:
I have some AI Agents that I want to navigate along a spline. The agents have a speed and a maximum turning radius. For some splines the curvature is too tight for the AI agents to navigate around and they end up shooting of the spline and then turning, which looks weird. How can I take a given spline and find the segments that are too tightly curved for a given agent to traverse without shooting off?

I thought about just taking the angle between control points, but that alone won't account for the speed limitations that I want to impose as well. Can someone point me in the right direction?

I am using Curvy for my spline implementation but using my own agent movement system to walk along the splines. http://www.fluffyunderware.com/pages/unity-plugins/curvy.php


texts: Efficiently pathfinding many flocking enemies around obstacles

texts:
I'm working on trying to improve the pathfinding for my game's enemies. Right now, they basically just constantly move towards the player's exact position by calculating the angle between themselves and the players and moving in that direction. I also have a flocking algorithm which prevents the enemies from stacking on top of each other, so they will form up into groups rather than clip through each other.

However, now that I've added a tile-based map, I need the enemies to also be able to path around obstacles and walls for example. I initially tried adding a separation value to "non-walkable" tiles so that the flocking algorithm would consider the walls and obstacles as objects to move away from. I have yet to work out whether or not this is feasible because my initial test showed the enemies hitting an invisible "wall" where there are no non-walkable tiles, yet for some reason, they hit it and start spazzing out.

I was wondering if it might be too performance heavy to calculate a path to the player using A* and then use the flocking algorithm to prevent clumping. Originally my game was going to be a wave-based shooter, but I've decided instead to make it level-based in the vein of Hotline Miami, so it's likely I'll have fewer enemies, with the occasional horde, and just make them stronger.

Is this a viable solution? I'm using Java with Slick2D as my game engine. Or is there a better solution / algorithm that tackles both these problems?


texts:
Suppose I have two game object located at two Vector3s v1 and v2, respectively.
If I wanted to locate a position between v1 ad v2, but 3 units away from v2, how would I manage that in terms of calculating the target vector (vT)?  Basically, I want object 1 to translate toward object2, so that it can play an attack animation a reasonable distance away from the combat target without being on top of it.

I calculate a vector pointing from v2 to v1:

Vector3 heading = v1 - v2;
Vector3 headingNorm = heading.Normalize();

From there, how to I "add 3 units in the direction of v1 from v2" to get the target position?

Thanks in advance!


texts: How to create a decent strategy game without becoming an artist?

texts: I love to make games. But I am not an artist. I never learned to make 2d or 3d models. I spent most of my time on programming. I know there are Game engines for non-programmers. But I am looking a way to create a decent strategy game (medieval theme) without spending time to learn how to model 2d or 3d models it is more time consume than learning how to program for an artist.


texts: Unity how to save the number of successive wins?

texts:
I'm making a trivia game on Unity, everything works fine and now I'm trying to save and retrieve the stats of a game. I have listed most of the stats (score, highscore, points) but now I would like to add the best series of consecutive correct answers, and I don't know how I can exactly set this value.

In theory I know that during the game when a correct answer is given, a counter is triggered to record the number of consecutive correct answers and it stops at the wrong answer. Then at the next triggered series the method checks if the new count is the best. But, as I'm a beginner, I don't know how I can save this kind of streak.

Could you help me please?

In order to understand the context:

public class ansButtonScript : MonoBehaviour {

public Text txt;
public Sprite im_basic, im_corr, im_wrong;

#region Pts&Score
    public int points = 1;
    string _allPts = "totalPts";
    static int totalPts;
    static int score = 0;
    string _score = "score";
    static int hiscore = 0;
    string _hiScore = "hiScore";
#endregion

public AudioClip sound_win, sound_loose;
public GameObject correctTxt, wrongTxt;

#region Cache Refs
public GameObject _canvas, _barInt;
private qManager _qManagerCanvas;
private progBarScript _progBarInt;
private countdownScript _barCountdown;
#endregion

public void Start()
{
    totalPts = PlayerPrefs.GetInt(_allPts);

    _qManagerCanvas = _canvas.GetComponent<qManager>();
    _progBarInt = _barInt.GetComponent<progBarScript>();
    _barCountdown = _barInt.GetComponent<countdownScript>();
}

public void updateTxt(string str_text)
{
    txt.text=str_text;
    GetComponent<Image>().sprite = im_basic;
}

public void SelectButton()
{
    if(_qManagerCanvas.canPlay)
    {
        _progBarInt.barTimeStop();
        _qManagerCanvas.canPlay = false;
        string reponse = _qManagerCanvas.reponse;

        if(transform.Find("Text").GetComponent<Text>().text == reponse)
        {
            //good answer
            GetComponent<AudioSource>().PlayOneShot(sound_win);     //SFX Win
            vraiTxt.SetActive(true);                                //animation Correct
            updateTrue();                                           //the answer is shown
            StartCoroutine(addPoints());
            StartCoroutine(next_question());                        //new question
        }
        else
        {
            //wrong answer
            GetComponent<AudioSource>().PlayOneShot(sound_loose);
            fauxTxt.SetActive(true);
            updateFalse();                                      //the answer isn't shown
            StartCoroutine(next_question());                    //new question
            _barCountdown.ResetTimer();
        }
    }
}

IEnumerator addPoints()
{
    yield return new WaitForSeconds(2.2f);
    playerStats.UpMoney += points;
    score++;                                    //set the nb of correct answers
    saveAllPts();                               //save the nb of points
    PlayerPrefs.SetInt(_score, score);          //save the nb of corr answers
    SaveBestScore();                            //save best score
}

IEnumerator next_question()
{
    yield return new WaitForSeconds(3f);
    _qManagerCanvas.tirage();
    _barCountdown.ResetTimer();
    correctTxt.SetActive(false);
    wrongTxt.SetActive(false);
}

public void updateTrue()
{
    GetComponent<Image>().sprite = im_corr;
}
public void updateFalse()
{
    GetComponent<Image>().sprite = im_wrong;
}

public void SaveBestScore()
{
    if (score > PlayerPrefs.GetInt(_hiScore))
    {
        PlayerPrefs.SetInt(_hiScore, score);
    }
}

public void saveAllPts()
{
    totalPts += points;
    PlayerPrefs.SetInt(_allPts, totalPts);
}
}


texts: How can I create explosions like in Zelda: Breath of the Wild?

texts:
The explosions in BotW look spectacular. Here's a video of them in slow motion: https://www.youtube.com/watch?v=bZtaNoUOSDQ

It looks like it's not all billboards, but also some volumetric geometry - it's hard to see all the details.

Ideally, an answer would be API agnostic, but I am using OpenGL with a homemade renderer, if that helps.

Which techniques are combined to create such a fantastic effect?


texts: How should I manage the update grouping of shader constants in D3D11?

texts:
I've been learning the "dragon book" written by Frank D. Luna and trying to implement the part of the demo on my own. As some of you can see, the demo of the book uses effects interfaces to update the shader constant, but I'm not gonna do that. Because the effects may be deprecated in the future. So I try to find a convenient way to handle this shader constant stuff.

For example, I defined two shader constant structures in my C++ application:

struct PerObjConst : register(b0)
{
    XMMATRIX world;
    XMMATRIX worldViewProj;
    //...other vars
};

struct PerFrameConst : register(b1)
{
    float3 EyePos;
    //...other vars
};

Should I encapsulate every element's updating method for each? like:

SetShaderParameters(ID3D11DeviceContext *deviceContext, XMMATRIX &worldViewProj);
SetShaderParameters(ID3D11DeviceContext *deviceContext, XMMATRIX &world);
//...and so on

That seems to be cumbersome, isn't it?
Instead, how about passing a whole structure's reference into the function? But I think that would be unnecessary to update whole structure when actually there is only a few of the elements are updated.


texts: XNA 2 3D Objects Depth Convergence Error

texts:
Gah! I have a scene with 2 3D objects - a plane and a sphere;

the plane sits on the xy axis with a depth if -100 and diameter of 200;

the sphere diameter is 32 and sits on the xyz = 0 position;

when rendering using indexedprimitive all appears fine.
the sphere appears in front of the plane.

however as i decrease the world z component of the sphere
and the sphere passes through the plane and becomes hidden
it shows the front of the sphere passing through first.

as if the plane were moving down over the sphere but only displaying
the parts of the sphere that should be hidden.

the most puzzling aspect is that this problem only appears as
one object passes through the other. when behind it is hidden,
when in front visible?

Help please :)

Edit 20/12/2015

Has been suggested I upload a sequence of pics to better illustrate my problem so... Hope these help

.

        GlobeTarget = new RenderTarget2D(graphicsDevice, GlobeDiameter, GlobeDiameter, false,
                          SurfaceFormat.Color, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents);
        graphicsDevice.SetRenderTarget(GlobeTarget);
        graphicsDevice.BlendState = BlendState.Opaque;
        graphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
        graphicsDevice.DepthStencilState = new DepthStencilState
            { DepthBufferEnable = true, DepthBufferFunction = CompareFunction.Less };
        graphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1, 0);


texts:
I discovered a weird animation bug and have no idea how to solve it. Below you find the script I attached to my humanoid character.

using UnityEngine;
using UnityEngine.AI;

public class PlayerCharacter : MonoBehaviour {

    private Animator anim;
    private NavMeshAgent agent;

    private bool dead = false;

    void Awake()
    {
        this.anim = GetComponent<Animator>();
        this.agent = GetComponent<NavMeshAgent>();
    }

    public void Kill()
    {
        this.dead = true;
        this.anim.SetBool("Dead", true);
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.X))
        {
            Kill();
        }
    }

    public bool IsDead()
    {
        return this.dead;
    }
}

My character makes use of the NavMeshAgent and can walk around and idle - everything works fine. But if I want to kill the player the dead animation loops continuously. This also happens if I change the death animation.

This is my AnimationController:

As you can see, the transition has the condition "Death" with is set to true in the Kill() method. The code for walking and idling in combination with the NavMeshAgent is similar, but the script shown above doesn't work as expected and I have no clue why the animation starts to loop continuously (which looks a bit funny btw). Additionally the animation is not played to end, it restarts after a few frames.

Any ideas? I could also post a video of the behavior if it would help.
Thanks in advance! :)


texts: Collisions between players at spawnpoints

texts: I am working on a FPS/MMORPG and ran into a problem at spawnpoints, when I enabled collision detection between players. Neither player would be able to move if both spawned at the same time, because both players would essentially be "trapped" within each other's meshes. What is the best way to resolve this problem?


texts: How to emulate PSX's graphics with OpenGL?

texts: I want to know what options (or shaders) to set so that my OpenGL game looks like Playstation 1 game. I know it probably can not be achieved 100 % because PSX used television and television renders differently that monitor. Thanks. :)


texts: Can I break the UI MASK hierarchy in unity 4.6?

texts:
I'm using unity 4.6. I saw a couple of UI masks tutorials and saw that there's a certain hierarchy I can't seem to break:

-Canvas
--- Panel (holds the mask component)
--------Image

I want to move the mask and leave the image in its place.

(Attach the mask to a moving object, and by that, exposing the image by the moving object position)

I have 2 problems with it:

My moving object barely moves my mask (I guess because of the canvas).
The image is a child of the mask, so even if it will move, it will move with it.
Can I even do it?


texts:
I am confused about the argument "m" of this function.

I also need to know how to make this work. I am working on a simple 2d game and I am really new to programming.
I don't know how to make things work in this Timer() function. I want to animate an object in a specific direction. I know the coordinates of the direction but after a lot of hit and trial, my object moves in a random direction. I have used sin and cos for the movement. But  my real problem is about the functionality of this Timer() function. Can anyone here help me about it? Any help will be appreciated.

float dt = 0, lastframe = 0;

void Timer(int m) {
    dt = (m - lastframe) / 1000.0;
    lastframe = m;

    glutPostRedisplay();
    glutTimerFunc(1000.0 / FPS, Timer, m + 1);
}


texts: Moving objects in a circular path, and also moving the whole group

texts:
I have eight elements distributed in a circle, with a common center.

All of them move along a circular path, just like the poster in this question asked:

Moving an object in a circular path

This solves half of my question, however I also need to oscillate the whole group of units from side to side, with an easing, or linearly, depending on the design.

I've been playing around with it, but I can't figure how to add or modify what I assign to the X and Y value so the objects move like if they were contained inside a Sprite, and I would be moving that Sprite.

Edit.:

I found that this:

var newX:Number = Math.cos(_angle) * 100;
var newY:Number = Math.sin(_angle) * 100;

y = _startingY + newY;

x = _startingX + newX + _incrementX;

_angle += 2 * Math.PI / 180;

_incrementX += 1 + Math.sin(_angle);

Gets close enough to what I need, however it still doesn't work. In theory, if I subtract the sin f the angle it should fix the rotation compensation.

Edit2: The stars moving in circle:

What happens when I just add a linear increment to each element: (it would represent in the code above doing _incrementX++)


texts: XNA GameComponent.Initialize() not called

texts:
I have a game which creates an object in its Initialize() method:

    private GameComponent1 _thingy;
    protected override void Initialize() //Game1.Initialize()
    {
        base.Initialize();
        _thing = new GameComponent1(this);
    }

In the GameComponent1 class:

    public GameComponent1(Game1 game) : base(game)
    {
        _game = game;
        game.Components.Add(this);
    }

    public override void Initialize() //GameComponent1.Initialize()
    {
        //Do stuff here
        base.Initialize();
    }

However, in this case, _thing's Initialize method is not called. Why is this?

It behaves fine when the object is created in, say, Game1's Update method...


texts: Can inflation exist in a fixed price Mmorpg world?

texts:
Assumptions:

Crafting materials are infinite. Limit is player boredom.
Players can only trade through the auction house. All prices are fixed. Players cannot decide arbitrary prices.
Goods in auction house stay stored for infinite duration and cannot be withdrawn by auction creator (except if he pays 100% item price + 10% auction fee).
Sell algorithm is FIFO (First item placed by any player is first item sold).
Crafting and gathering professions have a cool-down of 10 craft points per day.

Questions / Points to talk about:

All players will be happy, fair 100% prices, scam free, no need to play stock exchange market to make a profit through crafting. New Players would have the same experience even if they arrive too late to the game.
Money never loses its value, you could store money in a bank, arrive after 10 years to the game and buy everything at the same price. In contrast in WOW, a simple copper ore was worth 10 silver at the game start and now has ended as 200 silver. That's 2000% inflation.
By having fixed prices, you guarantee that even if all players in the universe have 99999999999g in their pocket, the goods are worth the same. So that's guaranteed 0% inflation. Hackers may cry all they want, but goods prices will never change.
Why didn't WOW / Diablo III used this model? They would have become billionaires with the 10% money grab technique.

Btw: my previous question on economy overflow was never answered, probably that site is dead. https://economics.stackexchange.com/questions/14609/understanding-inflation-in-a-video-game


texts: Basic AI FSM - Handling state transition

texts:
I'm starting to study on how to implement game AI, and it seems to me that a very simple FSM for my Pong demo would be a nice way to start.

My vision on implementing this would be to have a basic state interface and a class for each state, then the NPC would have an instance of the current state. The class should have an update method and directions on wich state to go next, depending on the event received.

The question is: How do I handle this event? Should I have a regular addEventListener and a costum event system? Or should I check on update for the things that could change the current state?

I'm feeling a bit lost, I feel I have a good grasp on the FSM concept but a good implementation seems tricky, thanks in advance.


texts:
I have this simple struct that is supposed to calculate the time difference between 2 frames:

struct Clock
{
public:
    Clock() {};
    ~Clock() {};

    double CalculateDifference()
    {
        previousFrame = currentFrame;
        currentFrame = SDL_GetPerformanceCounter();
        deltaTime = (double)((currentFrame - previousFrame) * 1000 / SDL_GetPerformanceFrequency());
        return deltaTime;
    }

private:
    uint64_t currentFrame = SDL_GetPerformanceCounter();
    uint64_t previousFrame = 0;
    double deltaTime = 0.0;
};

This is how I'm using it in my game loop:

DeltaTime = clock.CalculateDifference() * 0.001; // *0.001 to convert from ms to seconds because I heard deltatime should be in seconds...?

then:

velocityY -= 0.02f * m_DeltaTime;
Player.GetPosition().y += velocityY ;

The code above occurs every frame because I am making a simple doodle jump clone wherein the player is constantly jumping from one platform to another. I am using low level OpenGL programming for flexibility and exercise. I nearly got the game done but my timestamps seems messed up as sometimes the player jumps higher in one frame than previous frame...

Can someone please help me identify the issue with this?

Thanks!


texts: What is a fragment in 3D graphics programming?

texts:
What is a fragment in a fragment shader? Wikipedia says that:

  In general, a fragment can be thought of as the data needed to shade the pixel, plus the data needed to test whether the fragment survives to become a pixel (depth, alpha, stencil, scissor, window ID, etc.)

So is it textures, vertices or something else?


texts: ID3D10Device::RSSetState to be called every frame?

texts:
I am trying to create a ID3D10RasterizerState with direct3D10, and then call

ID3D10Device::RSSetState()
with the proper information. However, whenever the window get rescaled, or when the app goes fullscreen, the rasterizerstate seems to reset to the default state. I have tried to set the state with WM_SIZE messages, but awkwardly, nothing seems to happen...

It works properly when I call RSSetState() every frame, but that seems highly inefficient.

Does anyone know a solution to this? It seems to be poorly documented on msdn.

Code:

bool TestGameApp::InitGame()
{
    D3D10_RASTERIZER_DESC desc;
    desc.AntialiasedLineEnable = TRUE;
    desc.CullMode = D3D10_CULL_NONE;
    desc.DepthBias = 0;
    desc.DepthBiasClamp = 0.0f;
    desc.FillMode = D3D10_FILL_SOLID;
    desc.FrontCounterClockwise = false;
    desc.MultisampleEnable = true;
    desc.ScissorEnable = FALSE;
    desc.SlopeScaledDepthBias = 0.0f;

    m_pD3DDevice->CreateRasterizerState(&desc,m_pRSState);
    m_pD3DDevice->RSSetState(m_pRSState);

    //...more code
}

WndProc:

switch( message )
{
    case WM_SIZE:
    {
        m_pD3DDevice->RSSetState(m_pRSState);
        break;
    }
}


texts: What's the difference between Mathf.Lerp and Mathf.SmoothDamp

texts:
I want to smoothly go from one value to a new one (moving a slider or changing color). I tried using both functions and they all basically give the same result. What is the difference between them and which one should I use?

How I used SmoothDamp:

    // Show the HUD
private IEnumerator ShowHUD() {
    var HUDCanvasGroup = GameObject.FindWithTag("HUD").GetComponent<CanvasGroup>();
    var alphaValue = 1f;
    var velocity = 0f;
    var time = 0.30f;

    yield return new WaitForSeconds(1.5f);

    // Gradually fade in the canvas
    while (!Mathf.Approximately(HUDCanvasGroup.alpha, alphaValue)) {
        HUDCanvasGroup.alpha = Mathf.SmoothDamp(HUDCanvasGroup.alpha, alphaValue, ref velocity, time);
        yield return null;
    }

    HUDCanvasGroup.alpha = 1; // Since float is not accurate, manually set the alpha to 1 after
    HUDCanvasGroup.interactable = true;

    var blur = GameObject.FindWithTag("BlurryCamera").GetComponent<BlurOptimized>();
    blur.enabled = true;
}

How I used Lerp:

public static IEnumerator Dim() {
    while (t < 1) {
        t += Time.deltaTime / 0.4f;
        dimRend.material.color = Color.Lerp(undimColor, dimColor, t);
        yield return null;
    }
}


texts: What resolution should I render art for a 3D game for PC?

texts:
I hope this is not too stupid a question. I'm making my first game for PC and I'm wondering what resolution I should render the artwork at. It will be a fixed-perspective game, so I'm using a 2D background with 3D characters moving around.

How big should I render the background? Is 1920x1080 enough these days or should I go even higher? How big should the character textures be?

Thanks a lot!


texts: How to offset a 2D GameObject by a pixel amount?

texts:
I'm extremely new to game creation.

I'm playing around with creating a 2D Unity game. The scene is setup from the default Unity 5 2D template.  Following a tutorial, I've created a TerrainManager GameObject and Script.  The script instantiates tiles and sets their position using a standard double-loop.

I've found a 2D isometric tile set.
Each tile is visually rendered as rotated around the vertical axis by 45 degrees, creating more of a diamond shape rather than a square.  This requires that every second tile be offset by half the tile width on the x-axis, and half the tile height on the y-axis.

As each tile is of a different height, one can not simply offset the tile on the Y axis by half its height.  Each terrain "layer" is 16px tall in the PNG.  Some PNGs have a single "layer", some have multiple "layers".  (For instance, a single layer water tile is 83px in height, while a dual layer "grass on top of dirt" layer is 99px in height.

As the game object expects the transform.position as a Vector3 in (I assume) game units, I do not know how to compose this using pixel values.

So the question I have is, how do I achieve the 16px y-axis offset of the game object?

I'm more than happy to provide additional details if needed.


texts: Sphere Texture Mapping shows visible seams

texts:
As you can see from the above picture there is a visible seam in the texture mapping. The underlying mesh is a geosphere based on octahedron subdivisions. On that particular latitude, vertices have been duplicated. However there still is a visible seam.

Here is how I calculate the UV coordinates:

float longitude = (float)Math.Atan2(normal.X, -normal.Z);
float latitude = (float)Math.Acos(normal.Y);

float u = (float)(longitude / (Math.PI * 2.0) + 0.5);
float v = (float)(latitude / Math.PI);

Is this a problem in the coordinates or a mipmapping issue?

Edit: the GeoSphere is generated using SharpDX's Toolkit code. My SamplerState is set to Clamp. Further, I am using a normal mapping shader.

Could it be that the tangent of the duplicated vertices needs to be altered? I am using a Vector4 element for it, where w is the handedness. If so, how should it be modified?

Edit2: this is the code used to duplicate the vertices along the seam

int preCount = vertices.Count;
var indicesArray = indexList.ToArray();
fixed (void* pIndices = indicesArray)
{
    indices = (int*)pIndices;

    for (int i = 0; i < preCount; ++i)
    {
        // This vertex is on the prime meridian if position.x and texcoord.u are both zero (allowing for small epsilon).
        bool isOnPrimeMeridian = MathUtil.WithinEpsilon(vertices[i].Position.X, 0, XMVectorSplatEpsilon)
                                 && MathUtil.WithinEpsilon(vertices[i].TextureCoordinate.X, 0, XMVectorSplatEpsilon);

        if (isOnPrimeMeridian)
        {
            int newIndex = vertices.Count;

            // copy this vertex, correct the texture coordinate, and add the vertex
            VertexPositionNormalTexture v = vertices[i];
            v.TextureCoordinate.X = 1.0f;
            vertices.Add(v);

            // Now find all the triangles which contain this vertex and update them if necessary
            for (int j = 0; j < indexList.Count; j += 3)
            {
                var triIndex0 = &indices[j + 0];
                var triIndex1 = &indices[j + 1];
                var triIndex2 = &indices[j + 2];

                if (*triIndex0 == i)
                {
                    // nothing; just keep going
                }
                else if (*triIndex1 == i)
                {
                    Utilities.Swap(ref *triIndex0, ref *triIndex1);
                    Utilities.Swap(ref *triIndex1, ref *triIndex2);
                }
                else if (*triIndex2 == i)
                {
                    Utilities.Swap(ref *triIndex0, ref *triIndex2);
                    Utilities.Swap(ref *triIndex1, ref *triIndex2);
                }
                else
                {
                    // this triangle doesn't use the vertex we're interested in
                    continue;
                }

                // check the other two vertices to see if we might need to fix this triangle
                if (Math.Abs(vertices[*triIndex0].TextureCoordinate.X - vertices[*triIndex1].TextureCoordinate.X) > 0.5f ||
                    Math.Abs(vertices[*triIndex0].TextureCoordinate.X - vertices[*triIndex2].TextureCoordinate.X) > 0.5f)
                {
                    // yep; replace the specified index to point to the new, corrected vertex
                    indices[j + 0] = newIndex;
                }
            }
        }
    }

    FixPole(northPoleIndex);
    FixPole(southPoleIndex);

    // Clear indices as it will not be accessible outside the fixed statement
    indices = (int*)0;
}


texts:
I want to display coordinates from 0 to n, where n is int > 0.
The map is displayed correctly heaving it's center in the middle of the screen pointing top right. I would like to have it pointing bottom right.

My implementation is:

effect.Parameters["wvp"].SetValue(Matrix.Translation(0, 0, 0) *
    Matrix.LookAtLH(Vector3.Zero, Vector3.UnitZ, Vector3.Up) *
    Matrix.OrthoLH(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 1));
effect.Techniques[0].Passes[0].Apply();

GraphicsDevice.SetDepthStencilState(GraphicsDevice.DepthStencilStates.None);
GraphicsDevice.SetRasterizerState(GraphicsDevice.RasterizerStates.CullNone);
GraphicsDevice.Clear(Color4.Black);
GraphicsDevice.SetVertexBuffer(layer.Buffer);
GraphicsDevice.SetVertexInputLayout(layer.InputLayout);

GraphicsDevice.Draw(PrimitiveType.TriangleList, layer.Buffer.ElementCount);

And a screenshot of the situation now.

The white area is around coordinate (0, 0). The line is just at X = Y for orientation. The black line should be pointing bottom right as mentioned above. Any Idea how this can be done?


texts:
I made a simple spaceship that has a particlesystem. When I press "space" button, spaceship should fly and particle system should instantiate and play. But it's not playing. It seems in hierarchy as clone but not playing.
As you see, particle effect is instantiating but not playing. It should play at bottom of spaceship
Those are codes
void FlyShip()
{

    if (Input.GetKey(KeyCode.Space))
    {

        rb.AddForce(Vector3.up * jumpForce);

        if (!takeoffSound.isPlaying)
        {

            // _rocketJetParticle is gameobject.
            _rocketJetParticle = Instantiate(rocketJetParticle, new Vector3(transform.position.x, transform.position.y - 4, transform.position.z), transform.rotation);
            takeoffSound.Play();

        }

    }

    else
    {
        //Destroy(_rocketJetParticle);
        takeoffSound.Stop();

    }

}


texts: How to handle dynamic hierarchical entities in ECS

texts:
Here's the analogy:
I have an organism which is composed of cells which can be further composed of a medley of attachments.

What I have currently is a sort of event chain between child/parents to handle attaching and detaching components (which could affect anything along the chain) which doesn't involve ecs at all, they are functions in the entities.

Now I've used event components already (for mouse events on objects).
If I wanted the system to be pure, would I create an attach component when I attach components etc? Even then how would I get all the necessary recipients to the system that consumes the component? Is it even worth it to handle it this way instead of a chain of functions? Is there a better way?


texts: How to properly do top-down aRPG melee attacks?

texts:
I'm reposting this from my own thread in reddit's gamedev community, since there were too few responses:

I've been looking for some info on that, but I mostly find articles on the design of such systems, which are very useful, but not helpful from the coder's point of view. My main idea is similar to what the 2D Zelda games used to do, but with more directional freedom. In Zelda, you can only face one of the cardinal directions and attack the enemy there.
My idea is to have the same but with any direction, since we now have analog sticks, or even mice. I'm pretty sure this has been done before, and a few Flash games come to mind, such as the Zombie Apocalypse game Dead Frontier (which is now done on Unity3D, but was Flash back when I played it)

I'm working with Unity3D (although I'm making a 2D game), and I'm not completely happy with where I'm going.

This:  is my current hacky solution for a Melee hit check. The green triangle is the player, the faint green circle is a trigger that checks if there are enemies in this trigger, and the red boxy thing is an enemy.
When the player presses the "melee attack" button, it picks one of the enemies in the trigger (by order of the first one to enter the trigger) and causes damage.

Among a few things I've added to that are: Slow down the player movement during an attack, so that they can't "run n' slash" through an entire level, and also limit how many attacks the player can do per second. An attack cannot start if the previous one hasn't finished yet.

This is looking a bit crude, though. I just kind of hacked it together and it doesn't feel as natural as in other games I've played.

Here's my hacky Melee Attack script in my prototype (it uses a few magic numbers, such as the attack duration):

void Update()
{
 //other logic
    if (Input.GetMouseButtonDown (0) && sec <= 0)
    {
        attackDuration = 0.5f; //setting how long the attack takes from start to finish
    }
    if (attackDuration > 0)
    {
        attackDuration -= Time.deltaTime;
        if (attackDuration <= 0.25f && !done) //cause the damage when the attack is halfway done
        {
            if(EnemiesInRange.Count > 0)
            {
                Enemy target = ((GameObject)EnemiesInRange[0]).GetComponent<Enemy>();
                target.health -= 10;
                if (target.health <= 0)
                {
                    EnemiesInRange.Remove(target.gameObject); //if the enemy dies, it's no longer a valid target.
                }

            }
            done = true;
        }
    }
    else
    {
        done = false;
        sec = 0; //attack over, reset it to zero (to avoid stuff like -0,001)
    }
//other logic
}

Meanwhile, in the CharacterMovement.cs script:

void Update()
{
//other logic
    if(gameObject.GetComponent<MeleeAttack>().sec <= 0)
    {
        lookAtMouse();
        transform.Translate(new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0) * baseSpeed, Space.World);
    }
    else
    {
        transform.Translate(new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0) * (baseSpeed*0.25f), Space.World);
    }
//other logic
}

What I'm doing here is stopping the player to change their facing during the attack as well as slowing the movement down to 1/4 the base speed.

Anyway, any advice? How could I make attacking and moving feel more natural? What about the hit mechanics themselves?

My biggest gripe right now is: I don't think "Pick an enemy in a small circular area ahead of the player" is really good.  What should I do?


texts: Fatal Python error: (pygame parachute) Segmentation Fault when using PyGame and cx_Freeze

texts:
I'm using cx_Freeze to package my PyGame game. I'm running Ubuntu Linux, so I used the source package. However, I got the following error when I run cxfreeze game.py:

Fatal Python error: (pygame parachute) Segmentation Fault
Aborted

How can I fix this? I have seen other similar questions but no good answers.


texts: How many people are needed for making a good (MMO)RPG?

texts:
1) RPG?
2) MMORPG?

I'm talking more about good content here.

Update: Because it is said here that volume of information is low in my question, and because there was too much to say, I created an extension question


texts: Is There a Way To Keep Precision When Transforming GameObjects

texts:
I've seen this issue before, but it's never been a particular issue for me until today.  I have each "room" of a dungeon created with a class script that contains details of that room.  During the process of building the dungeon, rooms may be mirrored or rotated.  When I rotate the y-axis, it updates properly the first time, going from 0 to 180, but if I mirror it back and forth, it begins to get very small variances away from true 0 and 180.  Over time, this could impact some things.  The code I'm using to do this is:

    public void RoomMirror()
    {
        transform.Rotate(0, (transform.localRotation.y==180) ? 0.0000f : 180.0000f, 0);
        Mirror = !Mirror;
        Swap(ref _east, ref _west);
    }

I added the four places in the float to try to overcome this issue, but it doesn't seem to be making any difference.  Thanks!


texts:
I've added the Mobile Bloom shader to the camera and I have Emissive HDR objects in my scene and I've set the graphics quality to the highest. I do not have anti-aliasing enabled but the bloom effect only appears in the editor play mode and not on my android mobile device.

If anybody could tell me all the setting I have to check or post screenshots of a working setup it would be very helpful.

Thanks.


texts:
I read a lot about ECS (strategy) pattern and have a few questions. Consider simple space game.

We have stars there. Obviously star is an entity. What if I want to make a galaxy? It looks reasonable to make galaxy an entity. On the other hand galaxy is just a set of stars. In usual OOP design I would just made it a class which holds a list/vector of stars. Is it legial to make an entity which is just a container for other entities? Wouldn't it brake at some point?
Now consider planetary system. It looks like planet is an entity too. But it would be wise to link a planet to its parent star. May one entity refer to another (having pointer, or something like that)? How would you compose that?

Thanks in advance.


texts: Detecting single circle within multiple circles area

texts:
There are multiple circles with same radius, given another circle in different radius, how to detect the another circle is fully in multiple circles area.

Image below shows left samples is in the area, right is not.


texts: DirectX11 pixel shader in pipeline is missing

texts:
I'm writing a program which displays a MS3D model using DirectX, and unfortunately, the result shows nothing on the screen.
When I use the Graphics Debugger from Visual Studio 13, I notice that the pixel shader is missing from the pipeline, as it is shown in the below picture

This is my pixel shader source code:

 cbuffer SkinningTransforms
 {
    matrix WorldMatrix;
    matrix ViewProjMatrix;
 };
//--------------------------------------------------------------------------------
// Inter-stage structures
//--------------------------------------------------------------------------------
struct VS_INPUT
{
    float3  position        : POSITION;
    int4    bone            : BONEID;
    float4  weights         : BONEWEIGHT;
    float3  normal          : NORMAL;
    float3  tangent         : TANGENT;
    float2  tex             : TEXCOORD;
};
//--------------------------------------------------------------------------------
struct VS_OUTPUT
{
    float4 position         : SV_Position;
    float3 normal           : NORMAL;
    float3 light            : LIGHT;
    float2 tex              : TEXCOORDS;
};

Texture2D       ColorTexture : register( t0 );
SamplerState    LinearSampler : register( s0 );

//--------------------------------------------------------------------------------
VS_OUTPUT VSMAIN( in VS_INPUT input )
{
    VS_OUTPUT output;
    //Transform vertex and pass them to the pixel shader
    return output;
}

//--------------------------------------------------------------------------------
float4 PSMAIN( in VS_OUTPUT input ) : SV_Target
{
    // Calculate the lighting
    float3 n = normalize( input.normal );
    float3 l = normalize( input.light );

    float4 texColor = ColorTexture.Sample( LinearSampler, input.tex );

    float4 color = texColor * (max(dot(n,l),0) + 0.05f );
    return( color );
}

As I was known from Graphics Debugger, all of the graphics event are right. I listed in below important events, which might be relating to Pixel Shader:

106:(obj:4) ID3D11Device::CreateDepthStencilView(obj:24,NULL,obj:25)*
108:(obj:5) ID3D11DeviceContext::OMSetRenderTargets(8,{obj:1,NULL,NULL,NULL,NULL,NULL,NULL,NULL},obj:25)*
109:(obj:5) ID3D11DeviceContext::ClearRenderTargetView(obj:1,addr:21)*
111:(obj:5) ID3D11DeviceContext::ClearDepthStencilView(obj:25,1,1.000f,0)*
119:(obj:4) ID3D11Device::CreateSamplerState(addr:24,obj:27)*
134:(obj:4) ID3D11Device::CreatePixelShader(addr:27,21056,NULL,obj:30)*
135:CreateObject(D3D11 Pixel Shader,obj:30)
136:(obj:5) ID3D11DeviceContext::PSSetShader(obj:30,NULL,0)*
137:(obj:5) ID3D11DeviceContext::PSSetSamplers(0,1,{obj:27})*
139:(obj:4) ID3D11Device::CreateTexture2D(addr:28,addr:5,obj:31)*
140:CreateObject(D3D11 Texture2D,obj:31)
142:(obj:4) ID3D11Device::CreateShaderResourceView(obj:31,NULL,obj:32)*
143:CreateObject(D3D11 Shader Resource View,obj:32)
144:(obj:5) ID3D11DeviceContext::PSSetShaderResources(0,1,{obj:32})*
146:(obj:4) ID3D11Device::CreateRasterizerState(addr:29,obj:33)*
147:CreateObject(D3D11 Rasterizer State,obj:33)
152:(obj:5) ID3D11DeviceContext::RSSetState(obj:33)*
154:(obj:5) ID3D11DeviceContext::RSSetViewports(1,addr:30)*
156:(obj:4) ID3D11Device::CreateBlendState(addr:11,obj:34)*
157:CreateObject(D3D11 Blend State,obj:34)
159:(obj:5) ID3D11DeviceContext::OMSetBlendState(obj:34,addr:31,-1)*
162:(obj:4) ID3D11Device::CreateDepthStencilState(addr:32,obj:35)*
163:CreateObject(D3D11 Depth-Stencil State,obj:35)
165:(obj:5) ID3D11DeviceContext::OMSetDepthStencilState(obj:35,0)*

I debugged all of the function in the above list, and all of them return OK. Nothing wrong.
My question is what is the reason the pixex shader is missing from pipleline, which in turn may result in the empty screen.


texts: Moving platforms left and right between two walls

texts:
I'm currently working on a rocket game where the player needs to collect parts from each level and in the main menu they can upgrade their own rocket with the parts found. But now I'm trying to add platforms that the player can land on, these platforms need to move left and right randomly until they hit the side of the screen then they reverse in the opposite direction and repeat.

Problem is now I spawn the platforms in randomly on the X axis and I need them to move in a random direction(on the x axis) from the start. As the level moves up the screen I have a collider that generates more platforms further up.

Any Idea what I should try to achieve the desired result?

here is my current code to move the platforms into random directions.

public class MovingPlatform : MonoBehaviour
{
    private float platformMin = -6.5f;
    private float platformMax = 6.5f;

    void Start()
    {
        RadomizePlatforms();
    }

    public void RadomizePlatforms()
    {
        GameObject[] platforms = GameObject.FindGameObjectsWithTag("Platform");

        foreach (GameObject platform in platforms)
        {
            Vector3 pos = platform.transform.position;
            pos.x = Random.Range(platformMin, platformMax);
            platform.transform.position = pos;
        }
    }
}


texts: Why can changing a camera's position prevent it from rotating?

texts:
I am going through the official introductory series "Roll a Ball" by the Unity team, and am on part 3 (youtube link.

There is a ball with mouse controls attached, and a Camera set as a descendant of the ball so that it follows it around. As the tutorial mentions, the Camera at this stage "rolls" along with the ball and is unusable.

The fix, as shown in the video, is the following added to Camera:

public GameObject player; # added through GUI
private Vector3 offset;
void Start () {
  offset = transform.position - player.transform.position;
}
void Update () {
  transform.position = player.transform.position + offset;
}

I understand in terms of C# syntax what this does, but I don't understand why it stops the camera from rotating. Isn't position controlled separately from rotation?


texts: GLFW window freezes on title bar hold/drag

texts:
I am making a C++ program with Opengl and GLFW for window and input handling.
The program is updated with the main loop by delta time which is calculated by subtracting new frame start time with old frame start time.
My problem is that when title bar is hold the whole program stops, but when it is released the delta time is as big as hold time.
I am also using chrono library for calculating passed time.

My code:

unsigned long second = std::chrono::seconds( 1 ) / precision;
frameStartTime = std::chrono::system_clock::now().time_since_epoch() / precision;
while ( running && !glfwWindowShouldClose( glfwWindow ) && !input::keyboard::isDown( GLFW_KEY_ESCAPE ) ) {
    lastFrameTime = frameStartTime;
    frameStartTime = std::chrono::system_clock::now().time_since_epoch() / precision;
    deltaTime = float( frameStartTime - lastFrameTime ) / second;

    glfwPollEvents();
    mainScene->update( deltaTime );
    input::clear();

    mainScene->draw();
    glfwSwapBuffers( glfwWindow );

    countFps( deltaTime );
}

What am I doing wrong and how can I fix this issue?
Thanks.


texts: How to implement a symmetric 3d field of view algorithm for a roguelike

texts:
I've been thinking about adding 3d support in my roguelike. It would still be top-down like other roguelikes, yet it would have layers, such that things like platforms, tunnels, and bridges, etc, could be added to levels. Whether I do this hinges on whether I can get the fov routine I'm using working with the layers.

Note that I don't care that it doesn't make sense to some of you that I'm trying to have a 3d field of view routine for a 2d roguelike. The roguelike does have a 3d space, and I want to determine what the player can see, even if what the player can see can't logically be displayed. Let me worry about how to handle that problem.

I would be grateful for some advice in how to approach this problem. Perhaps this is utterly crazy, and I should just make a 2d roguelike...

Update:

I erroneously stated before that the problem with Bresenham's line algorithm was with artefacts. I should have mentioned that I needed the fov routine to be symmetric. Such a requirement can't be met by Bressenham's line algorithm.


texts: Can you sync screen update on vertical retrace with OpenGL?

texts:
In OpenGL, is there a way to ensure I get exactly, no more nor less, 60 (or whatever rate my monitor is set for) frames per second?

Of course given that the new frame can be calculated in less than 1/60 second.
I was thinking Windows more than Linux or Mac OSX, even though it is interesting to keep an eye on portability.


texts: Good Resources for Random World Generation

texts: Is there a good reference or tutorials available for adding world generation into a 2D game? I've gotten to the point where I have most of the resources available to add world generation but I don't really understand the concepts of creating a random world generation based map. Any tips and guides can help.


texts:
Hello I have a question about translation & rotation of a MatrixTRS...
So basicly I have a given MatrixTRS A in space, define by a positionA, rotationA and scaleA.
(DISCLAIMER: I am using Unity, but I do not use Transform, therefore I have a Matrix4x4, created like that:
Matrix4x4 A = Matrix4x4.TRS(position, rotation, scale);
Ok, Now I have a Point in space, with a given rotation, named PositionB, and RotationB.
I would like to translate & Rotate my TRS matrix to that positionB, and rotationB.
I know I have to do something like b.transform.TransformPoint() and Quaternion.Inverse(b.transform.rotation)*a.transform.rotation, but i didn't manage to make it right yet.
Thanks!


texts: Should I encrypt my multiplayer network traffic?

texts:
My plan has been to use RSA to exchange AES session-keys with a client, which is then used for all the usual in-game stuff. Clients never connect with each other, all communication is client to server only.

The question is: Would I be wasting my time by encrypting the communication? How are big AAA multiplayer games doing it? If I do do encryption, is the basic scheme I mentioned a good start?


texts: How to make Sprites scroll with the background image that are inside Scroll View?

texts:
I'm new in Unity, so I hope you guys can help. I'm developing a 2D-game for Android device, on the scene I have a huge background image inside Scroll View (UI - Scroll View).

Next, I created new empty Game Object "Players", attached to it "Players script" and added "Sprite Renderer" component.

From the Sprites I created two prefabs - housePrefab and dogPrefab. Inside "Players script" I have the following code:

[SerializeField] GameObject housePrefab;
[SerializeField] GameObject dogPrefab;

void Start()
{
var houseXPos = 1.41f;
var houseYPos = 2.63f;

var dogXPos = -0.41f;
var dogYPos = 2.63f;

GameObject house = Instantiate(housePrefab, transform.position = new Vector2(houseXPos, houseYPos), Quaternion.identity) as GameObject;
GameObject dog = Instantiate(dogPrefab, transform.position = new Vector2(dogXPos, dogYPos), Quaternion.identity) as GameObject;
}

After I run game both Sprites appears on the screen (as I expected). The problem occurs when I Scroll background image, both sprites stay in the same position under scrolling. In other words sprites not scrolling with the background image.

As far as I understand, the Sprites needs to be added to the background image, but I don’t know how to do it.
How to make Sprites scroll with the background image?

Thanks to all in advance.


texts:
I am building up a simulation where predator groups (tribes) try to hunt other agents in the simulation (whom also are clustered in groups).

Now I got to a point where members of a group follow their leader and wait for any sort of commands (currently passed as strings and vector that they need to move towards).
Anyway the idea is to implement some interesting surrounding behaviour just like predators hunt in group they surround their prey.I shall attach a picture for better explanation:

The green circles are the agents that predators are hunting. The red circle is the leader of the predator group and the black dots are other predators. The sort of behaviours I am looking for should be similar to shown in the picture where on the right side of the picture the predators are surround the pack of green agents as instructed so by the leader of the predator pack.

What I was thinking initially was find the leftmost agent in the green pack and the right most in green agents pack and make members of the predator group move towards them.However at this point I shall mention that predators have a fixed field of view so it may not see all of the pack at first.

So I am wondering if anybody came across something like so or have any good ideas how to go about producing this sort of behaviour.


texts: What is the maximum value of a LayerMask in Unity?

texts:
What is the maximum value of a LayerMask in Unity (the value when all layers are included)? And how can I find it using C# bitwise operations?

I tried ~0 but it shows -1 in intellisense.

Thanks in advance.


texts: What are effective strategies for a small game development team?

texts:
What are language/platform-agnostic best practices for a small game development team of intermediate to advanced developers?

High-level strategies (as well as suggestions in terms of frameworks, engines or IDEs which might offer a good ROI) are welcome.


texts: How can I calculate the orthographic projection needed to encompass an object with arbitrary rotation?

texts:
So I need to set up the dimensions of a orthographic projection that will encompass the entirety of a bounding box when viewed from any arbitrary position.

That's an eye (programmer art); and the vertical line next to it is my view. How can I work out what the size of this view should be so that it encompasses the furthest corners of my rotated rectangle (from the viewports perspective)?

I want to do this in 3D obviously, I thought 2D would explain it better.

So far, I've considered that if I have:

The coordinates of each corner of my bounding box from it's model matrix perspective
With this, I could easily work out what the furthest ones are IF I was able to multiply it with my view matrix. However, it's the view matrix I'm trying to calculate...


texts:
I recently made terrain generation for my game, and I created a lighting system (simply diffuse lignting), but there's a strange problem around the edges.

I know, OpenGL interpolates the different values between the vertex shader and fragment shader, but in this case, it comes out strangely. Here is the issue:

The edges of the squares look a little jagged (I use triangles).

I especially don't understand this one:

Every vertex of that area is dark, but the middle is lighter.

Here are the codes for the vertex and fragment shader:

Vertex shader:

#version 330 core

in vec3 vertex;
in vec3 normal;
in vec4 color;

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

out vec3 vertexNormal;
out vec3 cameraPos;
out vec3 vert;
out vec4 vertColor;

void main() {
    gl_Position = projection * view * model * vec4(vertex, 1.0);
    vertexNormal = normal;
    cameraPos = vec3(view[3][0], view[3][1], view[3][2]);
    vert = vertex;
    vertColor = color;
}

Fragment shader:

#version 330 core

in vec3 vertexNormal;
in vec3 cameraPos;
in vec3 vert;
in vec4 vertColor;

uniform vec3 sunColor;
uniform vec3 sunDirection;

void main() {
    vec3 toLightVector = -sunDirection;
    vec3 uLightVector = normalize(toLightVector);

    float diffuse = max(dot(uLightVector, vertexNormal), 0.1);
    vec3 lightColor = diffuse * sunColor;

    gl_FragColor = vec4(lightColor, 1.0) * vertColor;
}


texts: How to limit my scoreboard to 100 top Score then adding the number list?

texts:
so I want to make 100 top scorers on my leaderboard but I don't know how to make a number list, what I mean is when the user is top 1 so number list 1 and so on
so here the leaderboard script :
 public IEnumerator LoadScoreboardData()
    {
        var DBTask = DBreference.Child("users").OrderByChild("highscore").LimitToLast(100).GetValueAsync();

        yield return new WaitUntil(predicate: () => DBTask.IsCompleted);

        if (DBTask.Exception != null)
        {
            Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
        }
        else
        {
            //Data has been retrieved
            DataSnapshot snapshot = DBTask.Result;

            //Destroy any existing scoreboard elements
            foreach (Transform child in _MainMenuUI.instance.scoreboardContent.transform)
            {
                Destroy(child.gameObject);
            }

            //Loop through every users UID
            foreach (DataSnapshot childSnapshot in snapshot.Children.Reverse<DataSnapshot>())
            {
                string username = childSnapshot.Child("username").Value.ToString();
                int highscore = int.Parse(childSnapshot.Child("highscore").Value.ToString());

                //Instantiate new scoreboard elements
                GameObject scoreboardElement = Instantiate(_MainMenuUI.instance.scoreElement, _MainMenuUI.instance.scoreboardContent);
                scoreboardElement.GetComponent<_ScoreElementContent>().NewScoreElement(username, highscore);
            }

            //Go to scoreboard screen
            _MainMenuUI.instance.leaderboardPanel.SetActive(true);
        }
    }

as you can see there is no number list just order by highest score.


texts: Waiting specific time to increase sound libgdx

texts: I want to wait a moment (.5 seconds) before I increase the sound, how can i achieve this without using Thread.sleep, because i want my game to keep runnig.


texts: How do i manage skill collision target in Unity?

texts:
I wanted to make a skill that can be used by both Player & Enemy.

How do I make it such that the skill will not be colliding with the owner/caster or colliding with both?

One stupid way I have is to create empty gameObjects as the Skill's child and set their tag as "targetPlayer","targetEnemy" or "targetAll" whenever my player/enemy cast the skills.

And when the skill collided with Player/Enemy, i will check the skill's children and see if there's matching tag and proceed if so.

Is there better way to do what i wanted??