texts: Generate Angle for Projectile to Follow So It's Ends Facing Downward

texts:
I am building a game within a game engine. The game is a 2D platform, where the player can move left, right, and jump/fall down. Part of the game is the presence of physical projectiles falling from the 'sky'. When these objects are created (in the sky), impulse is applied to them toward the present location of the player [Pic 1]. Please note the impulse is applied one time using the location of the player at object location, it is not constantly being applied to the location of the moving player. The projectile should move toward that location of the player, not necessarily to the location - and it does - but as it reaches its destination the object starts to curl upward [Pic 2].

I have tried several formulas for setting the angle on each tick (every frame), namely

Set Angle Toward: PlayerWasAtX, LayoutHeight
Set Angle Toward: Self.X, LayoutHeight
Set Angle Toward: If (Self.X > Self.PlayerWasAtX)
                  Then (Self.X - PlayerWasAtX) / 2
                  Else (PlayerWasAtX - Self.X) / 2
                  , LayoutHeight

Where PlayerWasAtX is the stored location of the player upon projectile creation, LayoutHeight is the total height of the canvas, and Self.X is the X-coordinate of the projetile.

In those examples, example 1 would curl, example 2 would keep the object straight down at all times even when falling at a curve, and iirc example 2 just acted wacky.. or it acted the same as example 1.

Any help would be appreciated. Here are my reference pictures:


texts: Tutorial or Example of creating custom sprite tool/map editor for XNA?

texts:
I want to create various sprite tool and map editor using XNA. Now, the problem is I do not know how would I implement the window forms and components (such as button, check box, sprite list, etc.) into my program and allow it to completely control my XNA environment. If there is any tutorials or examples that show how to make editor for XNA, then I would be very pleasing.

Thanks


texts: Convert Autocad DWG to OBJ, FBX or similar

texts:
I know this is only partially game development related, but couldnt find another place to ask.

How can i convert an autocad dwg or dxf file to a more 'common' format like OBJ, FBX, 3DS, etc. ?

i tried directly using autocad LT but the export options dont have any other format.s

free and oss solutions preferred.


texts:
I wish to build a card tracker that reads in game text and keeps track on the cards that are out.

Like an Overwolf app, but for a card game.  I mailed Overwolf and asked what are my options, they suggested to use image recognition.  However, it sounds complex (and I luck any experience in it).  Is there a simple way to do it?

The tracker that I want to build is for Twilight struggle and I would like to automate this card counter such that It will track the cards that been played from the a text box in the game that state their name.


texts: Algorithm to find all tiles within a given radius on staggered isometric map

texts:
Given staggered isometric map and a start tile what would be the best way to get all surrounding tiles within given radius(middle to middle)?

I can get all neighbours of a given tile and distance between each of them without any problems but I'm not sure what path to take after that. This feature will be used quite often (along with A*) so I'd like to avoid unecessary calculations.

If it makes any difference I'm using XNA and each tile is 64x32 pixels.


texts: How do I add a sprite to an object layer?

texts:
I am using Tiled to create a map which I am then using for a game written in Phaser.

I cannot figure out how to add a Sprite into the Object layer using the Tiled editor.   I am having to do it with code but that's not ideal as I want to see the sprites in their positions on the map when I edit it.

I know this is very simple but I cannot see how to add/see sprites in Tiled.  Is Tiled not able to do this or not designed to do this?


texts: Implementations for storing entities in an ECS system

texts:
I'm restructuring my model of entities, components and systems, where entities are:

const createEntity = (name, components) => ({
    id: genUniqueId(),
    name: name,
    components: components
});

And I came across a question, and would like to hear someone's experience about it. The question is what are the advantages and disadvantages of each of the following implementation approaches:

1 - Implement all entities in a single global object, and traverse this object by applying the systems in each entity, example:

const entities = {};
for(let key in entities)
    for(let system of systems)
       system(entities[key]);

2 - Create several global variables for each group that the systems serve, example:

const players = {};
const monsters = {};
const clouds = {};

for(let key in players)
       systems['input'](players[key]);

for(let key in monsters)
       systems['simpleAI'](monsters[key]);

for(let key in clouds)
       systems['wind'](clouds[key]);

3 - Create local variables within the systems to store the entities, and functions for each system to add and remove entities from their internal objects, example:

const windSystem = () => {
    const clouds = {};
    for(let key in clouds)
       ...
};

const addEntityInWindSystem = () => {...};
const delEntityInWindSystem = () => {...};

My intention with the question is just to look for other solutions or even understandings about the cons and advantages that each implementation can bring me during development.


texts: Tiled - isometric map - how to find out tile width/height

texts:
so I'm playing aroung with Tiled and want to create an isometric map. I found this tileset:

https://opengameart.org/content/isometric-landscape

The downloaded file contains a big spritesheet with many sprites in it. What is the best way to find out what settings I need to have in Tiled to work with these?

I need to set a tile width/height for the map, and width/height for a tileset itself. What's the best way to find out? The problem with this specific tileset is that the tiles all have different sizes (but it's all in one big image).

There are images of each tile sprite itself, but I don't know how to "mass add" these to Tiled.

Thanks for any help


texts:
I am learning OpenGL (and learning the math behind it) and I'm making a simple OBJ viewer, nothing fancy.
I have diffuse, specular and ambient light/texture working fine and now I am implementing the bump mapping.
I based my code on what I learned with the OpenGL 4.3 Redbook and "Mathematics for 3D game programming and computer graphics" book.

There is probably something I didn't understand correctly, I just hope you will be able to help me :)

Anyway this is the result I get (from a free asset used just for testing -- the results are fine in blender) :

This is the diffuse texture and the bump map :

Fragment shader code :

void main() {
    vec3 normalDirection = normalize(tangenteSpace*(texture2D( bump_tex, f_texcoord ).rgb*2.0 - 1.0));
    //vec3 normalDirection = normalize(mat3(invTransp)*vertNormal);
    vec3 viewDirection = tangenteSpace*normalize(vec3(invView * vec4(0.0, 0.0, 0.0, 1.0) - position));

    float attenuation = 1.0;//none
    vec3 vertToLightSource = vec3(light.position - position*light.position.w);
    float distance = length(vertToLightSource);
    attenuation = mix(1.0,1.0/(light.constantAttenuation +
                    light.linearAttenuation *distance +
                    light.quadraticAttenuation*distance*distance),light.position.w);
    vec3 lightDirection = tangenteSpace*(vertToLightSource/distance);

    //spotlight if spotCutoff <= 90
    float clampedCosine = max(0.0, dot(-lightDirection, normalize(light.spotDirection)));
    float tempMix = mix(attenuation * pow(clampedCosine, light.spotExponent),0.0,clampedCosine < cos(light.spotCutoff * 3.14159 / 180.0));//if outside of spotlight nothing
    attenuation = mix(attenuation,tempMix,light.spotCutoff <= 90.0);

    //should there be any attenuation ?
    attenuation = mix(attenuation,1.0,light.position.w);

    //------------------------------ ambiant light
    vec3 ambientLight = vec3(ambientScene)*vec3(mat.Ka);

    //------------------------------ specular light
    //get the reflection
    vec4 specularMapPixel = texture2D(spec_tex, f_texcoord).rgba;
    vec3 specularColor = specularMapPixel.rgb;
    float shininess = specularMapPixel.a;
    vec3 specularReflection = mix(
    attenuation * vec3(light.specular) * vec3(mat.Ks)* pow(max(0.0, dot(reflect(-lightDirection, normalDirection), viewDirection)),mat.Ns*shininess) *specularColor.rgb,
          vec3(0.0, 0.0, 0.0),
          dot(normalDirection, lightDirection) < 0.0
          );

    vec3 diffuseReflection = attenuation*
    vec3(light.diffuse)*vec3(mat.Kd)
    *max(0.0,dot(normalDirection,lightDirection));

    vec4 Color = vec4(vec4(specularReflection,1.0) + vec4(ambientLight,1)*texture2D(amb_tex, f_texcoord) + vec4(diffuseReflection,1.0)*texture2D(dif_tex, f_texcoord));

    FragColor = Color;
}

Vertex Shader Code :

void main()
{
    //comnpute tangent space
    tangenteSpace[0] = mat3(mv)*normalize(tangent.xyz);
    tangenteSpace[2] = mat3(mv)*normalize(vertNormal);
    tangenteSpace[1] = mat3(mv)*normalize(cross(tangenteSpace[0],tangenteSpace[2])*tangent.w);
    tangenteSpace = transpose(tangenteSpace);

    //position in world space
    position = m * vertCoord;
    f_texcoord = vec2(texCoord);

    gl_Position = mvp * vertCoord;
}


texts:
I'm creating a 2D platformer game with HTML5 canvas and javascript. I'm having a bit of a struggle with animations. Currently I animate by getting preloaded images from an array, and the code is really simple, in player.update() I call a function that does this:

var animLength = this.animations[id].length;
this.counter++;
this.counter %= 3;
if (this.counter == 2) this.spriteCounter++;
this.spriteCounter %= animLength;
return this.animations[id][this.spriteCounter];

There are a couple of problems with this one: When the player does 2 actions that require animating at the same time, animation speed doubles. Apparently this.counter++ is working twice at the same time. I imagine that if I start animating multiple sprites with this, the animation speed will multiply by the amount of sprites. Other issue is that I couldn't make the animation run only once instead of looping while key is held down.

Someone told me that I should create a function Animation(animation id, isLooped boolean) and the use something like player.sprite = new Animation("explode", false) but I don't know how to make it work.


texts: Adding a video to a Level in a Portal 2 Mod

texts:
I'm currently working on my Portal 2 mod and I'd like to add a video to be displayed on a projector like the Dollar$ and SENSE video at the end of Portal 1. Currently what I have is a simple recreation of a room in The Fall chapter of Portal 2, and I want to have a video displayed on the projection screen.

If anyone could give me instructions, or point me a link on how to do this that would be great.


texts: Game Loop design that is speed hack proof

texts:
I'm not sure if this is possible, but it's worth a shot asking. How does one design a game loop in such a way that hooking and enabling a speed hack app to the game(dx11) doesn't matter?
I found this in stackoverflow:

I think the reason why i does not work in some applications (mostly games) is because some games link the in game clock to the frames per second. Therefore your game will either tank or crash altogether if you try to speedhack it
ref: https://stackoverflow.com/questions/17512906/how-does-cheatengines-speed-hack-work


texts: Using gametime.ElapsedGameTime to trigger an event

texts: I have a splashscreen object that waits for a user input before loading the next screen, but I would also like the next screen to load after a certain amount of time has passed. I tried adding a check to see if the elapsed game time is greater than or equal to a set amount of time in seconds. The user input still changes the screen, but the screen will not change after that time requirement has been met. What am I doing wrong?


texts: Press button event instead of onClick() in Unity

texts:
I want to add a nitro in my arcade game and i want to detect press UI button instead of click. unfortunately only onClick() event is available for UI button

