texts: How to decide the direction of movement, when navigating a fixed path in a 2d overworld?

texts:
Suppose, I have a 2D overworld like in Super Mario Brothers 3, but without junctions or intermediate nodes. Only a single, contiguous path of level nodes, which should be navigated with the arrow keys.

Currently, the path is calculated automatically by the order of which the nodes appear. Each node has at most two edges, which extend from the center of each node.

Now there are multiple possible layouts of said path. In the following pictures, "P" is the position of the player. Directions formatted as code will denote arrow key presses.

Axes-aligned paths

This is the trivial case, since each possible direction is aligned with the arrow keys. down moves the player down, left moves him left.

Angled paths

Here it gets a little trickier, since the possible directions are not aligned with the arrow keys anymore. Pressing left is ambiguous, the only option would be to use up and down to move the player up-left and down-left respectively.

Axes-aligned and angled paths mixed

In this case, left could be used to move the player either to the left or to the up-left. But here it would be more intuitive to use left for left and up for up-left movement.

Arbitrary paths

This is where I am kinda lost. Both possible paths lead up-left. Now I could say, since one node is "more left" than the other, let left walk the player to that node. The other node is "more up", so up can walk him there. But what if such a situation doesn't exist? For example, when one node is both "more left" and "more up" than the other one?

Some approaches I had

Give directions a priority, so when ambiguous situations exist, left gets picked over up for example. That means, left will always move the player to the most left node, no matter where the other node is. But with this I think I have to implement a lot of if-checks and it would also be not as intuitive for the player.
Add direction markers, so paths leading from one node to another are only connected at their direction specific markers. This will be more intuitive, since you can simply look at the markers and know, that the left marker is mapped to left.    But this looks rather ugly and unnatural, because the edges don't originate from the center of the node anymore. Furthermore, I think this will cause the same problem as before. I need to decide beforehand, which marker is connected to which other marker. So I basically relocated the problem to another point in the logic.
Restrict placement, so the nodes are only placed in such a way, that the path ends up axes-aligned. Since I'm free to place the nodes anywhere I want, this would be the easiest solution. But that would make the layout of the world map rather boring. I guess this could be my fall-back approach, when everything else fails.
Decide by angle of an edge. Divide a circle into four sectors at (2k + 1) * PI/4 with k = 0..3. Each sector defines one direction. An edge is now mapped to this direction, when the edge lies in that sector. If two edges are in the same sector, the one closer to the main-axis (x or y) in that sector is mapped to that direction. The remaining edge is then mapped to the direction of the next closer sector.  This one came to my mind, while writing this question, so I haven't given it much thought yet. I find this the most elegant approach so far. But I already see two problems where there is some ambiguity:  - If an edge lies exactly on a dividing line between two sectors (e.g.: at 45°)  - If two edges are symmetrical around an axis (e.g.: at 30° and 330°)

Questions:

How could I generalize the decision-making with arbitrarily connected paths?
Are my presented approaches reasonable?
What approach would be the most promising? Or is there a better one, which I haven't thought of yet?

Thanks in advance for your time! I look forward to your suggestions :)


texts: Using Mobile Accelerometer to trigger an action in my game unity

texts:
Hi I have this project I'm working on which is a bowling game controlled by mobile acceleration. I want the following:
when the player holds the phone up facing him for 2 seconds to enter strike state.
then he should rotate the phone all the way down and facing the other side then lift it halfway to call the action.


texts: How can I generate a 2d navigation mesh in a dynamic environment at runtime?

texts:
So I've grasped how to use A* for path-finding, and I am able to use it on a grid.  However, my game world is huge and I have many enemies moving toward the player, which is a moving target, so a grid system is too slow for path-finding.  I need to simplify my node graph by using a navigational mesh.

I grasp the concept of "how" a mesh works (finding a path through nodes on the vertices and/or the centers of the edges of polygons).

My game uses dynamic obstacles that are procedurally generated at run-time.

I can't quite wrap my head around how to take a plane that has multiple obstacles in it and programatically divide the walkable area up into polygons for the navigation mesh, like the following image.

Where do I start?  How do I know when a segment of walk-able area is already defined, or worse, when I realize I need to subdivide a previously defined walk-able area as the algorithm "walks" through the map?

I'm using javascript in nodejs, if it matters.


texts: Do games depend on the OS to scale resolution?

texts:
I'm having issues with my computer related with scaling when using different resolutions other than the native. So I started to wonder, in PCs, is scaling handled by the card driver or the game engine? Does it depend of what engine we are talking about? Do engines somehow bypass the scaling algorithm from the driver?

PS: I'm talking about the regular PC games that uses DirectX or OpenGL.


texts: Get object length and width divided by two?

texts:
I have googled and found a script for the following task; Make the camera move to touched position. However, this script will jump to x and y positions on an object, while i would like for it to move to the middle of the object, and then only be able to jump to others.

using UnityEngine;
using System.Collections;

public class TapToMove : MonoBehaviour
{
    // flag to check if the user has tapped / clicked.
    // Set to true on click. Reset to false on reaching destination
    private bool flagTouchCoords = false;
    // destination point
    private Vector3 cameraDestination;
    // alter this to change the speed of the movement of player / gameobject
    public float duration = 100.0f;
    // vertical position of the gameobject
    private float yAxis;

    void Start()
    {
        // save the y axis value of gameobject
        yAxis = gameObject.transform.position.z;
    }

    // Update is called once per frame
    void Update()
    {
        // check if the screen is touched / clicked
        if ((Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
        || (Input.GetMouseButtonDown(0)))
        {
            // declare a variable of RaycastHit struct
            RaycastHit hit;
            // Create a Ray on the tapped / clicked position
            Ray ray;
            // for unity editor
            #if UNITY_EDITOR
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            // for touch device
            #elif (UNITY_ANDROID || UNITY_IPHONE || UNITY_WP8)
            ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
            #endif

            // Check if the ray hits any collider
            if (Physics.Raycast(ray, out hit))
            {
                // set a flag to indicate to move the gameobject
                flagTouchCoords = true;
                // save the click / tap position
                cameraDestination = hit.point;
                // as we do not want to change the y axis value based on touch position, reset it to original y axis value
                cameraDestination.z = yAxis;
                Debug.Log(cameraDestination);
            }
        }

        // check if the flag for movement is true and the current gameobject position is not same as the clicked / tapped position
        if (flagTouchCoords
        && !Mathf.Approximately(gameObject.transform.position.magnitude, cameraDestination.magnitude))
        {
            // && !(V3Equal(transform.position, endPoint))){
            // move the gameobject to the desired position
            gameObject.transform.position =
                Vector3.Lerp(gameObject.transform.position,
                             cameraDestination,
                             1 / (duration * (Vector3.Distance(gameObject.transform.position, cameraDestination))));
        }
    }
}

So this is how the game looks. The script moves correctly, but will jump at different positions when it hits the collider on the lily pads. I could reduce the collider, but I feel like there should be an easy way to get length and width of a collider, and reduce it by /2 to make the camera move directly in the middle.

Anyone care to help? Thanks in advance. :)


texts: Custom Editor - keep default look but add more

texts:
What I would like to know is if there is a easy way using OnInspectorGUI, to replace the inspector with one that includes just one or two additional fields (so that it looks identical to the non-custom editor, except for the addition of one or two fields at the end). It seems like such a bother to recreate every field manually when I just want to add one little thing - so perhaps this is already a thing.

Or is there any way to easily tell unity to do it's default drawing for a specific type of field? When I was playing with this before, I had to commit to exactly what was to be shown, and I would need to manually write each field out --- which is bothersome if the public fields in my class(s) change - and they do frequently during development.

tl;dr - is there any way to simulate the default behavior of the inspector in a custom editor?


texts:
I'm just about finished developing a small Java/Lwjgl-based game. For Windows users, I intend to use Launch4J to package the game into a nice .exe. For Mac users, I'll be using JarBundler to produce a nice .app.

What do I do for Linux users? So far I've been distributing beta versions as a .jar file, a lib folder and a shell script for invoking the jar with the right virtual machine parameters. But this is less than pretty. Is there a cross-distro way of providing a single clear way to start the game?


texts: Manually update rotation of only Y-axis on Agent

texts:
I have some code to manage to rotation of my Navmesh agents:

if (Agent.isActiveAndEnabled && Agent.hasPath)
        {
            if (Agent.velocity.sqrMagnitude > Mathf.Epsilon)
            {
                transform.rotation = Quaternion.LookRotation(Agent.velocity.normalized);
            }
        }

It's causing my some issues with some odd rotations on the x/z axis for 1-2 frames every now and then, is there some way I can get this exact behaviour but only modify the y-axis?


texts: What external 2d animation formats can I use in android?

texts:
For an artist who won't be dealing directly with the code, what formats for 2d animation could they use that would be portable into an android game?

In my particular case there are no collision requirements or anything, just need to be able to place the animation on screen at a specific point.


texts: Implementing a 2D Collision method that can tell direction of collision (boxes)

texts:
Been searching for quite a while now and really struggling to find an easy way, or a good tutorial on how to create a collision detection system which can indicate what side on a box a collision has occurred.

I should specify that I am using SFML2 and their sprites class, this is what I currently use and it just picks up 2 sprites intersecting

//check rectangles for collision without taking into account where the collision is
bool Game::isRectCollision(sf::Sprite &sprite1, sf::Sprite &sprite2){

    sf::FloatRect r1=sprite1.getGlobalBounds();
    sf::FloatRect r2=sprite2.getGlobalBounds();
    return r1.intersects(r2);

}


texts: Why should every light source have its own ambient light?

