texts: How to destroy an object, and then instantiate it again later?

texts:
I'm creating an enemy spawner in Unity (2D). At long last, I have something that is quite close to working, but the problem is that I want it to destroy all instances of the enemy when the player can no longer see the spawn area.

That is, the player happens upon the spawn area to find several enemies, but if they move so that the camera can no longer see the spawn area, I want those enemies to be deleted and then a different set of the same enemies to be instantiated when the player (camera) happens upon the spawn area again. But when I attempt this initial delete, the script component no longer has an object to instantiate when the player returns.

Here's a snippet of what I have:

    if (!notOnScreen && spawned == false)
    {
        int numberOfEnemies = Random.Range(1, enemyMax);

        for (int i = 1; i <= numberOfEnemies; i++)
        {

            spawnX = Random.Range(minX + 1, maxX - 1);
            spawnY = Random.Range(minY + 1, maxY - 1);

            Vector3 spawnpoint = new Vector3 (spawnX, spawnY, 0);

            if (enemies.Length == 1) {
                typeOfEnemy = 0;
            }
            else if (enemies.Length > 1) {
                typeOfEnemy = Random.Range(0, enemies.Length);
            }
            else {
                typeOfEnemy = -1;
            }

            Instantiate(enemies[typeOfEnemy], spawnpoint, Quaternion.identity);
        }

        spawned = true;
    }

    if (notOnScreen) {
        spawned = false;

        currentEnemies = GameObject.FindGameObjectsWithTag("Enemy");
        for (int i = 0; i <= currentEnemies.Length; i++) {
            Destroy(currentEnemies[i]);
        }
    }

}

}

I'm sure there's a way to preserve an instance of the enemy so that they can be instantiated again later, but I'm not sure how (sorry--very new to this). I thought about cheating and having one enemy remain at a different z coordinate behind the map (as this is a 2D game), but that doesn't seem like an appropriate solution. Any thoughts or advice?


texts: Using quaternions, how do I determine if an object is upside down from an original rotation?

texts:
Imagine this scenario: An object is laying flat on a horizontal surface, from this an original rotation is determined. Then the object is moved, and at some point flipped upside down and put back down on the table, throughout this a second rotation is continuously updated.

I need a way to determine if the rotation is now pointing downwards compared to the first rotation. This rotation is updated using data from a gyroscope and an accelerometer.


texts: How could I constrain player movement to the surface of a 3D object using Unity?

texts:
I'm trying to create an effect similar to that of Mario Galaxy or Geometry Wars 3 where as the player walks around the "planet" gravity seems to adjust and they don't fall off the edge of the object as they would if the gravity was fixed in a single direction.

(source: gameskinny.com)

I managed to implement something close to what I'm looking for using an approach where the object that should have the gravity attracts other rigid bodies towards it, but by using the built in physics engine for Unity, applying movement with AddForce and the likes, I just couldn't get the movement to feel right. I couldn't get the player to move fast enough without the player starting to fly off the surface of the object and I couldn't find a good balance of applied force and gravity to accommodate for this. My current implementation is an adaptation of what was found here

I feel like the solution would probably still use physics to get the player grounded onto the object if they were to leave the surface, but once the player has been grounded there would be a way to snap the player to the surface and turn off physics and control the player through other means but I'm really not sure.

What kind of approach should I take to snap the player to the surface of objects? Note that the solution should work in 3D space (as opposed to 2D) and should be able to be implemented using the free version of Unity.


texts: Give a message box where yes no question should be answered

texts:
Message boxes, had some time put in creating some for my program, now it all were informative message boxes where an OK button was available and then it closed.

I worked with a canvas that would be enabled when needed and gets disabled on clicking OK.

But now I'm in need of a messagebox that gives an output.
I've tried to do the same and test some stuff with public variables, but my code kept going and didn't wait for the response of the "dialogue box" which results in the changes going through and an unused canvas that opened behind my active screen. (Another canvas is loaded when running the code while the current canvas gets disabled).