what kind of options do I have ?

Thank you


texts: Is it possible to add a sprite to a joint?

texts:
I want to have a joint between two objects, but I also want to highlight to the user that these two objects are connected together.

I am assuming this isn't the correct method, as a joint is just a component.

Note: I am a total Unity newbie.

I just want some method to indicate to a user which items are jointed together.

A code solution is totally fine - I am very comfortable programming. Maybe extending the joint class and adding a sprite selector?


texts: How can I make an OpenGl/GLSL varying vary throughout a quad instead of a triangle in OpenGl 3.3?

texts:
I am, like many others, currently working on a block-based game in C++ and OpenGl. Recently, I added ambient occlusion support. This ambient occlusion is created by modulating the brightness of a point on the face of a block by an OpenGl varying from each corner. The corner's darkness is proportional to the amount of blocks that intersect that corner. This usually works very well, as can be seen in this screenshot:

It does create some artifacts, however. One good example is seen at the base of a tree trunk:

In this example, the size of the pseudo-shadow varies based on the orientation of the triangles around the chunk as described here:

  Notice that the ambient occlusion is different for the vertices on the
  side than it is for the vertices on the top and bottom.  To fix this,
  we just need to pick a consistent orientation for the quads.  This can
  be done by comparing the ambient occlusion terms for each quad and
  selecting an appropriate orientation.

Their proposed solution, however, is not of the kind that I prefer. It seems more like a trick to cover up the fact that the varyings aren't being interpolated over the whole quad, as opposed to a real solution. As such, I thought that it may work to render with GL_QUADS instead of GL_TRIANGLES, as perhaps that would allow the varyings to vary as I want. Unfortunately, this is not possible in the version of OpenGl that I am targeting (3.3 core). As such, I ask: how can I interpolate the varying values (eg. the brightness) over a quad instead of a triangle? Is there some algorithm that I can use to change the brightness value at each corner of a quad to produce the same result? I have tried searching for this via a search engine, but no useful results came up.


texts: Drawing chunks, and positioning the camera

texts:
I've seen many questions and answers regarding how to draw tiled maps but I can't really get my head around it. Many answers suggest either loading the visible part of the map, or loading and unloading chunks of the map. I've decided the best option would be to load chunks, but I'm slightly confused as to how this would be implemented.

Currently I'm loading the full map to a 2D array of buffered images, then drawing it every time repaint is called. Q1: If I were to load chunks of the map, would I load the map as a whole then draw the necessary chunk(s), or load & unload the chunks as the player moves along, and if so, how?

My second question regards the camera. I want the player to be in the centre of the X axis and the camera to follow it. I've thought of drawing everything in relation to the map and calculating the position of the camera in relation to the players coordinates on the map. So, to calculate the camera's X position I understand that I should use cameraX = playerX - (canvasWidth/2), but how should I calculate the Y position? I want the camera to only move up when the player reaches cameraHeight/2 but to move down when the player reaches 3/4(cameraHeight). Q2: Should I check for this in the same way I check for collision, and move the camera relative to the movement of the player until the player stops moving, or am I thinking about it in the wrong way?


texts: Real-Time Speech & Verbal Communication with a Mecanim Character

texts:
What would be the simplest method of integrating real-time verbal communication within a mecanim character that is already being used in a Unity app/project? Something like an SDK or toolkit?

I have such a character that is animated by a motion-capture device, so the user puts on the suit and the Unity character is driven by receiving live motion data. This is the non-verbal part for research in Social Sciences & Psychology.

I tried integrating the Virtual Human Toolkit into my Unity app to use its real-time speech & lip sync & facial gestures, but their character is set up in a complicated way, so I still cannot animate it by using my motion-capture device.

So, now I am thinking what is the next best thing to do with a Unity mecanim character to make it say something, etc...?


texts: How to implement D&D 4e's line of sight algorithm?

texts:
D&D 4th Edition (the tabletop game) has combat on a 2D map with square tiles. A creature occupies an entire single tile.

The attacker has clear sight on the defender if lines can be drawn from one corner of the attacker's square to all four corners of the defender's square and none of these lines are blocked.

The rules are as follows:

  To determine if a target has cover, choose a corner of your square and trace
  imaginary lines from that corner to every corner of the target's square. If one or two of those lines are blocked by an
  obstacle, the target has cover. (A line isn’t blocked if
  it runs along the edge of an obstacle’s or an enemy’s square.) If
  three or four of those lines are blocked but you have line of effect,
  the target has superior cover.

So, in the following situation:

A can fully see B, but C has superior cover from A (the unblocked line is from topright corner of A to topright corner of C), and A cannot see D at all.
B can fully see A, C and D.

How can I implement this?

Over the years, I have tried several solutions: some forms of Bresenham's line, testing for walls pixel by pixel, giving some tolerance around corners, and even dividing the map into line segments and comparing rays from the attacker to these line segments using a line-intersection formula. But everything either wasn't sufficiently rules-accurate or was too computationally expensive.

Can this line-of-sight algorithm be implemented efficiently (enough so that hundreds of checks may be performed for maps of 100x100 tiles per second) and accurately, and if so, how?


texts:
I'm trying to deactivate an GameObject when a certain variable reaches a certain value.
It is an imported FBX and doesnt have a MeshRenderer. I'm trying to stop it now with TheGameObject.gameObject.activate = false; then nothing happens.

Is there any other way to do this or fix this?


texts: Twine Harlowe: Can I create passage links with the gui? Or any alternative way?

texts:
I'm confused how I am expected to organize and write a story within Twine using just the tools outlined in the manual. The main concern revolves around initiating links between my squares/charts/whatever (the passage link system). Am I expected to always manually type [[]] with the correct name of the passage to assign any flow of passage?

I see this as being problematic when designing a story, as you would need to consistently re-position/delete/add-new squares to tell the story properly. I am confused why the gui doesn't seem to support the drop and drag between existing flow arrows? OR does it..? Going in and manually changing the names of everything each time I have to change a position...and needing to use a brand new name cause the existing name won't overwrite or swap. Some people seem to recommend ordering the passage titles by number, but this creates the very problem I am outlining where when changing the position of 3 and 4 you'd have to use like some offbrand title, and do about 8 steps just to swap positions.

Am I supposed to use a different program instead when concocting my story and only use twine once I know where everything goes? Doesn't that defeat the point of it to begin with?


texts: Math needed to create a very simple 2D side view car game

texts:
I'm trying to create a 2D side view car game (something like Hill Climb Racing, but much more simpler), but I'm confused on the math and physics.

Most of the tutorials I found were about making a top-down view game. The rest referred to the Unity3D engine, which does all the math behind the scenes and uses complex objects, whereas I'd like to achieve my goal using simple objects, such as 2D vectors and abstract them on my own (that is, without any game engine).

The project I'm working on assumes that a car is a rectangle with 2 wheels, which are ellipses. It doesn't need to brake, turn back and speed up, it should just go straight ahead (and eventually stop in case it looses all of its velocity).

An example terrain the car would be driving on:

I can't figure out how to move the car on an irregular terrain, as well as how to rotate and move it when it falls from a hillock, etc.

Have you any idea how to move and rotate the car with respect to its current position and velocity?


texts: Dynamic vs Kinematic, do either of these cause a collision before OnCollisionEnter2D?

texts:
Firstly, it would be a great deal of help if someone could explain to me the differences between Dynamic, Kinematic and Static (especially if there is a box for static by the name of the object. I've looked at the APIs and tried playing around with them, they are so confusing. :/

Secondly, I understand that the physics engine evaluates first and can cause a collision (when the ball hits the paddle in my Pong game) but is there a way around this? I'm trying to send the ball in the opposite direction to which it hit the paddle by using OnCollisionEnter2D but this method gets called second and therefore the ball changes direction twice and the physics engine causes an unnecessary collision...

I have looked to tutorials on the movement in pong and tried following the tutorials but get the same problem (even though their game is faultless), this leads me to think that it's the Body Type property that is causing the physics engine to produce the extra collision because theirs is an older unity version. It could possibly be the bouncy material with no friction also, I don't know much purely because I'm a newbie to unity. I wonder whether anyone has had the same problem as me and can set me free.

Thanks in advance. I seriously appreciate any help I can get! :)


texts: Do I need to call Release() on D3D objects when I use them in another function?

texts:
For example, I have an IDirect3DSurface9 * Surface and IDirect3DSurface9 *BackBuffer.

If I were to use them directly in the render_frame function, I would need to release them on the closeD3D function. However, if I use them in a function in same file or in another .h and .cpp file, when I call Release in closeD3D it gives me an error.

So, do I not need to release them if I'm using them in a function, or am I doing something wrong?


texts: How can I customize the DefaultInput.ini?

texts:
I need to make some bindings false.  The ones are:
.Bindings=(Name="W", Command="GBA_MoveForward") and the same for S, A, D, LEFT, RIGHT, and LeftControl.


texts: Sending RPC calls from server to client inside Unity

texts:
In my game inside Unity, I have two scenes setup. One for the main server ( acts like authoritative server ) and the other scene for my client. The game starts once my client connects to the server.

Now I am able to send RPC function calls from my scripts in my client scene to the server but I am not able to do it the other way around.

** Further edit to my code after comments **
*********** This is my client side script attached to GameObject CursorDetection inside Scene2 *****

 using UnityEngine;
    using System.Collections;

    // ON THE CLIENT SIDE
    public class CursorDetectionScript : MonoBehaviour {

        private bool hasGameStarted = false;
        void Update()
        {
           if (Input.GetMouseButtonDown(0))
           {
              networkView.RPC("mouseDown", RPCMode.Server,true);
           }
        }

        [RPC]
        public void mouseDown(bool isMouseDown)
        {

        }

    }

**** On the server side script inside scene1 *******

private void OnPlayerConnected(NetworkPlayer player)
{
    Debug.Log(" PLAYER CONNECTED " +player);
    networkView.RPC("AddNetworkPlayer", RPCMode.AllBuffered, player);
}

[RPC]
public void AddNetworkPlayer(NetworkPlayer player)
{
    playersList.Add(player);
    Debug.Log(" FIRST PLAYER IS " + playersList[0]);
}

 if(startGame)
 {
    networkView.RPC("SendMessageToClient1", RPCMode.AllBuffered, playersList[0]);
 }

[RPC]
public void mouseDown(bool isMouseDown, NetworkMessageInfo sender)
{
    isMouseDown = true;
    Debug.Log("CAN PLACE PANELS NOW" + " VIEW IS " + sender.sender.guid);
}

**** back on the client side script inside scene2 I called the SendMessageToClient1 function call *******

[RPC]
public void SendMessageToClient1()
{
    Debug.Log(" INSIDE CLIENT 1 ");
}


texts: How do I sample a cubic shadow map in DirectX 11?

texts:
I've implemented a cubic shadow map for dealing with omni-directional light sources in my scene. By defualt it produces hard shadows