texts:
I'm currently learning how to use OpenGl, and I'm following a tutorial on learnOpenGL. I'm at the lightning chapter, and it has introduced basic lightning, ambient and diffuse with specular highlight. Phong shading essentially.
I'm confused about the ambient term. I understand that the ambient light is basically a light that comes from nowhere in particular, and it just fills the scene you're in with a soft light. And it's used to fake Global Illumination in renderers that do not compute it, so that the stuff that's not in the direct view of a light source is not completely black but it has some generic lightning on it.
So going by the definition, before actually trying to implement a renderer myself, and by using other engines like UE4, I always just assumed that ambient light would be a separate thing from say a point light or a directional light. I thought it would be a parameter independent of other stuff that would basically just light the scene.
But in the tutorial, at least for the basic lightning part, the ambient is actually part of the light "object" itself. Essentially every light source has its own ambient light.
This seems counterintuitive to me. Why does every light need an ambient part too? Wouldn't make more sense to have a "separate" ambient light object that provides the ambient light itself?
Also, if my light has a radius of say 100 units, then outside of that radius nothing will receive any direct light, obviously, but also no ambient and will be completely dark. Isn't the point of ambient light exactly not to have scenes without direct light go completely dark?
Most importantly I'm wondering if this implementation approach is the standard used in modern game engines, or if it's maybe a simplification in the tutorial. (For example I don't remember seeing a parameter for ambient light in the light objects themselves in UE4)
Links for context:
https://learnopengl.com/Lighting/Basic-Lighting
https://learnopengl.com/Lighting/Light-casters


texts: Looping OpenAL sounds with one buffer - or how to do it correctly?

texts:
I require to implement a statically played sound class which supports looping of the audio data - and requires this to be changed at runtime (e.g., turning off looping).

Maybe I understand something horribly wrong, but this is how I understood how to implement looping at all, and came to the following solution:

I have exactly one buffer containing all the audio data.
If looping is enabled, ensure that the source playing the sound has this buffer queued twice, so it replays the sound when the end of the current buffer has been reached:

if (Loop && _source.BuffersQueued == 1)
{
    _source.QueueBuffers(_buffer);
}

If a buffer has been processed (e.g. right after the sound audibly loops), it is unqueued and dismissed.

if (_source.BuffersProcessed > 0)
{
    _source.UnqueueBuffers(_source.BuffersProcessed); // Unqueue outdated buffers
}

Here I ran into the first problem: If the user sets the sound to not loop anymore, I cannot unqueue the upcoming buffer (to make it not loop over another time while looping has already been turned off).

This is because I only found methods to unqueue by the handle of the buffer, but since I queue the same buffer twice, the handle is always the same to the one currently playing. OpenAL tries to unqueue the currently played buffer then, which obviously fails.

Unqueuing by the number of processed buffers also doesn't help, as no buffer has been marked as processed yet.

Do I really need to completely duplicate the buffer with all the audio data, keep it stored twice in memory, just to have two different buffer handles to unqueue the second buffer if looping gets disabled?


texts: Engine Rendering pipeline : Making shaders generic

texts:
I am trying to make a 2D game engine using OpenGL ES 2.0 (iOS for now). I've written Application layer in Objective C and a separate self contained RendererGLES20 in C++. No GL specific call is made outside the renderer. It is working perfectly.

But I have some design issues when using shaders. Each shader has its own unique attributes and uniforms that need to be set just before the main draw call (glDrawArrays in this case). For instance, in order to draw some geometry I would do:

void RendererGLES20::render(Model * model)
{
    // Set a bunch of uniforms
    glUniformMatrix4fv(.......);
    // Enable specific attributes, can be many
    glEnableVertexAttribArray(......);
    // Set a bunch of vertex attribute pointers:
    glVertexAttribPointer(positionSlot, 2, GL_FLOAT, GL_FALSE, stride, m->pCoords);

    // Now actually Draw the geometry
    glDrawArrays(GL_TRIANGLES, 0, m->vertexCount);

    // After drawing, disable any vertex attributes:
    glDisableVertexAttribArray(.......);
}

As you can see this code is extremely rigid. If I were to use another shader, say ripple effect, i would be needing to pass extra uniforms, vertex attribs etc. In other words I would have to change the RendererGLES20 render source code just to incorporate the new shader.

Is there any way to make the shader object totally generic? Like What if I just want to change the shader object and not worry about game source re-compiling? Any way to make the renderer agnostic of uniforms and attributes etc?. Even though we need to pass data to uniforms, what is the best place to do that? Model class? Is the model class aware of shader specific uniforms and attributes?

Following shows Actor class:

class Actor : public ISceneNode
{
    ModelController * model;
    AIController * AI;
};

Model controller class:
    class ModelController
    {
        class IShader * shader;
        int textureId;
        vec4 tint;
        float alpha;
        struct Vertex * vertexArray;
    };

Shader class just contains the shader object, compiling and linking sub-routines etc.

In Game Logic class I am actually rendering the object:

void GameLogic::update(float dt)
{
    IRenderer * renderer = g_application->GetRenderer();

    Actor * a = GetActor(id);
    renderer->render(a->model);
}

Please note that even though Actor extends ISceneNode, I haven't started implementing SceneGraph yet. I will do that as soon as I resolve this issue.

Any ideas how to improve this? Related design patterns etc?

Thank you for reading the question.


texts: How can I make a falling down effect in 2D - Birds Eye View

texts:
Currently whilst making my game, I'm not sure how I am going to implement the actual gameplay/environment of it. At first I thought to do a side-on plat-former, where my character falls down the screen, from the side on. However, I think it would be much better gameplay (better gameplay mainly for mobile) to do this falling down in a birds eye view perspective.

What I want is my character to start at some arbitrary point in the world (say the sky) and fall down infinitely. Obviously, I don't actually have to make the character fall down, but I have to make it so that it looks like it is. Now I'm no artist, but how would an artist make art for the scrolling down background? Would he/she have to create sprites for the objects in the environment (i.e. clouds)?

Reference Image (sorry for the quality, and don't judge my lack of art skills):

Now as you can see, my character (the turtle) is in the sky. I eventually want it to go past the clouds and look like it is going closer the ground. Now that I think about it, would it be better for this type of game to not actually transition the setting (i.e. keep one type of setting per game). What I mean is should I just keep the sky so the character never reaches the "bottom".


texts: How can i check/inspect the performance of my network game via Wireshark and specifically the Graphs available in Wireshark,i want to test the performance of my network game. which kind of graphs can be helpful and relevant  and give me the idea of network performance of my game? i m really newbie to networking so i m unable to decide.


texts: Update Project Version, or other Project Settings, from command line

texts:
Is it possible to update UE4 Project Settings from command line?
More specifically I would love to be able to update the following Project Settings attributes from command line using, for instance, RunUAT.bat

Project > Description > Project Version
Platform > Android > Store Version
Platform > Android > Version Display Name
Platform > IOS > Version Info

I have checked the unreal documentation without finding anything, and looked through the documentation for ue4 cli, also without any luck.
I have already tried to read the Config/DefaultEditor.ini file (and other INI files) using various tools, but apparently the INI format used by UE4 is somehow different than what the parsers I have tested accepts. (+-icons for indicating array elements and so on)
Am I missing something obvious? Or is this not normal to do?

Running from Windows, MacOS, or Linux (whichever will work)


texts: What Type of Options should be on the Game Settings Menu?

texts:
I have seen a post about the main menu options here:
UI: Main Menu options for mobile games. What options should be listed? What do users want to see?

But I want to know what kind of options should/need to be available on the settings screen.

I am making a rather simple 2D game for Android, but really I haven't found many aspects that warrant an options button or a check box besides turning the sound and music on/off.  I was thinking graphics settings but then again, how many apps really need graphics settings besides immersive 3D ones?


texts:
I am developing a card game in XNA.

Is there any OnClick event in XNA for objects?

I am trying to make cards move when the player clicks on them. In this project, there is a Sprite class that draws the card, but I am a little stuck because I don't know how to use OnClick events or anything like that.


texts: How can I reduce the performance impact of rendering trees?

texts:
I'm making a low poly stylized kind of game. I have a terrain with some water, and I want lots and lots of trees; I have 10,000 trees mass placed, at the moment. Each tree consists no more than 200 triangles, so they aren't too taxing.

The main problem is, there are lakes, and the lakes are quite large. You can't actually see any trees on the other side of the lake, and that looks really bad, especially when you walk there and trees suddenly appear.

To fix this, I have to increase the tree distance so that you can see a decent amount of trees on the other side of the lake, but that reduces performance to 40-50fps, and there is hardly anything else in the game yet. I'm using a GTX 1080, if that helps.

What can I do to make my game run faster with more trees?


texts:
Should I call glLoadIdentity each time I render or cumulatively add translations? Does the latter option provide any performance advantage?

With glLoadIdentity (pseudo-code)

// in game loop
glLoadIdentity();
glTranslatef(position.x, position.y, position.z);
glDrawArrays(...);

// in input handling code
if (KeyDown(LEFT))
  position.x = position.x - 0.01;

Without glLoadIdentity (pseudo-code)

// in game loop
glTranslatef(change_position.x, ...);
glDrawArrays(...);

// in input handling code
if (KeyDown(LEFT))
  change_position.x = -0.01;


texts:
I'm trying to add unity ads to my game. In my game there are three panels - startgame, ingame and gameover. Once the game starts, only the startgame panel is active and once you tap on the screen, the ingame panel gets actived and startgame panel is deactivated. In the ingame panel I have added a button to show ads (once an ad is ready) so that after watching the ad, user can receive 100 additional points. Here is my admanager script:
string GooglePlay_ID = "123456";
bool test_mode = true;
string myPlacementId = "rewardedVideo";

public Button inGameAdBtn;

void Start()
{
  inGameAdBtn = GetComponent<Button>();
  inGameAdBtn.interactable = Advertisement.IsReady(myPlacementId);
  if (inGameAdBtn) inGameAdBtn.onClick.AddListener(ShowRewardedVideo);

  Advertisement.AddListener(this);
  Advertisement.Initialize(GooglePlay_ID, test_mode);
}

public void ShowRewardedVideo()
{
    Advertisement.Show(myPlacementId);
}

public void OnUnityAdsDidFinish(string placementId, ShowResult showResult)
{

    if (showResult == ShowResult.Finished)
    {
        GameManager.instance.GetPoints();
    }

else if (showResult == ShowResult.Skipped)
    {

    }

    else if (showResult == ShowResult.Failed)
    {
        Debug.LogWarning("The ad did not finish due to an error.");
    }
}

public void OnUnityAdsReady(string placementId)
{
    // If the ready Placement is rewarded, show the ad:
    if (placementId == myPlacementId)
    {
        inGameAdBtn.interactable = true;
    }
}

public void OnUnityAdsDidError(string message)
{
    // Log the error.
}

public void OnUnityAdsDidStart(string placementId)
{
    // Optional actions to take when the end-users triggers an ad.
}

When I hit play, I get an error in the console saying - NullReferenceException: Object reference not set to an instance of an object. When I click on it, it takes to this line of code "inGameAdBtn.interactable = Advertisement.IsReady(myPlacementId);".
I believe this is because once the game starts, the ingame panel is inactive and the admanager script is looking for the inGameAdBtn (which is in the ingame panel). Is there any way to resolve this issue?
EDIT
I have added a screenshot of the game. This is after I hit play, the first panel that is activated is the StartPanel and once I tap on the screen, the next panel will activate (InGamePanel) and the StartPanel will deactivate. The inGameAds button is in the InGamePanel which is currently inactive.


texts: LibGDX - button change image on hover over time

texts:
As we all know, LibGDX has a TextButtonclass which has a TextButtonStyle and ButtonStyle. The style has some parameters:

up - an image which is shown normally as a button background
down - shown when the button is being 'pressed'
over - on hover

My question is:
Is there any way to implement the 'hovering' / changing the background image IN TIME? So for example it takes 2 seconds and it's smooth?

I tried with actions and tween engine, but honestly, I really have no idea how I should implement this. Maybe some alpha operations?

If you have any ideas, I would be grateful :)


texts:
I am trying to setup a viewport using perspective camera. I am trying to render a scene like this
   I read an official blog post about the cameras and found a few tests within gdx test suits. However, I am still kinda confused. I have no idea how to manipulate the test suits nor i have any idea what the code does other than just following the code given in the test.

I have a couple of sub-questions,

was the game in the screenshot rendered with perspective camera or just the grids?
Is it possible to work with Orthographic and Perspective Camera at the same time? so that i can render different elements with different camera?
Is there any detailed and easy to understand guide that explain perspective camera really well? I find libgdx severely lack of documentation regrading these.


texts: Does this constitute as copyright infringement?

texts:
Say there is a card game, and it has cards that arc out, and has certain types of memberships with certain features such as premium members being allowed to chat, or use private game rooms etc. If I, from scratch created a card game (for example, Hearts) that had similar arced cards, and had similar basic and premium memberships, but used all my own, graphics, sound, and theme, would this constitute as copyright infringement? Where is the line drawn for this sort of thing?

Thanks


texts: Damage-calculating formula for turn-based RPG with a twist: I have developed a formula, do you the experts think it will scale up successfully?

texts:
I’m developing a turn-based combat system for an RPG. It’s a little different to your standard RPG though. The idea being, the faster the player solves the problem they are presented with each time it's their turn to attack, the stronger their attack is. I have come up with a very simple formula for this and have gone through examples at different levels to test scalability and it seems OK.
I just wanted to show the experts here and see if anyone could spot any issues with this formula for scalability or anything else I haven’t thought of. I also did some research online but couldn’t see examples of a similar model, though I did find more typical examples of damage calculating formulas.
For the game I am making, the input for the damage done is based on 2 things: there will be 20 seconds to answer a question, so the time taken to answer it is one factor; and, the level of the player. All decimal answers to this formula are rounded up to determine the damage and if you go over the time you miss your attack. The formula looks like this:
Damage = (20 - time taken) x level
Level in this will be counted through decimal points. Here are some examples:
Level 1: we would input 1.1 into the formula
Level 5: 1.5
Level 10: 2
Level 13: 2.3
Level 37: 4.7 ….etc.
Examples
If a player takes 8 seconds to answer the question and is level five, the formula works like this:
(20 - 8) x 1.5 = 18
The character would inflict 18hp damage.
If they were level 10 and answered in 12 seconds:
(20 - 12) x 2 = 16
The character would inflict 12hp damage.
If the player were level 29 and answered in 17 seconds:
(20 - 17) x 3.9 = 11.7 = 12
The character would inflict 12hp damage.
What do you all think? Any feedback is very welcome. Thank you for reading.


texts:
I have two aabbs and I need to know the collision normal of the to help me slide the aabbs across themselves. I have searched google but nothing really came up.

How do I get the collision normal of two aabbs colliding together


texts: In Gamemaker Studio 2 how can I find out in code whether the platform is HTML5 or not?

texts: I want to be able to run or not run code depending on which platform I am building for. Some code should only run for the HTML5 platform. How can I find out whether the platform being run is HTML5 inside my gamemaker events?


texts: EXC_BAD_ACCESS error when box2d joint is destroyed

texts:
When I destroy the weldJoint in the update method (see below) I get an EXC_BAD_ACCESS error pointing to the line

world->DestroyJoint(weldJoint);

in the update method below:

    -(void) update: (ccTime) dt
{

int32 velocityIterations = 8;
int32 positionIterations = 1;

// Instruct the world to perform a single step of simulation. It is
// generally best to keep the time step and iterations fixed.
world->Step(dt, velocityIterations, positionIterations);

// using the iterator pos over the set
std::set<BodyPair *>::iterator pos;

for(pos = bodiesForJoints.begin(); pos != bodiesForJoints.end(); ++pos)
{

    b2WeldJointDef weldJointDef;

    BodyPair *bodyPair = *pos;
    b2Body *bodyA = bodyPair->bodyA;
    b2Body *bodyB = bodyPair->bodyB;

    weldJointDef.Initialize(bodyA, bodyB, bodyA->GetWorldCenter());

    weldJointDef.collideConnected = false;
    weldJoint = (b2WeldJoint*) world->CreateJoint(&weldJointDef);

    // Free the structure we allocated earlier.
    free(bodyPair);

    // Remove the entry from the set.
    bodiesForJoints.erase(pos);
}

for(b2Body *b = world->GetBodyList(); b; b=b->GetNext())    {
    if (b->GetUserData() != NULL)
    {
        CCSprite *mainSprite = (CCSprite*)b->GetUserData();
        if (mainSprite.tag == 1) {
            mainSprite.position = CGPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO);
            CGPoint mainSpritePosition = mainSprite.position;
            if (mainSprite.isMoved) {

                        world->DestroyJoint(weldJoint);

                    }
            }
        }
    }

}