Code example:

 cnvCleanup.enabled = true;
 //Here it should wait till i have "answered" on cnvCleanup
 if (CleanUpDone == true)
 {
 usages = 0;
 }
 else
 {
 usages++;

The cnvCleanup will get disabled on the script I wrote for clicking on the OK button.
In case the Not OK button is clicked the bool CleanUpDone should remain false so there the cnv gets disabled.

EDIT: More code.
The CleanUpDoneis public bool CleanUpDone; that gets changed in the cnvCleanup.

int usages;
usages = System.Int32.Parse(AssetList[2]);
if (usages < 10)
 {
 usages++;
 AssetList[2] = usages.ToString();
 }
 else
 {
 cnvCleanup.enabled = true;
 //Here it should wait till i have "answered" on the cnvCleanup
  if (CleanUpDone == true)
  {
  usages = 0;
  AssetList[2] = usages.ToString();
  }
  else
  {
  usages++;
  }
}


texts: How to Initialize OpenGL without 3rd party libraries?

texts:
How can I initialize OpenGl in C++ without any 3rd party library such as glew, freeglut or glut. How would I initialize basic OpenGL requirements, like the context?

I am running Windows 10, and I use Visual Studio.


texts: How do games have low tick rates without causing input lag?

texts:
For example, Minecraft. It updates the gamestate at a rate of only 20/second. And from what I've read, these multiplayer games do the same with their network communication, sending updates at that same speed. So it sounds like the entire game is, internally, running very slow (ignoring the render interpolation to not appear slow).

But what I don't understand is how player input doesn't feel laggy as a result. If player input was only being sampled 20/second, you would feel the delay. But that isn't the case in Minecraft, it is extremely responsive. I assume that means player input is being sampled as fast as possible, at renderer speed. But that means the game is gathering input way faster than it can use it. If it updates the gamestate and talks to the server 20 times in a second, but gathers 200 input samples in that same time, how does it handle that?

Is it perhaps just faking it locally, taking the latest player input and interpolating the renderer with it to appear responsive, even though that input isn't actually being used anywhere in the game?

How does it decide which particular input sample to use when it's comes time to do a gamestate/network update without losing information?

I don't understand how to resolve the conflict between having too many input samples to use, and having input feel too slow.


texts: Why do I get 'Input Assembler: "No mesh available for stage"' error?

texts:
My question is basically why VS2012 tells me that there is no mesh available for the Input Assembler stage because if I click on the DeviceContext next to the Draw call in the Grahics Event List the Input layout is set correctly, the vertex buffers, too, the index buffer is NULL as I do not call DrawIndexed and the primitive topology is set correctly. My background color is drawn using g_pImmediateContext->ClearRenderTargetView( g_pRenderTargetView, Colors::MidnightBlue );. Only the mesh does not appear. What did I miss?

If anything maybe this file which can be opened using VS2012 may help, it is the Graphics Experiment.vsglog file (link no longer available).

Here is my InputLayout struct:

struct VERTEXPOSITIONCOLOR
{
    DirectX::XMFLOAT3   position;
    DirectX::XMFLOAT4   color;

    static D3D11_INPUT_ELEMENT_DESC* GetVertexLayout()
    {
        static D3D11_INPUT_ELEMENT_DESC layout[] =
        {
            { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT,
                0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
            { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT,
                0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
        };
        return layout;
    }

    static UINT GetNumElements(){ return 2; }
};


texts: How to access material properties in metal shader

texts:
I am struggling to find any clear information on how to access the properties of a material inside a metal shader, specifically the diffuse color.

My geometry sources are defined with vertices, normals and texture coordinates:

let sources = [SCNGeometrySource(vertices: vertices),
                   SCNGeometrySource(normals: normals),
                   SCNGeometrySource(textureCoordinates: textureCoordinates)]

let elements = meshIndices.map { SCNGeometryElement(indices: $0, primitiveType: .triangles) }

self.init(sources: sources, elements: elements)

Inside my shader I can access the vertex position and normal using the semantic attributes:

typedef struct {

    float3 position [[ attribute(SCNVertexSemanticPosition) ]];
    float3 normal [[ attribute(SCNVertexSemanticNormal) ]];

} Vertex;

Whilst SCNVertexSemanticColor is a valid attribute, these are not defined on a per vertex basis in my case with the color instead being derived from the diffuse property of the material attached to the shader program.

Is there a way to access the properties of the material attached to my geometry? I would assume that creating a struct and binding it to an input attribute is the correct way forward but I am unsure how these are surfaced to the shader.

typedef struct {

    float3 diffuse [[ materials? ]];//how to reference material.diffuse.contents?

} Material;

I assume that these properties must be available to the shader as everything is rendered as expected if you leave SceneKit to do its own thing. Do I need to bind these properties as uniforms myself or is there a specific argument I can use to access them?


texts: What research areas exist in game programming?

texts:
I'm currently in a group that researches network optimizations and various distributed applications, I'm much more interested in games but more from a research side.Is there a resource that focuses on research topics specific to game development and what are some common areas of research?

Note:I understand game development is made up of various topics that are thoroughly researched, my question is more geared towards the areas that are exclusive to gaming applications or at least only important for gaming.

One example could be maybe a "genetic algorithm approach to character skill progression". Which would focus on building a skill progression that is most optimal to player returns. Etc etc...Random idea, but you get my point. I also mean the technical side of development too, but I didn't want to limit this.


texts: How to make AI detect a target behind a wall, who is only partially exposed?

texts:
I'm making an FPS game where, even when a target's whole body is behind a wall or box, but its finger or foot exposed, the AI should be able to detect it and shoot its finger.

So far the way I've thought of to implement this it so traverse all the targets, find who is near a wall, and compare their position with the corner of wall. But I don't know how to check whether its finger is exposed.

I could use a raycast forward from the AI's gun, but would I need to add a collider to every small body part of every target?


texts: What is a good clock implementation for a multiplayer game?

texts: In cases where players need to send out their times for game state sync, can everyone send out their default timestamp implementation or should something like NTP be used? http://en.wikipedia.org/wiki/Network_Time_Protocol


texts: Node.js Lockstep Multiplayer Architecture

texts:
Background

I'm using the lockstep model for a multiplayer Node.js/Socket.IO game in a client-server architecture. User input (mouse or keypress) is parsed into commands like 'attack' and 'move' on the client, which are sent to the server and scheduled to be executed on a certain tick. This is in contrast to sending state data to clients, which I don't wish to use due to bandwidth issues.

Each tick, the server will send the list of commands on that tick (possibly empty) to each client. The server and all clients will then process the commands and simulate that tick in exactly the same way. With Node.js this is actually quite simple due to possibility of code sharing between server and client. I'll just put the deterministic simulator in the /shared folder which can be run by both server and client. The server simulation is required so that there is an authoritative version of the simulation which clients cannot alter.

Problem

Now, the game has many entity classes, like Unit, Item, Tree etc. Entities are created in the simulator. However, for each class, it has some methods that are shared and some that are client-specific. For instance, the Unit class has addHp method which is shared. It also has methods like getSprite (gets the image of the entity), isVisible (checks if unit can be seen by the client), onDeathInClient (does a bunch of stuff when it dies only on the client like adding announcements) and isMyUnit (quick function to check if the client owns the unit). Up till now, I have been piling all the client functions into the shared Unit class, and adding a this.game.isServer() check when necessary. For instance, when the unit dies, it will call if (!this.game.isServer()) { this.onDeathInClient(); }.

This approach has worked pretty fine so far, in terms of functionality. But as the codebase grew bigger, this style of coding seems a little strange. Firstly, the client code is clearly not shared, and yet is placed under the /shared folder. Secondly, client-specific variables for each entity are also instantiated on the server entity (like unit.sprite) and can run into problems when the server cannot instantiate the variable (it doesn't have Image class like on browsers).

So my question is, is there a better way to organize the client code, or is this a common way of doing things for lockstep multiplayer games? I can think of a possible workaround, but it does have its own problems.

Possible workaround (with problems)

I could use Javascript mixins that are only added when in a browser. Thus, in the /shared/unit.js file in the /shared folder, I would have this code at the end:

if (typeof exports !== 'undefined') module.exports = Unit;
else mixin(Unit, LocalUnit);

Then I would have /client/localunit.js store an object LocalUnit of client-side methods for Unit.

Now, I already have a publish-subscribe system in place for events in the simulator. To remove the this.game.isServer() checks, I could publish entity-specific events whenever I want the client to do something. For instance, I would do this.publish('Death') in /shared/unit.js and do this.subscribe('Death', this.onDeathInClient) in /client/localunit.js. But this would make the simulator's event listeners list on the server and the client different. Now if I want to clear all subscribed events only from the shared simulator, I can't. Of course, it is possible to create two event subscription systems - one client-specific and one shared - but now the publish() method would have to do if (!this.game.isServer()) { this.publishOnClient(event); }.

All in all, the workaround off the top of my head seems pretty complicated for something as simple as separating the client and shared code. Thus, I wonder if there is an established and simpler method for better code organization, hopefully specific to Node.js games.


texts: Problem with FPS camera in Software Renderer

texts:
I am currently creating a software renderer (I know they aren't particularly useful anymore, it is purely from a knowledge and learning standpoint). I am using GLM and following OpenGL rules(as GLM is designed for OpenGL).

It's currently pretty basic, just a cube being rendered as either a pixel for each vertex or as a wireframe. Everything was going fine with it till I implemented camera controls. The camera works fine until there is a model directly behind it in the world space. The model behind the camera will be rendered, but flipped (hard to tell which axis it has been flipped on due to it being wireframe). The controls for moving forward and back become inverted. If I put one object in front of the camera and one behind, they are both visible but when the camera moves forward one model moves closer while the other moves further away.

I am not sure if this is a bug or a limitation of the mathematics involved. From what I can tell it is a problem with the perspective division (which is being handled by GLM). It seems that when the camera crosses the Z of an object, it gets flipped. If I spin the camera around the object everything is fine, this only happens when the object is behind the camera. Is this likely to be a bug in my code, or is this normal and anything not in the camera's field of view needs to be culled to stop this happening? (I know things will need to be culled at some point for performance anyway).

The code is a mess at the moment so I am just cleaning it up so it is readable, in case this is likely a bug in my code.


texts: I can easily rotate sprites using the Draw method. However I would like to simply rotate a Rectangle (the structure) so that I can get the coordinate of the four corners of the rectangle. How can I do that?


texts: How to flip sprite and all collision children of a KinematicBody2D at the same time?

texts:
I have tried to use the scale property of KinematicBody2D to flip at the same time the sprite and the collision/area/raycast children. For flipping, one just has to set scale.x = -1.
If it works in the editor, it does not work properly because the engine seems to reset scale.x to 1 each frame (as stated here):

NB: Here the original sprite is looking left (that is why it is blinking when going to the right, not very didactic sorry).

How to do the same without flipping every collision children one by one?


texts: Distributed C++ game server which use database

texts:
My C++ turn-based game server (which uses database) does not stand against current average amount of clients (players), so I want to expand it to multiple (more then one) amount of computers and databases where all clients still will remain within single game world (servers will must communicate with each other and use multiple databases).

Is there some tutorials/books/common standards which explain how to do it in a best way?


texts: How do I organize and sync multiple animated sprites in Unity2D?

texts: I have a human with three parts: legs, body and head, 2D, top down view (GTA 1-2 alike). Head does nothing, legs have walking animation and body has 2 animations: walking animation (moving hands which match with legs animation) and some additional animation. I have 3 gameObjects with SpriteRenderer, for each part, stored in parent. How do I animate all parts synchronously so that if human walks, then does additional body animation while legs are walking and returns to body walking animation so that if e.g. legs play 5th frame of its animation, body also plays its 5th frame, not 1st. Is it possible and if yes, then how? Also, do I need separate Animators for each body part or only one?


texts: I am registering a game on a site so that I can sell it, and it needs me to put in my game studio.  I work on my games in c++ and I dont't have a team, or a company.  Can I throw out a name and be done with it? or do I need to have a registered company?


texts:
What does the unity's RectTransformUtility.ScreenPointToLocalPointInRectangle do
I've read unity documentation but I didn't get the clear meaning.


texts:
I'm programming a little web strategy game. In the country map I pretend to display each country with a national color. The issue is how to render the borders in a simple and efficient way. Right now I'm planning to set a field to each tile called "border" with values from 0 to 8. The algorithm would check for EVERY tile is its adjacent has a different "owner". If the tile is inside the territory, the border value would be 0, because would not have adjacent any tile with different owner, if not, would vary between 1 (north) clockwise to 9 (north-west) and then draw the border.

I find this simple but too processor-intensive. Are there any other "pro" choices to render territories borders?


texts: How to handle slopes/bridges in a 2d grid turn based strategy game

texts:
I was wondering about the following:

In a 2D turn-based strategy game (using some grid(i.e. tiles, isometric hexagons) as movement), what techniques do they use to determine where a character moves next, especially how this works when stuff is happening that as far as I can see cannot be so easily implemented using a two-dimensional grid, such as slopes/different heights of movement and also things like bridges that characters might both walk over or under, depending on how they approach it.


texts: Make health bar follow the player not the camera

texts:
I wrote a script to create small bars of life & mana on top of the character.

So far it's following him and everything ok, but the problem is that it has a delay, for example the player arrives first and then the bars arrive shortly afterward.

How can I keep the bars it fixed to the player?

using UnityEngine;
using UnityEngine.UI;

public partial class UIMiniHealthMana : MonoBehaviour
{
     public GameObject panel;
     public Slider healthSlider;
     public Slider manaSlider;

     void Update()
     {

         Player player = Utils.ClientLocalPlayer();
         panel.SetActive(player != null); // hide while not in the game world
         if (!player) return;

         healthSlider.value = player.HealthPercent();

         manaSlider.value = player.ManaPercent();

     }

}

Example of the error:


texts: Converting to and from local and world 3D coordinate spaces?


texts: Can't work out how matrix is applied to 2D vertices

texts:
I have a texture, some 2D vertices, and a matrix. The matrix is used to calculate the texture coordinates for each vertex, but the problem is that the matrix comes with absolutely no documentation and I'm having trouble working out how to calculate the texture coords correctly. I have it partially working.

The matrix is in this format:

sx rx tx
ry sy ty

Where s means "scale", r means "rotate", and t means "translate".

If the matrix doesn't contain any rotation (i.e. ry = rx = 0), I can correctly calculate the texture coordinates u and v like this:

u = x/sx - tx
v = y/sy - ty

But I can't figure out how to put rx and ry into the equation and get the correct results. Normal matrix multiplication involves multiplying and adding but this one involves dividing and subtracting, so I know I'm missing something but I don't know what it is.

Here is one of the matrices with rotation:

26.191574096679688   7.0180206298828125  1579
-7.0180206298828125  26.191574096679688  1879

Here is one of the matrices without rotation:

27.115478515625  0                1867
0                27.115478515625  800


texts:
I am working on 2d games only. In that context, when would I ever need to use a shader rather than simply manipulate the pixel-data of an image?

For example, I have an image of a car and I want to change the color of the car (leaving the rest as is).

Why should/shouldn't I iterate over the whole image and change a specific color to another?
Why should/shouldn't I use shaders for this instead?


texts: Generate objects on playground on random location

texts:
How can I generate an object on my play ground? Note that there are some locations where the new generated item can't be placed.

(Click on image to see the real size)

I was following a tutorial on the site from unity but now I'll add some features by my own. In the tutorial I've done anything whit the 'Navigation'-tab.

(Click on image to see the real size)

For what I need is the blue area on the screenshot above, are good locations to generate a new object on a random place.

However, there are some locations (see red marks on image) where the objects can't be generated because that are the places where the players enemy's spawns.

Can anyone help me to generate the objects?
Thanks in advance.


texts: Why can't I read .ttf file when running Android configuration?

texts:
When running or debugging my game on Android device, I get this error in the logcat:

  com.badlogic.gdx.utils.GdxRuntimeException: Error reading file: data/fonts/myFont.ttf (Internal)

Which is created by this code line:

FreeTypeFontGenerator generator = new FreeTypeFontGenerator(fontFile);

where fontFile is defined like this:

FileHandle fontFile = Gdx.files.internal("data/fonts/myFont.ttf");

This doesn't happen when I run the desktop configuration.

I know that for desktop configuration you have to define the working directory of your project, but I don't see such option in android configuration and it also makes no sense, so I don't think it's a "working directory"-related problem.

Obviously, the file is in the correct path.

Also note that everything worked fine in my previous project. I created this new project by creating a new blank prj using libgdx-setup and then copying all the classes and packages from the older project. So maybe it's a problem related to some Gradle file?


texts:
Curious about how developers approach the use of purchased hints and scoring.

Context:

I have a puzzle app that allows users to incrementally reveal an optimal solution via purchased hints. They can choose to ultimately reveal the whole solution or only pieces of the solution.

There are hundreds of puzzles in the app. The nature of each puzzle is not so memorable (many look similar). Each puzzle has multiple solutions and an optimal solution so a player can return to an already solved puzzle to improve her/his score and strive for the optimal solution. Scoring is based on the number of moves (lower is better). The app tracks the personal best score for each puzzle.

Question:

From a standpoint of user experience and better/longer gameplay...

Would it be a bad idea to somehow penalize (in scoring) the player for using hints? Is there precedence for this? I had the notion of adding a point (low score is better) for every hint used. The penalty would preclude reaching the perfect score. This way the player can use a hint when stuck but still return to try for the optimal solution without hints.


texts:
I have multisampled rendertarget where I use red channel as stencil data, but the problem is I get incorrect results around borders if "Antialiasing - Gamma Correction" is set to on in Nvidia Control Panel. Is there a way to turn that off while writing to that specific render target (if user has it enabled in graphics card's control panel)?

This is with XNA 4.0.


texts: Compute directional light frustum from view furstum points and light direction

texts:
I'm working on a friends engine project and my task is to construct a new frustum from the light direction that overlaps the view frustum and possible shadow casters. The project already has a function that creates a frustum for this but its way to big and includes way to many casters (shadows) which can't be seen in the view frustum. Now the only parameter of this function are the normalized light direction vector and a view class which lets me extract the 8 view frustum points in world space. I don't have any additional infos about the scene. I have read some of the related Questions here but non seem to fit very well to my problem as they often just point to cascaded shadow maps. Sadly i can't use DX or openGl functions directly because this engine has a dedicated math library.

From what i've read so far the steps are: Transform view frustum points into light space and find min/max x and y values (or sometimes minima and maxima of all three axis) and create a AABB using the min/max vectors.

But what comes after this step? How do i transform this new AABB back to world space?

What i've done so far:

CVector3 Points[8], MinLight = CVector3(FLT_MAX), MaxLight = CVector3(FLT_MAX);
for(int i = 0; i<8;++i){
    Points[i] = Points[i] * WorldToShadowMapMatrix;
    MinLight = Math::Min(Points[i],MinLight);
    MaxLight = Math::Max(Points[i],MaxLight);
}

AABox box(MinLight,MaxLight);
box.GetPoints(Points); //save new aabb points to the array
CMat4 ShadowMapToWorld = WorldToShadowMapMatrix.Inverse();

for(int i = 0; i<8;++i){
    Points[i] = Points[i] * ShadowMapToWorld;
}

I don't think this is the right way to do it. The near plain probably has to extend into the direction of the light source to include potentional shadow casters.

I've read the Microsoft article about cascaded shadow maps http://msdn.microsoft.com/en-us/library/windows/desktop/ee416307%28v=vs.85%29.aspx which also includes some sample code. But they seem to use the scenes AABB to determine the near and far plane which I can't since i cant access this information from the funtion I'm working in.

Could you guys please link some example code which shows the calculation of such frustum?

Thanks in advance!

Additional question: is there a way to construct a WorldToFrustum matrix that represents the above transformation?


texts: How do I export a Java project on Eclipse as an executable?

texts:
I made a Java project with images, external JARs, and natives(the JARs and natives are for LWJGL and Slick). How can I export this as an executable? I already tried JarSplice and WinRun4J, but when I run the executable, nothing happens. Why?

EDIT: There are also sound files and TrueType fonts.


texts:
For an arbitrary convex shape in 3D, how can I calculate its center-of-gravity?

I have face-normals, and the vertices for each face.

@Ocelot No, it most certainly is not the average of the vertices, as demonstrated in this simple 2D case.

The average of coordinates is in top of shape, whereas the C.o.M. is in the bottom half.


texts: Corgi Engine - Character glitches with "jump" animation on top of a ladder

texts:
I'm new to Corgi Engine and Unity in general. I have an issue that I could find a way to resolve.
I'm using CorgiEngine's "RetroLadder" prefab and extended "Rectangle" character with custom animations from "MinimalLevel":

The problem is that when character finishes climbing the ladder, for a very short amount of time, jump animation appears. As in my case jump animation is very different from idle animation, this feels like an unpleasant glitch to me, so that's why I want to fix it. You can see it on the GIF below (at first I jump near the ladder to show how animation looks and then start climbing the ladder and on the top jump glitches) -

I checked some other demos (e.g. RetroVania, which uses some ladders there) and they also have this "glitch" with Corgi demo character, but as the character's idle and jump animations are not very different, it doesn't seem wrong (GIF below) -

I suspect that this glitch happens because "CharacterLadder.cs" script disables gravity during ladder climbing and then enables it back which triggers fall of the character -

Do you think it's possible to workaround it somehow?
Thanks!


texts: How to keep balance / Unlock items / achievement rules

texts:
I'm working on an engine for a game, too learn javascript and just because its fun. I'm a flashdeveloper, I know how to build websites. Now making games is a different challenge, javascript is a challenge, but I'd love to learn how to structure code and what patterns are common. I dont mind if the game ever finish, I'm mostly interested in the programming part of it. I dont have a particular endresult in mind, so I'll see where it takes me.

I currently have a system where you can buy items. The items cost a specified amount of gold, silver, diamonds etc. When you have selected and bought the item, it takes time before getting rewarded. When time is over, you are getting rewarded with other properties (gold, energy, diamonds).
For example, you can buy an apple for 50gold, It takes a minute, you get rewarded with 75energy. Or if you take a run, it cost 50energy, it takes 5minutes, reward is 25gold and 25silver. These definitions is what i call actions. Currently I already have a system where this already works and I can define as much actions with as much properties as I want.

The definitions I have kinda looks like this:

{id:101, category:544, onInit:{gold:-75}, onComplete:{energy:75}, time:2000, name:"Apple", locked: false}
{id:102, category:544, onInit:{gold:-135}, onComplete:{energy:145}, time:2000, name:"Banana", locked: false}
{id:106, category:302, onInit:{energy:-50, power: -25}, onComplete:{gold:100, diamonds:2}, time:10000, name:"Run", locked: false}
{id:107, category:302, onInit:{energy:-70, silver: -55}, onComplete:{gold:100}, time:10000, name:"Dance", locked: false}
{id:108, category:302, onInit:{energy:-230, power: -355}, onComplete:{gold:70, silver:70}, time:10000, name:"Fitness", locked: false}

Now, I would love to add a system where I can lock/unlock the actions using achievement rules. Lets say, if you buy 10 apples, you unlock a new action, like bananas which cost more, and reward more. In the future I maybe want to restrict achievements and actions to levels. I am kinda stuck how to structure this.

I have 2 questions:

Which patterns are used to define achievements? How/where are they defined? Should it be part of the action, or should it be a separate controller? Is it a good idea to register all completed actions to it? I think I want multiple types of achievement rules, Id love to hear some ideas how to develop it.
How do you create/find a good balance, so the user does not get stuck or can cheat by repeat a pattern of actions to get too much rewards. I know there is not a simple answer and i'm lacking of a good game-concept, but I wonder if anyone created such a game and how you dealed and played with it.


texts: How to have a successful beta test with a small team?

texts:
I've done a lot of work (pro-bono) on a patch to a commercial game from ~11 years ago that needs some beta testing. Loads of people are waiting for it.

What are some ways to get good (by that I mean useful) feedback during the beta test phase for a game? I've got lots of people who want to play with it, but I'm concerned about getting good feedback without getting bogged down in the development. I'm also concerned that people will be more concerned about having the tweaks they want to see added to the patch than really testing the work that has been done.

Do you provide the ability to log bugs directly into a bug tracker, or send them all to a person on the development team?
How do you ensure you cover all the platforms you support (in my case: Mac OSX (x86/ppc), Windows (multiple versions), Linux (multiple versions)?

Are there any good software packages (like a web portal) for running a beta test for a project like this? Any good documents out there with tips?


texts:
I currently have a scenario where I am rendering terrain with a shadow map.  I have two passes, one for the depth buffer to create the shadow map (which is rendered to a texture) and a second that takes the shadow map texture as input and actually shadows the terrain, the terrain gets drawn once for each pass.  Within the second shader I also texture the terrain.

I now want to split the second shader so that shadows and texturing are separate shaders.  How do I go about getting the output from the shadow shader to the texture shader (or vice versa), or do I simply do it in the same way as I have with the shadows (rendering to a texture, passing it as an input).


texts: How can I project a vector on another vector?

texts:
I have a generic not normalized Vector3 v1 and I want to calculate its component along another Vector3 v2. I used to normalize the vector I want to be the direction and then multiplying the other vector's magnitude for it. I can't really understand if it would also work to multiply the other vector (not just its magnitude), but I want to know if there is a lighter way to do it, since compute the magnitude of a vector implies evaluating a square root.

In code I would say

Vector3 v1;
Vector3 v2; v2.Normalize();
Vector3 resulting_v = v1.Length() * v2;

the other case (I am not sure if can work) would be

Vector3 v1;
Vector3 v2; v2.Normalize();
Vector3 resulting_v = v1 * v2;

or, if there is a better solution, I'm listening


texts: Does anybody know of any resources to achieve this particular "2.5D" isometric engine effect?

texts:
I understand this is a little vague, but I was hoping somebody might be able to describe a high-level workflow or link to a resource to be able to achieve a specific isometric "2.5D" tile engine effect. I fell in love with http://www.youtube.com/watch?v=-Q6ISVaM5Ww this engine. Especially with the lighting and the shaders!

He has a brief description of how he achieved what he did, but I could really use a brief flow of where you would start, what you would read up on and learn and the logical order to implement these things.

A few specific questions:

1) Is there a heightmap on the ground texture that lets the light reflect brighter on certain parts of it?

2) "..using a special material which calculates the world-space normal vectors of every pixel.." - is this some "magic" special material he has created himself, or can you hazard a guess at what he means?

3) with relation to the above quote - what does he mean by 'world-space normal vectors of every pixel'?

4) I'm guessing I'm being a little bit optimistic when I ask if there's any 'all-in-one' tutorial out there? :)


texts:
So, my first attempt to create a component based game object is this:

class GameObject;

class GameObjectComponent
{
public:
    virtual ~GameObjectComponent();
    virtual void Update(GameObject* obj, const sf::Time& deltaTime) = 0;
};

class GameObject
{
public:
    GameObject();
    virtual ~GameObject();

    virtual void Update(const sf::Time& deltaTime);
    virtual void AddComponent(
      std::unique_ptr<GameObjectComponent> component,
      std::string componentName);
    virtual GameObjectComponent* GetComponent(std::string componentName);

    float GetVelocity();
    float AddVelocity(float velocity);
    void SetVelocity(float velocity);
    sf::Vector2f GetPosition();
    sf::Vector2f MovePosition(sf::Vector2f movement);
    void SetPosition(sf::Vector2f position);

private:
    float mVelocity;
    sf::Vector2f mPosition;
    std::unordered_map<std::string, std::unique_ptr<GameObjectComponent>> mComponents;
};

The cpp

#include "GameObject.h"

namespace Engine{
GameObjectComponent::~GameObjectComponent()
{
}

GameObject::GameObject()
{
    mVelocity = 0.f;
    mPosition = sf::Vector2f(0.f,0.f);
}

GameObject::~GameObject()
{
}

void GameObject::Update(const sf::Time& deltaTime)
{
    for (
      auto iterator = mComponents.begin();
      iterator != mComponents.end();
      ++iterator)
    {
        iterator->second->Update(this, deltaTime);
    }
}

void GameObject::AddComponent(
  std::unique_ptr<GameObjectComponent> component,
  std::string componentName)
{
    mComponents[componentName] = std::move(component);
}

GameObjectComponent* GameObject::GetComponent(std::string componentName)
{
    return mComponents[componentName].get();
}

float GameObject::GetVelocity()
{
    return mVelocity;
}
float GameObject::AddVelocity(float velocity)
{
    mVelocity += velocity;
    return mVelocity;
}
void GameObject::SetVelocity(float velocity)
{
    mVelocity = velocity;
}
sf::Vector2f GameObject::GetPosition()
{
    return mPosition;
}
sf::Vector2f GameObject::MovePosition(sf::Vector2f movement)
{
    mPosition += movement;
    return mPosition;
}
void GameObject::SetPosition(sf::Vector2f position)
{
    mPosition = position;
}
}

and it works, but now I'm worried about priority.

Let's say I have these components: Movement, Phyisic, Renderer, NetworkSync
then they should run in order, otherwise the player could be rendered in the wrong spot, make a movement they should be able to do, or don't sync correctly with other players.

I'm not sure how to handle this without tanking the performance, and without losing too much flexibility.

Any suggestions?

Thank you.


texts: Design/Architecture of a game waiting room

texts:
I have some experience in creating singleplayer games, but for a new project I want to implement also a multiplayer.

I can imagine what kind of information (position, textureId, ...)  i have to send over the network. But hey, I can't figure out how I "could" represent a game waiting room. Which means :

One player creates a new game (What happens here?Does the server code calls a new instance of the game, but does not start the game yet???)
The player, who created the game then either waits for additional players(in maximum 4) or he starts a solo game (Should my game has something like a value for currentPlayers ? Or is this managed by server code?)
Also can you explain what exactly server code means? Which common functions should it handle (in context of creating a game room)?
How can I make sure, that other players can also start new games

As you can see I am a complete beginner to networking, but i do know about TCP and UDP, but the only thing i have done with it was a simple echo server...
What am i looking for are simple pseudocodes oder examples, but please explain briefly.


texts: Fix broken Portal 2 Chapter Handling in my Mod

texts:
I am running again into issues where my mod and the Portal 2 base game do not like each other!

In order to provide the proper menu background images and the music for each of the 5 (internal - internal means here the division in 5 acts while having about 12 chapters ingame so the player can choose rather a chapter than a act to start with) chapters of my mod I have included the following to override the base game:

/media/menu_act(01 | ... | 05).bik: The background video/image which is displayed in the main menu.
pak01_dir.vpk/materials/vgui/backgrounds: Images of the main menu background which are displayed before the bik video files are loaded and played. Usually the first frame of the video.
pak01_dir.vpk/sound/music/mainmenu/portal2_background(01 | ... | 05).wav: Main menu background music overide with my content rather than the original.

However I have and issue and one question concerning this one:

Assume I play the first level of my mod, this is obviously Act 1 and Chapter 1. Now i close my mod and start playing Portal 2 - let's say we start with a new Game in Chapter 7 which is Act 3 internally. When I now change back to my mod it thinks it is already in Act 3 and therefore displays the wrong menu background and could spoiler the player etc. therefore the chapter handling of the base game influences my mod and I do not want to everybody something like "don't play Portal 2 unless you play through my mod.".
Is there any way to fix this issue? I already tried to mess around with the sv_unlockedchapters variable but it looks like this not affect Portal 2.

A workaround would be to use only one background and the same music for all chapters but it would very neat if the menu is contextual based on the progress in the mod!

My experiments so far

I have started again my mod and it shows Chapter 3 (changed the BGs to be able to distinguish and debug which chapter is selected), after running my very first map once, which is for the sake of simplicity called sp_a1_intro1 and returning to the menu the chapter was set (and saved!) to be 1. Experimenting a bit revealed, that naming the map sp_a4_intro1 does not change the chapter to 4. Even including map sp_a4_intro1 in the chapter4.cfg did not help.

I figured out that it seems that the relation map <-> chapter is hardcoded into the game. Naming my map the as one of the original ones here or putting them in a separate folder and using symlinks with "original" allowed me to change the current chapter... (I don't know where this information is stored! I NEED to know it!) however that way I am restricted to either the original names AND the maximum amount of maps available. I need to find out, how to change this behaviour, otherwise I probably have to stick to having only one menu setting...


texts:
I've recently started working on a turn based strategy game much like games from the Fire Emblem or Final Fantasy Tactics series. However, I'm running into a few problems concerning the storage of the tile data and unit data. For example, just like in Fire Emblem I want to show all possible movement when you click on one of the units. Here is an image showing what I mean.

In this image the possible fields to move to have been indicated with a blue color. Fields that are in range for an attack have been indicated with the red color. Normally the tile the enemy unit is on would be in range to move to, however since there is someone standing on the tile the game has recognized that you can't move there.

I understand the need for an algorithm like Breadth-First Traversal to find out all possible fields to move to, but I'm unsure how to exclude fields occupied by an enemy. In order to avoid circular dependencies between fields and units I only store a reference to field in the unit class and not the other way around. So when I work my way through the fields to check all possible moves, how do I best find out if that field is actually valid?

I could of course just loop through the list of all enemies for each field that I process to see if it's occupied. Another way to potentially solve it would be to loop through the list of possible fields and removing fields occupied by enemies from that list, but I think that wouldn't work properly because occupied fields can also have the effect that empty fields around them are no longer reachable (due to the enemy blocking access to them). The easiest way to solve it would be to also store a reference to the unit within the field class. This would of course introduce a circular dependency.

I feel like there should be a much better solution than the ones I can think of, but I just can't figure it out.

Thanks in advance!


texts: OnMouseDown() and Collision not working for game object created within another game objects script

texts:
I have created a game object (Brick) and added a script (BrickScript) to it. Within this script I create a Window game object if a certain condition is satisfied. Please see code below:

if (hasWindow) {
    if (window == null) {
        var size = gameObject.GetComponent<SpriteRenderer>().bounds.size;
        window = (GameObject)Instantiate (Resources.Load ("Prefabs/OtherPrefabs/Window"),
            new Vector3 (transform.position.x + 0.5 * size.x,
                        transform.position.y + 0.5f * size.y,
                        transform.position.z),
            Quaternion.Identity));
        window.name = gameObject.name + "Window";
    }
}

The Brick and window game objects actually overlap a bit. I realized that when hasWindow = true (the window is created) the condition in the code below is not satisfied and other game objects don't collide with the Brick. But when hasWindow = false (the window is not created), everything seems to work well. How can I solve this?

void OnMouseDown () {
    if (Input.GetMouseButtonDown(0)) {
        Debug.Log ("touch down");
        hasBeenTouched = true;
    }
}


texts: How Can Create Line Renderer Runtime When Player in Gravity

texts: I want to Create functionality Like Rock Runner Game.when player into the gravity and hold the button then generate line and player hold the line and move forward. After So many Research i couldn't find anything in google and also in YouTube then i post the question. I put some snippets to very well understand what i want actually. if any one have idea how to do this then tell me. thanks in advance


texts: Java delaying commands in a method with time (Sys.getTime)

texts:
LWJGL 2.9.3 and Slick2D
Hello, so Im making this game and its going quite well, but I cant figure this out: Ive got a 2d tile based map (wich is stored in a 2d array) and each tile has a coresponding class and an arrayList for it. Here is what I try to make: I want to be able to click on a stone tile (I have this part done), and then I want the stone tile to disapear after a set ammount of time (e.g. 10 seconds).
The code:

    last = (int) (Sys.getTime() / Sys.getTimerResolution());
    globaltimed = last - (int) (Sys.getTime() / Sys.getTimerResolution());

    last = (int) (Sys.getTime() / Sys.getTimerResolution());
    globaltimes = last - (int) (Sys.getTime() / Sys.getTimerResolution());

    lastn = (int) (System.nanoTime() / 100000000);
    timesn = lastn - (int) (System.nanoTime() / 100000000);

^^ This is the part wich goes in the init method in my Play state class. ^^

    timesn = (System.nanoTime() / 100000000);
    // Global time w/ millisecond
    globaltimed = (timesn - lastn) / 10;
    // Global time in seconds
    globaltimes = (timesn - lastn);

    sec = (int) (globaltimed % 60);
    min = (int) (Math.floor(globaltimed/60));
    hour = (int) (Math.floor(min/60));

^^ This part goes in the update method of the Play state class. ^^
Thats all the time stuff.

if(Mouse.isButtonDown(1)){
        for(Stone ss : blocks){
            if(Collision.playerCBlock(new Point(mx, my), ss)){
                if(ss.selected && ss.selectable){
                    //map[Collision.contxy(new Point(ss.x / 32, ss.y / 32), ss, 0)][Collision.contxy(new Point(ss.x / 32, ss.y / 32), ss, 1)] = 3;
                    //blocks.remove(ss);
                    //ss.setSolid(false);
                    //ss.setSelectable(false);
                    ss.addMine(globaltimed, gc);
                    //dirt.add(new Dirt(ss.x,ss.y,false));
                }
            }
        }
    }

^^ Ignore the comments, but here I go through the stone tiles, check if the mouse is on that tile, if that tile is selectable and selected (I select it when left clicking, same for loop pretty much). I want to be able to say ss.addMine(whatever) and then in the stone class to make it wait some time (while displaying that time on the tile) and after that time has passed I want to replace the stone tile with a dirt tile. ^^

    if(!dead){
        //timedl = timed;
        minig = true;
        if(timed + minetime >= Play.getTimed()){
            //gc.sleep(minetime * 1000);
            setSolid(false);
            setSelectable(false);
            Play.dirt.add(new Dirt(x,y,false));
            dead = true;
        }
    }

^^ This is the addMine method in the stone class. I played with this for about an hour but I dont really have any time left now. setSolid and setSelectable baisicly remove its collision and make it unselectable. play.dirt.add(...) adds a dirt tile ontop of the stone tile (Replaces it; not efficiently, but it works for now). ^^
Thats all the important code, now, does anyone have a concept to delay the replacement of the tile(setSolid(false)...dead=true   that part) for some time in seconds w/ or w/o milliseconds (globaltimed is w/ millis, and globaltimes is in seconds only(and int)).
Thank you


texts: Wheel rotation for a raycast car in Unity?

texts:
I've been learning unity and 3d modelling over the last couple of months and I'm trying to set up a basic car game using raycasts, as the wheel colliders in unity aren't great.
Right now I'm trying to get the wheel mesh (wheelTransform in the code) to rotate with as the car moves.
I have the following line to get the speed of the car at the point where the raycast hits the ground in the local space of the car, in the direction that the car is facing.
wheelForwardVelocity = transform.InverseTransformDirection(carRigidbody.GetPointVelocity(hit.point)).z;
Then I have the following line to calculate how much the wheel must rotate each frame depending on wheelForwardVelocity. I am not implementing wheel slip at this point so I can just have the wheel rotate based on the car speed.
wheelRotationAngleAddition = (wheelForwardVelocity * 360 * Time.deltaTime) / (Mathf.PI * 2 * wheelRadius);
Finally I have the following 3 lines to add change the wheels rotation:
Vector3 rotation = wheelTransform.localRotation.eulerAngles;
rotation.x += wheelRotationAngleAddition;
wheelTransform.localRotation = Quaternion.Euler(rotation);

However, when I test the game in Unity the wheel rotation does not work:

At slow speeds, the wheel rotation seems to be right, but then it will (seemingly at random) start freaking out rotating back and forth. I cannot for the life of me figure out why! I would really appreciate any help :)


texts: Move 2d tank with independently controlled treads

texts:
I have made a tank object that knows its position, speed, rotation, and a double value ranging from 1.0 to -1.0 for each tread. I want it to move base on those values. For example, if the value for the left tread is 1.0 and the value for the right tread is 0.5 the tank should follow a clockwise circular path. However, the closest I have come is when the left tread turns forward (positive) and/or the right tread turns backward (negative), the tank spins CCW and moves down the screen, while the reverse is true if the left tread turns backward and/or the right tread turns forward.

This is my code for moving the tank, where lts is the left tread speed and rts is the right tread speed:

rotation += speed * (rts / 12);
rotation -= speed * (lts / 12);
location.x += speed * (Math.cos(rts / 12) * 14.5);
location.x -= speed * (Math.cos(lts / 12) * 14.5);
location.y -= speed * (Math.sin(rts / 12) * 14.5);
location.y += speed * (Math.sin(lts / 12) * 14.5);


texts: Send mesh to a video card with the help of ngui instead of DragonBones in Unity

texts:
I am working at the project. It is pretty huge. And there is ngui at its core, so I can not go away from it (from ngui).

Now I am assigned to incorporate the DragonBones into the project. There are visual elements made with DragonBones which are (those elements) displayed behind the ngui elements.

I know that ngui works as follows: it gathers all the meshes and sends them all to the video card at once.

Is it possible to make DragonBones put the meshes in that gathering, so that DragonBones visual elements were sent to the video card along with ngui elements and hence were displayed in accordance with ngui elements?

Will extending the UIBasicSprite help me to tackle the issue?


texts: "Non-additive" alpha blending in OpenGL ES 2.0, Android (AndEngine)

texts:
I have several monochromatic sprites and I render them with alpha = 0.25 (all of them the same value). I want to "paint" with them, so when they overlap, the alpha won't be added. I am not sure if I can express myself properly in English - here is an image of what I want to achieve (background visibility is important).

Is this achievable in OpenGL ES 2.0? I was trying to figure out the different modes of alpha blending, but without success. Also if anyone can tell me, how is this called, I can continue my search.

If this is not possible, I was thinking maybe I can somehow render the monochromatic sprites (alpha = 1) to a texture and only then render this texture on screen. How can this be done in AndEngine?


texts: How do I add leaderboard feature of OpenFeint in android?

texts:
I am developing a game in android, by extending a class with view. I have integrated OpenFeint in it by studying the tutorial provided on the OpenFeint site, but I am not able to add the leaderboard feature in my app. How can I achieve it?

My game class is like this

public class GameActivity extends Activity {

Intent i;

Grapic g;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(new Grapic(this));

and Grapic is a class which extends view and where scoring is done with touch events.


texts: Find Entity Orientation In Degrees Given Two Coordinates

texts:
I'm trying to find the orientation for an entity, as an angle in [0º-360º). I've searched for an answer and tried to implement something of my own, but it always fails on the edge cases. For a better understanding of what I am trying to achieve I've created the following image.

EDIT: It is worth mentioning that I do the conversions to and from radians where needed. Additionally, this is used for an internal simulation (meaning this will not be rendered on screen).

What is known: the center point coordinates which is always at (0,0) and the position of the red entity (x,y)

What needs to be computed: the orientation of the red entity such as it faces the center point (0, 0) in degrees 0-359

In my particular case I have to support negative coordinates. The degrees start at 0 which is at the top and goes CW.

What I tried

I've tried using atan2(y, x) which I almost got working, but it fails at some edge cases as I will describe.

When the entity is in the first quadrant I get, let's say 45 degrees, but this is not good in my case, because if the entity is in the first quadrant and it's facing the center the angle should be between 270 and 180. So I did some mapping and it seems to be working.

When the entity is in the second quadrant I get, let's say -45 degrees, which again is not good because I need it to be in range of 0-359. So I check if the degree is less than 0, add 360 and mod by 360. The result I get is good since it's between 270 and 359.

I could go on about the rest of the quadrants, but then I get another issue: when the x or y coordinates for the entity are 0 (only one, not both).

I could write some if cases to adapt the result accordingly, but I figured there must be a smarter solution to this and a faster one, since this needs to be computed 60 times a second.

I've also tried some custom math, using triangles, but ultimately I have to manually do some checks to get the correct answer.

I don't know if this is of any value for the answer, but I'm trying to implement this in Java/Kotlin, though I'm not looking for someone to just give me the magic piece of code that I can just paste and have it working, I'm looking to understand how it can be done better.

Is there a better way to achieve the result I want here?

The solution that worked perfectly for me is the following

angle = -(toDegrees(atan2(y, x)) + 90) % 360

As far as I can see it covers the edge cases.


texts:
I am developing side scrolling game using AndEngine, and looking for additional camera control.  I would like to view the whole level and then zoom/pan the camera to the left corner of the scene.

My whole scene is 4096px wide by 768px high, and my camera resolution is 1024px wide by 768px high.  I used AndEngine's ZoomCamera class for this purpose and setZoomFactor to 0.1f to show whole game play.

So how do I pan the camera to the default left corner?


texts: Movement velocity relative to a static object (Vector Maths)

texts:
I have a static object. I have a moving player.

If the player is moving directly towards the object then I want to return the value of 1.
If the player is moving directly away from the the object then I want to return the value of 0.
If the player is moving somewhat between these two directions then I want to return a value proportionally relevant to the two previously mentioned values - between 0 and 1 depending on the direction.
The direction that the player is facing is irrelevant, it's the velocity of the player that's important for my situation.

How do I calculate this value?

This is so frustrating, as I know that I've solved this exact problem in the past but I'm currently drawing a blank. It involves some trig and some dot product, but for now I'm clueless and would appreciate any help that's offered.


texts: Identifying Entity 'Types' in an Entity-Component System

texts:
If an Entity has no explicit 'type' (e.g. player) and is simply a collection of components, how do I identify the entities that my systems should and should not be working on? For example, in a game of Pong the paddle and ball both collide with the window boundaries. However, the collision handling systems for each will be different, therefore a system should not handle entities of the wrong type.

void PlayerCollisionSystem::update(std::vector<Entity *> entities) {
  typedef std::vector<Entity *>::iterator EIter;
  for (EIter i = entities.begin(); i != entities.end(); ++i) {
    Entity *player = *i; // How do I verify that the entity is a player?

    // Get relevant components.
    PositionComponent *position = player->getComponent<PositionComponent>();
    VelocityComponent *velocity = player->getComponent<VelocityComponent>();
    SpriteComponent *sprite = player->getComponent<SpriteComponent>();

    // Detect and handle player collisions using the components.
  }
}

Both the player and the ball share the same relevant component types for collision handling yet their system implementations will be different.

If I have a container of all game entities, how do I identify specific types of entity without inheriting Entity or including a member variable such as std::string type, in which case an entity is no longer simply a collection of components?


texts:
I'm relatively new to color blending in DirectX, and I'm hoping there is a relatively simple answer to this question. I am targeting Direct10.1.
What I am trying to achieve is colour blending of two overlapping 2D shapes, where the blend factor between the two layers varies (in quite a simple manner).

The shapes in the output I want should be completely opaque. I can achieve the blend variation I need very easily using alpha blending and modifying the alpha value in the pixel shader, but of course this then ends up giving me a final image with areas of partial transparency. One way I think I could resolve this would be to simply render the original render target again in a quad, and multiply out the alpha values to give me a 100% opaque images, but I have a niggling feeling that the blend operation I want must be possible via some blend state configuration.


texts: Is it a good idea to analyze and compensate for gamepad joystick deadzones?

texts:
For example, the player may want to be able to aim precisely in a top down shooter.  However, if the player is using a junky controller that has axis-independent deadzones, they will not be able to aim just a few degrees off of top, bottom, left, or right due to deadzones.  Is it a good idea to jump through hoops to sense this limitation and compensate for it?  Are there any best practices for that?
Here is an example of what I mean by axis independent deadzones:

The red area represents the deadzone.  The horizontal red area would give y=0, and the vertical red area would give x = 0.
I imagine that I could find these deadzones if I ask the user to calibrate their gamepad and do a sweep along the perimeter of the joystick.  Then I could compensate for them by squashing all values between 0 and (1 or -1) into that grey quadrant.  That said, I can see some issues arising with the player performing the calibration sloppily or too quickly, or otherwise sensing the deadzones inaccurately.
Is this a bad idea?  Should the player just get a better controller?


texts: Premake a texture in SDL (C++) and save it

texts:
I am new with SDL, and am making a Conway Game of Life.

I want to make a grid appear on the screen, so of course I could make one manually with SDL_RenderDrawLine and two loops. But I don't want to create this grid every single time, once is enough, after I can just copy it to the screen.

So I want to create the grid once, and save it somewhere, like a texture.

The problem is, how do I draw to a texture ?

From what I understand, SDL_RenderDrawLine will need a renderer (which is associated with a window) and so it won't work for my purpose as it will be drawing to that renderer buffer or something, and then to a window.

How can I do that ? You can load an image instead, but I'll lose the whole point of drawing it algorithmically (what if the tile size change, etc).

EDIT :
So I'm trying to use SDL_SetRenderTarget, as well as the correct flag to create the texture. However it simply doesn't show up.

Here is the code that create the whole texture, and should render to it :

// part of my init function for SDL

SDL_SetRenderDrawColor(d_renderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(d_renderer);
// Create square grid once
d_grid = SDL_CreateTexture(d_renderer, SDL_GetWindowPixelFormat(d_window), SDL_TEXTUREACCESS_TARGET, WINDOW_WIDTH, WINDOW_HEIGHT);
if (d_grid == NULL){
    fprintf(stderr, "Error creating blank grid texture: %s\n", SDL_GetError());
    return false;
}
SDL_SetRenderTarget(d_renderer, d_grid);
for (x = 0; x < MAP_WIDTH; x++){
    SDL_RenderDrawLine(d_renderer, x * 10, 0, x * 10, WINDOW_HEIGHT);
}
for (y = 0; y < MAP_HEIGHT; y++){
    SDL_RenderDrawLine(d_renderer, 0, y * 10, WINDOW_WIDTH, y * 10);
}
// TODO: Draw the grid to the texture
 SDL_RenderPresent(d_renderer);
// Renderer will now draw to screen again
SDL_SetRenderTarget(d_renderer, NULL);

I've checked it, the two loops does create what I want.

Now when I update the screen:

// Reset display
SDL_RenderClear(d_renderer);
SDL_RenderCopy(d_renderer, d_grid, NULL, NULL);

SDL_SetRenderDrawColor(d_renderer, 0x00, 0x00, 0x00, 0xff);

/* Code used to render the game grid, removed for clarity */

SDL_RenderPresent(d_renderer);

I don't understand how I'm supposed to do. According to LazyFoo tutorial, I need to use the SDL_RenderDraw* function, which will render to the texture, but using SDL_RenderPresent or not doesn't change anything. What am I doing wrong ?


texts:
I'm trying to make game like portal which players can transform between two holes.
My problem is, how to detect if player's have the right angle to the hole. (hole has an angle to a direction, if player's angle to hole meet the right direction can do transform)

Pseudo code:

var range=30;
 if(collission){
     if(abs(ball.getAngle()-player.getAngle())<=range){
            ball.doTransform(player);
     }
 }

below is some situation:

ball.setAngle(20);
player.setAngle(30);
abs(ball.getAngle()-player.getAngle()) ==10 //ok
player.setAngle(350);
abs(ball.getAngle()-player.getAngle()) ==320 //not ok
ball.setAngle(350);
player.setAngle(20);
abs(ball.getAngle()-player.getAngle()) ==330 //not ok
ball.setAngle(120);
player.setAngle(100);
abs(ball.getAngle()-player.getAngle()) ==20 //ok

and anybody can help me to figure out the right condition so that ball can transform player? thanks!


texts: How is the terrain generated in Commandos and Commandos game clones/look-alikes?

texts:
The Commandos series of games and its similar western counterpart, Desperados, use a mix of 2D and 3D elements to achieve a very pleasing and immersive atmosphere. Apart from the concept that alone made the series a best-seller, the graphics eye-candy was also a much appreciated asset of that game.

I was very curious on what was the technique used to model and adorn the realistic terrains in those titles? Below are some screenshots that could be relevant as a reference for whomever has a candidate answer:

The tiny details and patternless distribution of ornamental textures make me think that these terrains were not generated using a standard heightmap-blendmap method.


texts: Unity 2D - Instantiate a GameObject and scale it every second

texts:
I want to make a bomb-like game object, that when instantiated, takes 2 seconds to charge, and then some other event triggers. The problem is I can't make it scale smoothly for 2 seconds, and then trigger some other event.

Here's what I have:

public GameObject bombGO;

// This method is inside a Input.GetButtonDown("Fire2") event in Update()
void ChargeBomb() {
    Vector3 offset = transform.rotation * playerOffset;
    GameObject bomb = (GameObject) Instantiate(bombGO, transform.position + offset, transform.rotation);
    bomb.transform.localScale += new Vector3(0.2f, 0.2f, 0.2f);
    // Now I want this transform to be fired continuosly for 2 seconds, while the object progressivelly and smoothly gets larger, up to 1.0f scale
    // after 2 seconds, destroy the said object
}

How can I do it?


texts: How does the Simple Stupid Funnel Algorithm work?

texts:
Working with the funneling algorithm shown on Digesting Duck I'm not sure how the detection of the funnel works.

Can someone explain the method clearly to me or suggest an alternative way of detecting the funnel and if the funnels sides overlap?


texts: How can I make shadows darker in unity5 without changing light intensity?

texts:
I have a problem where I want the shadow cast by an object to be a well defined and dark one. However I have to do it without changing how illuminated the object looks so only increasing the intensity of the light won't do(I have already maximized shadow strength).

Is this something i can manipulate in engine or will I have to make some sort of shader adjustments?

This one has the correct illumination on the character:

This one has the correct shadow color on the shadow cast by the character but it is to strongly illuminated:


texts: Why and how should I cast DirectX function parameters?

texts:
I'm learning DX11 and I found that in some D3D functions, a parameter has to be cast just like in the GetBuffer function of the swapChain: the third parameter has to be of type void*, so when calling this function the conversion is done just writing (void*) before, a C conversion if I'm not wrong.

But in other functions with a pointer like type** (where type IS NOT void) is used the reinterpret_cast. I wanted to know if the difference is because of the void type respect to the other types and, if it's not because of the void type, when should I use (type**) and when should I use reinterpret_cast.


texts: Where to start creating a 2d rain simulation with OpenGL ES 1.1?

texts: I'm using opengl 1.1 and i'm creating a 2d side scrolling game.How can i render a 2d rain simulation?What is logic for that?


texts: What broad-phase collision algorithms are suited to a static tiled world with dynamic objects of different sizes?

texts:
Sorry for this routine question, but I can't think of what broad-phase collision algorithms really work in the following, reasonably standard, setup:

2D tile based world, consisting of objects that do not move but might be altered/changed in some ways (not too often).
Significant amount of dynamic objects, interacting with eachother and with the static tiles. These objects can be of variable size, possibly much larger than the tile size.

I started thinking about using just a grid to store the static tiles, but that has its issues. One example would be a level which is a long corridor following the edges of a square; I'm anxious about creating a whole nxn grid when there is a huge amount of irrelevant space in the middle. Also I'm not sure a grid is going to be helpful when figuring out what needs to be considered for collision, or needs to be drawn on screen; a quadtree seems more appropriate.

So far, I'm thinking of:

using a quadtree to store the static tiles (to account for the possibility of large empty spaces in the middle of the grid for instance); hopefully that won't be prohibitively expensive when I need to modify some tiles (this shouldn't happen excessively often);
using some other data structure (I'm undecided which is most suited) to store the dynamic objects, which might have very different sizes;
once that's done, from the tile map I determine which tile edges are empty, solid or need further investigation for collisions; then I would use axis aligned bounding boxes for the dynamic objects to see if there is a possible collision with the static world, and some other algorithm (depending on the data structure for the dynamic objects) to model collisions between dynamic objects.

Maybe something slightly different would be more suited for the tiles, I'm thinking some sort of grid but with "off limits" regions that can be dismissed.
I'm also somewhat anxious about fast-moving dynamic objects; so maybe those could belong to yet another data structure. I wouldn't expect them to be of large size (so they should fit inside tiles nicely), but I'd like to keep my options open in case I make some design changes.

(One thing I am completely neglecting is what generally happens with off-screen dynamic objects; I'm ignoring that problem for now and assuming everything is to be simulated together, but that might be a blunder.)


texts: Detect two specific objects collision with bullet physics

texts:
I have got some problem with defining collision between objects in my game using bullet physics.

I know that objects are colliding with each other simultaneously and I don't have to do anything more. However I need to be noticed when one object collides with one of the rest.

It is quite awkward written so I will tell what I want to achive. I have got ball which hits wall from tubes. Everything is on the floor. When ball hits wall some fragments fall down to infinity. So I have got bellow floor btStaticPlaneShape. This is place where most of objects is stoping and then I can start another action. But not all of them.

So I've been trying to use function checkCollideWith but it isn't good method as it was said in reference and wiki.

So I've checked method described in wiki http://bulletphysics.org/mediawiki-1.5.8/index.php/Collision_Callbacks_and_Triggers called contact information. This isn't good method either because it is extremly hard to identify what is what when colliding. You have to also remember that ball is almost all the time colliding with something - floor, wall or eart level.

So is there any other method to check what is colliding with what?


texts: Issues with depth calculation in HLSL shader

texts:
I'm currently trying to implement shadow maps in my graphics framework.
I ran into an issue with depth calculations I wasn't able to solve myself (yet). I did a lot of testing and debugging and think I finally localized the problem.

To get the position in light-projection space I do this in the vertex shader:

float4 worldPosition = mul(input.position, worldMatrix)
output.lightPosition = mul(worldPosition, lightViewProjectionMatrix);

Note that I premultiplied the view and projection matrix on CPU.

To calculate the corresponding uv coordinates I'm doing the following in the pixel shader:

float2 shadowCoords;
shadowCoords.x =  input.lightPosition.x / input.lightPosition.w / 2.0f + 0.5f;
shadowCoords.y = -input.lightPosition.y / input.lightPosition.w / 2.0f + 0.5f;

This appears correct too, as I used the sampled value as surface colors and it went exactly as expected.

Now I want to calculate the depth (in relation to the light of course) of the current pixel. The corresponding code:

float depth = input.lightPosition.z / input.lightPosition.w;

(input.lightPosition is the float4 I output in the vertex shader as shown above)
However, this apparently gives wrong results. If I use this depth as surface color (disabling any lighting) I get
,
which is obviously wrong. Note that the point light is right above the black line.

Now, if I use input.position (which is calculated by multiplying the camera viewprojection-matrix with the world position) to calculate the depth, I get correct results.

I figured this has to be caused by semantics. input.position is using SV_POSITION, while input.lightPosition used POSITION0 (I also tried TEXCOORD0 without success). I verified this by modifying the DepthmapShader and got different results when using SV_POSITION instead of POSITION0. If you need more information I'll happily post them.

Now for the final question: What semantic do I have to use to properly calculate the depth? As SV_POSITION is already in use for the actual screen position I can't use that. Or do I have some general missconception? I just can't wrap my head around what's happening and would be glad if someone could help me out.

For the sake of completeness, here's my Depthmap-Shader:

struct VertexInputType {
    float4 position : POSITION;
};

struct PixelInputType {
    float4 position : SV_POSITION;
    float4 depthPosition : POSITION0;
};

PixelInputType DepthmapVertexShader(VertexInputType input)
{
    PixelInputType output;

    input.position.w = 1.0f;

    float4 worldPosition = mul(input.position, worldMatrix);
    output.position = mul(worldPosition, viewProjectionMatrix);
    output.depthPosition = output.position;

    return output;
}

float4 DepthmapPixelShader(PixelInputType input) : SV_TARGET
{
    float depth = input.depthPosition.z / input.depthPosition.w;
    float4 color = {depth, depth, depth, depth };
    return color;
}

Edit: I'm constructing the view-projection matrix like that (in response to Tim's answer) (Snippet is located inside of the PointLight class):

XMVECTOR dir = XMLoadFloat3(&XMFLOAT3(0, 0, 1));
XMVECTOR up = XMLoadFloat3(&XMFLOAT3(0, 1, 0));
XMVECTOR pos = XMLoadFloat3(&Location);

XMMATRIX proj = XMMatrixPerspectiveFovLH(XM_PIDIV2, 1.f, 0.1f, 1000.f);
XMMATRIX view = XMMatrixLookToLH(pos, dir, up);

return view*proj;

Is this valid? Or do I have to do something else? As Tim mentioned it projects on a plane. How should I setup the matrix (and how would I write the depth information to texture for the case that this procedure changes?)? (Bonus question: Is there a way to do a 360° shadow map with a single matrix?)


texts: How to efficiently filter by a component with a specific value in an entity component system (all entities in grid position [x,y,z], for example)?

texts:
I'm working on a 3d grid based game, and I am trying to implement it using an ECS.

I have a position component which indicates the entity's position on the grid. It is comprised of 3 integers (for example [1,3,2]). Now lets imagine the user clicked on position [1,3,2]. I now want to efficiently retrieve all entities in position [1,3,2].

I can see only one way to achieve that using an ECS. I need to filter for all components that have a position component (this can be done in O(1)), then filter through all the position components to find only those positions that equal [1,3,2]. This is extremely inefficient, since I have a hundred thousand entities with a position component to loop through, but I only need a minuscule fraction of them.

It's important to note that I never need to loop through all the hundred thousand position components in a single frame in any other case. For all other systems, I filter entities that have both a position component as well as other components, so I end up only looping through a small fraction of positions in each frame. This means I cant just retrieve all the relevant entities as part of the loop that goes through all the positions, since I dont have such a loop.

Traditionally using OOP, I would have a dictionary from a position to a container that contains all the objects in that position, which would allow me to accomplish the above in O(1). This isn't correct design for an ECS though, from what I understand.

Am I misunderstanding something about Entity Systems? If anyone has any advice I would be glad to hear it.

Thank you.


texts:
I'm making a multiplayer game where players fight in vehicles, and I am doubting my server architecture. As it will be physics, network and AI intensive I would like to split these 3 topics into their own thread. Perhaps even one thread per AI.
The physics thread will run at a fixed time-step and do the same loop over and over.

Integrate gamestate at fixed timestep of 0,005s (200Hz)
Solve gamestate for constraints and collisions
One such constraint is a vehicle controller, which is a struct consisting of throttle, steer, brake etc. is applied to a single vehicle.
Callback

The network is called every 6 physics frames, thus the networking runs at ~33Hz
The AI is also called every 6 frames.
Note: network and AI can be called in lockstep

The AI threads will calculate the next move on a need-by-need basis.

Copy gamestate into private memory
Calculate next move
Update their vehicle controller in the game state

The network thread will

Listen for incoming UDP packets, handle them, apply changes to gamestate such as player's vehicle controller, bullet spawn
When called for, broadcast the new gamestate to clients

Copy gamestate into private buffer
Create array of differences from last state

Vehicle parts removed/added
Vehicle parts moved/rotated
Players joined/left
Projectile impacts and damages

Pack the differences together and broadcast.

When a new player joins:

grab the last private game state buffer and send it whole
Change gamestate by spawning a vehicle and allocating a controller

What I'm having trouble with:

Creating threads on the fly has overhead, so I would like to avoid it by pre-creating and "parking" the threads, and calling them when needed. Once called, they do their duty, such as calculate the next move for the AI to make. Then the threads "hibernate". Note that I don't want the threads to wait in a busy loop and read some shared memory for "activation".
The AI and Network threads need to make private copies of the game state, because the physics run so fast the game state might be changed mid-read.

Mitigation 1: swapping game state buffers. Still no guarantee.
Mitigation 2: locking the gamestate. This is a bad idea because the physics should not be held up.

How can I achieve this in C++? Does x86 offer actual interrupts for this? How about other architectures, or are there libraries that do this for me?
Or should I do it another way?


texts: glm rotating quaternion in Y axis deforms object

texts:
I'm implementing my own game engine in C++ and I need help here,

I have a game object, its orientation property is a quaternion and I want to rotate it A degrees in the Y axis.

So, I have:

currentAngle += 0.01; // currentAngle is a member variable, so yes i initialized it
quat q(currentAngle, vec3(0, 1, 0));
myGameObject->SetOrientation(q);

GameObject::SetOrientation(quat q)
{
 myOrientation  = q;
}

but as the game object rotates, it also gets scaled (deformed). So I checked how I am applying the transformation matrices

myModelMatrix = Math::CreateTransformationMatrix(
    transformation->GetPosition(),
    transformation->GetOrientation(),
    transformation->GetScale());

mat4& Math::CreateTransformationMatrix(vec3&    translation, quat& orientation, vec3& scaleSize)
{

     mat4 translate = glm::translate(glm::mat4(), translation);
     mat4 rotate = glm::toMat4(orientation);
     mat4 scale = glm::scale(glm::mat4(), scaleSize);

    return  translate * rotate * scale;
}

but it looks ok (at least to me), I removed the scale matrix form the multiplication to check if somehow I was doing something with it. However, it didnt fix anything.

I also tried:

  quat q(currentAngle, vec3(0, 1, 0));
   quat orientation = myGameObject->GetOrientation();
   orientation  = orientation  *q;
   myGameObject->SetOrientation(orientation);

But it didnt work either.
I also checked the code in my shaders and I am positive is not the problem.

This is how I send the matrices to the shader:

glUseProgram(progarmId);1
    glUniformMatrix4fv(uniforms[name], 1, GL_FALSE, glm::value_ptr(matrix));

I tried modifying the 3rd parameter to True and swapping the order of the projection view matrix multiplication and it didnt work either :/

So, guys ... any ideas what could I be doing wrong ? I'm out of ideas :/


texts:
I have MS Visual Studio 2010 installed on my machine (a Windows 7 Pro 64-bit), and im developing a game in XNA 4.0 with it. I can run the program just fine from the .exe file in the bin directory, and it appears to have no bugs.

But when trying it on Windows 8 64-bit, it just doesn't run. Am I doing something wrong or is XNA suddenly incompatible in this case?

BTW this game has no 3d graphics at all, just 2D stuff, but iirc every texture2D is rendered through the GPU thing as some sort of flat 3D surface, so idk.


texts: Unity - Set rotation of object using angle between two points?

texts:
I have a LineRenderer that draws a line between two points, Vector3 startPos and Vector3 endPos. How can I get the angle between these points, and apply it to an objects transform rotation, so that it points in that direction?

Here is my code that draws a line between 2 points by dragging your mouse, if you want to test just Replace the Interact methods with Input.MouseButtonDown(1), hold and up.

Vector3 startPos;
Vector3 endPos;
float angle;

LineRenderer lr;

private void Awake()
{
    lr = GetComponent<LineRenderer>();
    lr.useWorldSpace = true;
}

public override void InteractOnDown()
{
    base.InteractOnDown();

    lr.enabled = true;
    lr.positionCount = 2;
    startPos = PointerHandler.RaycastScreenPoint(Input.mousePosition, UnitManager.instance.movementMask, GameManager.instance.cam).point;
    lr.SetPosition(0, startPos);
}

public override void InteractOnHold()
{
    base.InteractOnHold();

    endPos = PointerHandler.RaycastScreenPoint(Input.mousePosition, UnitManager.instance.movementMask, GameManager.instance.cam).point;
    lr.SetPosition(1, endPos);
}

public override void InteractOnUp()
{
    base.InteractOnUp();

    lr.positionCount = 0;
    lr.enabled = false;
}


texts:
Pretty new to the whole game development scene, but I have experience in other branches of programming. Anyway, I was wondering what methods are used to implement a skill structure. I imagine a skill in itself would a class. I'm using actionscript 3 for this project btw.

public class Skill
{
    public var power:int;
    public var delay:int;
    public var cooldown:int;

    public function Skill(user:Mob, target:Mob)
    {

    }
}

Each skill would extend the Skill class and add it's own functionality.

public class Tackle extends Skill
{
    public function Tackle(user:Mob, target:Mob)
    {
        super(user, target);
        executeAttack();
    }

    private function executeAttack():void
    {
        //multiply user.strength with power etc
        //play attack animation
    }
}

This where I get stuck. How do I termine which mobs has which skills? And which skill will they later be able to retrieve (by reaching a certain level etc).
How does the player actually execute the skill and how is it determine if it hits. It's all very new to me so I have no idea where to begin.
Any links would also be appreciated.
Thanks in advance.


texts:
I'm pretty new to 3D development of any kind, nonetheless games. As I read through tutorials and examples, I find that the X/Y/Z coordinates seem a bit backwards than my first guess.

I had imagined that if a person were walking around a field, their X/Y position would be changing and if they were to jump or walk up or down a hill, then their Z position would be changing. My assumptions appear to be wrong because walking around a field seems to change X/Z and jumping or going up/down a hill alters the Y.

1) Are my observations correct? 3D is new to me and I may not be thinking about things properly.

2) What's the logic behind horizontal movement being X/Z and vertical movement being Y?

3) Would it be so wrong of me to use X/Y as horizontal movement and Z as vertical movement in the XNA Framework?