Obviously a shadow map with higher resolution (currently using 512x512) would produce a finer edge but that would also result in larger memory footprint for the application.

I'm currently using a very simple approach to sample the cubic shadow map using the TextureCube::SampleCmp method

float depthBias = 0.002f;
float shadowFactor = omniShadowMap.SampleCmp( omniShadowSampler, -lightVec, lightVecLength / pointLight.positionAndRadius.w - depthBias );

if( shadowFactor == 0.0f )
    shadowFactor = 0.5f;

return float4( ( finalDiffuse + finalSpecular.xyz  ) * shadowFactor , 1.0f );

The SamplerComparisonState is configuered like this

D3D11_SAMPLER_DESC samplerDesc;

samplerDesc.Filter = D3D11_FILTER_COMPARISON_MIN_MAG_MIP_POINT;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.MipLODBias = 0;
samplerDesc.MaxAnisotropy = 1;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_LESS_EQUAL;
samplerDesc.BorderColor[0] = 0.0f;
samplerDesc.BorderColor[1] = 0.0f;
samplerDesc.BorderColor[2] = 0.0f;
samplerDesc.BorderColor[3] = 0.0f;
samplerDesc.MinLOD = 0.0f;
samplerDesc.MaxLOD = 0.0f;

One approach would be to use Percentage-Closer Filtering but I don't know how to access the texels in a TextureCube.

Any suggestions? Thank you!


texts: What datastructure would you use for a collision-detection in a tilemap?

texts:
Currently I save those blocks in my map that could be colliding with the player in a HashMap (Vector2, Block). So the Vector2 represents the coordinates of the blog.

Whenever the player moves I then iterate over all these Blocks (that are in a specific range around the player) and check if a collision happened.

This was my first rough idea on how to implement the collision-detection. Currently if the player moves I put more and more blocks in the HashMap until a specific "upper bound", then I clear it and start over.

I was fully aware that it was not the brightest solution for the problem, but as said, it was a rough first implementation (I'm still learning a lot about game-design and the data-structure).

What data-structure would you use to save the Blocks? I thought about a Queue or even a Stack, but I'm not sure, hence I ask.


texts:
I currently try to rotate a camera (using gluLookAt()) around a point  , i successfully do it for rotating around one global axis.

But when i want to use more than one axis , I'm stuck . I've searched around and it's seem i need to use something like axis-angle or quaternion (that i don't understand at all for now)

for rotating my camera i have 3 angles (using accelerometer and geomagnetic values).

How can i determine the point of view , using three angle and the radius ? knowing the the camera itself is at the point of origin (0,0,0).

I prefer using gluLookAt() than moving the whole scene if possible(event if i know that almost the same thing).


texts: How can I edit multiple sprites in Sprite Editor at once?

texts:
I have 100 sprites in one atlas. I want to edit some of them with same values.

For example, I want to edit sprite's position no 1 ~ 30. Do I have to edit them one by one?

Is there any function like Shift + drag for selecting several sprites?


texts: How can I organize render and transformation data in a scalable fashion?

texts:
I am writing for OpenGL 2.0 and in the future porting to OpenGL ES 2.0. I only use VBOs and shaders (no immediate mode, no vertex arrays).

I already have working solutions, they just... feel wrong. All my calls related to OpenGL are tucked away in a separate class called RenderManager (this includes creation of VBOs and IBOs, texture IDs and shader programs) and rendering. I called the creation of OpenGL objects logging in and out, so majority of this action is invoked from the ResourceManager object upon loading of data. However, a lot of geometry (level) is generated dynamically and therefore some RenderManager calls to create the VBOs/IBOs is scattered throughout the level class.

Now, I have a Renderable interface which returns the (single) transformation matrix and a RenderOp object when it is time for rendering. RenderOps is an object that has Vertex/Index Buffer pointers (has actual geom. data which in turn has VBO/IBO indices) and some parameters such as whether to use the index buffer and if the RenderOp needs blending and stuff.

There is also the RenderView object; it has the viewport parameters, projection matrix and view matrix (camera).

The game objects reside in the World class (single-dimension arrays). These game objects are added upon their creation, and are derived from Entity interface. Entity is able to  return the number of Renderable-type objects within as well as the actual pointer to a Renderable at a given index.

The magic happens when the main loop traverses the World. First it collects all Light objects visible from within Frustum. Then it collects Entity object that's within Frustum (it gets added to std::vector inside RenderView if it is), and then it checks that same object to see if it is inside any of the visible Light's bounding volumes (and gets added into Light's std::vector).

Then the RenderView is passed onto the RenderManager class, which  extracts appropriate Renderables from each Entity, applies Renderable's shader, then applies Renderable's textures, then stores the transforms inside itself and promptly shoves them down the programmable pipeline's throat along with attributes stored inside the RenderOperation (that gets extracted from Renderable as well).

Last note - I have NO way to render debug data, which is extremely annoying.

A lot of what I am doing feels wrong. My question is, how do you organize all your Renderable and Transformation data to facilitate your rendering needs? I am burning out thinking of semi-flexible ways of managing this data and I want to hear your ways. I am not a big fan of scene graphs, and consequently don't really want to implement one as I feel there are no real hierarchies inside the game, but I feel like I'm running myself into a corner.

Please throw me a bone here, how do you manage all this data? And if you suggest an event based rendering system, how would you design it?


texts:
I have a sphere that represents the Earth textured with real pictures.
It's rotating around the x axis, and when user click down it has to show me the exact place he clicked on.
For example if he clicked on Singapore the system should be able to:

understand that user clicked on the sphere (OK, I'll do it with unProject)
understand where user clicked on the sphere (ray-sphere collision?) and take into account the rotation
transform sphere-coordinate to some coordinate system good for some web-api service
ask to api (OK, this is the simpler thing for me ;-)

some advice?


texts:
How to calculate, in 3D environment, the closest point, from which an AI character can jump onto a platform?

Setup

I have an initial velocity V(Vx,Vy,VZ) and a spot where the character stands still at S(Sx,Sy,Sz). What I'm trying to achieve is a successful jump on a spot E(Ex,Ey,Ez) where you have clicked on(only lower or higher spot, because I've in place a simple steering behavior for even terrains). There are no obstacles around.

I've implemented a formula that can make him jump in a precise way on a spot but you need to declare an angle: the problem arise when the selected spot is straight above your head. It' pretty lame that the char hang there and can reach a thing that is 1cm above is head. I'll share the code I'm using:

    Vector3 dir = target - transform.position;  // get target direction
    float h = dir.y;  // get height difference
    dir.y = 0;  // retain only the horizontal direction
    float dist = dir.magnitude ;  // get horizontal distance
    float a = angle * Mathf.Deg2Rad;  // convert angle to radians
    dir.y = dist * Mathf.Tan(a);  // set dir to the elevation angle
    dist += h / Mathf.Tan(a);  // correct for small height differences
    // calculate the velocity magnitude
    float vel = Mathf.Sqrt(dist * Physics.gravity.magnitude / Mathf.Sin(2 *a));
    return vel * dir.normalized;

Ended up using the lowest angle (20 degree) and checking for collision on the trajectory. If found any increase the angle. Here some code (to improve the code maybe must stop the check at the highest point of the curve):

Vector3 BallisticVel(Vector3 target, float angle)
    {
        Vector3 dir = target - transform.position;  // get target direction
        float h = dir.y;  // get height difference
        dir.y = 0;  // retain only the horizontal direction
        float dist = dir.magnitude ;  // get horizontal distance
        float a = angle * Mathf.Deg2Rad;  // convert angle to radians
        dir.y = dist * Mathf.Tan(a);  // set dir to the elevation angle
        dist += h / Mathf.Tan(a);  // correct for small height differences
        // calculate the velocity magnitude
        float vel = Mathf.Sqrt(dist * Physics.gravity.magnitude / Mathf.Sin(2 * a));
        return vel * dir.normalized;
    }

    Vector3 TrajectoryPoint(Vector3 startingPosition, Vector3 startingVelocity, float n )
    {
         float t = 1/60 ; // seconds per time step
      Vector3 stepVelocity = t * startingVelocity; // m/s
      Vector3 stepGravity = t * t * Physics.gravity; // m/s/s

      return startingPosition + n * stepVelocity + 0.5f * (n*n+n) * stepGravity;
    }

    bool CheckTrajectory(Vector3 startingPosition,Vector3 target, float angle_jump)
    {
        Debug.Log("checking");
        if(angle_jump < 80f)
        {
            Debug.Log("if");

            Vector3 startingVelocity = BallisticVel(target, angle_jump);

            for (int i = 0; i < 180; i++)
            {
                //Debug.Log(i);
                Vector3 trajectoryPosition = TrajectoryPoint( startingPosition, startingVelocity, i );

                if(Physics.Raycast(trajectoryPosition,Vector3.forward,safeDistance))
                {
                    angle_jump += 10;
                    break; // restart loop with the new angle
                }
                else
                    continue;

            }

                return true;
                JumpVelocity = BallisticVel(target, angle_jump);
            }

        return false;
    }


texts: How to handle MANY enemies in networked P2P game?

texts:
Let's suppose a game of 4 players, one is the host.

They will fight many enemies, along the lines of 20-40 at the time. Among other things like sending their own state to the other players (position, rotation, shot this frame, crouched, etc). How do I handle the enemies?

Do the host "decides" the enemies state? (again position, rotation, isattacking, etc). And then sends several messages to the other players so they sync their own game? or do I "divide" the enemies, lets say 40, and 4 players, 10 enemies "controlled" by each player game? and then, each player sends those messages to the other players so all enemies are in sync?

Also, should I group the messages and send one big message instead of 40 little ones? How do I know how big can the message be (how many enemies info in each message)?

Basically I'm asking whats the best way to handle a 4 player p2p game with many enemies on screen.

Any good tip is appreciated.


texts: How to animate a MeshRenderer color in Unity 3D?

texts:
I need to animate MeshRenderer.material.color.a, but fail.

Code:

    private void Method()
{
    AnimationClip clip = new AnimationClip();
    AnimationClipPlayable playable = AnimationClipPlayable.Create(clip);

    AnimationCurve alpha = AnimationCurve.Linear(0, 1, 1, 0);
    clip.SetCurve("", typeof(MeshRenderer), "Material._Color.a", alpha);

    //gameObject.GetComponent<MeshRenderer>().material.SetColor("_Color", Color.red); // Works
    gameObject.GetComponent<Animator>().Play(playable); // Doesn't work
}


texts: Unity SkinnedMeshRender: is there a way to cache mesh and restore later?

texts:
In unity, I'm writing a script that deforms a mesh associated with a SkinnedMeshRenderer pretty significantly. However, at some point, I'd like to reset it back to particular states. I'd like the ability to both reset to its original position, and an intermediate position.

Right now, I've tried baking the mesh:

Mesh originalMesh = new Mesh();
skinnedMeshRenderer.BakeMesh(originalMesh);

But when I then try to restore it:

skinnedMeshRenderer.sharedMesh = originalMesh;

It doesn't seem to behave as I would have expected.

I've also tried:

Mesh originalMesh = skinnedMeshRenderer.sharedMesh;
//deform sharedMesh
skinnedMeshRenderer = originalMesh;

but this does nothing since it seems to be just storing a reference.

Am I missing something obvious here?

Just to add detail, I want to take a snapshot of all the verticies, weights, blendshapes, etc. And then restore everything back to the snapshot at a later moment in time. I can reset the blendshapes fine, but the mesh seems to be messed up.


texts:
I have drawn a line on sprite representing the string of a bow. I want to stretch it with finger touch input, using onTouch. I have added a Physics body but I don't understand how to stretch the line.

It's a bow and arrow demo:

Here is the code I use:

protected Scene onCreateScene() {
        this.mEngine.registerUpdateHandler(new FPSLogger());
        mScene = new Scene();
        mScene.setBackground(new Background(0.3f, 0.8f, 0.9f));
        float centerX = CAMERA_WIDTH/2;
        float centerY = CAMERA_HEIGHT/2;

        Sprite sprite = new Sprite(centerX,centerY,this.regionBow, this.getVertexBufferObjectManager());
        mScene.attachChild(sprite);

        PhysicsWorld physicsWorld = new PhysicsWorld(new Vector2(0, 300), false);
        Line line = new Line(99, 10, 99, 240, 4, getVertexBufferObjectManager());
        line.setColor(0f,0f,0f);

        FixtureDef lineFixtureDef = PhysicsFactory.createFixtureDef(1, 4f, 0.5f);
        Body body = PhysicsFactory.createLineBody(physicsWorld, line, lineFixtureDef);
        mScene.getLastChild().attachChild(line);

        PhysicsConnector physicsConnector = new PhysicsConnector(sprite, body, true, true);
        physicsWorld.registerPhysicsConnector(physicsConnector);

        mScene.setOnAreaTouchListener(new IOnAreaTouchListener() {
            @Override
            public boolean onAreaTouched(TouchEvent pSceneTouchEvent, ITouchArea pTouchArea, float pTouchAreaLocalX, float pTouchAreaLocalY) {
                return false;
            }
        });

        return this.mScene;
    }


texts: Unity "Text Mesh Pro UGUI" component rewrites my text! Make it stop?

texts:
I'm having this terribly annoying problem where my text is being overwritten by Unity. This Happens regardless of whether I am using tags or not.

Here is what I want to appear (more or less, I don't think this example is using the tag):

And here is what happens when I try to include a monospace tag:

Since you might not see it here, the text I inputed is

<mspace=64px>A</mspace>

This works FINE for regular TMP objects, which the other 3 are (and are using). I am trying to implement dropdown (and left, and up, and right) menus.

You can see that Unity overwrites it as "Option A", like it has a clue what I'm doing. What can I do?


texts:
Im trying to, in cocos2d for the iPhone, move a CCSprite (in this case "player" up and down (the app is in landscape). How can I accomplish this? I have been unable to do so. ex.

-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    player.position.x = acceleration.x * 10;
    NSLog(@"Accelerometer x value is %f\n", acceleration.x);
}


texts: OpenGL ES 1.0 to OpenGL ES 2.0, I cant draw a square

texts:
I am learning open GL ES 2.0 and I just made 1 easy game for 1.0

I am following tutorials but I cant understand this thing

In OpenGL ES 1.0 if I define a square that way:

private float[] vertices = { // Vertices for a face
0.0f, 0.0f, 0.2f, // 0. left-bottom-front
1.0f, 0.0f, 0.2f, // 1. right-bottom-front
0.0f, 1.0f, 0.2f, // 2. left-top-front
1.0f, 1.0f, 0.2f // 3. right-top-front
};

and draw it that way  it Works

public void draw(GL10 gl)
{

    gl.glFrontFace(GL10.GL_CCW); // Front face in counter-clockwise
                                    // orientation
    gl.glEnable(GL10.GL_CULL_FACE); // Enable cull face
    gl.glCullFace(GL10.GL_BACK); // Cull the back face (don't display)

    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
    gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); // Enable
                                                            // texture-coords-array
                                                            // (NEW)
    gl.glTexCoordPointer(3, GL10.GL_FLOAT, 0, texBuffer); // Define
                                                            // texture-coords
                                                            // buffer (NEW)

    gl.glEnable(GL10.GL_BLEND);
    gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

    // front
    gl.glBindTexture(GL10.GL_TEXTURE_2D,TextureLoader.TeclaBlancatextureIDs[0]);

    gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);

    gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); // Disable
                                                            // texture-coords-array
                                                            // (NEW)
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDisable(GL10.GL_CULL_FACE);
    gl.glDisable(GL10.GL_BLEND);
}