In the HelloWorldLayer.h I set the weldJoint with the assign property. Am I destroying the joint in the wrong way? I would really appreciate any help. Thanks


texts:
I'm working with godot 3.2 to make this screen shake, but my issue is that i don't have a target, like in the example, in the example code, it's a kinematic body that is being followed by the camera, i don't have that, i'm  making a match-three type of game, so i don't use those.
What i tried it's to use the main node, in which the game loop logic is executed but the camera shake didn't work, also tried with another elementsd but it failed beacuse they are mostly HUD elements
and shows an error about global positions.
Also i not sure how to get the board/grid, since it's instantiated by code.
How i can make shake camera without a target or get a similar effect?


texts:
I am new to minecraft modding but i program for a living and it looks quite simple to get around. I have this fantasy and a quick internet search shows im not the only one. For those of you who do not know tibia is an MMORPG first released in 1997. It is a 2d tile based game and i would like to see it in 3D. since it is a tile based game it fits nicely with the minecraft architecture. Tibia is a close sourced game but there is TibiaOT which is developed by the community and the map file format is OTBM (open tibia binary map). This is a set of 15 2D grids where each grid represents a floor or the height of the grid, the file comes with two more files with monster spawns and default item locations like chests.

There is a tibia texture pack for minecraft called "Tibian texture pack", so we got the materials covered.

all in all we have the following: a native tibia map and a minecraft texture pack

people have been building tibia maps manually for years now, it seems stupid because we have a binary file for the real map. what we need is a way to map the OTBM file to a minecraft map. i am looking for tools and any other tips a on how to digest the files into a minecraft map file. an explanation of minecraft map file format would also be very helpful.


texts: Can you access the vertices passed into GLSL as an array?

texts:
So in the vertex shader I receive my vertex data as:

layout(location = 0) in vec3 position; //(x,y,z) coordinates of a vertex
layout(location = 1) in vec3 norm; //a 3D vertex representing the normal to the vertex
layout(location = 2) in vec2 texture_coordinate; // texture coordinates

In particular I would like to access the first 2 fields as if they were arrays (Imagine an SSBO).

The reasoning for this is because I need the mesh information not only to render the mesh itself but also to shade (shadows). An obvious solution is to simply pass the mesh data as well as an SSBO, but this means that now I have passed twice the same information into the GPU once as vertices for rendering and once as mesh data.

I would like to be able to access all the vertex data as if it was an array, is this possible?


texts: Understanding ticksPerSecond and duration with skeletal animations

texts:
That's my first question here so i hope to do all correctly. From various weeks i started surfing the net about Skeletal animation aiming to add a simple animation controller into my small game engine. After following a video tutorial by ThinMatrix, i successfully added skeletal animation into my engine (i used Assimp to load a .dae file from Blender with one animation in it). Once finished all the base stuff i started thinking about how to change animations speed by a factor (like x2 x3 etc...) and here i found some problems. As i think i understand every animation is measured by a duration field (in ticks) that, as i suppose, should be at least something like 25fps (to obtain some kind of smooth animation) times animation's length in seconds. Then for every animation there is also another field called ticksPerSecond that (as the name says) is the amount of ticks in every second.

Into my engine i've a data structure called Animator that contains an array of Animation objects and for each one it has a ticks_per_second and duration array. The following code shows how i took data from assimp.

animator->ticks_per_second[animation_index] = scene->mAnimations[animation_index]->mTicksPerSecond != 0 ?
    scene->mAnimations[animation_index]->mTicksPerSecond : 25.f;
animator->duration[animation_index] = scene->mAnimations[animation_index]->mDuration;

If i print the two variables i get this result:

DEBUG: ticks per sec: 1.000000
DEBUG: total ticks: 0.833333

So here is my question: Why do these variables take on these values?
I am trying to explain it to myself and the idea I found is that if ticks is equal to 1 the animation would go at the same mainloop's frame rate but, at the end, I am not sure about it and I would appreciate your help.