texts: How do you structure a 2D level format with collisions etc. in Java (Slick 2D)?

texts:
I am developing a game in Java. 2D Fighter, Kind of like the 2d flash game Raze(http://armorgames.com/play/5395/raze). I currently am using the Slick 2D game library and am researching how to structure my levels. I am currently stuck on the problem of the level format(e.g. file format). How do you structure a 2d level with collisions etc.?

Level Notes: Will go up down left right

NOTE: New to gamedev


texts:
I've created a square using linerenderer but my problem now is that the line is not smooth. see below picture. I've tried enabling anti-aliasing and setting lr.numCapVertices to no avail.

 private void DrawLine()
{
GameObject myLine = new GameObject();
myLine.transform.position = start;
myLine.AddComponent<LineRenderer>();
lr = myLine.GetComponent<LineRenderer>();
lr.material = new Material(Shader.Find("Sprites/Default"));
lr.positionCount = 4;
lr.startWidth = .1f;
lr.endWidth = .1f;

lr.SetPosition(0, new Vector3(1, 0, 0));
lr.SetPosition(1, new Vector3(2, 0, 0));
lr.SetPosition(2, new Vector3(2, -1, 0));
lr.SetPosition(3, new Vector3(1, -1, 0));
lr.loop = true;

Gradient gradient = new Gradient();
gradient.SetKeys(
    new GradientColorKey[]
    {
        new GradientColorKey(Color.red, 0.25f),
        new GradientColorKey(Color.green, 0.50f),
        new GradientColorKey(Color.blue, 0.75f),
        new GradientColorKey(Color.yellow, 1f),
    },
        new GradientAlphaKey[] { new GradientAlphaKey(1f, 0.0f)

    }
    );
lr.colorGradient = gradient;

}


texts: Can not tweak collider`s border manually in Unity

texts: Why can not I change collider`s border manually? I remember being able to do that. I just clicked the gray button under in this case Box Collider 2D component, then went to the Scene view and tweaked it as I wanted by clicking and moving collider`s border. But now when I do the same procedure on trying to click and drag the border in Scene view I am just losing focus of the collider, but do not change it in any way.


texts:
So when I choose the texture in the Inspector window I see three tabs: Default, Standalones & Android. I can choose some variants of how to compress this texture, but:

My texture is a png (so it's RGBA). When I click the Default->Format I can see stuff like Alpha 8, R 8, RGB 24 bit. So if I choose R8, for example, does that mean that my GBA channels will be thrown away?
What is the Max Size? My texture is 600x375. If I choose 512 will it clip my texture to 512x375 or what? And why it is called Max Size if I am working with a single texture right now?
If I choose Default->Format to Automatic and does not do any override on any specific platform will Unity choose default texture compression formats for a specific platform using this table?


texts: Unity: RaycastHit2D continually returns point (0,0)

texts:
firstly I'm a bit of a Unity noob so sincere apologies if I've done something dumb.

I'm attempting to use a RaycastHit2D to detect when the player is on a platform. If he is, the point it returns should be passed back and used to set the player's rigidbody transform y coordinate so he sits on top of the platform.

The problem appears to be that the RaycastHit2D is continually returning a point of (0,0), so the player keeps getting reset to (x,0) - which causes an amusing bouncing effect, but not the desired effect.

Here's the code:

if (onPlatform) {

  RaycastHit2D walkingOnPlat = Physics2D.Raycast(rb.transform.position,Vector2.down,Mathf.Infinity,8);
            platYCollision = walkingOnPlat.point.y;
            rb.transform.position = new Vector3(x, platYCollision,-5f);

        }

If I can clarify anything please do let me know, and thanks in advance for your help!


texts: locking a rotation on an axis(yaw/pitch/roll) based on a parental transform

texts:
I am currently attempting to lock a non rigid body transform rotation around on an axis. It is parented to a gameobject that is rotating in 3D space. I want the
Original transform to have the same rotation as the parent's but I want it to be locked on a certain certain axis. For the sake of clarifying my question I will provide some code and an example.

Example:
There is a 3D model with a plane attached to the left upper arm subsegment(see hierarchy) whose initial normal is aligned with the global x-axis <1,0,0> or the initial right vector of the subsegment. In the context of this post, what I would like is to be able to align the normal of the plane with the subsegment's right vector but keep the plane's up axis locked.

For instance, I do not want to the yaw component of the transform to change. Trying the following code does not result in the intended effect.

Vector3 eulerRepresentation = parent.transform.rotation.eulerAngles;
eulerRepresentation.y = 0;
Quaternion fromEuler = Quaternion.Euler(eulerRepresentation);
transform.rotation = fromEuler;

This is very likely because of the duality of a rotation of Euler angles.
An example is (180,0,180) is the same as (0,180,0)

When inspecting the euler values, it is exactly like I suspected. There doesn't seem to be correlation with the object's yaw and the object's euler.y value.

How would I go about locking either Yaw/pitch/roll?


texts: Should I be caching the assets in my asset manager, or will the browser handle it?

texts:
I use the asset manager class below in my game to download all the game data at launch. It's about 5000 files. Each file is retrieved like so:

const image = AssetsManager.getImage("rooms.lounge.floor");

Will the browser cache these itself or should I add a caching layer myself?

import {
    ASSET_URL
} from 'src/AssetsManager';

export default class AssetsManager {

    static resolveUrl(path)
    {
        path = path.split('.').join('/');

        return ASSET_URL + path;
    }

    static async getJSON(path)
    {
        const url = AssetsManager.resolveUrl(path) + '/.json';

        return fetch(url)
            .then(response => response.json())
    }

    static async getImage(path)
    {
        const image = new Image();
        const url   = AssetsManager.resolveUrl(path) + '/.png';

        image.onload = () => {
            if (image.complete) Promise.resolve(image);
            Promise.reject();
        }
        image.src = url;
    }


texts: How do I get the vertical angle between 2 vectors?

texts:
So I'm modding a 3D game, my goal is to place a label on the screen pointing to the unit's direction. I'm getting the horizontal angle by projecting these vectors in a plane, like this:

private double getXAxisAngle(EntityPlayer player,EntityPlayer player2){

    double meYaw = player2.rotationYaw;
    double meX = player2.posX;
    double meZ = player2.posZ;
    double playerX =  player.posX -meX;
    double playerZ =  player.posZ-meZ;
    double yawX = Math.cos(Math.toRadians(meYaw));
    double yawY = Math.sin(Math.toRadians(meYaw));
    double dist = getDist(playerX,playerZ);
    playerX = playerX / dist;
    playerZ = playerZ / dist;
    dist = getDist(yawX,yawY); //get the vector magnitude
    yawX = yawX / dist;
    yawY = yawY / dist;
    double angle1 = Math.toDegrees(Math.atan2(yawY, yawX));
    double angle2 = Math.toDegrees(Math.atan2(playerZ, playerX));
    double angle = angle1-angle2;
            angle+=90; //So when it's facing the other unit it becomes 0
    if(angle > 180)
        angle-=360;
    else if(angle < -180)
        angle += 360;

    return angle;
}

This function gives me an angle between 0/-180 and 0/+180, depending on which side I'm facing then I get this angle and transform into a coord into the screen like this:

private double angleXToPosition(double angle,FontRenderer fontrenderer,String label)
{
    ScaledResolution scaledresolution =
        new ScaledResolution(mc.gameSettings, mc.displayWidth, mc.displayHeight);

    double width = scaledresolution.getScaledWidth();

    double namePosX =
        (int)(angle * ((width / 2 - (fontrenderer.getStringWidth(label) / 2)) / 50)) +
        width / 2 - (fontrenderer.getStringWidth(label) / 2);

    //If the angle is bigger then 50 the label sticks on the side of the screen
    if (angle > 50)
        namePosX = width - (fontrenderer.getStringWidth(label));
    else if (angle < -50)
        namePosX = 0; //Same as above

    return namePosX;
}

And it works until this, the label moves perfectly to the sides, accompanying the unit position on the screen, but now I'm trying to make the label move up and down and the same functions doesn't work, and I can't figure this out.

Some info: the pitch of the player when facing the sky is -90 and when facing the ground is 90.


texts: Is window creation decoupled from a game engine?

texts:
I'm new to game development, and I was wondering about a architecture question.

The window creation code in C++ is given by doing the following:

Fill out a WNDCLASS struct
Register the window class using the struct by calling RegisterWindow(WNDCLASS)
Get a handle to the window from calling CreateWindow()
Handle Windows events in your WndProc function, and call TranslateMessage, and DispatchMessage to forward messages in the message queue when retrieved from PeekMessage().

Then, in a game you might have a Game engine which contains a simple game loop like so:

while (running)
{
    ProcessInput();
    UpdateState();
    RenderStates();
}

My question is how do you include the window creation with the game engine. Do you decouple the two? If you decouple the two, how do you handle input to the WndProc function if it has no idea about the GameEngine class to set particular flags about keys that are pressed?


texts: Should I initialize a Box2D World per Level?

texts:
I'm using a LevelManager to load Tiled maps in my libGDX game, which stores:

Static:

final Size of map in Tiles
final Size of map in Pixels
final Size of an individual tile
TiledMap ACTIVE_MAP
World WORLD

When the map is loaded, it creates a new World and stores it in the static WORLD, later populating it with static bodies based on objects found in the map's Collision layer.

My reasoning for using static is down to the fact that logically, only one map will be playable at any one time, however I've got it in my head that only constants and singletons should be static, so this feels strange for me. Is there a better, more efficient way of handling this?

Should I have one World per Level, or a global World independent of what TiledMap is active?

In other words, should I initialize WORLD once and leave it as is, making it final, or continue what I am doing and initialize it as a new World whenever a new TiledMap is loaded?

How do I correctly dispose of all bodies within the World, essentially clearing it?

I'm going to have to do this every time I load a new map, regardless of whether or not WORLD is global.