but in OpenGL ES 2.0 if I do this that way( with the same vertex) it only write a triangle:

private void drawSuelo(Suelo suelo)
{
    // Pass in the position information
    suelo.mPositions.position(0);
    GLES20.glVertexAttribPointer(mPositionHandle, mPositionDataSize, GLES20.GL_FLOAT, false,
            0, suelo.mPositions);

    GLES20.glEnableVertexAttribArray(mPositionHandle);

    // Pass in the color information
    suelo.mColors.position(0);
    GLES20.glVertexAttribPointer(mColorHandle, mColorDataSize, GLES20.GL_FLOAT, false,
            0, suelo.mColors);

    GLES20.glEnableVertexAttribArray(mColorHandle);

    // Pass in the normal information
    cubo.mCubeNormals.position(0);
    GLES20.glVertexAttribPointer(mNormalHandle, mNormalDataSize, GLES20.GL_FLOAT, false,
            0, cubo.mCubeNormals);

    GLES20.glEnableVertexAttribArray(mNormalHandle);

    // This multiplies the view matrix by the model matrix, and stores the result in the MVP matrix
    // (which currently contains model * view).
    Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, mModelMatrix, 0);

    // Pass in the modelview matrix.
    GLES20.glUniformMatrix4fv(mMVMatrixHandle, 1, false, mMVPMatrix, 0);

    // This multiplies the modelview matrix by the projection matrix, and stores the result in the MVP matrix
    // (which now contains model * view * projection).
    Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0);

    // Pass in the combined matrix.
    GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix, 0);

    // Pass in the light position in eye space.
    GLES20.glUniform3f(mLightPosHandle, mLightPosInEyeSpace[0], mLightPosInEyeSpace[1], mLightPosInEyeSpace[2]);

    // Draw the cube.
    GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 6);
}

It seems to need all of this vertex in order to draw a square

final float[] PositionData = {

// Top face
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f };

Why is happening this? Why I am missing? Is there any way in Open GL ES 2.0 to write a square with 4 vertex?


texts: How do I make a MoveToward() GameObject jump without Rigidbody, CharacterController or Raycast?

texts:
I have a prefab that is moving from one point to another thanks to  MoveTowards().

Currently, I am having trouble with a functionality where the player can press a button and make the object jump, affecting only the Y coordinate.

I tried doing the following before putting the MoveTowards() code down:

void Start()
{
    playerInstance = Instantiate(playerPrefab, startPos.position, Quaternion.LookRotation(endPos.position), null);
    speed = Random.Range(2f, 8f);

    currentPlayerInstancePositionY = playerInstance.transform.position.y;
    isGrounded = true;
}