texts:
Is it possible to control the key-frame/sample value or the time based position in the animator? I’ve set a global float that identifies the rotation of an object on its Y axis and I would like the rotation value to equal/manipulate the time or key-frame in an animation – I’ve converted 360 degrees to a float of 10.00. So.. if I rotate this object to ‘5.00 (180 degrees), it would update to the 300th key-frame/sample or 5.00 seconds into the animation and update every frame from the value changes.

It’s basically scrolling though the position of a cross fade by manually changing the value.


texts: Which data structure should be best used to store a pile of tiles from which a player can pick a random tile?


texts:
I'm new to programming, and I finally delved into XNA/MonoGame for wanting to practice coding game logic.

I'd like to know what the difference is between a Position (Vector2) and a Destination Rectangle (Rectangle), when it comes to positioning a sprite.


texts:
I have an image I want to move like it's hovering up and own in a cycle.
For that image I have the Y

float _sMY = 10;

My cycle is this:

if (!_hoveredDown)
{
   _sMY -= 0.1f;
}
else
{
   _sMY += 0.1f;
}

if (_sMY < -10)
   _hoveredDown = true;
else if (_sMY > 10)
   _hoveredDown = false;

But during this cycle, the image stutters in certain positions and debugging told me that _smY goes way to -5.677342E-06.

Why do you think this is happening?

Fix, which won't work:

float hoverSpeed = 0.1f;
hoverSpeed += (float)(GameTime.ElapsedGameTime.TotalSeconds);

if (_hoveredDown)
{
   _sMY += hoverSpeed;
}
else if (!_hoveredDown)
{
   _sMY -= hoverSpeed;
}

if (_sMY < -10)
    _hoveredDown = true;
else if (_sMY > 10)
    _hoveredDown = false;


texts: Can threads be used to run resource consuming methods without -ever- freezing UI?

texts:
Until recently I was sure that running expensive operations in threads can prevent UI freezing, but now I'm not.

Is it not guaranteed that a threaded operation will not hog the main thread's resources? If not, then how can I run a method in a way that it will never ever drain resources from UI thread (until told to)?


texts: Move an object to a point relative to the second camera

texts:
I have two cameras, one for the UI, one for the 3d objects.

The UI camera is just a simple, perspective camera.
The 3d objects camera is rotated by (30,45,0) so it displays things with an isometric view. (It's parent it rotated).

On the UI camera's canvas I have two 2D objects (images or something) with a RectTransform. These are invisible here, but they're marked as X.

What I need to do is to move the 3d object on the X/Y axis. To be super clear, I need to move it towards one of these two X objects (left or right).

For now, the camera is rotated, so it doesn't look like it's moving left/right/up/down, but it's moving to the corners (cause of the camera's rotation).

At the start it looks like:

Now I do a _3dObject.transform.DOMove(leftXObject, 3f); // DOTween lib, doesn't matter

And it moves to:

Because of the angle of the 3d camera.

What to do?!


texts: using #if UNITY_EDITOR && !UNITY_ANDROID greys out the code

texts:
I'm trying to exclude part of my code when building(android) but keeping it while in the editor for testing purposes.

Using #if UNITY_EDITOR only will result in this code getting built, but using  #if UNITY_EDITOR && !UNITY_ANDROID will grey out the code making it unusable in play mode.


texts: How do I perform an xBR or hqx filter in XNA?

texts:
I'd like to render my game scaled up with one of the hqx filters (hq2x, hq3x or hq4x) or an xBR filter in a shader.

How can I do this in XNA 4.0 and SM3?

Side note: this question has been heavily edited to become what it is now.


texts: GameMaker project works fine when targeting Windows but not when targeting HTML5

texts:
As mentionned in the title, my GameMaker project works fine when targeting Windows.

However, when I build it for HTML5, I got those errors in the Chrome developer console:

Destructive Dark.js?VYNZB=1666826811:7 Uncaught TypeError: Cannot read property '_42' of undefined
    at _Qw1._M [as _L] (Destructive Dark.js?VYNZB=1666826811:7)
    at _Qw1._a4 (Destructive Dark.js?VYNZB=1666826811:1490)
    at _a72._a4 (Destructive Dark.js?VYNZB=1666826811:1380)
    at _lK1 (Destructive Dark.js?VYNZB=1666826811:1155)
    at _9v2 (Destructive Dark.js?VYNZB=1666826811:1742)
    at _Mu2 (Destructive Dark.js?VYNZB=1666826811:1748)
    at _Ju2 (Destructive Dark.js?VYNZB=1666826811:1733)

I suppose this error is not really useful since it seems to come from the obfuscated Javascript... However, I noticed that this error appears on the "Left mouse button released" event on one of my object. The code associated with this event is the following:

/// Select the square or switch its place with the current selected square

game_manager = instance_find(obj_game_manager, 1);

if (game_manager.lock_timer == 0) {
    if (game_manager.selected_square == noone) {
        game_manager.selected_square = self;
        inst = instance_create(x, y, obj_selection);
        inst.depth = -100;
        inst.image_alpha = 0.6;
    }
    else if (game_manager.selected_square == self) {
        game_manager.selected_square = noone;

        with (obj_selection) {
            instance_destroy();
        }
    }
    else {
        // Lock interactions
        game_manager.lock_timer = 2;

        // Switch the array cells
        var x_temp = game_manager.selected_square.x_grid;
        var y_temp = game_manager.selected_square.y_grid;
        var color_temp = game_manager.selected_square.color;

        game_manager.grid_array[x_temp, y_temp] = color;
        game_manager.grid_array[x_grid, y_grid] = color_temp;

        game_manager.selected_square = noone;

        with (obj_selection) {
            instance_destroy();
        }

        with (game_manager) {
            event_perform(ev_alarm, 0);
        }
    }
}

Not much info sorry, but I have no ideas where this error came from.


texts:
I am trying to combine two cameras together: Background camera, Foreground camera.

I created 3 cameras in my project, 2 for the background and foreground and one for the foreground depth.

I then created a simple shader that combine the first two cameras (they render to render texture as well as the foreground depth), the problem I am having is that because the depth buffer is too pixelated the result looks funny and you clearly see the lines around the foreground (players in my case).

I created a depth camera with these properties:

Notice the Output Texture, I have set the Render texture to:

This is the result depth texture (zoomed so you can see the pixels):

Any idea how I can create that effect maybe using something different then the depth buffer? or can I improve the depth quality? what can I do to reach a good final result?


texts:
I want to check in an shape, wether an point is in it or not.
The shape is descriped with one Array of float vectors.
The vectors are added in clock direction.
The first I can check very easy, the second too, but the third is more difficult.
How I can calculate this ? How this category is in math named, so that I can google ?


texts: MCS character mouth open - is this mo cap animation problem?

texts:
I have MCS Female Character where I can assigned Mocap to my character. I have downloaded mixamo animation and assigned this to the character but the problem is, the character mouth remains open. I am not 3d artist or animation guy, so here are my question.

How can I solve mouth open problem in unity?
What is the reason that mouth is open? Either mocap data has open the mouth or what else problem?


texts:
I want to create something similar to this using farsser and Kinect:
https://vimeo.com/33500649
This is my implementation until now:
http://www.youtube.com/watch?v=GlIvJRhco4U
I have the outline vertices and the triangulation of the user. And following the Texture to Polygonmsample i used this line to create the shape, where farseerObject is a list of vertices of the triangles:
_compound = BodyFactory.CreateCompoundPolygon(World, farseerObject, 1f, BodyType.Dynamic);
But I have to update the body each frame (like 30 fps) and this is very slow. I get just 2 or 3 fps.
There's another (faster) way to create the Body from a list of triangles or the contour vertices?
How do you think they do this on Box2D?
Update:
After some testings i used EdgeShapes for the user contour (without triangulation) and i update the vertices for that edges in the fixtures every frame, now all is faster.
((EdgeShape)(farseerBody.FixtureList[i].Shape)).Vertex1 = new Vector2(farseerVertices[i].X, farseerVertices[i].Y);

But the collisions does not work!
My approach is incorrect?


texts: Is it possible to retrieve shader function names associated with a technique pass using the DirectX Effect API?

texts:
For example, given the pass

pass p0
{
    SetVertexShader(CompileShader(vs_4_0, VSFunction()))
    SetPixelShader(CompileShader(ps_4_0, PSFunction()))
}

Ss it possible to retrieve the names VSFunction and PSFunction? It doesn't look like any of the associated shader descriptors actually contain the name of the entry point.


texts: LibGDX getYpercent of a child inside scrollpane

texts:
So I have this scrollpane with a bunch of labels alfabetic organized, its quite anoying scrolling all the way down to select a label starting with Z letter

So I put the whole alfabet in the right of the screen and my goal is that when users touch the letter 'X' it scrolls all the way to the names starting with 'X'

So I hard coded it like this...

if(letter.equalsIgnoreCase("a"))      setSPy(0);
else if(letter.equalsIgnoreCase("b")) setSPy(0.112212256f);
else if(letter.equalsIgnoreCase("c")) setSPy(0.21482526f);
else if(letter.equalsIgnoreCase("d")) setSPy(0.32874277f);
//etc...
private void setSPy(float percent) {
    scrollPane.setScrollPercentY(percent);
}

It works, but 2 problems:

it looks ugly and I refuse update it every time I decide to add another label.

Then since I could not find a function that tells me the percentY of the item I did this:

private void scrollToLetter(String letter) {
     //loop tru items inside scrollpane
    for (int i = 0; i < spItems.size; i++) {
        BrandSelectorItem  item = spItems.get(i);

        if(item.getString().substring(0, 1).equals(letter)){
            int number = i+1;
            //This gets the posY axis-Y starting on top
            float posY = (number*item.getHeight())- item.getHeight();
            float percentY = posY/(spItems.size*item.getHeight());

            scrollPane.setScrollPercentY(percentY);
            break;
        }
    }
 }

I thought this was going work, but if I hover the "A" works fine, go to 0%, if I hover the "B" its off by little bit, "C" more off, "D" more more off and etc..

seems like something about scrollpane coordinates that i do not understand.

Thank you!