void Update()
{
    if (isGrounded)
    {
        if (Input.anyKeyDown)
        {
            playerInstancePositionY = jumpForce;
        }
        else
        {
            playerInstancePositionY = currentPlayerInstancePositionY;
        }
    }
    else
    {
        playerInstancePositionY -= gravity * Time.deltaTime;
    }

    currentPlayerInstancePositionY = playerInstancePositionY;

    playerInstance.transform.position = Vector3.MoveTowards(playerInstance.transform.position, endPos.position, speed * Time.deltaTime);

I just used custom gravity to decide when the object falls. But the problem I found was that MoveTowards() takes a Start Position, an End Position and a Float in its method. But it cannot change individual coordinate values.

As the only control you have over the object is making it jump, I was wondering if there was another way to implement this since the Y value is not being inserted into the prefab before it is given the MoveTowards() function. I am trying to implement the jump mechanic without any RigidBodies, CharacterControllers or Raycasts.

Any help would be appreciated.


texts: 3DS Max equivalent to vertex weight painting

texts:
I'm working in 3ds max on models for an Iphone game project and finding that using the Physique modifier is to general for rigging. When working with so few vertices I want to be able to directly tell how much weight a bone should have on a specific vertex.

Is there a 3ds max equivalent to the Softimage XSI vertex weight painting? As this would be perfect for this job.

Many thanks


texts: Using The Box2D Polygon "Set()" function?

texts:
I'm using the Box2D physics engine. And there's a type of shape for box2D called b2PolygonShape.

In this class, you can create polygons. There is also a Set() function that takes an array of points and a vertex count.

Box2D has an example like this:

// This defines a triangle in CCW order.

b2Vec2 vertices[3];

vertices[0].Set(0.0f, 0.0f);

vertices[1].Set(1.0f, 0.0f);

vertices[2].Set(0.0f, 1.0f);

int32 count = 3;

b2PolygonShape polygon;

polygon.Set(vertices, count);

This works. Yet when I tried to practice and mess with this function, I did this:

  b2Vec2 vertices[4];

  vertices[0].Set(0, 0);
  vertices[1].Set(0,10);
  vertices[2].Set(10,10);
  vertices[3].Set(10,0);

  int32 count = 4;

  b2PolygonShape polygon;

  polygon.Set(vertices, count);

When I compiled and ran this, it crashed after the Set() function. Wouldn't this create a square?

Also in the console I got this:

Assertion failed: s > 0.0f

What did I do wrong?


texts: Unity color transparency is affecting image transparency

texts:
I am building a chess board in Unity.
I have a Grid Layout component made out of 64 Single_Field PreFabs.
I instantiate the field like this
public GameObject[,] fields = new GameObject[9,9];
public GameObject field;
public GameObject fieldParent;

//double for loop over I,J,
GameObject newField = Instantiate(field);
fields[i, j] = newField;
newField.transform.SetParent(fieldParent.transform, false);

Then outside of the loop I do
    fields[3, 4].GetComponentInChildren<Single_Field>().pieceSprite.GetComponentInChildren<Image>().sprite = blackPieceImages[0];

Nothing shows up. Because the color of the prefab where the piece image will be has a transparency of zero.
If I add this line,
    fields[3, 4].GetComponentInChildren<Single_Field>().pieceSprite.GetComponentInChildren<Image>().color = Color.white;

Then the piece shows up exactly correct, with the chess board behind it.
However, if I start out by making the prefab non-transparent, it covers my whole chessboard with squares.
Any ideas?


texts: Player won't move correctly due to gravity force pushing him into the ground

texts:
I am making a tilemap platformer with pygame ad I defined the X and Y movement for the player and also a Y force that represents the gravity force to make it jump correctly. However, when my player falls off to the ground and the game begins, it doesn't move correctly neither to the right nor to the left direction due to the gravity force that keeps pushing him to the down. In addition to that, when the player jumps and i move it to the right, it's like it doesn't recognize the collision with the bottom rect of the wall (see gif below for a visual explanation of that).

I tried disabling that gravity force when the player hits the ground and enable it when the player jumps but it didn't work as expected and I've got problems managing collisions (also, it doesn't make sense to disable gravity, right?)

Here's a gif of the issue i'm facing with:

Here's my Player class:

class Player(pg.sprite.Sprite):
    def init(self, game, x, y):
        self.groups = game.sprites
        pg.sprite.Sprite.init(self, self.groups)

    self.game = game

    self.image = pg.Surface((TILESIZE, TILESIZE))
    self.image.fill(GREEN)
    self.rect = self.image.get_rect()

    self.move_left = self.move_right = False

    self.pos = pg.math.Vector2(x, y)
    self.acc = pg.math.Vector2(0, GRAVITY)
    self.vel = pg.math.Vector2(0, 0)

def jump(self):
    self.vel.y -= 3

def update(self):
    self.vel.x = 0

    if self.move_left:
        self.vel.x = -PLAYER_SPEED
    if self.move_right:
        self.vel.x = PLAYER_SPEED

    self.vel += self.acc

    self.pos += self.vel
    self.rect.x = self.pos.x * TILESIZE
    self.rect.y = self.pos.y * TILESIZE

    if self.vel.y > 0.5:
        self.vel.y = 0.5

    hits = pg.sprite.spritecollide(self, self.game.walls, False)
    if hits:
        if self.vel.x > 0:
            self.pos -= self.vel
            self.rect.right = hits[0].rect.left
            self.vel.x = 0
        if self.vel.x < 0:
            self.pos -= self.vel
            self.rect.left = hits[0].rect.right
            self.vel.x = 0

    hits = pg.sprite.spritecollide(self, self.game.walls, False)
    if hits:
        if self.vel.y > 0:
            self.pos -= self.vel
            self.rect.bottom = hits[0].rect.top
            self.vel.y = 0
        if self.vel.y < 0:
            self.pos -= self.vel
            self.rect.top = hits[0].rect.bottom
            self.vel.y = 0


texts: I made more than 10 robots. all of them had not less than 4 materials, and some had 12 materials. I can't go back and fix this. How this will effect on the game performance later ?


texts: How can I have parent-child transform in a component system?

texts:
Before when using inheritance, I could draw all my objects using this recursive function:

void Object::innerDraw(sf::RenderTarget& target, sf::RenderStates states)
{
    states.transform *= Object::getTransform(); //translate by this object's position
    this->Draw(target, states); //draw this object
    for (Object *child : m_children)
    {
        if(child->isVisible)
            child->innerDraw(target, states); //draw all children
    }
}

However, I am now looking at a component design where the graphics component pushes it's sprite to the renderer   Renderer::toDraw.push_back(&sprite);

The renderer then draws all the sprites in it's container

for (sf::Drawable *Entity : toDraw)
{
    target.draw(*Entity, state); // (state isn't doing any transforming here)
}

How can I be able to draw things relative to parents position?


texts: Animating object, setting isKinematic=false, and then letting physics take over

texts:
I'm trying to create a "tree felling" effect, where the tree trunk falls over after being cut down by the player. I've used one prefab which contains my tree stump and tree trunk as children.

In its default state, my tree trunk as a rigidbody with isKinematic=true. When the player cuts down the tree, I begin an animation on the trunk which "tips it over". On the last frame, it sets isKinematic=false - at this point it should "fall over" because physicals/gravity is in control and the center of mass is definitely over its base.

However, the animation seems to be preventing it, like it's still "controlling" the transform.

Adding a transition from the "fell" state to an "exit" state just resets the position/rotation.
Setting the animator to "animate physics" kind of works, but the tree just flies away, probably colliding with the stump or something.
Disabling the animator after the animation kind of works, but this also causes the tree to go flying with some crazy physics.
When left alone, OnCollisionEnter is called on the tree for colliding with my ground, yet the gameobject appears to still be stuck at 45 degrees and never touched the ground. It seems like the rigibody/collider is not where the mesh/transform is?

Animating the object and then turning off isKinematic should work, it's been recommended to me on reddit and is the accepted answer on this question, so I'm not sure what could be wrong.

Edit: I can ease the physics problems by telling the trunk to ignore it's own stump (Physics.IgnoreCollision(Trunk.transform, Stump.transform);), but the base of the tree still "jumps" away from the stump, rather than "continue tipping over". I'm not sure what else could be at play.


texts: Algorithm to produce 'Lady or Tiger' puzzles?

texts:
What my problem is:
There is a puzzle by Raymond Smullyan that works something like this: You are in a room with many doors. Behind some of those doors, there are ladies; behind the others, there are tigers. Your goal is to pick one of the right doors (the ones with the ladies). On every door, there's a sign that says something like There's a lady behind this door or There is a lion behind door II and VI and so on. Now, you also have some additional information like Only one of the signs says the truth or The sign on a door is true only if there is a lady behind that door and so on. For example, the first puzzle goes like this:

There are two doors with one sign each. One of the signs is true, the other one is false:
 ---------------------    ---------------------
|      DOOR I         |  |      DOOR II        |
| There's a lady in   |  | In one of those     |
| this room and a     |  | rooms, there's a    |
| a tiger in the      |  | lady, in the other  |
| other one           |  | one there's a tiger |
 ---------------------    ---------------------

Behind which door is a lady?

Now, getting to the topic of this question: I'm looking for possible ways to auto-generate such puzzles. The (far away) goal is to build an algorithm that requires, as parameters, the number of doors (and maybe the difficulty of the resulting puzzle) and creates corresponding texts for the doors.
What I have tried so far:
Not much, as I don't really know where to start. It's easy to create a pattern for the text on the signs and it's also easy to randomly assign true and false statements to those signs, corresponding to the true-false-rule you use (e.g. Only one sign says the truth). But that's the part where it get's tricky: How to create a puzzle that is solvable and has a unique solution? My first idea was to create a random puzzle and use backtracking to search for solutions. But that way, it could take very long until the algorithm has finally found a working set of signs. Also, that way you can't easily determine how difficult a given puzzle is.
So, summing it up: Do you have any idea, any helpful links, etc.? Any help is appreciated, I don't expect anyone to post a perfect and complete solution for my problem.
(Note: I originally asked the following question on stackoverflow but was told there that I would be more likely to get an answer here!)


texts: How do I remove specfic OptionData from Dropdown?

texts:
How would I remove one of the elements from the dropdown? For example, how would I remove Sprites? Here is my code:

public Dropdown researchFeatureDropDown;
researchFeatureDropDown.options.Add(new Dropdown.OptionData("Sprites"));
researchFeatureDropDown.options.Add(new Dropdown.OptionData("Scrolling - 2000"));


texts:
I was wondering how I should approach the runtime changes on the game UI when selecting different types of units in a RTS.

For example, in Starcraft, each unit type has its own portrait, attributes, buffs and command cards displayed in the UI. Selecting another unit will update all of these.

I can see two possible solutions:

Each unit type has its own UI panel created (in memory), and selecting another unit disables the current UI panel and enables the new one.
There is only one UI panel, and selecting a unit fills the portrait, attributes, command cards, etc. dynamically.

Both solutions seem inefficient. The first may consume too much memory, and the second makes no caching at all. Maybe the way to go would be something in-between, or completely different.

I'm working with Unity, but I think the discussion should stay pretty high level.


texts: Using libGdx and Box2d for game and getting this error- "incorrect checksum for freed object"

texts:
I am new in game development and I am using libGdx with box2d in my game, whenever I try to switch screen (both screens has box2d bodies with Tiled map), I encounter the following error.

  java(610,0x70000297a000) malloc: * error for object 0x7f8d642fd600:
   incorrect checksum for freed object - object was probably modified after  being freed.
   * set a breakpoint in malloc_error_break to debug

The code which I use to switch screen is in render method

if((mapPixelWidth - 200) <= frog.body.getPosition().x * PPM){
        game.gm.setPrefLevel(0);
        Gdx.app.postRunnable(new Runnable() {
            @Override
            public void run () {
                Array<Body> bodies= new Array<Body>();
                world.getBodies(bodies);
                for (Body b: bodies) {
                    world.destroyBody(b);
                }
            }
        });
        game.manager.unload("maps/World1Level3.tmx");
        game.setScreen(game.levelLoading);
    }

Apart from this error, I want to ask that the way I am using Asset Manager and Box2d bodies are correct or not?


texts:
I just want to make one SphereCastAll with a center and a radius.

I don't want unnecessary sweeping in a desired direction with a desired length. How is this achievable? My solution is pretty unreliable, I think.

var hits = Physics.SphereCastAll(center, radius, forward, 0.0001f, mask);


texts: C# Collision test of a ship and asteriod, angle confusion

texts:
We are trying to to do a collision detection for the ship and asteroid. If success than it should detect the collision before N turns. However it is confused between angle 350 and 15 and it is not really working. It moves sometimes and it is not shooting at the right time.

I just want to ask how to make the collision detection working? And how to solve the angle confusion problem?

// Get velocities of asteroid
// IF equation is between -2 and -3
if (equation1a <= -2)
{
    // Calculate no. turns till asteroid hits
    float turns_till_hit = dx / vx;

    // Calculate angle of asteroid
    float asteroid_angle_rad = (float)Math.Atan(Math.Abs(dy / dx));
    float asteroid_angle_deg = (float)(asteroid_angle_rad * 180 / Math.PI);
    float asteroid_angle = 0;

    // Calculate angle if asteroid is in certain positions
    if (asteroid.Y > ship.Y && asteroid.X > ship.X)
    {
        asteroid_angle = asteroid_angle_deg;
    }
    else if (asteroid.Y < ship.Y && asteroid.X > ship.X)
    {
        asteroid_angle = (360 - asteroid_angle_deg);
    }
    else if (asteroid.Y < ship.Y && asteroid.X < ship.X)
    {
        asteroid_angle = (180 + asteroid_angle_deg);
    }
    else if (asteroid.Y > ship.Y && asteroid.X < ship.X)
    {
        asteroid_angle = (180 - asteroid_angle_deg);
    }

    // IF turns till asteroid hits are less than 35
    if (turns_till_hit < 50)
    {
        float angle_between = 0;

        // Calculate angle between if asteroid is in certain positions
        if (asteroid.Y > ship.Y && asteroid.X > ship.X)
        {
            angle_between = ship_angle - asteroid_angle;
        }
        else if (asteroid.Y < ship.Y && asteroid.X > ship.X)
        {
            angle_between = (360 - Math.Abs(ship_angle - asteroid_angle));
        }
        else if (asteroid.Y < ship.Y && asteroid.X < ship.X)
        {
            angle_between = ship_angle - asteroid_angle;
        }
        else if (asteroid.Y > ship.Y && asteroid.X < ship.X)
        {
            angle_between = ship_angle - asteroid_angle;
        }

        // If angle less than 0, add 360
        if (angle_between < 0)
        {
            //angle_between %= 360;
            angle_between = Math.Abs(angle_between);
        }

        // Calculate no. of turns to face asteroid
        float turns_to_face = angle_between / 25;

        if (turns_to_face < turns_till_hit)
        {
            float ship_angle_left = ShipAngle(ship_angle, "leftKey", 1);
            float ship_angle_right = ShipAngle(ship_angle, "rightKey", 1);
            float angle_between_left = Math.Abs(ship_angle_left - asteroid_angle);
            float angle_between_right = Math.Abs(ship_angle_right - asteroid_angle);

            if (angle_between_left < angle_between_right)
            {
                leftKey = true;
            }
            else if (angle_between_right < angle_between_left)
            {
                rightKey = true;
            }

        }

        if (angle_between > 0 && angle_between < 25)
        {
            spaceKey = true;
        }
    }
}


texts:
I want to develop a game on multiple devices such as PC, Android or IOS.
Want it to be in 1080p, but that means a massive scale down for the smartphones.

I know how to do that, just render everything on a 1080p rendertarget and then render it on the screen smaller.

But what should I do so that the scalling down doesn't look bad and blury?
I can't do it vector based or anything because the sprites simply need a specific size.
Should I make the sprites power of two size to get some nice mipmapping? And which other settings can I do?

Or should I rather go with a lower resolution but then having a little bit worse look PC version? The performance seems not to be a problem for me, so would be sad not using 1080p because of other problems.


texts: How do I toggle color writes in SlimDX 11/Direct3D 11 with FeatureLevel 10?

texts:
I'm having trouble setting the RenderTargetWriteMask field of a RenderTargetDescription struct. I simply want to toggle color writes but every time I try to enable the color writes are changed back to zero. Here is the code:

BlendState bs = null, bs1 = null;

try
{
    RenderTargetBlendDescription rtBlendDesc = new RenderTargetBlendDescription()
    {
        RenderTargetWriteMask = ColorWriteMaskFlags.All,
        BlendEnable = false,
        BlendOperation = BlendOperation.Add,
        BlendOperationAlpha = BlendOperation.Add,
        DestinationBlend = BlendOption.Zero,
        DestinationBlendAlpha = BlendOption.Zero,
        SourceBlend = BlendOption.One,
        SourceBlendAlpha = BlendOption.One,
    };

    // default blend state
    bs = BlendState.FromDescription(_device, new BlendStateDescription()
        {
            AlphaToCoverageEnable = false,
            IndependentBlendEnable = false,

        });
    for (int i = 0; i < Constants.MaxSimultaneousRenderTargets; ++i)
        bs.Description.RenderTargets[i] = rtBlendDesc;

    // set default blend state
    _device.ImmediateContext.OutputMerger.BlendState = bs;

    // in debug you will see that the RenderTargetWriteMask field of each render target is set to 'None'...
}
catch (Exception e) { e.Handle(); F.DisposeResource(ref bs); F.DisposeResource(ref bs1); }

Update:
I'm not able to set any of the values stored in RenderTargetBlendDescription.


texts: Is there a grey-area with Copyright infringement?

texts:
Currently a student, I'm trying to put together a game for iOS. From everywhere I've read, it seems any game's sound and art are apart of their IP and covered under their Copyright.

That being said, say I wanted to use the coin sound effect from the original Mario (less than 1s long and used sparsely)... would anyone really care? Having no experience with this, I'm just wondering if cases like this are treated like "Ya you're driving slightly over the speed limit, but nobody cares" or as "you stole that car".

Thanks for any insight anyone may be able to provide.


texts: How do I draw a world rectangle as a GUI

texts:
I would like to draw a perspective green rectangle that glows (=it constantly changes its alpha between 0 an 1).

I already achieved this, but not as a GUI element, but as a real 3D object.

In order to show this rectangle in front of everything else, I have to turn this into a GUI element. And I don't know how I would draw a perspective rectangle that constantly changes its alpha on the GUI.

I do not only mean the math behind it, but also how to do it exacetly:
Do I use actual materials, or do I use an image in the size of the green box?

Thank you.

Edit:

This is what I'm trying to rebuild:


texts:
I'm making something for a dialogue system that reads "cues" from a textfile to identify which emotion to show in the character's portrait during a conversation. Basically if the current line says "2", it means change the portrait to where the character is smiling. "1" for neutral, etc. Unfortunately the part that compares the emotion variable, and the string from the text file doesn't return true.
I already checked using debug.log if the string from the text file is showing the right number, and it does. I tried comparing them using "==" sign and ".equals();" but neither seems to work.
public TextAsset textFileP;
public string[] textLineP;
public GameObject character;
public Animator anim;
public string smile = "2";

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

    if (textFileP != null)
    {
        textLineP = (textFileP.text.Split('\n'));
        character.SetActive(true);
    }
}

void Update()
{

    if (DialogueParser.nextLine < DialogueParser.textLine.Length - 1)
    {

        //change portrait
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            string cue = textLineP[DialogueParser.nextLine];
            // Debug.Log(cue);
            if (cue.Equals(smile))
            {
                anim.SetInteger("2", 2);
            }

        }


texts: Unity Particle System How to rotate particle effect?

texts:
My Particle System creates a "puff" of smoke.
When I rotate the particle system it doesn't rotate the effect, just the way the particle is shot.

What I want to do is when I shoot a wall have it "puff" horizontal not vertical. And vertical when hitting floor. I want it to follow the normals of the surface I am raycasting to.

My problem is that the texture doesn't turn with it's parent rotation.

Do I need to write my own Custom Simulation Space to be able to rotate the effect?
Assigning the transform of the parent does nothing.

Prefab structure:

Particle Settings:


texts: Can somebody recommend a free C++ open source library which I will use to build a networked game using UDP. Must be available for Windows/Linux/Mac. As lightweight as possible please.


texts: Play store leaderboard not working unity

texts:
I added a leaderboard on my android game using  cloudOnce and than i built an aab file and uploaded it on playstore to internal tester but leaderboard is not working.
Here is what happens when I click on leaderboard button using logCat


texts:
I got a full functioning heightmap loader, however I can only use one texture. Now I want to implement more textures (like diffrent textures depending on heights ect, Possibly a structure that makes it easy to implement diffrent coditions of where to use certain textures)

But I'm a bit unsure how to go about doing this. Could anyone point me in the direction of a good guide on how you would implement something like this.


texts: How can you use Fractals to perturb an image?

texts:
I've been playing around with Procedurally Generated World. I've so far managed to create the Height Map, and a translate map, but now i'm attempting to create Caves,
The main idea is to use another Noise map, with values being either 0 or 1, and multiply it with the Height Map.
I've managed to achieve this:

This is currently described with a float[Width, Height], which has value 0 for those points (x,y) such that (x,y) is black, or 1, for those which (x,y) is white.
I want to apply some fractal to this to achieve this:

However, i have no idea how to do this!
(I also apologize for any grammatical errors. I haven't slept in like 18 hours and i can't think straight)


texts: Level progression starting from target total XP

texts:
I'm sort of a newbie here, so pardon me if I don't get any of the lingo right.

But I'm trying to create a level progression that charts with the "10,000 hr" rule such that, basically, each hour worked will equal 1 XP and level 99 (xx, if you will) charts with having accumulated 10,000 XP.

I understand how I can make a straight progression of levels, but what I really want to do is create a sloped progression, where you level up more often early and then it requires more and more effort to level up as the progress goes on. (The only targets, I guess, are level 1 being 0 and level 99 being 10,000.)

Any ideas? Can anyone help? (I'm sure this is simple, but if you can show me the way toward the answer, I'll gift you by first-born sword.)


texts: I'm trying to do a very simple ball bouncing setup in Unity. I have a sphere with a sphere collider and a plane below it was a rectangular mesh on it, isTrigger set to false for both, and they both have a physics material with bounciness of 1. I have the ball start a couple units above the plane, gravity pulls it down, but instead of bouncing it stops right at the collider for the plane, then (weirdly) slowly falls through the collider. Once it falls through the bottom it starts falling normally again. The collider is already really thick (I've been trying to fix this by changing collider types and making them way bigger than needed). I just have no clue what's going on and feel like I'm missing something obvious.


texts: What kind of gaming experiences does hiding game play stats and formulas cultivate?

texts:
There are varying degrees of providing players with information on their characters abilities - including but not limited to showing players their character's stats and how they tie into formulas such as total damage, damage reduction, etc. When these numbers and formulas are provided outright it can lead to a lot of min maxing / work to create an optimal build which can detract from simply enjoying the game by worrying too much about the numbers behind the scenes.

From a game design perspective I am looking for insight on:

Personal experiences with designing stat systems where most if not all the information was hidden from the player. Include the types of decisions you made on what to hide and what to show to the player as well as the reasons behind those decisions and how they impacted the way players play the game.
Personal experiences where you actively chose to provide as much information to the player as possible because you were against hiding information. Explain the thought process that drove you to this decision and the impact it had on the way players play the game.
References to / resources on how different games have approached designing their stat systems that hide most of the information from the players and how the design has impacted the way players play the game


texts: Place tile values over 'chunk' boundries

texts:
My game has a 'chunk' engine similar to Minecraft's but in 2 dimensions.
Each chunk is a square of 32 by 32 tiles.

What I want to do is generate a defined shape across multiple chunks without breaking the shape.

This is made difficult by the fact that chunks are generated one chunk at a time in unknown intervals of time, so I cannot place a structure after the amount of chunks it needs to fit in are generated, as the player might move into the area before that time.

Another problem is that I cannot simply tile the shape uniformly because the shape needs to be exactly one tile above the surface, which is a heightmap generated using simplex noise, so it is not flat.

Is there any way I can generate this structure from one point of origin placed at random intervals over a heightmap that is known?

Example of what I want:

Grey Lines - chunk bounds

White Tiles - structure generation

Blue Tiles - known 1D heightmap

How can this be done?


texts: What solutions are available for 3d character creation/editing in games?

texts: Many RPGs and MMOs offer a system for creating a character model, with varying levels of customization. Are there any open source libraries for this? Any libraries which can be licensed? Has anyone built anything related to this themselves?


texts: Calculate the Z of a line intersection given the XY coordinates?

texts: I'm intersecting a line in 2D and I calculate the X,Y coordinates of the intersection point. What I need is the Z of the intersection point given the X,Y,Z of the line points, and the X,Y of the intersection. From what I understand of equations it should be a one-liner but I don't know enough math to get there.


texts: elements of list are changing their values

texts:
I'm making an app that's similar to an alarm, the user enters time and days, for days I'm using toggles,and storing the values of toggles states in a list which is stored in a list that contain all the inputs of the type days, then the user could edit any of his inputs, his old input are supposed to be shown there , but the problem is even when I'm storing them, old values are changing when I add new elements,(that's when currentToggle is changing) so when he press edit values aren't the same as he entered them

I think it has something to do with nested lists but I can't figure out how, ( assigning hours and minutes is perfectly working and both are normal lists)

the confirm method is for when the user confirm his choice, and there's edit button that open a panel ,its values are the same as the user entered them before

the index gives the number of the selected group of input, dayholder is the gameobject that contains all the toggles , and that's the part of the code that's related to what I've said

Toggle[] toggles;
List<bool> currentToggle = new List<bool>();
List <List<bool>> daysAll = new List<List<bool>>();

void Start () {
    toggles = dayHolder.GetComponentsInChildren<Toggle>();
}
public void confirm()
{

    checkON();
    daysAll.Add(currentToggle);
}
 public void editBut()
{
    GameObject panelC = EventSystem.current.currentSelectedGameObject.gameObject.transform.parent.gameObject;
    int index = panelC.transform.parent.gameObject.transform.GetSiblingIndex();
    assignDays(index);
}
void assignDays(int index)
{
    for (int i = 0; i < daysAll[index].Count; i++)
    {
        if (daysAll[index][i] == true)
            toggles[i].isOn = true;
    }
}
public void checkON()
{
    currentToggle.RemoveAll(item => item != null);
    for (int i = 0; i < toggles.Length; i++)
    {
        if (toggles[i].isOn)
            currentToggle.Add(true);
        else
            currentToggle.Add(false);
    }

}


texts: How can I project a 3D point onto a 3D line?

texts:
Let's say I have a line defined by two points, A and B, both in the form (x, y, z). These points represent a line in 3D space.

I also have a point P, defined in the same format, that isn't on the line.

How would I calculate the projection of that point on to the line? I'm aware of how to do this in 2D but 3D seems to have bugger all resources on it.


texts:
I dont know how to explain this, so I will use images to describe my problem.

The image I made using InkScape:

What it looks like in-game (ignore the runner):

As you can see the edges are not "sharp" ingame, even the static background (front-mountains and grass is scrolling) is distorted. I think you can see what I mean. What causes this? How can I fix it?

I use LibGdx to build my game, inside Android studio.

some relevant code:

background = new Sprite(new Texture(Gdx.files.internal("runner_background.png")));
camera = new OrthographicCamera();
viewport = new FitViewport(480, 800,camera);
viewport.apply();
camera.position.set(camera.viewportWidth / 2f, camera.viewportHeight / 2f, 0);
camera.update();

I draw my background like this, my RunnerScreen render method:

runnerWorld.update(delta);
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
runnerWorld.render(batch);
batch.end();

my runnerWorld render-method:

public void render(SpriteBatch batch){
batch.draw(background, 0 ,0);
scroller.render(batch);
runner.render(batch);
}


texts: Function call to AndroidJabaObject to an instance of com.prime31.PlayGameServicesPlugin causes the application to stop responding

texts:
Using Prime31 PlayGameServices attempting to call 'authenticate' causes the game to stop responding very soon after.

There isn't much I can show as there's literally no logs showing up in logcat.

Is there any way I can debug this?

I did notice 'enableDebugPrints' on the AndroidJavaObject was 'false' and I don't know how to set it to true, which might help with prints?

I've tried catching an exception but that hasn't worked.


texts: How can I toggle between single shots when clicking the mouse left button and automatic none stop shooting when clicking the mouse right button?

texts:
I'm talking in build not in editor !

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

public class Shooting : MonoBehaviour
{
    [SerializeField]
    private Transform[] firePoints;
    [SerializeField]
    private Rigidbody projectilePrefab;
    [SerializeField]
    private float launchForce = 700f;
    [SerializeField]
    private Animator anim;
    [SerializeField]
    private bool automaticFire = false;
    [SerializeField]
    private bool slowDownEffect = false;

    private void Start()
    {
        anim.SetBool("Shooting", true);
    }

    public void Update()
    {
        if (isAnimationStatePlaying(anim, 0, "AIMING") == true)
        {
            if (Input.GetButtonDown("Fire1")/*automaticFire == false*/)
            {
                automaticFire = false;

                if (anim.GetBool("Shooting") == true)
                {
                    anim.Play("SHOOTING");
                    LaunchProjectile();
                }
            }
            else
            {
                if (/*automaticFire == true &&*/Input.GetButtonDown("Fire2"))
                {
                    automaticFire = true;
                }
            }
        }

        if(automaticFire == true)
        {
            anim.Play("SHOOTING");
            LaunchProjectile();
        }
    }

    private void LaunchProjectile()
    {
        foreach (var firePoint in firePoints)
        {
            Rigidbody projectileInstance = Instantiate(
                projectilePrefab,
                firePoint.position,
                firePoint.rotation);

            projectileInstance.AddForce(new Vector3(0, 0, 1) * launchForce);

            projectileInstance.gameObject.AddComponent<BulletDestruction>().Init();
        }
    }

    bool isAnimationStatePlaying(Animator anim, int animLayer, string stateName)
    {
        if (anim.GetCurrentAnimatorStateInfo(animLayer).IsName(stateName))
            return true;
        else
            return false;
    }
}

I tried to do it in the Update using the automaticFire variable but it's not working fine.

When clicking first the left mouse button it's shooting singles but then when clicking the mouse right button it's shooting automatic but then when clicking the left mouse button again it's not back to single shots again it's staying on automatic.

The idea is right click mouse button automatic fire left button each time clicking the left mouse button the automatic should stop and then single shots with the left mouse button. And this way to toggle between the Fire1 and Fire2.

Fire1 = left mouse button click Fire2 = right mouse button.


texts:
I'm using Slick2D and LWJGL for my StateBasedGame and I was wondering if there was a way to enter into my splashscreen on application load using a transition?

I tried using:

this.enterState(SPLASH, new FadeInTransition(Color.black), new FadeInTransition(Color.black));

However, it fades in nicely but then it flashes again for the second transition :(

Anyone know how I can get around that?

Would I have to create my own transition?


texts: I have a character with 2 2D Colliders, one for the head, and one for the feet, How do I Disable only the Head Collider in C#.


texts:
I'm having a bit of an issue when it comes to 3D- and 2D camera(s), in relation to a game's window resolution.
I want to let the player choose from different window resolutions, either from a menu or by just resizing the window by dragging the window border, and can't get the scaling of the graphics to work properly.
In games I've played, I can go into the options menu, choose a screen resolution and then the window resize itself and the graphic's, menu buttons etc just scales up to the correct sizes.

At the moment, I've tried two different window resolutions; 800x600 and 1280x720 (don't mind
the different aspect ratios).

800x600

1280x720

As you can see, more of the game world can be seen (more stone tiles can be seen, if that makes sense) in the window with a resolution of 1280x720 and I want my 3D/2D game(s) to be resolution independent and that the same amount of the game world to be seen, independent of what window resolution the player chooses to use.

My camera class consist of:

Camera matrix - used to translate and rotate my camera
View matrix - the inverse of the camera matrix
Perspective matrix - see code below
View projection matrix - view matrix * perspective matrix
Fov - 45.0f
Aspect ratio - camera width / camera height

Note: row-major matrices

Perspective matrix:

const float Tangent     = 1.0f / tanf(DEGREES_TO_RADIANS(Fov * 0.5f));
const float NearToFar   = FarClip - NearClip;

PerspectiveMatrix(Identity);

PerspectiveMatrix[0]    = -Tangent / AspectRatio;
PerspectiveMatrix[5]    =  Tangent;
PerspectiveMatrix[10]   =  FarClip / NearToFar;
PerspectiveMatrix[11]   =  1.0f;
PerspectiveMatrix[14]   = (-NearClip * FarClip) / NearToFar;
PerspectiveMatrix[15]   =  0.0f;

At each update, I'm also setting the viewport by calling glViewport(0, 0, CameraWidth, CameraHeight).
This might change in the future if I decide to make two cameras in a game, for a splitscreen game for example.

How can I solve the window resolution independence issue?

I have though about creating a framebuffer the size I want, attach it to a quad and then render the quad the size of the window, which will scale up/down the framebuffer if the window is bigger/smaller than the framebuffer's original size, but if it's an easier way of doing it, I would gladly use that instead.


texts: How do I spawn more than one spawnpoint in my scene in Unity?

texts:
I have different enemy AIs and two spawn-points in a scene, so far. The problem I am having is that only one enemy AI spawns, and the other enemy AI won't spawn, in that scene. How can I fix this problem?

Here is my code:

using UnityEngine;
using System.Collections;

public class EnemiesSpawner : MonoBehaviour
{
    public GameObject [] enemy;
    public Transform [] spawnPoints;
    public float spawnTime = 5f;
    public Vector3 spawnValues;

    void Start ()
    {
        //Call the "Spawn" function every 10 seconds.
        InvokeRepeating("Spawn", spawnTime, spawnTime);
    }

    void Spawn ()
    {
        int spawnPointIndex = Random.Range (0, spawnPoints.Length);

        Instantiate(enemy[Random.Range(0, enemy.Length)],
            spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);

        Vector3 spawnPosition = new Vector3 (Random.Range (-spawnValues.x, spawnValues.x),
            1, Random.Range (-spawnValues.z, -spawnValues.z) );
    }
}


texts: Is it a good idea to perform all matrix operations on the GPU?

texts: I was wondering if it is a improvement to use OpenGL for matrix calculations instead of using the CPU. And if it is a improvement, is it worth it to change the math class to use OpenGL?


texts: SharpDX: Render to bitmap using Direct2D 1.1

texts:
I have a command line application that I am currently using SharpDX (Direct2D 1.0) to render to PNG files. This is a window-less application.

It's currently creating a SharpDX.WIC.WicBitmap, a WicRenderTarget, then rendering to that. I then save the WicBitmap to the PNG file.

For various reasons, I need to migrate to Direct2D 1.1 to take advantage of some of the effects available in 1.1.

I'm trying to get a SharpDX.Direct2D1.Bitmap that I can save as PNG.

I cannot use FromWicBitmap because that copies the bitmap, it does not share it.

I see CreateSharedBitmap in the Direct2D1 API that takes a IWICBitmapLock. However, I do not see this implemented as a constructor of SharpDX.Direct2D.Bitmap.

This is what I'm trying to do:

// Bunch of setup
var d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice);

var d2dDeviceContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice,
    SharpDX.Direct2D1.DeviceContextOptions.None);

using (var wicFactory = new SharpDX.WIC.ImagingFactory())
{
  using (SharpDX.WIC.Bitmap wicBitmap =
    new SharpDX.WIC.Bitmap(wicFactory, 500, 500,
      SharpDX.WIC.PixelFormat.Format32bppPBGRA,
      SharpDX.WIC.BitmapCreateCacheOption.CacheOnDemand))
    {
    var wicLock = wicBitmap.Lock(SharpDX.WIC.BitmapLockFlags.Write);

    var props = new SharpDX.Direct2D1.BitmapProperties1();
    props.BitmapOptions = SharpDX.Direct2D1.BitmapOptions.Target;

    var bitmap = new SharpDX.Direct2D1.Bitmap1(d2dDeviceContext, wicLock, props); // This is not available

    d2dDeviceContext.Target = bitmap;

    // Do the drawing
    // Save the PNG
  }
}

Is there a way to do what I'm trying to accomplish?


texts: Game with static scene and bouncing balls. How to?

texts: How to make a game with a static scene and balls that can bounce on it? What is used for this, generally? Physics engines? Even if this is a simplistic example?


texts: 2D Platformer - Methods to Implement a Whip Weapon

texts:
I hope posting here isn't a faux pax, if it is please feel free to direct me to the correct location. Or, if there is a thread that already covered this I would love to be pointed in its direction.