Solution:

 private void scrollToLetter(String letter) {
     //loop tru items inside scrollpane
    for (int i = 0; i < spItems.size; i++) {
        //This is the label
        BrandSelectorItem  item = spItems.get(i);
        if(item.getString().substring(0, 1).equals(letter)){
            int itemNumber = i+1;
            //This gets the posY axis-Y starting on top
            float posY = (itemNumber*item.getHeight())- item.getHeight();
            scrollPane.setScrollY(posY);
            break;
        }
    }
 }


texts: Collision detection with non-rectangular images

texts:
I'm creating a game and I need to detect collisions between a character and some parts of the environment. Since my character's frames are taken from a sprite sheet with a transparent background, I'm wondering how I should go about detecting collisions between a wall and my character only if the colliding parts are non-transparent in both images.

I thought about checking only if part of the rectangle the character is in touches the rectangle a tile is in and comparing the alpha channels, but then I have another choice to make... Either I test every single pixel against every single pixel in the other image and if one is true, I detect a collision. That would be terribly ineficient.

The other option would be to keep a x,y position of the leftmost, rightmost, etc. non-transparent pixel of each image and compare those instead. The problem with this one might be that, for instance, the character's hand could be above a tile (so it would be in a transparent zone of the tile) but a pixel that is not the rightmost could touch part of the tile without being detected. Another problem would be that in different frames, the rightmost, leftmost, etc. pixels might not be at the same position.

Should I not bother with that and just check the collisions on the rectangles? It would be simpler, but I'm afraid people.will feel that there are collisions sometimes that shouldn't happen.


texts: Nested Entities in Entity Component Systems (ECS)

texts:
Say I have an entity that has these components:

-Transformation

-Visual

Imagine that these components can nest:

If I have a parent transformation component, a child transformation relies on the parent transformation data.

Similarly, if I have a parent visual component, a child visual component may rely on the parent visual data.

Suppose we have two entities that both have a visual and transformation component. Say we have a concept of composing the entities themselves: which requires us to compose their respective Transformation and Visual components in some way.

Where would that logic go? Using pure ECS, these entities' components would be registered to their respective systems, but not amongst each other- Would I have to create a new system that houses the logic for composing entities that have certain sets of components?

One option would be to create a component along the lines of
VisualTransformation which gets added to an entity in addition to the visual and transformation components; This new component would have the transformation and visual components dependency injected into it:

The entity would then have

-Transformation

-Visual

-VisualTransformation

And then a system that operates on VisualTransformation components would have its own composition logic for entities that have both, and delegate some logic to the respective systems that compose them separately (TransformationSystem and VisualSystem).

This starts to exhibit a code smell reminiscent of extending deep inheritance hierarchies; clearly not an extendible solution.

My other idea is then to create a generic component-bag system that works on entities with certain component sets, and register those entities with the correct bag of components to a system. Is this the right approach? How would this be done?


texts: Approach on how to split game assets into split archives

texts:
With a custom binary file format for archives that is structured similiar to Valve's VPK files I have a Game.index.gcf which holds information about all files and where exactly they are stored. I can split up and say, that the /Assets/Maps and /Assets/Scripts folders should be stored in Game.000.gcf while the bigger /Assets/Music folder could be split up into Game.001.gcf and Game.002.gcf. This should boost performance but only if done right. Moreover with updates I could say, just update this particular split archive and not the entire archive (when storing everything in one really huge a file).

As of yet, I don't know how to write such an adaptive algorithm which automatically decides the best way to split all archives and files. What aspects should I keep in mind and what should I be aware of when creating these? Do you have any suggestions?


texts: Unreal C++ Detecting new Key Down during current Key Hold

texts:
I am currently working on a combat system and I wanted to be able to have key combos to execute combat moves and such, and I am detecting key input type as well for example, if the key is tapped, or long pressed.

I use this line below to record the time a key is pressed, and time when the same key is released, so I can differentiate whether the key is just a quick tapped or long pressed.

  FPlatformTime::Seconds();

and when the the game detected a key press, it will execute the function below, using a timer and stopped on released.

//Long Press
void ABasePlayerController::StartRepeat(UFunction* FunctionNamesToCall, FKey KeyInput)
{
  //Execute if Timer is still active
  if (IsKeyDown != false && GetWorld()->GetTimerManager().IsTimerActive(RepeatTimerHandle) && WasInputKeyJustPressed(KeyInput))
  {
     CalledFunction.Broadcast(FunctionNamesToCall, KeyInput);
  }
}

The problem is when I wanted to make a key combination, and I stopped this function, whenever a new Key is pressed, the new key will be considered as a Long Pressed as well. My current codes only able to register input types after the key is released, and I wanted to be able to make a charging combo as well.

For example when I'm holding a Tab and I tap a new different key, both keys will be considered as a Long Pressed, while the expected result supposed to be Long Pressed Tab key, and the new pressed key is a simple quick tap.

Any ideas? Thanks!


texts: Can not enable IME to capture Chinese characters in SharpDX

texts:
Just found that direct integration of IME is blocked in Windows 8, moving on to TSF now.
  By now, there is lack of Microsoft's Document about TSF, this will be hard.

I am using SharpDX and the RenderForm. However, when I execute the game, IME is disabled and I can only capture English chars.

Hot Keys are not working. I tried using

ImmSetOpenStatus(imeContext, true);

and

this.ImeMode = System.Windows.Forms.ImeMode.On;

but nope, not working, and I tried to disable DirectInput in the game, still can not switch on the IME.

Are there any window message that tells IME to open?
Here is my code of capturing window's message:

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WindowMessage.InputLanguageChange)
            return;
        if (m.Msg == WindowMessage.ImeSetContext && m.WParam.ToInt32() == 1)
        {
            IntPtr imeContext = ImmGetContext(this.Handle);
            if (context == IntPtr.Zero)
                context = imeContext;
            ImmSetOpenStatus(imeContext, true);
            ImmAssociateContext(this.Handle, context);
        }
        base.WndProc(ref m);

        switch (m.Msg)
        {
            case (int)WindowMessages.WM_GETDLGCODE:
                if (Is32Bit)
                {
                    int returnCode = m.Result.ToInt32();
                    returnCode |= (DLGC_WANTALLKEYS | DLGC_WANTCHARS);
                    m.Result = new IntPtr(returnCode);
                }
                else
                {
                    long returnCode = m.Result.ToInt64();
                    returnCode |= (DLGC_WANTALLKEYS | DLGC_WANTCHARS);
                    m.Result = new IntPtr(returnCode);
                }
                break;
            case (int)WindowMessages.WM_CHAR:
                int charInt = m.WParam.ToInt32();
                InputChar InputChar = new InputChar();
                InputChar.IsUsed = false;
                InputChar.Chars = (char)charInt;
                    switch (charInt)
                    {
                        case 8:
                            InputChar.CharacterType = charType.BackSpace;
                            break;
                        case 9:
                            InputChar.CharacterType = charType.Tab;
                            break;
                        case 13:
                            InputChar.CharacterType = charType.Enter;
                            break;
                        case 27:
                            InputChar.CharacterType = charType.Esc;
                            break;
                        default:
                            InputChar.CharacterType = charType.Char;
                            break;
                    }
                    if (OnInput != null)
                    {
                        InputChars.Add(InputChar);
                        OnInput(this, InputString);
                    }
                break;
        }
    }

Hope you guys can help me, really don't know what to do now.


texts: Animation shown as playing in the animator, but it doesn't show in game (Unity 2D/C#)

texts:
I have an Animator on this gameObject. The Animator hits one state when some parameters are true, it can transition to this state from any state. The parameters are fine because i can see in the animator that the state is getting hit when i want it to. The blue progress bar is showing, but the animation doesn't play on the screen in the game, it just shows the state before it.
I have tried changing exit time, apply root motion, update mode, static batching.
Nothing works
Help pls internet gods

As requested here are some images, first this is my animator and the transition that is set up: (I have also tried this with the same transition but from flies buzzing directly and the same behaviour happens)

Also here is what the animation state looks like and the preview of it, showing that it works in scene (just not in game)

And here's how it behaves in game, as you can see the blue bar is progressing (and this is going into the state at the correct time, after dealing 2 damage to the fly, isDead gets set to true). However the only animation that plays is the fly buzzing one.

Here's my code:

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

public class FlyCombatAndFollow : MonoBehaviour
{
    [Space]
    [Header("References:")]
    public Animator animator;
    public GameObject fly;

    [Space]
    [Header("Character attributes:")]
    public int maxHealth = 2;
    int currentHealth;

    // Start is called before the first frame update
    void Start()
    {
        currentHealth = maxHealth;
    }
    public void TakeDamage(int damage)
    {
        currentHealth -= damage;
        //Play hurt animation
        animator.SetTrigger("IsHit");
        animator.SetInteger("Hit", damage);

        if (currentHealth <= 0)
        {
            StartCoroutine(Die());
        }
    }
    public IEnumerator Die()
    {
        Debug.Log("Fly died");
        //play death animation
        animator.SetBool("IsDead", true);
        yield return new WaitForSeconds(1.0f);
        //Disable fly
        Destroy(fly);
    }
}


texts: How can I cleanly separate the UI from the game logic in my Cocos2d game?

texts:
I've been working on a little game for the last few months, trying to approach it as a software engineer and employ best patterns and practices in my coding. I have gotten to the point where I have to distinct elements in my game.

The Game Logic: aka business logic. Its the meat of the game rules. It contains all information about game objects (such as Character, Weapon, and Item class definitions). It contains the game world as far as rules are required; mainly so Characters are aware of the world they are in, and who else is in it. It contains a chunk of logic use to determine how Fighting is resolved between Characters, as we as other game actions requiring rules. It contains my AI implementations. So in reality it's a combination of Class definitions and Service logic.

As it stands, the Game Logic can actually play out a game without any interface. All I need to do is create a World, add some Characters to it, assign some AI's to them, then in a loop tell their AIs to run. The result of each AIs action is reflected in the states of the Characters (eg, if damaged, health is reduced), and a summary of what happened is returned by the execution (which is intended for the UI to make sense of what happened).
The Game UI: which is using Cocos2d-xna for WP7. It contains definitions of all the different animations. It takes in inputs and sends the to the Game Logic, and renders its results.

As it stands, as well as all UI components for a Character (textures, sprites, animations) a UI Character also contains a Begin method which executes a Cocos2d Sequence (ccSequence) to do two things 1) Execute AI and render result for this Character 2) Re-Execute the sequence (essentially its own call back loop for executing actions).

The problem I keep running into is, the more I try to keep these two layers separate, the more they need to come together. E.g., my UI Character which is used to render what the Game Logic character is doing, so it needs a reference to the Character object from Game Logic. When this Character's AI attacks someone in the Game Logic world, the UI needs to know what happened. This works fine for rendering its own Animations based of its results, but to know what to do for other Characters affected by this action is difficult as I dont have reference to them. At the moment I do this by queuing up Pending Animations in the other character's Game Logic Character and render it when that character next executes, but this is anti SoC (Separation of Concerns) as it now contains something specific for the UI to focus on.

I don't want the two projects to merge into one where a Game Logic Character contains all things UI as well, such as animations and actions. Is there a nice clean way that is used for this separation? Ideally something that works nicely with Cocos2d's Action pattern?


texts: Unity Ads. Is the Ad.show placementId parameter used anymore?

texts:
I started a project a long time ago with the Unity ad api v1, now that they have moved onto Advert api v2 i'm wondering if they still use the placementId parameter.

I'm only wondering this because they used to support video and image based Ads. As far as I know they only do video now. They used to have examples similar to this:

Advertisement.Show("rewardedVideo", options);

Which specified which of the supported advert types you want, rewardedVideo for video and rewardedImage (or something similar) for images.

With the loss of images and the integration guide (behind the login screen) having been changed does the palcementId parameter still matter since I noticed that you can pass in only the callback stuff?


texts: Building a chunk w/ blocks: making ramps. How to detect if blocks are making "stairs" (like in a mountain) and should be turned into ramps?

texts:
My question is quite simple, but the answer may be not.

I am studying and making a voxel engine, generating block vertices around its center position with TriangleList primitive at C#/XNA.

The problem is that I don't want that my game make those ugly "stairs" of cubes in mountains or hills. I want that the cube turns into a ramp when needed (when it has no connection with blocks at some sides, for example: no connection at top and east, then it turns into a ramp from west top to east bottom).

Another example that already exists may be found at SimCity 2000 maps. Edges become ramps, in many types, depending of how the squares of the terrain grid are modeled. Even corners between two directions of ramps become a new type of ramp, with two triangles.

I don't know how to detect that in a easy way, like, do I have to test each side and then check between the sides detected for selecting the type of ramp to create?... Or what should I test first, and then select the way of placing the vertices?

Thanks for any answer. And sorry for my English, if something is wrong.


texts:
Tutorials wrote Sys.getTimerResolution() for LWJGL time method.

public long getTime() {
   return (Sys.getTime() * 1000) / Sys.getTimerResolution();
}

I thought Sys.getTimerResolution() is just 1000. So the shorter way gives same value.

// shorter way
public long getTime() {
   reutrn Sys.getTime();
}

Is Sys.getTimerResolution() value always 1000?


texts: Cube map faster than 6 2D textures? - shadow mapping

texts:
I've managed to implement shadow mapping to a scene. However, I had problems using a cube map so I eventually gave it up and used 6 2D texture maps instead. To make this work with 6 2D maps, during the rendering process I have to identify in which texture of the 6 each fragment belongs. I'm afraid this could be dropping my frames significantly.

I'm not gonna go into many details for now. I will upload the relevant code if necessary. My main concern is if this method makes my program slower.Will my fps increase using a cube map?


texts:
I have, in MonoGame, a project for which I require the game to not use the full screen depending on the resolution. The game elements etc all behave as they should (So they bounce off for example between 25% and 75% of the screen, instead of the edges). Yet I'm trying to draw a background between these two constraints, and it doesn't work.

To draw the background I am using the following code

spriteBatch.Draw(Background, new Rectangle(leftEdge,0,rightEdge,top),Color.White);

Yet when running the game, the image starts at "LeftEdge" but goes beyond "rightEdge". How would I go about scaling the image appropriately in this scenario?


texts:
I want to be able to have a big tilemap (e.g. like Terraria, or an infinite procedural generated one), with only a handful of tiles on my screen.

This means that I have a texture atlas (i.e. spritesheet) which contains the textures for the tiles. For the sake of simplicity, let's assume that I have a huge internal 2D array, containing the tileIDs and a lookup tablel/hasmap for the UV coords for each tile type. All the tiles have the same dimension (the texture AND the onscreen tiles). I know a couple of methods to render such a 2D grid/tilemap, but I don't know which one of them is a solid foundation for a game which heavily relies on modifiable tiles.

Additionally, I want to be able to dynamically change the tilesize (i.e. zooming in/out), modifying the tiles/tilemap (e.g. destroying, building) and fast loading (fast paced player actions).

Using a single draw call. I create a VBO with all the quads to fill the screen (multiple overlapping vertices, because each quad needs a different texture) and have a persistent buffer to modify the texture buffer object. As soon as the camera moves, I update the UV coordinates in the TBO.
I can use attributeless rendering. I make a glDrawArrays call on an empty VAO, and use gl_VertexID%6 and gl_VertexID/6 to get the vertex ID and the tileID. To map the UV coordinates, I pass a TBO, which is updated at every camera move. I don't know how expensive this calculation is for the GPU.
Hoping on the train of attributeless rendering, I can pass a uniform or create a const array to hold the UV offsets of every tile type, and only pass at every camera move the updated tile type IDs to the shader (with a uniform?). With gl_VertexID/6 I know which index holds the current tiles type information, and then with this type, I can access my constant array to lookup the UV coordinates.
Either using triangle strips, or indices to reduce the vertex count, and use provoking vertices to correctly map the UV coordinates (this can be combined with attributeless rendering). The vertices are all fixed for the window, and only the textures change. Here, once again, I have to map the TBO to a persistent buffer and update it at every camera move.
Every tile gets a separate draw call (thus a separate VBO, IBO, TBO) and I can therefore render only the tiles which are seen by the camera. Because of the low amount of onscreen tiles, those separate draw calls shouldn't be too expensive.
I put the whole map at the start of the game in the VAO and TBO, and modify the indices buffer, to only render the onscreen tiles (the IBO only holds enough indices to render the onscreen quads). My problem here is that I send too much data to the GPU every frame, and I have a really bad cache locality, because the information has to be accessed from different parts of the buffer objects.
There might also be a way to use a geometric shader, although I have never used one.

My concrete question is, is there a "state of the art" method to render big tilemaps, is any of my above mentioned ideas a good solution, and, does it really matter which option I use?

Thank you!


texts: Why don't C++ Game Developers use the boost library?

texts:
So if you spend any time viewing / answering questions over on Stack Overflow under the C++ tag, you will quickly notice that just about everybody uses the boost library; some would even say that if you aren't using it, you're not writing "real' C++ (I disagree, but that's not the point).

But then there is the game industry, which is well known for using C++ and not using boost.  I can't help but wonder why that is.  I don't care to use boost because I write games (now) as a hobby, and part of that hobby is implementing what I need when I am able to and using off-the-shelf libraries when I can't.  But that is just me.

Why don't game developers, in general, use the boost library?  Is it performance or memory concerns?  Style?  Something Else?

I was about to ask this on stack overflow, but I figured the question is better asked here.

EDIT :

I realize I can't speak for all game programmers and I haven't seen all game projects, so I can't say game developers never use boost; this is simply my experience.

Allow me to edit my question to also ask, if you do use boost, why did you choose to use it?


texts: Why do I get an error about being unable to change rasterizer states in this code?

texts:
I'm trying to toggle between wireframe and full mode while drawing a 3d model. So far I have this

 rs = new RasterizerState();

In my update method:

  if (state.IsKeyDown(Keys.V))
        {
            rs.FillMode = FillMode.WireFrame;
        }

        if (state.IsKeyDown(Keys.C))
        {
            rs.FillMode = FillMode.Solid;
        }

and in my draw method:

  GraphicsDevice.RasterizerState = rs;

But I get the error:

 Cannot change read-only RasterizerState. State objects become read-only the first time they are bound to a GraphicsDevice. To change property values, create a new RasterizerState instance.

What am I doing wrong here?


texts: In SDL2 what is the fastest / most efficient way to draw pixels onto the screen? Using SDL_RenderDrawPoint or SDL_RenderCopy with a Texture?

texts:
I want to add pixel splatters and particle effects to a game. For this my options were to have a bunch of pre-made animations in the form of textures, OR create a particle engine.

For the particle engine approach, my options as far as I know are to create pixels and render them either using:

SDL_RenderDrawPoint(s) (Using SDL_SetRenderDrawColor)
SDL_RenderCopy (Using Textures with SDL_SetTextureColorMod)

I'm not sure what's a better approach. #2 is probably easier as I have a whole system built around fast texture rendering (not necessarily faster than 1., but seemingly easier to implement with my current system.) #1 seems ideal because it's in the SDL2 library for a reason I'd think, but really I'm unsure which approach I should go with.


texts:
Say you have two objects in a vacuum with no forces acting on them.
The objects may or may not be moving.
Object A's acceleration is not equal in all directions, and object B may change its acceleration over time.
Knowns:
A position
A velocity
A acceleration
A max acceleration for a given vector
B position
B velocity
B acceleration

So for object A, how can I iteratively calculate the the direction of thrust needed to go to B's position and match B's velocity in the smallest amount of time?


texts: Essential skills to be a games programmer

texts:
I recently posted a question about the kinds of things to expect in game programming tests for games companies as I found myself unprepared for some of the topics. There are two things I can say about myself, and I think these probably apply to a lot of people. 1. I went and did a course at university that, although got me interested in programming, was poorly taught and didn't prepare me to really get any sort of decent job.. and 2. I'm still completely determined to get into the games industry.

I'm currently working at a little start-up, but I know that if I want to make the games I like playing I have to keep cramming!

My question is this: Can some of you professionals / graduates from better courses enlighten me as to the things I need to learn to become a really solid candidate for programming jobs.