I've tried looking in quite a few different forums and I can't seem to find very much information about this. What I'm looking to do is implement a whip weapon for a character that's similar to that of Castlevania 4's whip.

I have no idea where to start. I'm really just looking for any information. Things like how to program it, the idea of how it was done in the game, really just anything to help me figure out how to make a whip like Castlevania 4.

I would appreciate any help. Thank you.


texts: shadow mapping with directional light and octree

texts:
i am about to add shadow mapping to my simple game, i have a map level structured in an octree the camera culls out the octree nodes out of the vieweing frusutm and everything runs smooth. Now i want shadows and i have a doubt , the directional light runs is set at an infinite distance so basically it encompasses all the octree destroying the purpose of node culling. How can i add a directional shadow map and cull nodes outside the light frusutm if it is at an infinite distance ?
thanks in advance


texts: GLM conversion from euler angles to quaternion and back does not hold

texts:
I am trying to convert the orientation of an OpenVR controller that I have stored as a glm::vec3 of Euler angles into a glm::fquat and back, but I get wildly different results and the in-game behavior is just wrong (hard to explain, but the orientation of the object behaves normally for a small range of angles, then flips in weird axes).

This is my conversion code:

// get `orientation` from OpenVR controller sensor data

const glm::vec3 eulerAnglesInDegrees{orientation[PITCH], orientation[YAW], orientation[ROLL]};
debugPrint(eulerAnglesInDegrees);

const glm::fquat quaternion{glm::radians(eulerAnglesInDegrees)};
const glm::vec3 result{glm::degrees(glm::eulerAngles(quaternion))};
debugPrint(result);

// `result` should represent the same orientation as `eulerAnglesInDegrees`

I would expect eulerAnglesInDegrees and result to either be the same or equivalent representations of the same orientation, but that is apparently not the case. These are some example values I get printed out:

39.3851 5.17816 3.29104
39.3851 5.17816 3.29104

32.7636 144.849 44.3845
-147.236 35.1512 -135.616

39.3851 5.17816 3.29104
39.3851 5.17816 3.29104

32.0103 137.415 45.1592
-147.99 42.5846 -134.841

As you can see above, for some orientation ranges the conversion is correct, but for others it is completely different.

What am I doing wrong?

I've looked at existing questions and attempted a few things, including trying out every possible rotation order listed here, conjugating the quaternion, and other random things like flipping pitch/yaw/roll. Nothing gave me the expected result.

How can I convert euler angles to quaternions and back, representing the original orientation, using glm?

Some more examples of discrepancies:

original:      4; 175;   26;
computed:   -175;   4; -153;
difference:  179; 171;  179;

original:     -6; 173;   32;
computed:    173;   6; -147;
difference: -179; 167;  179;

original:      9; 268;  -46;
computed:   -170; -88;  133;
difference:  179; 356; -179;

original:    -27; -73;  266;
computed:    -27; -73;  -93;
difference:    0;   0;  359;

original:    -33; 111;  205;
computed:    146;  68;   25;
difference: -179;  43;  180;

I tried to find a pattern to fix the final computed results, but it doesn't seem like there's one easy to identify.

GIF + video of the behavior:

Full video on YouTube

Visual representation of my intuition/current understanding:

The above picture shows a sphere, and I'm in the center. When I aim the gun towards the green half of the sphere, the orientation is correct. When I aim the gun towards the red half of the sphere, it is incorrect - it seems like every axis is inverted, but I am not 100% sure that is the case.


texts:
With Scene2D, in the act() method of a Group, under certain circumstances I add actions to some children (eg a moveTo, or a fadeOut), which last a few tenths of seconds. Now I need ALL these action to complete before I start running the code in act() again. Right now I'm using a kludge with a timer, I set a variable actionRunTime before attaching the actions to children, set to the value of how long all actions should take to complete, then in act() I do

public void act(float delta){

  super.act(delta);  // to have the actions run on children

  actionRunTime -= delta;

  if (actionRunTime >= 0) return;

  // ... code to run when no action is running

This looks terrible to me. Is there some cleaner way?


texts: Unity Shader blending colors and color values above 1

texts:
I have source images where each pixel is one of exactly 4 colors:

red = (1,0,0)
green = (0,1,0)
blue = (0,0,1)
black = (0,0,0)

I'm trying to modify Unity's default sprite shader to use those colors (besides black) as a key to change to other colors. For example, any pixel that's red should become _RedColor. My first attempt was:

fixed4 _RedColor;
fixed4 _BlueColor;
fixed4 _GreenColor;

fixed4 frag(v2f IN) : SV_Target {
    fixed4 c = SampleSpriteTexture (IN.texcoord) * IN.color;

    fixed4 modColor;
    modColor.rgb = _RedColor.rgb*step(1, c.r);
    modColor.rgb = _BlueColor.rgb*step(1, c.b);
    modColor.rgb = _GreenColor.rgb*step(1, c.g);

    modColor.rgb *= c.a;
    return modColor;
}

This worked. The problem was it was very jagged. In exporting the image and being compressed in Unity I think some pixels had multiple colors but the shader simply would set the color to the last matching color.

So I tried to modify it to not reset the color if the next color matches, but instead blend between any colors present in the pixel weighted by their contribution. Here was my second attempt:

fixed4 frag(v2f IN) : SV_Target {
    fixed4 c = SampleSpriteTexture (IN.texcoord) * IN.color;

    float total = c.r + c.b + c.g;

    // we set the total to 1 if it's 0 so that we don't divide by zero when the color is black
    total += step(total, 0);

    c.rgb = _RedColor.rgb*c.r + _BlueColor.rgb*c.b + _GreenColor.rgb*c.g;
    c.rgb /= total;

    c.rgb *= a;
    return c;
}

This also worked and the jaggedness went away everywhere except the border of black and nonblack colors. So then I tried getting rid of the total and it was perfect:

fixed4 frag(v2f IN) : SV_Target {
    fixed4 c = SampleSpriteTexture (IN.texcoord) * IN.color;

    c.rgb = _RedColor.rgb*c.r + _BlueColor.rgb*c.b + _GreenColor.rgb*c.g;

    c.rgb *= c.a;
    return c;
}

It's perfectly blended between any of the pixels. But I don't get why. I was dividing by the total so that the color values wouldn't go above 1 and it would blend between them. For example if a pixel had both red and blue present it would be adding the 50% of _RedColor's rgb value and 50% of the _BlueColor's rgb value. So when I didn't divide by the total it appears nothing changed besides blending between black and other colors.

This implies to me that I never had any pixels that actually had more than one nonzero color component to them (or else I could/would be getting white colors at those pixels). But if that's the case, why did switching from the first step function approach to a blend approach even do anything?

This is my first foray into shaders so it's entirely possible I'm doing something terribly, but I just want to wrap my head around what's going on and why. So I definitely appreciate any help/ideas.


texts: When is the Z coordinate normalized in GLSL?

texts:
I thought that whenever you transform an object to world space, then view space and finally screen space, the last matrix you apply(the projection matrix) normalizes the z values between 0 and 1.

However, I'm getting big z coordinates, which implies that the projection matrix didn't normalize it. Am I doing something wrong? I mean, all I do is:

gl_Position = projection * view * world * gl_Vertex;


texts: Problems with object collision detection using mesh colliders in unity

texts:
So I'm working on a project and I need to detect when an empty object with a mesh attached to it collides with another object. Essentially, I want to know when the mesh is touching a cube. I've tried using the mesh collider (And it works) but the problem is: I have a circular mesh and therefore need to Inflate the mesh. This
decreases its accuracy and increases lag by a lot and I can't have that happen.

TL;DR: I copy my mesh to a mesh collider but the mesh collider is inaccurate and laggy for collision detection.


texts: Can I apply a force to particles from a script?

texts:
I'm working on a game which involves streams of electrically-charged particles, being manipulated with electric and magnetic fields. Since I want a large number of small objects coming from an emitter and lasting a limited amount of time, a particle system seems like the way to go.

My only problem now is: how to apply the force? Suppose, for example, I have a charged object somewhere in the scene; I want to apply a force toward it, varying with the radius squared. If my particles were Rigidbodies, applying this force in the FixedUpdate would be easy; is there a way to do the same to an individual particle?


texts: How do I get Apple to pull an App that violates a copyright?

texts: A friend of mine has had his Flash game stolen and published on the iPhone app store without his consent.  What is the best way to get Apple's attention about this?


texts:
I need to detect the position of a knob on a touchpad. I need to detect if it is in particular areas and if so, which one. The sections, of course, being the colored parts.

I know that the black center circle ends at 0.8f and -0.8f for both the X and Y axis.

The information I can get is the percent X and percent Y which is 0 to 1 from center or 0 to -1 from center the other way.

How would I go about doing this?


texts: Convert gl_TexCoord[0].st to match version #330

texts:
I'm currently working on a sfml based library where I'm implementing widgets with shaders. I'm defining an quad with position and texcoord in sfml to make the shader apply to the object like this:

quad[0].position = sf::Vector2f(100, 100);
quad[0].texCoords = sf::Vector2f(0, 0);
quad[1].position = sf::Vector2f(410, 100);
quad[1].texCoords = sf::Vector2f(1, 0);
quad[2].position = sf::Vector2f(410, 410);
quad[2].texCoords = sf::Vector2f(1, 1);
quad[3].position = sf::Vector2f(100, 410);
quad[3].texCoords = sf::Vector2f(0, 1);

This way I'll make gl_TexCoord[0].st ready to use without dividing with resolution to make it in rage [0, 1]. But when I'm adding #version 330 I get a deprection error. Since I'm using OpenGL 3.3, I'm looking to stick with the moder shader methods and to avoid deprecated stuffs.

Here's how my shader looks like and works without version definition:

void main() {
     vec2 pos = gl_TexCoord[0].st; // deprecated since #120
     gl_FragColor = vec4(pos.y, pos.x, 1.0, 1.0); // also deprecated too
 }