I'm talking about things like Big O Notation, calculating complex recursion, linked lists , matrix / quaternion maths etc.

The first in that list I was not taught, and the second I didn't even know was something I might ever be expected to do. A list of all these and more, plus a good place to start learning about them would be extremely useful, I think to others as well as myself.

(re-tag and re-word this question as appropriate)


texts: Multiple traversal of a component-based hierarchy

texts:
Let's say a game use a component-based hierarchy to store all of its entities.
So it can have objects, characters, lights organized in some kind of tree.

When rendering the game, it needs to first render objects, then lights. So it needs to first traverse the hierarchy and render all the objects it finds, then traverse a second time to render all the lights it finds.
What is a better way to do this? If the hierarchy has thousands of entities, it could be slow to traverse twice the tree.

I thought about having two lists, one containing objects to render, the second one being lights. Each time the user adds an entity to the hierarchy, it adds it to the corresponding list. This way, the game only have to traverse the object list then the light list, without traversing useless entities.

What is the best option?


texts:
So I want to make automatic ragdoll generation system for all my enemies in my game, the assets are already made and have been paid for a while ago so I can't really ask the artist to change anything or generate some extra info, they are a variety of models (humans, robots, beasts) with a hard limit of 32 bones. Each bone is labelled and there is only a single mesh provided, which is skinned and ready to go.

I am trying to understand how an automated system can generate ragdolls from this. So far my idea involves convex decomposition (v-hacd?) to split up the mesh into small convex hulls and attach them using hinge and cone twist constrains (in bullet physics).

The idea sounds simple in my head but actually there are so many questions such as, how to do it automatically? how to make each convex hull be attached to a bone correctly? how to join the convex hulls with constraints in the correct place? the ragdoll would be generated from the bind pose, but how to transform the ragdoll so that it is perfectly aligned with the skeleton after its death animation?

I would very much appreciate some guidance on this, thanks.


texts: Why does my vertex shader produce no output until I add some arbitrary value to the position attribute?

texts:
I want to draw a textured quad but there is nothing drawn and the setup should be right.
This is my vertex shader:

#version 330

in vec2 position;
in vec2 texel;

out vec2 texCoord;

void main() {
    texCoord = texel;
    gl_Position = vec4(position, 0.0, 1.0);
}

This code is producing no output on screen. Now comes the crazy stuff. If I add the following,

#version 330

in vec2 position;
in vec2 texel;
in vec2 foo;

out vec2 texCoord;

void main() {
    texCoord = texel;
    gl_Position = vec4(position + foo, 0.0, 1.0);
}

everything is as it should be.

I am pretty sure that my setup is correct. I have checked the values of the vertex attributes by passing them as texCoord instead of the uv coordinates, and assigning them to my fragment color output in the fragment shader. In both cases this produces the expected color gradient. The extra uninitialized attribute foo must be zero, because its rendered as the vertex color.

So the thing is, nothing is drawn unless I add an vertex attribute to position. It doesn't matter if I add texel or the mysterious, uninitialized vertex attribute. The output is the same.

update:

glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), sizeof(glm::vec2);

This is my vertex struct:

struct Vertex {
    glm::vec3 pos;
    glm::vec2 tex;
    glm::vec3 normal;
    Vertex(const glm::vec3& _pos,const glm::vec2& _tex,const glm::vec3& _normal):
    pos(_pos),tex(_tex),normal(_normal){}
    Vertex(const Vertex&)=default;
    Vertex& operator=(const Vertex&)=default;
};

The buffer is correct. I have mapped the vertex buffer and put it on the standard output.
All numbers are correct.


texts:
hey everyone any ideas why im getting a 400 error? im trying to post a json to a subscription list. doing that through postman works just fine!
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class testing : MonoBehaviour
{
    //public InputField field;
    [SerializeField]
    private Email _email = new Email();
    private string URL = "https://a.klaviyo.com/api/v2/list/YeXzKp/members?api_key=pk_ec448e1bdab7504c143466ca5eeabc5e95&profiles=[]";
    IEnumerator SaveIntoJson()
    {
        string data = JsonUtility.ToJson(_email);
        System.IO.File.WriteAllText(Application.persistentDataPath + "Data.json", data);

        //UnityWebRequest www = UnityWebRequest.Post("URL", data);
        //www.SetRequestHeader("Content-type", "application/json");
        UnityWebRequest request = UnityWebRequest.Put(URL, data);
        request.SetRequestHeader("Content-Type", "application/json");
        yield return request.SendWebRequest();
        //yield return www.SendWebRequest();

        if (request.isNetworkError || request.isHttpError)
        {
            Debug.Log(request.error);
        }
        else
        {
            Debug.Log("Form upload complete!");
        }
        Debug.Log(data);
    }

    public void SaveData()
    {
        StartCoroutine(SaveIntoJson());
    }
}
[System.Serializable]
public class Email
{
    public List<Profiles> profiles = new List<Profiles>();
}

[System.Serializable]
public class Profiles
{
    public string email;
}


texts:
I'm a beginner in libgdx, and I'm trying to create my first game. It's pretty simple, circles are falling from the top and sides of the screen, and the user needs to "blow" them before they touch the ground.
It is a single screen game, where the world isn't moving, like Tetris.

My problem is that I'm having bad time understanding what viewports should I use, and when.

So, what viewport should I use for this type of game, without generating black bars or stretching the graphics? Will it be possible to check the screen width and height, and act accordingly? let's say the screen is 400x800, can I save it in the code and just spawn the circles out of the screen?

Again, I don't want my graphics to be stretched, since the circles will look weird.

Thanks.


texts: Why the skyline continues to stay on the same place and how to change this?

texts:
I started my first Unity3D project and in this game main hero should be able to fly up passing clouds and then reaching open space but i faced with the problem. No matter how long and fast i am flying after takeoff the skyline continues to stay on the same place. Currently i'm going to rotate the main hero so that skyline would go down. But maybe someone can suggest me more common and better way to achieve the effect of leaving the Earth?

I think it would be bad idea to post all my code here because there is a lot of code that does not relate to the topic. But i will try to explain what i'm doing now and i will show you short piece of code. I have global parent object and a main hero is added as a child to it. Then when as main hero moving up relative to the global object i start to rotate this global object around z-axis so that gradually the main hero is looking to the sky.

And for skyline i'm using procedural skybox.

I hope this piece of code will explain better of what i'm doing now:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class PlayerController : MonoBehaviour
{
    float gravity;

    GameObject global;//main hero’s parent

    Vector3 startHeroLocalPos;//start hero position relative to the global object

    public float degreesPerUnit = 1.0f;//global object will rotate by this amount of degrees after the player has moved up by one unit

void Start ()
{
    global = GameObject.FindGameObjectWithTag ("GlobalObject");
    startHeroLocalPos = transform.localPosition;
}

void Update ()
{

    float curAngle = (transform.localPosition.y - startHeroLocalPos.y)*degreesPerUnit;
    global.transform.rotation = Quaternion.AngleAxis(curAngle, Vector3.back);

}
}


texts: How will the velocities of two moving objects change once they collide?

texts:
I'm making a small game where things can fly around and collide. Things like boxes and so on. For each object, I have an array of all forces acting upon it, I have it's mass, it's position and it's velocity in both directions (a 2D vector). I know how to detect collision between them, but I just don't know how to react.

I used to calculate their orientation towards each other, it they were on top one another, I would just negate their y speed (v.y = -v.y), and if they were next to each other on the x axis I would negate their x speed (v.x = -v.x).

Now, this isn't very realistic, so, how do I do it? All objects are rectangles represented by [x, y, w, h] vectors.

Objects can't rotate.


texts: Sprite Animations in XAML for Windows Phone 8

texts:
I'm developing a 2D game for windows phone. It will feature rather simple 2D graphics and animations. I can get most things done using XAML an storyboards for animations. The performance is fine as long as the images are cached and I don't use standard user-controls (doesn't seem to work well with animations) and stick to using only canvases and images. I really like how simple it is to create basic animations using storyboards.

However, I'm not sure how far XAML and storyboards will get me. Specifically, I have no idea to do sprite-animations. Is there a way to do sprite animations in XAML?

Is it a bad idea to try create a 2D game in XAML?


texts: 2D Collision: Check before or check after?

texts:
I'm using velocity to move my character, I just add/subtract 0.4f and then update the players position in the update loop.

I was wondering, when would be the best place to check for collision? Do I go ahead move the player, and then if I colliding push him out of the wall until there's no collision? Or do I check collision as soon as the key is pressed, and if there is - somehow find the distance and move the player?

My problem is that my game is tile based, but the world is constantly rotating around the player - I have a function that returns a list of objects of each block that the player is colliding with, and I'm having trouble separating wall collisions with floor collisions


texts: How to implement a hint-system for nearby matches (in a Match-3 puzzle game)?

texts:
Taking Candy Crush as an example:

In a Match-3 game, how would you figure out which nearby tiles are 1 move away from creating a match?

Do you basically have to do it by trial-and-error on every single possible moves (behind-the-scenes) to see which resulting matches it would create?


texts: 2D grid based placement (limited to 1 tile in each direction) in Unity

texts:
I've been trying to get my head around this for hours now, I hope one of you is able to help.

I'm trying to make a small game (2D using sprites) that allows you to place blocks (tiles). That is pretty simple in itself, I use ScreenToWorldPoint and mouse position to place the block (no snapping to grid yet).

Now, what I need to do is ensure that the player places blocks on either side of the block that was just placed, and not just some random place on the screen.

A block is just a 1x1 sprite in this case.

For example. Player placed a single block on the screen:

            can place here
                  |
can place here - [#] - can place here
                  |
            can place here

Player then places another block next to the already placed block:

            can place here
                  |  |
can place here - [#][#] - can place here
                  |  |
            can place here

As you see, there is always room to place 1 block around each block placed (using the word block too much!). This is in 2D space.

So in the end, the player might make this:

                   can place here
                      |  |   |
can place here     - [#] |  [#] - can place here
can place here  - [#][#][#][#][#] - can place here

As you also see here, there is always room for 1 block to be placed around the already placed blocks - obviously not when there's already a block placed next to it.

Hope it makes sense.

I guess what I'm after is just: How would I go about creating a grid around a single game object (2D sprite) - I can then use Ray's to figure out if player has pressed one of the grids around it.

Thanks a lot!

EDIT:

So, I managed to get something working. I made a game object with 4 parents (1x1 sprites: top, right, left, bottom) - clicking on one of these parents, "replaces" (destroys) the object and inserts another tile with 4 parents.

This seems like a really bad implementation, so please suggest alternative ways of doing this.

Screenshot:

Code:

using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour {

    public Transform boatObject;
    public GameObject tile;
    public GameObject boatPlank;

    private Vector2 mousePosition;

    void Start ()
    {
        Vector3 position = new Vector3 (boatObject.transform.position.x, boatObject.transform.position.y, 0);
        GameObject gridTile = Instantiate (tile, position, Quaternion.identity) as GameObject;
        gridTile.transform.SetParent (boatObject.transform);
    }

    void Update ()
    {
        // Mouse button 1
        if (Input.GetMouseButton (0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction);

            if (hit.collider.gameObject.tag == "GridItem")
            {
                Vector3 position = new Vector3 (hit.collider.transform.position.x, hit.collider.transform.position.y, 0);

                GameObject gridTile = Instantiate (tile, position, Quaternion.identity) as GameObject;
                gridTile.GetComponent<SpriteRenderer> ().sortingOrder = 10;
                gridTile.transform.SetParent (boatObject.transform);

                // Destroy the grid item that was clicked
                Destroy (hit.collider.gameObject);

                Debug.Log ("Hit something: " + hit.collider.gameObject.tag);
            }
        }
    }
}


texts: How can I test if an oriented rectangle contains another oriented rectangle?

texts:
I have the following situation:

To detect whether is the red rectangle is inside orange area I use this function:

- (BOOL)isTile:(CGPoint)tile insideCustomAreaMin:(CGPoint)min max:(CGPoint)max {
    if ((tile.x < min.x) ||
        (tile.x > max.x) ||
        (tile.y < min.y) ||
        (tile.y > max.y)) {
        NSLog(@" Object is out of custom area! ");
        return NO;
    }
    return YES;
}

But what if I need to detect whether the red tile is inside of the blue rectangle?
I wrote this function which uses the world position:

- (BOOL)isTileInsidePlayableArea:(CGPoint)tile {

    // get world positions from tiles
    CGPoint rt = [[CoordinateFunctions shared] worldFromTile:ccp(24, 0)];
    CGPoint lb = [[CoordinateFunctions shared] worldFromTile:ccp(24, 48)];
    CGPoint worldTile = [[CoordinateFunctions shared] worldFromTile:tile];

    return [self isTile:worldTile insideCustomAreaMin:ccp(lb.x, lb.y) max:ccp(rt.x, rt.y)];
}

How could I do this without converting to the global position of the tiles?


texts:
I'm currently coding a heavily text-based RPG game which requires you to do deals with characters or suppliers in the game, sometimes the deals are good/bad.

Currently the way I'm doing it is that, given your current XP level, you get a list of suppliers with the offers/prices they give are fixed.

Its okay, but a bit basic -- plus there's no sense of feeling where you're cutting a good deal or not.

I've been thinking of other ways to handle negotiation, the only game I'm aware of that has a deal system is the old Amiga and DS game, Theme Park as seen in this movie clip on Youtube:

Theme Park DS,
http://www.youtube.com/watch?v=vS8i9E8mUmg

Other than this, what would be a good way to display or design a negotiation deal which gives the user a sense of a good/bad deal.

Thanks


texts: Combining rotation (using Quaternion* Quaternion) doesn't work as expected

texts:
I have fragment of code that has to rotate the camera to the direction where my cursor is as below:

float yaw = mouseSensitivity.x * Input.GetAxis("Mouse X");
float pitch = mouseSensitivity.y * -Input.GetAxis("Mouse Y");

Vector3 camRotDir = new Vector3(pitch, yaw, 0);

// this works
Vector3 camRot = mPlayerCamera.transform.rotation.eulerAngles + camRotDir;
mPlayerCamera.transform.rotation = Quaternion.Euler(camRot);

// this doesn't work
//var rotation = Quaternion.Euler(camRotDir);
//mPlayerCamera.transform.rotation =  mPlayerCamera.transform.rotation * rotation;

WithmouseSensitivity being an arbitrary Vector2 value representing mouse's sensitivity respectively on axis X and Y.

The problem is when I convert the current camera's rotation in Quaternion to Euler angle, add the camRotDir to it and then convert the result back to Quaternion, it works properly, the z component in camera's rotation remains unchanged during this process. But when I first convert the camRotDir to Quaternion and add it to camera's current rotation by multiplying them together, I get unexpected behaviour, the z component was somehow changed.

I have no idea why this happens, should Quaterion of (euler_a + euler_b) == (Quaternion of euler_a) * (Quaternion of euler_b) ?

Code run in Unity 2018.3.12f1.


texts: Can I legally use retro video game music in a quiz game?

texts:
I am considering making a video game music quiz game, where you guess the game that the music is taken from. For example from NES and SNES games.

In that regard I was wondering if anyone know of any legal issues this might have. Could I for example limit the music playback to 'X' seconds without any legal repercussions?

Seeing that these are really old games, who actually owns the licenses to the music now? For example for games made by developers that no longer exist?

Also, if I would provide screenshots from the games in question, would that be a legal issue as well?

UPDATE

My thoughts was not to copy gameplay elements from the games, but to create a game consisting of a quiz on music from other games. So the games wont be similar to the games that the music is from at all.

Examples of this type of game:

Can you name the video games from clips of music from their soundtracks?
Sampla - The Video Game Music Quiz
Were you a nineties gamer
NES music quiz

If using the music from other games is a violation, are these games violating the copyright?


texts: Ordering a List doesn´t work. - InvalidOperationException: Operation is not valid due to the current state of the object

texts:
I have this method. It´s for ordering actors and only displaying the ones which are in direct line of sight with the player.

public Actor OrderActorListByDistance(List<Actor> list, Vector2 pos)
{
    return list.FindAll(d => Physics2D.Linecast(d.transform.position, pos, LayerMask.GetMask("Default")).collider == null).OrderBy(i => Vector2.Distance(pos, i.transform.position)).First();
}

But that Method throws that error
InvalidOperationException: Operation is not valid due to the current state of the object

I already made a lot of google research but I couldn´t find any solution.
I would appreciate any suggestion or help. Thanks in advance


texts: Changing JavaScript Player Object based on keypress

texts:
I'm currently working on a basic JavaScript top-down shooter and I've run into a dilemma. I'm trying to implement a basic toggle weapon system however when I press the key it changes the weapon properly but when I press it again to toggle back it doesn't work. I don't think it's an issue with the rendering because the drawing function is able to detect the different weapons properly. I feel it's an issue with the actual toggle system code.

Here's the code for the player class

class Player{
    constructor(set){
        this.cx = set.x;
        this.cy = set.y;
        this.r = set.r;
        this.color = set.color;
        this.angle = 0;
        this.toAngle = this.angle;
        this.state = 1;
        this.up = false;
        this.down = false;
        this.right = false;
        this.left = false;

        this.bind();
    }
    bind(){
        const self = this;
        c.addEventListener('mousemove', (e) => {
            self.update(e.clientX, e.clientY);
        });
        window.addEventListener('keydown', (e) => {
            if(e.keyCode == 81){
                if(self.state = 1)
                    self.state = 0;
                if(self.state = 0)
                    self.state = 1;
            }

        });
        //toggle code:
        window.addEventListener('keyup', (e) => {
            if(e.keyCode == 81){
                if(self.state = 1)
                    self.state = 0;
                if(self.state = 0)
                    self.state = 1;
            }

        });
    }
    update(ex, ey){
        this.toAngle = Math.atan2(ey - this.cy, ex - this.cx);
    }
    canv(){
        if(this.angle !== this.toAngle){
            clear();
            ctx.save();

            ctx.translate(this.cx, this.cy);
            ctx.rotate(this.toAngle - this.angle);
            ctx.translate(-this.cx, -this.cy);

            drawPlayer(this.cx, this.cy, this.r, 0, 180, this.color, this.state);

            this.angle = this.toAngle;
        }
    }
}
//drawing code (above this one in the complete file)
function drawCircle(x, y, rad, startAngle, endAngle, color){
    ctx.fillStyle = color;
    ctx.beginPath();
    ctx.arc(x, y, rad, startAngle, endAngle);
    ctx.fill();

}
function drawPlayer(x, y, playerR, playerStartAng, playerEndAng, color, state){
    //left hand start
    if(state == 0){
        ctx.fillStyle = color;
        ctx.beginPath();
        ctx.arc(x - 15, y - 15, 10, 0, 180);
        ctx.fill();

        //border
        ctx.strokewidth = 10;
        ctx.strokeStyle = "brown";
        ctx.stroke();
        //end

        //right hand start
        ctx.beginPath();
        ctx.arc(x + 15, y - 15, 10, 0, 180);
        ctx.fill();

        //border
        ctx.strokewidth = 10;
        ctx.strokeStyle = "brown";
        ctx.stroke();
    }
    if(state == 1){
        //right hand start
        ctx.beginPath();
        ctx.arc(x + 7, y - 21, 10, 0, 180);
        ctx.fill();

        //border
        ctx.strokewidth = 10;
        ctx.strokeStyle = "brown";
        ctx.stroke();

        ctx.fillStyle = color;
        ctx.beginPath();
        ctx.arc(x - 7, y - 17, 10, 0, 180);
        ctx.fill();

        //border
        ctx.strokewidth = 10;
        ctx.strokeStyle = "brown";
        ctx.stroke();

        //gun start
        ctx.fillStyle = "black";
        ctx.beginPath();
        ctx.ellipse(x, y - 20, 3, 25, 0, 0, 2 * Math.PI);
        ctx.fill();

        //gun border
        ctx.strokewidth = 10;
        ctx.strokeStyle = "black";
        ctx.stroke();
        //end

    }

    //draw player
    drawCircle(x, y, playerR, playerStartAng, playerEndAng, color);
}