texts: Weird libGDX BitmapFont Color Change (And Alpha) Bug

texts:
I want to change the color of my libGDX BitmapFont, but it can't change it. The font is generated with Hiero v5 (Lastest as I Know) but the color of the font doesn't change. Here is the example code, the important part here is how modify the alpha channel for an animation I want.

font = new BitmapFont(game.getAssets().getFont(0.9f).getData(), game.getAssets().getFont(0.9f).getRegion(), false);
textLayout = new GlyphLayout(font, "Tap to Start");
textPosition = new Vector2();
textPosition.x = Constants.HALF_WIDTH - (textLayout.width/2);
textPosition.y = 150;
//font.setColor(255f/255f, 183f/255f, 77f/255f, 0.3f); This doesn't work as well
font.getCache().setColor(255f/255f, 183f/255f, 77f/255f, 0.3f);

//Font Drawing in render Method
font.draw(batch, textLayout, textPosition.x, textPosition.y);

Here is a screen of the result of this code (color doesn't change).

Font resource image has white letters and transparent background.


texts:
I am implementing a before-match setup in following way:

Users request a multiplayer match (click "New Game" button or similar)
After enough users request the match – connection is established
Users are then moved into Select level view
On that view, there is "Become Master" button, which an user can use to become Master
The Master has ability to select level to play
After clicking "Become Master" – the users vote – simple popup appears "Accept User X becoming Master?"
If > 50% agrees, user X becomes master.
Master then selects level he wants. After 10 seconds, game starts – all users are moved to In-game view, to play selected level.

Question: I am wondering if I am not doing this too complicated? Shouldn't I randomly choose the master, or somehow make selection mechanism simpler?


texts:
I'm new to C# and Monogame, and I'm trying to create an effect of a 'psychic' ability, the user will press a key and a circular aura blast will emit from their position. I'm just trying to get the actual blast working before setting up the positions and all that, but my problem is when trying to get all the particles to move out from the origin of a circle to the outside.

I've never worked with circles yet and only with Rectangles so my knowledge of this is very basic. You'll probably recognise the code from a youtube channel and that's because I've been trying to learn from wherever I can, most of the time that leads me to youtube since a video demonstration works best but I digress.

This is my code for the particle generator so far.

class ParticleGenerator
{
Texture2D texture;
float spawnWidth;
float density;

List<Particles> particles = new List<Particles>();

float timer;

public ParticleGenerator(Texture2D newTexture, float newSpawnWidth, float newDensity)
{
    texture = newTexture;
    spawnWidth = newSpawnWidth;
    density = newDensity;

}

public void createParticle(GraphicsDevice graphics)
{

    particles.Add(new Particles(texture, new Vector2(graphics.Viewport.Width / 2 , graphics.Viewport.Height /2), new Vector2(5, 1)));

}

public void Update(GameTime gameTime, GraphicsDevice graphics)
{
    timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
    while (timer > 0)
    {
        timer -= 1f / density;
        createParticle(graphics);
    }

    for (int i = 0; i < particles.Count; i++)
    {
        particles[i].Update();
        if (particles[i].Position.Y > graphics.Viewport.Height)
        {
            particles.RemoveAt(i);
            i--;
        }
    }
}

public void Draw(SpriteBatch spriteBatch)
{
    foreach (Particles particle in particles)
    {
        particle.Draw(spriteBatch);
    }
}

Many thanks for any help :)


texts: How can I get a property of an entity without having to call getEntityByType every time?

texts:
I'm trying to get an entity (a bullet, a grenade, and an explosive) from my player. Specifically, I want the shootingRate of my bullet (how frequently it can be fired).

How can I do this without having to call getEntityByType each time I fire this projectile? There has got to be a cleaner way from what I'm doing right now, which is:

// Shooting
var isShooting = ig.input.state('shoot');

if (isShooting && this.lastShootTimer.delta() > 0) {

switch (this.activeWeapon)
{
    case("EntityBullet"):
        ig.game.spawnEntity(this.activeWeapon, this.pos.x, this.pos.y - 10);
        var equipedWeap =  ig.game.getEntitiesByType(EntityBullet);
        this.lastShootTimer.set(equippedWeap.shootingRate);
        console.log(equipedWeap.shootingRate);
        break;
    case("EntityGrenade"):
        ig.game.spawnEntity(this.activeWeapon, this.pos.x, this.pos.y +5);
      var  equipedWeap =  ig.game.getEntitiesByType(EntityGrenade);
        this.lastShootTimer.set(equipedWeap.shootingRate);
        console.log(EquipedWeap.shootingRate);
        break;
    case("EntityExplosiveBomb"):
        ig.game.spawnEntity(this.activeWeapon, this.pos.x, this.pos.y +5 );
     var   equipedWeap =  ig.game.getEntitiesByType(EntityExplosiveBomb)[0];
        this.lastShootTimer.set(equipedWeap.shootingRate);
        console.log(equipedWeap.shootingRate);
        break;
   }
}


texts: No project in visual studio using unity created

texts:
As I have sometimes problems with intellisense in visual studio using unity, I searched for some answers. It was almost everytime pretty much the same: Reloading the project. But in my solution explorer, there is not even a project shown that i could reload.
Are you able to manually create the project or are there some reasons for that behaviour?

ps: I just updated unity from version 2017.3.0f3 to 2018.1.0f2, may that be the problem? (I'm using visual studio 2017 (i'm updating in the moment on version 15.7.1) community)

edit:
What I've tried so far:

Simply re-launching Visual Studio by double-clicking on the script file inside unity (-> DMGregory)
reloading the project
reimport all in the asset-explorer inside unity (S. Tarik Cetin)
deleting the .sln file to force Unity to regenerate them from scratch (-> Ed Marty) + opening the solution from inside Visual Studio

Doing the last point created - as intended - a new solution, but there is still no project created, as you can see in the following picture (Projektmappe = solution). That's how the solution looks like.
While opening the script from Unity, it shows the message in the following picture. Translation: "The following files were stated in the command line: [source path (name censored)] These files were not found and are not loaded."

When trying opening a script from a different (new) Project, it showed the same message, which leads to a new problem: Even in new unity projects, the solution cannot be opened, and the scripts are all assigned to a certain solution ("solution1"), which is the one that was generated. (Even scripts from different projects end up in the same solution!)

So in the moment, I have no idea what else to do. Is there something simple I'm just missing? Or should I reinstall one of the 2 programs?
Or might the update of unity be the problem? (exact versions mentioned above)

If there's any extra information needed, please just mention it in the comments. (I'm not so sure what might be helpful and what isn't)


texts: Use eyeray trigger to speak with NPC in Unity3D for Vive

texts: I'm developing a first-person-player game in Unity for HTC Vive. Basically, I want my NPC to speak when my player looks at him for more than a second. I didn't find any eyeray tutorials to achieve this for Vive. Please help.


texts:
Would Ada be a practical language for game development (at least for the PC--I understand there aren't compilers for PlayStation and other consoles)?

It has bindings to OpenGL, it has decent performance, and it's less error-prone than C++. Please feel encouraged to support your point with relevant example projects you know about.


texts: How can I use a 3x3 matrix within a 4x4 matrix representation?

texts:
In XNA there is only one Matrix class which is actually 4x4 matrix. How to use it to represent a 3x3 matrix?

I am trying to represent the inertia tensor of a body which is a 3x3 matrix, so I have data for only a 3x3 matrix. How can I store that in a 4x4 matrix and still have operations on it be valid?


texts: Is it worthwhile recording your own or buying stock sound effects?

texts: A unique graphical aesthetic is obviously important when developing a game.  I wonder if the same is true for audio?  Is it worth investing my time in recording, producing my own sounds or should I just buy stock effects?


texts: How do I determine the look-at vector of a free-look camera?

texts:
I'm trying to create a free-look camera with DirectX 10.

I've figured out how to get the directions for forward and back and left to right. However, I don't know how to rotate the look-at vector of my view matrix around the camera position so as to rotate in-place. How can I do this?


texts: How to achieve highly detailed textures on buildings/architecture?

texts:
I have a bit of experience when it comes to 3D modeling, but something I never really wrapped my head around is environment modeling. You know, you walk down a road and you see lots of buildings, they all look good, with great texture details, and yet they don't go over the texture budget and the framerate is nice.

Now I'm working on a little prototype, and I wanted to test how to make assets for it.

This is supposed to be one floor of a fantasy tower. I did the modeling in Blender (with a rough UV), then I exported it into Quixel, I made a simple texture, 4K resolution because why not at this stage. The problem is, when I look at it ingame or in blender, it's quite awful. This is a single texture and a single material for the whole mesh.

I was expecting this result, because the wall is some 20 meters long, so the texel density is really low. But this is already a 4K texture, when I should be using a 512 or 1k texture really. I mean, when you look at modern games, stuff like this looks sharp enough, with lower res textures than what I'm using now.

So, basically, what is the right approach to something like this?

I was thinking about something like this:

Have the "core" with a low res tiling texture, and then details as separate meshes that I would build in the engine (UE4 in this case). But I'm kinda worried about performance. I mean one floor would be at least 15 meshes, so 15 draws calls, so for ten floors it would be 150 drawcalls or something, I could barely make a village this way.

I know some games do fully modular buldings, like Fallout 4, they have a bunch of "kits" made of 2x2m blocks that snap together and each block has its texture and it looks good. But I don't really need that level of granularity, and I want more individual looking buildings, that don't look really copy-pasted.

And even if I did go that way, if one building is like 100 pieces alone, that's some 100 draw calls, how does that even work ingame?

An example from RDR2, how would go about making something like this? It can't possibly be one single mesh with just one texture.

How can I achieve this kind of result?


texts: How to draw smooth moving curve in libgdx?

texts: i need to draw curve like this picture, I have tried from this link https://github.com/libgdx/libgdx/wiki/Path-interface-&-Splines , but the curve is not so smooth like some game(Amazing Wire) which is already in the market.


texts: Tool to create a bitmap font from a true type font

texts:
What tool do you use to convert ttf fonts to bitmap fonts?

Following is a list of features I'm looking for.  I'd be happy with any tool really, but one that had these features would be better.

outputs power-of-2 texture atlas
parsible config file (so I don't have to use their rendering library)
output kerning information
cross platform
a rendering library would be great if it lets me make the actual OpenGL calls.

So what tool have you used?  Were you happy with it?


texts: Where to start when building a 3D terrain editor?

texts:
I'm looking to build (for start) a simple tool, that could raise, lower, smooth and texture the terrain.

So, what are the things I have to go through in order to make such terrain editor?

And maybe there are valuable resources available on subject?

Yes, forgot to mentioned, that I'm interested in a 3D terrain editor.


texts: How to store variables in between scenes? Unity

texts: How would that be possible, and would I be able to access them from anywhere?


texts: How to handle interactions between a sprite (player) and another sprite?

texts:
What's the proper way, a proper way, or any proper way at all, to handle interactions between a sprite (usually a player) and another sprite (can be any other object)? (in a tile based world)

i.e. getting into a vehicle, talking with other character, reading signs, etc.

My first instinct is to have some kind of "feeler" or interaction rectangle that's always in front of the player in the direction the player is facing. Then if that rectangle overlaps some kind of intractable object (driver door on vehicle, other character, sign, etc) I would be able to initiate an interaction.

Is this a naive implementation?

EDIT

This is for a 2D engine, written in C# for Xbox Live Arcade and Windows.


texts: Character axis gets messed up when I add the armature into it

texts: So basically Ive been working on a walking animation in Blender, but theres a problem when I import it to Unity, the axis get inverted… The only thing that is messing it up is the armature that animates the character, if I only import the character itself the axis are normal, if I also import the armature, the axis get inverted...


texts: Floating Point Precision (fp:precise vs. fp:fast)

texts:
In C or C++, does the compiler option of floating point precision really make a difference in real world (small/indie) games?

From my observations, setting fp:fast is many times faster than fp:precise and from what I understand here ( https://stackoverflow.com/questions/6889522/fpfast-vs-fpprecise-what-kind-of-errors-can-i-encounter ) the precision difference between the two compiler options only changes from the 16th digit of a floating point number.

Has anyone encountered an example when using fp:fast went terribly wrong for 2D or 3D games?

Edit: To clarify, I am not asking about the precision of floating point values themselves (ie. float vs double vs decimal). Only about precision related to the compiler option.


texts: Why does SDL2 blur pixel art even with SDL_HINT_RENDER_SCALE_QUALITY set to 0?

texts:
I am working on a game with SDL2 and having trouble turning off linear filtering when upscaling textures.

My game has a bunch of 32x32 tiles. I used SDL_RenderSetLogicalSize so that there is a one-to-one pixel mapping (i.e. my logical size is n * 32 x m * 32.)

However, when the the whole scene is upscaled to fit the actual screen, it seems to be interpolated (blurry).

I saw these two other posts (1, 2) which recommended using SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0");. I did that, but nothing seems to change at all. It returns true and it is in fact changing the hint, but the rendering just doesn't change at all. I even tried setting it with priority but nothing changes.

Any idea how to fix this? I am on Windows if that's relavent.


texts: Best practice for play location of projectile sound effects?

texts:
I am encountering an issue where I have a bullet that is destroyed on impact which is cutting off my bullet impact sound effect due to the audio source being destroyed. I like the idea of the sounds being attached to the projectile, but not sure if that is best practice.
I can play the sound from an NPC script, but not sure if that will open up other issues. Is this a better approach since the NPC material is "metal" so I should store all the "Metal hit" sound effects on the NPC?
...vs. having to store all material variations of impact on the projectile?


texts: Unity 2d circle collider not stopping after collision with box collider 2d

texts:
I'm using unity circle collider 2d and rigid body 2d but when it hits the box it doesn't stop there but instead just pass through and fall. Can someone help?

Circle Collider and rigid body 2d setting

Box Collider Settings

Game output

As you can see in game output my circle instead of stopping at collision it is getting passed by box. I want the circle to fall in square rather than free fall.


texts: Elastic Circle-Circle collision detection and response / Slime Volleyball physics

texts:
I am trying to recreate the Slime Volleyball game; however I am unsure how to go about implementing the physics of the ball movement.

The game consists of a circular ball and semi circle players that hit the ball over a net and against a wall. The ball cannot touch the floor.

I need to understand how exactly to implement the hitting of the ball against the player and what the physics entails.

I have already implemented gravity with a bouncing ball.

It is hard to find information related to implementing such physics from a game development perspective and I only have vague ideas about change in momentum from googling. If anyone could explain how to do so, I would greatly appreciate it.


texts: How can I make players move diagonally at equal speeds?

texts:
In a tile-based 2D RPG, a character is supposed to walk into all eight directions.

However, if we blindly tell the player to move in the direction (1, 1), he will be around 41% (√2-fold) faster. Thus, my next idea was to normalize the direction vector before moving.

Unfortunately, since the vector (1, 1) normalizes to (√2 / 2, √2 / 2) ≈ (0.71, 0.71), but the game functions on a whole-pixel basis, this will make the player reach invalid 2D locations. My next idea was that I should just make diagonal movement slower by √2 somehow.

So next, I tried another approach: When I receive an input and the player isn't already walking, I set the player's destination point. Then, I compute how much of his way to the destination the player can actually walk in one frame, given the player's velocity in "pixels per frame". I will repeat the player position update every frame, until the destination is reached.

So for example, if the player needs to move from the origin (0, 0) in the direction (1, 1) at speed 1, his sprite will be displayed at (0.71, 0.71) after one frame, and in the next frame it snaps to his destination (1, 1). This is okay, because the player ends up at a valid coordinate.

While this last approach sounds okay, it has only created more problems, because now diagonal movement takes two frames, and orthogonal movement takes only one frame. In other words, the walking speeds are still not equal.

How do you usually solve this?


texts: How do I make a custom tileset for Flixel that supports autotiling?

texts: I've been Googling this problem for a while now. I'm currently porting one of my Java games to Flixel, and I want to use the original 16x16 tileset I made. In the original game I implemented my own autotiling system, but I would prefer to use Flixel's autotiling system. However, I cannot determine how to lay out my tileset, or how to tell Flixel to use it. I have two different types of tiles, and I want both types to autotile to connect with tiles of the same type but not tiles of the other type, if possible.


texts: I have my character fixture and body(is a tank), so when I press the screen it throws a rocket(which also has a body and a fixture) that the player can controlll touching the screen. My game also has coins, which are dropped from boxes, when I destroy them, I don't want the rocket to collide with the tank, because the player can guide it anywhere(even to the tank), and it only get destroyed when touching an enemy. The problem here is that the rocket can touch a coin and move it, but it wouldn not happen. I've read that this can be solved using collision filtering, but I didn't understand very much this concept. I want the tank to collide with the coins, but not with the rocket, which should not collide with the coins.


texts: How do you simulate UV light and materials with UV-reflective/fluorescent properties within a PBR renderer?

texts:
I have a PBR setup, say, in Unity (or Unreal, doesn't really matter, I'm asking about the general principle, not specific implementation), and I would like to add a UV light source, and have control over how my materials respond to it, but still ideally have it conform to the rules of physically-based rendering.
Question is: what do I need to extend with what kinds of properties, and what are the equations to wire them together, and where do I plug those?
Do I need to actually do modifications like this, or does the fact that it already is PBR mean that I only need to plop in a light source with correct combination of settings, and correct responses to that UV source just naturally happen?
Edit:
I am asking about fluorescence, where I want certain materials to glow in particular visible light colours in places where the invisible UV light hits them.


texts: Many-to-one and feedback loop connections allowed in UE4 blueprints

texts:
Under what circumstances is it allowed to connect:

Multiple execution output ports (those with the blank triangle) in
different branches to one single execution input, effectively
merging the branches into one.
Either an output port to an input in the same node, or to an input
in a different node connected to the same branch but that is executed before.
Both, for execution and data ports. Therefore effectively creating a feedback
loop.

I know those rules are enforced by the editor, but I don't have one available at the moment.


texts: Rotating a row of Rubik cube in response to mouse position and drag

texts:
I made this cube in ue4..now I am able to rotate cubes separately without any problem.

But how do I move a row of cubes in response to mouse drag..

How do I detect what row is selected when my mouse is clicked and dragged on only one cube


texts: What is the difference between Sprite and SpriteBatch, specifically in the context of libGDX?

texts:
I'm using libGDX and I'm confused about the difference between the Sprite and SpriteBatch.

Anybody can explain it to me in a simple way?


texts: Project updates don't show up on mobile device

texts:
I've made a small application with libgdx framework, which works perfectly on desktop. It runs on Android too, however once I change something in my main project and try to recompile it on my phone, it seems like the Android still runs the old version.

I've tried to re-install the app, but it does not help. The only way I can see the changes on my phone is to recreate a different Android project.

Any ideas what might be causing this kind of behavior?

My projects are created the way it is shown here: http://code.google.com/p/libgdx/wiki/ProjectSetup

EDIT: Not sure why, but everything seems to work fine after "re-installing" Eclipse


texts: Struggling to smoothly implement 4-directional movement in Unity2D

texts:
This is my code so far:

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed;

    public Rigidbody2D rb;
    public Animator animator;

    Vector2 movement;

    void Update()
    {
        movement.x = Input.GetAxisRaw("Horizontal");
        movement.y = Input.GetAxisRaw("Vertical");
        movement = movement.normalized;

        if (movement.x != 0)
        {
            movement.y = 0;
        }

        else if (movement.y != 0)
        {
            movement.x = 0;
        }

        animator.SetFloat("Horizontal", movement.x);
        animator.SetFloat("Vertical", movement.y);
        animator.SetFloat("Speed", movement.sqrMagnitude);
    }

    void FixedUpdate()
    {
        rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
    }
}

I'm trying to restrict diagonal movement. The issue is that whenever up/down is being pressed, you can press left/right at the same time, and the object will then move left/right. When moving left/right, however, pressing up/down at the same time still has you continue left/right. Switching the position of the if/else if statements causes the same issue with converse directions. I'd prefer to have the player go in whatever the latest key press was for either direction!

I've tried making both statements if statements, as well as separating +/- values for both axes, but nothing changed! Any help is appreciated.


texts:
I'm creating a simple game with space ships made of blocks that are all the same size.  After having looked at this: Calculating the rotational force of a 2D sprite I have created the following code for applying a force

public void AddForceAtBlock(Vector2 force, Block block)
    {
        float mass = 1F*blocks.Count;
        this.velocity.X += force.X/mass;
        this.velocity.Y += force.Y/mass;
        Vector2 momentArm = GetGameWorldCoordinates(block) - centerOfMass;
        Vector2 parallelComponent = momentArm * (Vector2.Dot(force, momentArm) / Vector2.Dot(momentArm, momentArm));
        Vector2 angularForce = force - parallelComponent;
        Vector2 torque = angularForce * momentArm.Length();
        float momentOfInertia = 10000F*blocks.Count;
        float angularAcceleration = torque.Length()/momentOfInertia;
        this.rotationalVelocity += angularAcceleration;
    }

However this code is unable to create negative rotational acceleration so I think I did it wrong.  Will someone point out to me what's wrong here?

All blocks are 50 units wide, this is the output for a 3 block ship like so: TST where T are thrusters and S is a dull forceless block.  Floats are slightly imprecise as is shown in the debug log but it shouldn't matter for videogames.

Right Thruster
Stop 1: force = (0, 0.951147) momentArm = (50,0) parallelComponent = (0,0) torque= (0, 47.55) angularAcceleration = 0.001585 centerOfMass = (0,0)

Left Thruster
Stop 2: force = (0, 0.951147) momentArm = (-50, 0) parallelComponent = (-8.315191E-08, 7.269371E-15) torque = (4.157595E-06, 47.55735) angularAcceleration = 0.001585245 centerOfMass = (0,0)

As you can see the equation seems to be working but it fails to make the right thruster's angular acceleration negative.


texts:
I'm finishing my game,
i'm in the stage of optimisation, i tried multithreaded rendering and dynamic batching, with OpenGLES3..
i get a little bit increase , but now i'm getting function Clear take too much GPU ms..
any help guys


texts: Unity Webgl build: fast in Chrome, slow in Firefox, Opera and Edge

texts:
Good day.
I've a Chrome 'factory default' settings that can Run my unity webgl app fast, without problem (between 40 and 60fps).
Same app run at 1 fps in others browsers: edge, firefox and opera.
What can I check to solve ?
Thanks


texts: Odd blending result (semi-transparent 2d quad over 3D scene)

texts:
I'm working on a GUI library for my game, and I'm having problems with my blending.

I have a 3D scene, which I render with glDrawArrays. In the fragment shader the alpha color is hardcoded 1.0f (gl_FragColor).

When I render a 2D quad on my screen with 1.0f in the alpha channel, my quad is semi-transparent, while it should be completely opaque.

I render the quad with the basic glBegin(GL_QUADS) and glColor4f(0.0f, 0.0f, 1.0f, 1.0f).

I enabled blending with the function:

glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

What am I doing wrong? Why is my quad semi-transparent?

Screenshot:

Fragment shader:

#version 130
varying vec2 texture_coordinate;
uniform sampler2D texture;

void main()
{
    vec3 textureColor = texture2D(texture, texture_coordinate).rgb;
    gl_FragColor = vec4(textureColor, 1.0f);
}

Quad render code:

glBegin(GL_QUADS);
        glColor4f(0.0f, 0.0f, 0.7f, 1.0f);
        glVertex2f(position.x, position.y + size.y);
        glVertex2f(position.x + size.x, position.y + size.y);
        glVertex2f(position.x + size.x, position.y);
        glVertex2f(position.x, position.y);
    glEnd();

Thanks in advance.


texts: Height field/Shallow water eqation water simulation with ground height

texts:
Hey guys I found a lot of tutorials on 2D height field/swe water simulation but I have yet to find one that takes into account of ground height, i.e.

http://zejiazheng.com/?p=87

The overall water simulation results is fantastic however it does not takes into account of ground height and it doesnt work when the height of water is 0.

Would appreciate help on how to implement that as I've been stuck for several weeks on how to implement it. Thanks!


texts: Prevent cheating in html Javascript game

texts:
I have made a Javascript/html game. Now the problem I have is anyone can edit the client code and cheat in game for example there is a man shooting a enemy.

Man HP:          100
Enemy HP:      50

<div id ="man" hp="100" >
</div>

Now if someone changes the hp attribute to a very high value then he becomes literally immortal making the game easy.  Now how can I prevent this type of thing ?


texts:
Is there a way to check if a point is intersecting a body?

For example, lets say there's a body in the world at a position of (100,100).

Is there a way to check if a point at (100,100) intersects that body?

Another example is related to a game called "PHUN". In PHUN you can click and drag bodies around. How would you check if a mouse point is intersecting a body?


texts: Mesh-level acceleration structures for collision detection when mesh instances can be rotated, scaled and/or resized

texts:
Short version: in the mid-phase or narrow-phase of collision-detection, does any acceleration structure organizing the mesh's vertices (e.g. AABB-trees, Octrees, Quadtrees) work for the mesh's instances that are re-scaled, re-sizes and/or rotated?

Long version: suppose a concave mesh composed of a very high number of triangles (e.g. 200k) and for which I cannot use convex decomposition in order to perform collision detection. The most efficient solution usually employed would be to organize the vertices of the mesh using acceleration structures to quickly prune which parts of the mesh are likely to have been collided with.

However, that mesh is used for generating instantiated copies - and each of these can have different size, rotation and/or scale at any of the X,Y,Z axis. Would any acceleration-structures work since the instances can be re-scaled, rotated and resized? Suggestions, tips, academic references, are all appreciated.


texts:
I found many threads about line stipple (dashed or dotted lines) with OpenGL ES2.0, but there are never any code examples or tutorials on how to implement it.

How do I implement line stipple in OpenGL ES 2.0?


texts:
I'm having a problem with my game. If I press the "Home button" the game is paused... everythings fine, but if I then go back to the game all the resources are reloaded before I can continue the game. And it takes quite a bit. Is this normal, or is there a way to avoid the reloading?

I have write following code in onResume and onPause method. It loads same texture again and again on resume of game.

    @Override
    protected void onPause() {

            super.onPause();
            if (Utility.flagSound && mScene != null) {

                    if (mScene.getUserData().equals(Constants.GAME_SCENE))
                            Utility.isPlayLevelMusic = false;
                    else
                            Utility.isPlayLevelMusic = true;

                    audioManager.gameBgMusic.pause();
                    audioManager.levelBgMusic.pause();
            }

            if (this.mEngine != null && this.mEngine.isRunning()) {
                    this.mEngine.stop();
            }

    }

    @Override
    protected void onResume() {

            super.onResume();
            if (audioManager != null && Utility.flagSound && dataManager != null) {
                    if (Utility.flagSound) {
                            if (Utility.isPlayLevelMusic)
                                    audioManager.levelBgMusic.play();
                            else
                                    audioManager.gameBgMusic.play();
                    }
            }

            if (this.mEngine != null && !this.mEngine.isRunning()) {
                    this.mEngine.start();
            }

    }

I would be glad if anybody could help...


texts: Resolving collisions after initial collision

texts:
Given a sweep test for a ray, how do we check collisions after the 1st collision has been detected, and the ray has been deflected.

Physics system steps are:

Update velocities (gravity, etc)
Resolve collisions

The ray will intersect the floor, and will be moved back at the penetration amount.
The new velocity is calculated as a reflection

Update positions

The ray is now on the wrong side of the wall

This all happens in 1 frame

If the orange ray hits the floor just before the wall, the new velocity will tunnel the ray through the wall within one frame.
The naive way to fix this would be to after each collision check all the bodies again with the new velocity, but this can take multiple iterations if the ray bounces around in a corner. There is no way of knowing how many times the ray will need to be processed.

What would be a good way to fix this issue?


texts: Getting Started with Component Architecture: DI?

texts:
TLDR:  if I have entities like Ship and Bullet and components like Positionable and Drawable, should I create interfaces for each component and inject them into my entities using DI, or should I be doing something else?

(In this case, Ship would extend IPositionable and have an instance of a PositionableComponent which is injected by DI. Any calls to ship.getX or ship.setX would be implemented as myPositionable.getX or myPositionable.setX.)

I just moved away from MVC towards something more component-architecture-like. I have no concept of messages yet (it's rough prototype code), objects just get internal properties and values of other classes for now.

That issue aside, it seems like this is turning into an aspect-oriented-programming challenge. I've noticed that all entities with, for example, a position component will have similar properties (get/set X/Y/Z, rotation, velocity).

Is it a common practice, and/or good idea, to push these behind an interface and use dependency injection to inject a generic class (eg. PositionComponent) which already has all the boiler-plate code?

(I'm sure the answer will affect the model I use for message/passing)

Edit: The DI model I'm proposing is as follows.

Create entity classes like Ship and Bullet
Create interfaces to represent these components. Eg. I can expect a PositionableComponent.getX method.
Create component classes like PositionableComponent, DrawableComponent which implement my interface
Entities like Ship will have components like PositionableComponent. They will implement the methods by internally keeping an instance of a positionalbleComponent and redirecting all interface calls to the component.
My DI framework will (presumably automatically) wire up components by interface, eg. Ship._positionableComponent = new PositionableComponent(). This is how NInject works, which is the only framework I've ever used (and I'm working in Haxe now).

This will allow me to work on a higher level (ships contain components), and reduce boilerplate code (component implementations), but introduces duplicate code (redirecting to the internal component). Since I'm working in Haxe, I may be able to avoid writing that boilerplate by hand.

However, the advantage is that I can override component behaviours. If undeadMonster.IsAlive() should return true when its HP is above -100 (instead of 0), I can easily code this, and the change becomes very visible from the code level.

But I'm not sure if I'm solving this correctly.


texts:
I'm currently building a small 2D game in Processing (and it has to be Processing) for a school project. The basic makeup of the game is 4 different cells (objects, all are circles): An avatar, controlled by the player, a number of cowardly cells fleeing from all other cells, huntercells hunting and attempting to eat everything, and passive disruptorcells which will burst apart other cells in differnt ways depending on what they hit. Also, whether one cell is bigger than another affects the outcome of collisions. All these different cells are child classes of the cell superclass, all stored in a cells ArrayList, which is handled inside a World class, which is updated/displayed in the main Draw loop.

My main problem right now is how I should handle the outcome of all these different collisions, without too much code-duplication: My idea is to do it through a double for-loop, which would then again need 16 different if-like methods to figure out who's colliding with who, and what to do about it.

E.g. if a predator cell collides with prey cell, the latter will be eaten and the predator will grow a certain amount in size and speed. The outcome should be the same (predator grows, prey dies) if the tested subjects are found in reverse order through the for-loops. Cells also need to know where they are in relation to eachother all the time, so they know when/what to flee from/chase.

Any thoughts/suggestions on best practices and how to do this most efficiently are much appreciated.


texts: Retrieving DirectX9 Shader Input Parameters (vertex Input Layout)

texts:
Is it possible to retrieve the vertex input layout from an effect file in Direct3D9?

In Direct3D11 I can achieve this by using

D3D11_SIGNATURE_PARAMETER_DESC paramDesc;
ID3D11ShaderReflection* pRefector->GetInputParameterDesc(paramIndex, &paramDesc);

to get info about the input parameters.

I wish there was a way in Direct3D9 to do the same.


texts: Find X,Y Spiral positions by given ID. Hard formula.

texts:
I need to spawn new villages in my grid-based game map. But i am weak in advanced math.. I need to fetch coordinates by id. These 2 constants can be other numbers. Please help with the function in javascript :)

const DISTANCE = 3;
const FIRST_VILLAGE = [0,0];

function get_coordinates_by_id (id) {
  ..
}

get_coordinates_by_id(6) // returns [0, -3]
get_coordinates_by_id(11) // returns [0, 6]
get_coordinates_by_id(2) // returns [0, 3]

And in addition - i want it to return the coordinates without iteration of all the previous positions. I need a formula which just simply does many calculations and without iterations. If i have billion villages, i don't want it to iterate billion times until it finds the position.


texts: changing a sprite width when playing a reel using Crafty.js

texts:
can anyone help me with this : http://jsfiddle.net/B5UsC/20/

you can see that the sprite animation is not rendering correctly when the reel is in the last frame when animating Hardpunch is it possible to change the character width when playing a specific frame ? like you see my spritesheet does not contain a static width and height so it's a bit confusing for me

THE CODE :

// initialize the sprite
Crafty.sprite("http://i.imgur.com/bkYVEe5.png", {
    Ryu: [0, 0, plrw, plrh]
});

// initialize the component
Crafty.c("RyuAnimation", {
    init: function () {
        this.requires("SpriteAnimation,Keyboard")
        .addComponent("Ryu")
        .reel('idle', 300, [
            [0, 0],
            [plrw * 1, 0],
            [plrw * 2, 0],
            [plrw * 3, 0]
        ])
        .reel('punch', 300, [
            [plrw + 12, plrh],
            [plrw * 2 + 15, plrh]
        ])
        .reel('Hardpunch', 300, [
            [plrw * 3 - 25, plrh],
            [plrw * 4 + 32, plrh],
            [(plrw + 19) * 5 - 38, plrh]
        ]); //
        this.animate("idle", -1);

    }

    // creating the player
    plr1 = Crafty.e("2D,Canvas,RyuAnimation")
    .attr({
    x: 15,
    y: ch - 100
})
.start(3);
this.bind('KeyDown', function () {
    if (this.isDown('A')) {
        if (!this.isPlaying("Hardpunch")) {
            this.pauseAnimation().animate("Hardpunch", 1);
        }
    } else {
        this.stop();
    }

});

I read about handling complex sprite sheet with different width and height and all the answers was about creating evenly sized boxes for all sprites like this example here : How do I support animation with frames of different sizes?  but i actually couldn't understand what the mean by that and how would i do it they didn't provide an example . what is evenly sized boxes?


texts: Pix for visual studio express 2012 (Desktop)

texts:
(Originally asked on stackoverflow)

Using visual c++ express 2010 for direct3d you have to download the directX sdk and there is a tool called pix for debugging shaders, looking at 3d resources etc.

With visual studio 2012 express the directx sdk is included in the windows sdk that comes with it but this does not seem to include the winpix.exe tool. Is this very useful tool still available? I guess I can still use the one from the previous sdk but it seems wrong to install the entire sdk just for that tool.

Is there a version for VS2012 express that I'm missing?


texts: How to set up Easy Mobile Pro to work with assembly defintions?

texts:
I have a project with EMP imported, and now I would like to use assembly definitions to clean up my project a little bit. Everything works fine in the editor, but when I hit Build player script in my Addressables or just trying to Build I get a bunch of nasty error messages. When I switch to VS obviously there are no issues in the code editor.
I have asmdef files in:

Core folder in my Scripts folder, these are scripts created by myself. -asmdef
EMP-Editor folder -> this one references 3. -asmref
EMP-Scripts folder -asmdef

There are the kind of errormessages coming up(when trying to build only, there are 200 of them):

Assets\Plugins\EasyMobile\Editor\EM_BuiltinObjectCreator.cs(6,19): error CS0234: The type or namespace name 'SceneManagement' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)
Assets\Plugins\EasyMobile\Editor\EM_SettingsEditor_Privacy.cs(9,24): error CS0234: The type or namespace name 'SerializedProperty' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)
Assets\Plugins\EasyMobile\Editor\EM_SettingsEditor_Privacy.cs(10,24): error CS0234: The type or namespace name 'EditorStyles' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)

I tried adding a refernece to the Unity.Editor dll in VS to the EMP assembly, but VS just doesn't do anything, no errors, no messages...Tried the same in asmdef file in Unity with no luck...

I got the inspiration from this video, and it was working ok...

Unity 2019.3
VS 2019
Android platform
EMP 2.5.2

Thanks


texts: Which app markets should I deploy my Android game to?

texts:
I just launched my Android game today. I'm curious to know where I can deploy it. Of course, Google Play is the veritable king of markets, and my own game site will be next.

After that, which marketplaces are mature and are worth deploying to?

I looked at:

SlideMe
GetJar
Soc.io

And some other ones that I didn't use:

YAAM (kept crashing and erroring out)
1Mobile (couldn't figure out how to upload my app)
Insyde Market

My question is really, which ones are out there and are worth uploading too? (And 1Mobile seems good, but just can't figure out how to upload.)

Each site requires their own size screenshots and logo, so it's a bunch of extra work. I'd rather stick to the 80/20 rule and apply 20% effort to hit 80% of the markets.


texts: Best aproach to Ground level detection for spells/skills

texts:
I'm making a 3d Hero Defense/Tower defense kind of game with unity3d. A made a skill system with scriptable objects that lets the Defender use skills on the terrain doing damage to enemies that can be damaged. Because of the complexity of the terrain in some parts (slopes going up or down) i made a function to detect ground level like this:

protected float GetGroundPosition(Vector3 position)
{
    LayerMask GroundLayer = 1 << GROUND_LAYER;
    RaycastHit hitInfo;
    Physics.Raycast(position, -transform.up, out hitInfo, GROUND_DETECT_DISTANCE, GroundLayer);
    if (hitInfo.collider != null)
    {
        return hitInfo.point.y;
    }
    else
    {
        Physics.Raycast(position, transform.up, out hitInfo, GROUND_DETECT_DISTANCE, GroundLayer);
        return hitInfo.point.y;
    }
}

Then i subdivided my raycast in several small ones like this:

protected void DealBaseDamageInALine(Vector3 cursorPosition, float slashSize)
{
    List<GameObject> alreadyHit = new List<GameObject>();
    Vector3 startRaycast = new Vector3(transform.localPosition.x, GetGroundPosition(transform.position), transform.localPosition.z);
    for (int i = 1; i <= GROUND_COLLISION_RAYCAST_NUMBER; i++)
    {
        Vector3 endRaycast = startRaycast + transform.forward * (config.GetAoe() / (i * 2));
        endRaycast = new Vector3(endRaycast.x, GetGroundPosition(endRaycast), endRaycast.z);
        Debug.DrawLine(startRaycast, endRaycast, Color.blue, .5f);
        RaycastHit[] hits = Physics.CapsuleCastAll(startRaycast, endRaycast, slashSize, Vector3.up);
        foreach (RaycastHit hit in hits)
        {
            var hitObject = hit.collider.gameObject;
            var damageable = hitObject.GetComponent<HealthSystem>();
            if (damageable != null && !alreadyHit.Contains(hitObject))
            {
                float damageToDeal = config.GetDamage();
                damageable.Damage(damageToDeal, config.GetElementalType());
                alreadyHit.Add(hitObject);
            }
        }
        startRaycast = endRaycast;
    }
}

I made a graph to better conceptualize what i made:

I use around 64 segments and a 50f raycast depth for the ground detection and it works/performs quite well (i noticed a 3-4ms increase in my older PC though).

But my question is: are there better approches to this? maybe i overdid something that could be done more easily.


texts: Why would anti-aliasing work for the debug runtime but not the retail runtime?

texts:
I'm experimenting with setting various graphical settings in my Direct3D9 application, and I'm currently facing a curious problem with anti-aliasing. When running under the debug runtime, AA works as expected, and I don't have any errors or warnings. But when running under the retail runtime, the image isn't anti-aliased at all. I don't get any errors, the device creates and executes just fine.

As I honestly have little idea where the problem is, I will simply give a relatively high-level overview of the architecture involved, rather than specific problematic code. Simply put, I render my 3D content to a texture, which I then render to the back buffer.

Why would this be?


texts:
I'm creating a simple 2d game with c++ and SFML, and I've got a simple framework going for animating a sprite using a "SpriteSheet" image (an big image containing all the "frames" of an animation)

I've got it working fairly well, I've attempted to copy the concept from another engine i'm familar with (Starling for Flash).. in which they use a "Juggler" which updates a sprite's properties based on a timeline, independant of the sprite...

I've got the animation working for swapping frames using a class i created called Tween... it calls a function update(float gameTime); which updates the sprites subRect to the correct frame...

I'd like to make this a more rebust solition, allowing the Tween class to do more than just frame animations.. I've been trying to use polymorphism to create Children to Tween such as "Anim", "Move", "Rotate", and "Scale" which all have a update() function which updates the sprite accordingly... The idea being a list of a number of these classes (for instance, a Scale and Rotate) can be added to a vector list and then each can call their update function, each updating their specific functions.. the problem seems to be that if i create a list of Tweens, then call update, it uses Tweens implementation of Tween.update() and not it's inherited children, I don't know how/if it's possible to allow this...


texts: Using different shaders based on desktop or mobile?

texts:
Most of my assets use the Unity standard shader. It looks and runs fine on Desktop, but on mobile the performance isn't good.

I assume the solution is to switch to one of the mobile friendly vertex-lit shaders for mobile. But how can I switch shaders depending on platform? Is there a way that Unity can do this for you, or do I need to manually change them before building? Also, would I be able to just specify the shader, or would I need to create all new materials for all my assets?

I really have no idea how to approach this, and I'd appreciate it if I can be pointed in the right direction.


texts: Collision detection of player larger than clipping tile

texts:
I want to know how to check for collisions efficiently in case where the player's box is larger than a map tile.

On the left is my usual case where I make 8 checks against every surrounding tile, but with the right one it would be much more inefficient.

(picture of two cases: on the left is the simple case, on the right is the one I need help with)

How should I handle the right case?


texts: I am looking to make a spaceship tilt as it corners but I cant get it to return

texts:
I am using the TL game engine I am not allowed to use a physics engine but I need to make the spaceship lean as it corners, I can make it lean but cannot make it return to its starting position. I have looked at implementing some kind of spring physics but I don't understand it.

Here is my code so far

if(myEngine->KeyHeld(Key_A))
    {
        car->RotateY(carSteer * frameTime);
        if(carSteer >= -carMaxSteer)
        {
            carSteer -= carSteerIncrement;
            car->RotateLocalZ(-(carSteer * frameTime));
        }
    }
    if(!myEngine->KeyHeld(Key_A))
    {
        if(carSteer < 0)
        {
            carSteer = 0;
        }
    }
    if(myEngine->KeyHeld(Key_D))
    {
        car->RotateY(carSteer * frameTime);
        if(carSteer <= carMaxSteer)
        {
            carSteer += carSteerIncrement;
            car->RotateLocalZ(-(carSteer * frameTime));
        }
    }
    if(!myEngine->KeyHeld(Key_D))
    {
        if(carSteer > 0)
        {
            carSteer = 0;
        }
    }

All the functions I am calling are built into the engine and I did not write them.
Any Help Would Be Appreciated Thanks.


texts: Unwanted line between chunks in heightmap infinite terrain

texts:
I can't figure out what is causing the line between my two chunks.  They are completely aligned.  It must be something to do with the algorithm.  I am using lua with the love2d game engine.  Here is a pic:

Here is the code:

seed = 257
local canvas = love.graphics.newCanvas()

function Interpolate(a, b, x)
    ft = x * 3.1415927
    f = (1 - math.cos(ft)) * 0.5

    return  a*(1-f) + b*f
end

function Noise(x, y)
    n = x + y * seed
    n = bit.bxor((bit.lshift(n,13)),n)
    return ( 1.0 - ( bit.band((n * (n * n * 15731 + 789221) +
      1376312589), 0x7fffffff) / 1073741824.0))
end

function SmoothedNoise1(x, y)
    corners = ( Noise(x-1, y-1)+Noise(x+1, y-1)+Noise(x-1,
      y+1)+Noise(x+1, y+1) ) / 16
    sides   = ( Noise(x-1, y)  +Noise(x+1, y)  +Noise(x, y-1)  +Noise(x,
      y+1) ) /  8
    center  =  Noise(x, y) / 4
    return corners + sides + center
end

function InterpolatedNoise_1(x, y)
    integer_X, fractional_X = math.modf(x)
    integer_Y, fractional_Y = math.modf(y)

    v1 = SmoothedNoise1(integer_X,     integer_Y)
    v2 = SmoothedNoise1(integer_X + 1, integer_Y)
    v3 = SmoothedNoise1(integer_X,     integer_Y + 1)
    v4 = SmoothedNoise1(integer_X + 1, integer_Y + 1)

    i1 = Interpolate(v1 , v2 , fractional_X)
    i2 = Interpolate(v3 , v4 , fractional_X)

    return Interpolate(i1 , i2 , fractional_Y)
end

function getExampleMap()
    mapWidth = 400
    mapHeight = 400
    mapMin = InterpolatedNoise_1(0, 0)
    mapMax = mapMin
    map = {}
    amp = 128
    freq =32
    octaves = 6
    for x = 0, mapWidth - 1 do
        map[x] = {}
        for y = 0, mapHeight - 1 do
            map[x][y] = 0
            for i = 1, octaves do
                map[x][y] = map[x][y] + getNoiseValue(x, y, freq / i,
                  amp / i)
            end
            mapMin = math.min(mapMin, map[x][y])
            mapMax = math.max(mapMax, map[x][y])
        end
    end
    -- /*scale the values between 0 and 255 for rendering in grey
      scale.*/
    mapMultiplier = 255 / (mapMax - mapMin)
    for x = 0, mapWidth - 1 do
        for y = 0, mapHeight - 1 do
            map[x][y] = map[x][y] * mapMultiplier
        end
    end
end

function getExampleMap2()
    mapWidth = 400
    mapHeight = 400
    mapMin = InterpolatedNoise_1(0, 0)
    mapMax = mapMin
    map2 = {}
    amp = 128
    freq =32
    octaves = 6
    for x = 400, (mapWidth + 400) do
        map2[x] = {}
        for y = 0, mapHeight - 1 do
            map2[x][y] = 0
            for i = 1, octaves do
                map2[x][y] = map2[x][y] + getNoiseValue(x, y, freq / i,
                  amp / i)

            end
            mapMin = math.min(mapMin, map2[x][y])
            mapMax = math.max(mapMax, map2[x][y])
        end
    end
    -- /*scale the values between 0 and 255 for rendering in grey
      scale.*/
    mapMultiplier = 255 / (mapMax - mapMin)
    for x = 400, (mapWidth + 400) do
        for y = 0, mapHeight - 1 do
            map2[x][y] = map2[x][y] * mapMultiplier
        end
    end
end

function getNoiseValue(x, y, freq, amp)
    return InterpolatedNoise_1(x / freq, y / freq) * amp
end

function love.load()
    love.window.setMode( 1920, 1080, {fullscreen=false})
    getExampleMap()
    getExampleMap2()
end

function love.draw()

    for x = 0, mapWidth - 1 do
        for y = 0, mapHeight - 1 do
            love.graphics.setColor(map[x][y], map[x][y], map[x][y], 255)
            love.graphics.point(x,y)
        end
    end
    for x = 400, (mapWidth + 400) do
        for y = 0, mapHeight - 1 do
            love.graphics.setColor(map2[x][y], map2[x][y], map2[x][y],
              255)
            love.graphics.point(x,y)
        end
    end

end

function love.update()

end

function love.keyreleased(key)
    if key == "escape" then
        love.event.quit()
    end
end

If I use seed 345 there is no line.


texts:
I need to map texture to shape. Texture:

This is a example of shapes I need to map texture to:

Notice that each piece in mesh has exactly 4 point to map texture. Logic is pretty straight forward: Top center edge to top in mesh etc.

I found some methods on Graphics object like texture(...) however these methods cannot handle diamond texture properly..?

I found this method:

ShapeRenderer.texture(shape, image, generator)

Where generator is:

org.newdawn.slick.geom.TexCoordGenerator

However I don't understand How It can be used to map the image to the shape.

How to use it? Is there other way?


texts:
I am trying to add spherical harmonics based ambient lighting to my game but have run into some problems and while trying to solve this I have reduced the test scene to the following very basic scenario.

The scene consists of

Two walls (red and green)
Single light probe in the middle. Since a probe is just empty space there need to be some ‘normal’ vector used when integrating over the hemisphere (defined by that vector). To fit this simple example this probe only have two such vectors pointing in opposite directions (i.e. at each wall).

The light source is rotated 360 degrees (2*PI radians) while the final light solution is evaluated in the two directions.

Now if I simply plot the magnitude of the two light color vectors I get

Since the scene is symmetrical except for the colors I would expect that the magnitude of the ‘color vectors’ (as plotted above) to be identical except for a phase shift. This, however, does not appear to be the case and this is my problem.

Further if I simply plot the shadowed solution (i.e. exclude the bounced coefficients), I get

which is what I expect (i.e. seemingly identical except for a phase shift).

Also, if I just take the bounced coefficients into account (i.e. exclude the shadowed), then I get

which again looks reasonable in that the two curves are identical (the color components, not visible in this plot, are rearranged but the magnitude stays the same).

As far as I know I am supposed to be able to add the two coefficient sets (shadowed and bounced) to get the final result but when I do, it just looks wrong as can be seen in the first plot.

I have been stuck on this for quite a while now so if anyone could offer some advice I would appreciate it. I'd be happy to post more details if there is any interest.


texts: Calculating the correct particle angle in an outwards explosion

texts:
I'm creating a simple particle explosion but am stuck in finding the correct angle to rotate my particle. The effect I'm going for is similar to this:

Where each particle is going outwards from the point of origin and at the correct angle. This is what I currently have:

As you can see, each particle is facing the same angle, but I'm having a little difficulty figuring out the correct angle. I have the vector for the point of emission and the new vector for each particle, how can I use this to calculate the angle?

Some code for reference:

 private Particle CreateParticle()
        {
...

            Vector2 velocity = new Vector2(2.0f * (float)(random.NextDouble() * 2 - 1), 2.0f * (float)(random.NextDouble() * 2 - 1));

            direction = velocity - ParticleLocation;

            float angle = (float)Math.Atan2(direction.Y, direction.X);

...

            return new Particle(texture, position, velocity, angle, angularVelocity, color, size, ttl, EmitterLocation);
        }

I am then using the angle created as so in my particles Draw method:

spriteBatch.Draw(Texture, Position, null, Color, Angle, origin, Size, SpriteEffects.None, 0f);


texts:
I am working in unity and I have a group of buttons that I activate/deactivate at various times in the game. However, I have noticed that when I call button.SetActive(true) the button doesn't appear in the scene right away. In one particular circumstance, I need the button the appear before the next line of code is run. Is there a way to force the button/scene to update immediately?

Edit: To give some context, I am working on a card game similar to Magic the Gathering where there are different types of mana and there are some cards with a neutral cost. When a player plays one of these cards I activate 5 buttons (one for each mana type), and I want the player to click a button to spend one mana of that color, and to repeat that process until the neutral cost is met.

When I try to use a while loop or a coroutine to essentially pause execution until a user clicks a button (or multiple, depending on the card's cost), I cause an infinite loop because even though I set the buttons to active before the loop/coroutine, they don't actually activate by the time the loop starts.


texts: How to access an uniform array with a float as index in GLSL?

texts:
I'm trying to do basic multitexturing of terrain in OpenGL.

Im building the terrain with an image representing different elements (beach, water, jungle...) :

Im trying to map each color of this image with a texture in my game: green color means grassTexture (id 0), blue color means waterTexture (id 1), etc...

My fragment shader contains an uniform array containing all textures that I use (grass, water, ...) :

// Terrain.frag
uniform sampler2D terrainTextures[50];

For each vertex of the terrain, I pass a float in_TextureId corresponding to a texture id :

// Terrain.vert
layout (location = 0) in vec3 in_Vertex;
layout (location = 1) in vec4 in_Color;
layout (location = 2) in vec3 in_Normal;
layout (location = 3) in vec2 in_TexCoord;
layout (location = 4) in float in_TextureId;

Then im trying to display the correct texture for a vertex with this textureId in the fragment shader :

outputColor = texture(terrainTextures[int(textureId)], texCoord);

With this line, I have this result :

If I modify the code of the fragment shader with the following code :

highp int tid = int(textureId);
if(tid == 2)
{
   outputColor = texture(terrainTextures[int(textureId)], texCoord);
}
else if(tid == 1)
{
   outputColor = texture(terrainTextures[int(textureId)], texCoord);
}
else outputColor = texture(terrainTextures[int(textureId)], texCoord);`

It works better :

I can't understand why it's working with this code, i'm doing exactly the same thing in the first example.

Maybe it's not the good way to access an uniform array ?


texts: Drawing a circle in OpenGL ES Android, squiggly boundaries

texts:
I am new to OpenGL ES and facing a hard time drawing a circle on my GLSurfaceView.  Here's what I have so far.

The circle class

public class MyGLBall {

private int points=40;
private float vertices[]={0.0f,0.0f,0.0f};
private FloatBuffer vertBuff;

//centre of circle

public MyGLBall(){

    vertices=new float[(points+1)*3];
    for(int i=3;i<(points+1)*3;i+=3){
      double rad=(i*360/points*3)*(3.14/180);
      vertices[i]=(float)Math.cos(rad);
      vertices[i+1]=(float) Math.sin(rad);
      vertices[i+2]=0;
    }
      ByteBuffer bBuff=ByteBuffer.allocateDirect(vertices.length*4);
      bBuff.order(ByteOrder.nativeOrder());
      vertBuff=bBuff.asFloatBuffer();
      vertBuff.put(vertices);
      vertBuff.position(0);

}

public void draw(GL10 gl){
    gl.glPushMatrix();
    gl.glTranslatef(0, 0, 0);
//  gl.glScalef(size, size, 1.0f);
    gl.glColor4f(1.0f,1.0f,1.0f, 1.0f);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glPopMatrix();
 }

 }

I couldn't retrieve the screenshot of my image but here's what it looks like

As you can see the border has crests and troughs thereby rendering it squiggly, which I do not want. All I want is a simple curve.


texts: Does HDR rendering have any benefits if bloom won't be applied?

texts:
At the moment I use an image based light in my game for environment lighting. I sample a sky cubemap to get diffuse and specular lighting. At the moment I use a HDR rendering pipeline - the skybox uses 16 bits of storage. I draw to a 16 bit rendertarget, then at the end use a tonemapping operator to scale the values into the 0.0 - 1.0 range to be drawn to the backbuffer.

Recently I noted that most of my rendering pipeline was basically made pointless when I removed the bloom postprocessor. Nothing is actually done with the higher dynamic range values - they just get processed down to lower dynamic range values at the final stage of post processing.

Would I be right in saying that I might as well just use a low dynamic range pipeline and manually tonemap my skyboxes in Photoshop? This would make the pipeline much simpler.
Is there any reason other than bloom why I might want to have HDR data?


texts: how to control units in a game using scripts

texts:
I'm looking to create a game like screeps, in which the user controls their units using javascript.  I am planning on using lua as the scripting language that controls the units in my game, as it is supposedly easily embeddable.  After doing some research, I decided that I should code the game in C++ and allow the player to access the objects (or the C++ equivalent of Lua's tables) in C++ that represent the units in the game through lua.

So far I have been able to send C++ functions to a Lua environment using LuaBridge.  However, I'm not sure how to expose unit objects to the player through lua.  The player should only be able to change certain attributes of the object (for example, they shouldn't be allowed to change the object's position to anywhere on the map, but they should be able to view the unit's position).  The user should also be allowed to run functions like unit1.forward that can change the units position.

What is the best way to implement this behavior?


texts: What's the Unity way of implementing data driven UI

texts:
I'm used to application development with frameworks like Qt, and I'm really fond of using MVC-like patterns. Now I'm diving into game dev and I have a bunch of data that I want to show the user and I'm wondering the Unity way to do that. For example, say I want a flyout menu that appears on hover of an ability that looks like this badly drawn paint image below:

Say I have 60+ abilities on paper that all have the following data:

ability art icon
name
description
attributes such as cooldown amount, type, modifiers, etc

I want to make it such that I can feed some system this data and it just displays the correct thing at the right time. This way when I add new abilities the system already just knows how to handle it.
My question:
What is the Unity way to:

Store this data?
Use this data to drive a UI element?

I've looked at scriptable objects, they seem like they will play a role here but I'm still unclear as to how that gets mapped to UI elements. I'm also guessing that scriptable objects are preferred over reading in a JSON file or data on a database? Maybe someone can confirm that. I suppose I'm asking for best practice here.


texts: How to orient a surface normal to a cubic surface

texts:
The immediate question is: in HLSL, how can I orient a surface normal generated in UV space so that I can apply it to a cube face?

The overall project is that I'm trying to build a procedural planet generator.  I'm using a cube projected to a sphere where each face is a quad-tree.  The intermediate project is that I want to generate a normal map for the terrain.  I think the best way for me to do this (and understand what I'm doing) is to generate the normals for the cube version first, then work out the transformations to warp those normals to the sphere.

Ideally the method would not involve branching code based on which face I'm working on (i.e., if we're on the top side of the cube, then U = X and V = Y).  In other words, what I'm hoping for is some math-magic like "Oh, just cross multiply the terrain normal by the dot product of the cube face normal and blah blah blah".

9/20/10 ETA:

I know how to calculate normals for a flat surface.  My subsequent problem is two-fold:

How do I rotate the normal map so it is oriented correctly on each of the cube faces?
how do I warp the flat normal map so that it wraps the sphere?

I've found one solution that uses a Jacobian matrix, but I can't get it to work.  Even when all of the normals are pointing straight up (i.e. a flat surface), the HLSL code involving the Jacobian totally messes up the lighting--so it makes me not trust my implementation of the solution.


texts: Rotating a swinging sword in LWJGL gives wierd results

texts:
I'm making a 2d top down game in Java using LWJGL(OpenGL, essentially). I recently tried adding a swinging sword mechanism. My coordinate system is set to the bottom left FOR ALL objects. The rotation worked, but it happens with respect to the bottom left corner of the Sword Quad. I want it to rotate with the center of the bottom line as the pivot for rotation. I tried a lot of solutions from the internet like:

translating the object to origin(0,0 of the screen), then rotating, then translate to the point of pivot.
translating object normally, then rotating, then again translating to the point you want it to pivot at.

But they all yield weird results.

Here's the code:

The Sword Class:

public class Sword extends GameObject {

    private static int speed = 5, deg = 0;;

    private Texture tex;

    public Sword(float x, float y, ObjectId id)  {
        super(x, y, id);

        //tex = ImageLoader.loadTexture(null, null);
    }
    protected void update(ArrayList<GameObject> objects) {
        if(deg < 360) deg += 1;
        else deg = 0;
    }

    protected void render() {
        Draw.rect(x, y, 10, 32, deg, 1, 0, 0);
    }

    public Rectangle getBounds() {
        return null;
    }

}

The Draw.rect method:

public static void rect( float x, float y, float width, float height,
                         float deg, float r, float g, float b) {
        glDisable(GL_TEXTURE_2D);

        glPushMatrix();
        {
            glTranslatef(0, 0, 0);
            glRotatef(deg, 0, 0, 1);
            glTranslatef(x + (width/2), y, 0);

            glColor3f(r, g, b);

            glBegin(GL_QUADS); // Specifies to the program where the drawing
                               // code begins. just to keep stuff neat.
                               // GL_QUADS specifies the type of shape
                               // you're going to be drawing.
            {
                glVertex2f(0, 0); // Specify the vertices. 0, 0 is on BOTTOM
                                  // LEFT CORNER OF SCREEN.
                glVertex2f(0, height); // 2f specifies the number of args
                                       // we're taking(2) and the type
                                       // (float)
                glVertex2f(width, height);
                glVertex2f(width, 0);
            }
            glEnd();
        }

        glPopMatrix();

        glEnable(GL_TEXTURE_2D);
    }

EDIT: Here is an image of what "weird result" is. In the pic, I'm translating first to origin[(0, 0) of the WORLD], then rotating(by 90 degrees), then translating to translating to [x - (width/2) , y]. As you can see, the red block that represents the sword is out of the "arena", even though I've set the x, and y of the sword to near the player. The image:


texts: How to make Box2D bodies automatically return to a initial rotation

texts:
I have two long Box2D bodies, that can collide while moving one of them around with MouseJoint. I want them to try to hold their position and rotation.

Blue body is moved using MouseJoint (yellow) towards the Red body. Red body has another MouseJoint - Blue can push Red, but Red will try to return to the start point thanks to the MouseJoint - this works just fine.
Both bodies correctly rotate along the middle. This is still as I want. I change the MouseJoint to move the Blue away.
What I need is both bodies return to their initial rotation (green arrows)
Desired positions and rotations

Is there anything in Box2D that could do this automatically? The MouseJoint does that nicely for position. I need it in AndEngine (Java, Android) port, but any Box2D solution is fine.

EDIT: By automatically I mean having something I can add to the object "Paddle" without the need to change game loop. I want to encapsulate this functionality to the object itself. I already have an object Paddle that has its own UpdateHandler which is being called from the game loop. What would be much nicer is to attach some kind of "spring" joint to both left and right sides of the paddle that would automatically level the paddle. I will be exploring this option soon.


texts:
I am trying to do an appication in monogame windows. I have a long text to be displayed on screen. I tried to render it on screen using spriteBatch.Drawstring, was succesful to an extent. But, the text did not fit into a required area. I had followed this tutorial. I need a vertical scroll to be implemented to have the entire text inside my desired area. Can anyone suggest some help. This is my current code :

protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        _boxTexture = new SolidColorTexture(GraphicsDevice, Color.Red);
        _borderRectangle = new Rectangle(100, 100, 500, 500);
        _textboxRectangle = new Rectangle(105, 105, 490, 490);
        _font = Content.Load<SpriteFont>("Rockwell");
        _text = "He determined to drop his litigation with the monastry, and relinguish his claims to the wood-cuting and fishery rihgts at once. He was the more ready to do this becuase the rights had becom much less valuable, and he had indeed the vaguest idea where the wood and river in quedtion were.";

    }

private String parseText(String text)
{
String line = String.Empty;
String returnString = String.Empty;
String[] wordArray = text.Split(' ');

foreach (String word in wordArray)
{
    if (font.MeasureString(line + word).Length() > textBox.Width)
    {
        returnString = returnString + line + '\n';
        line = String.Empty;
    }

    line = line + word + ' ';
}

return returnString + line;
}

and inside draw function :

spriteBatch.DrawString(font, parseText(text), new Vector2(textBox.X, textBox.Y), Color.White);


texts: Does it make sense to implement the logic to skip rendering objects outside the viewport or should I not care about it and let the Framework do it?


texts:
What are some proven and preferable patterns to realise multiple "screens" in the game? Not in the sense of displays (monitors) but "views" within the application.

Say it's a Civ/Heroes-type game. We will typically have these screens during the proper gameplay:

Main map (strategic)
Battle map (tactical)
City management screen
Research screen
etc.

As you can see, some of them are UI-like in nature but some are full-blown interactive scenes.

We need to be able to:

Quickly switch between them
Keep a global game state between them (e.g. the (in-)famous GameManager instance must stay intact)
Bonus points if able to make a fancy transition (e.g. city screen rolling down from above)
Bonus points if able to keep one screen (e.g. city screen) only partly covering another (e.g. the strategic map) and both are animated

Theoretical solutions I can imagine (I'm still a Unity noob):

Separate scenes for each screen. But will the engine be able to switch between them fast? (I read that a scene is akin to a "level" in a traditional game, which usually means a loading time?) Also, how will I track the global state (GameManager)? Can I overlay one screen over another?
Everything in one Unity scene but multiple cameras looking at different objects, with switching between them or nesting. E.g. one camera looking at the map grid, another at a city screen etc. But then I run the risk of objects from one "scene" (only virtually) affecting others (e.g. lights or particles) unless I place them sufficiently far apart.

Is any of my ideas going in the right direction? Is there a better pattern that I'm missing?


texts: How can I incrementally generate an graph?

texts:
I just started a new project in which I'd like the game world to consist of procedurally-generated locations connected by teleporters.  After a bit of research, I've discovered this to be called either "graph theory" or "bloody complicated", depending on who is discussing it.  Unfortunately, I've found very little information on generating graphs; most of the tools I've seen are directed toward examining existing graphs.

Assuming I have the terminology correctly sorted out, my requirements are that the graph be:

simple — no location (vertex) should have a teleporter (edge) which connects back to itself, nor should two vertices have multiple edges connecting them
connected — it should be possible to travel between any two vertices in the graph (though I don't foresee ever needing to find the path; simply knowing the player could find one if they chose to is sufficient)
cyclic — there should be more than one path between any two vertices
undirected — all edges can be traveled in either direction
infinite — if the player so wishes, they should be able to travel indefinitely, with the graph continuing to generate incrementally as they approach its outermost unexplored vertices
locally finite — a vertex's degree should never change after the player has visited it
stably labelled — each vertex represents a location which will itself be procedurally generated from a seed; the same seed must be assigned to a vertex regardless of what path the player used to travel there or how large the graph is when they do

I've had some ideas (which I've not yet tried to implement) regarding using the local maxima of 2D perlin noise as vertices (the input x and y could then be used as its label), but that feels clunky and overcomplicated.

Is there a better way to generate a graph like this?  I'm developing in Python 2.6 using Panda3D and numpy, and would of course be willing to look at including other libraries if they'll help with this problem!

Edit

I think I've done a poor job explaining some of my requirements, so it's illustration time!  Hopefully, this will clear things up.

What I mean by having stable labels is that I want, for example, Player A to be able to do a bunch of exploring and find, among other things, a cyclic path back to their starting location and a mountain that looks like a cat.  His game now looks something like the following (vertices are numbered with their seed and edges with the order in which the player traversed them).  He started on vertex 8329 (green) and Happycat Mountain is in vertex 6745 (blue).

Player A's good friend Player B is a fan of cats, so he wants to show it to her.  He gives her the root seed for his world and directions along the shorter route to the mountain of interest.  Her game should now look like this:

The problem I'm currently having the most difficulty with is "How do I generate the same seeds for Player B when her exploration hasn't followed the same path?"  That's what led me to the idea of using Perlin noise — as long as the same root seed is used, the maxima won't move, so their coordinates could be used as stable vertex seeds.


texts: Unity: how do I get a list of prefab tiles from the TileMap?

texts:
I'm building a 2D strategy game where I've decided to use TileMap for spaces which characters can traverse. My tiles need to be prefabs, because they will have a script attached to them to store things like their type, cost, any effects they might have on them, name, etc.
To build the TileMap I imported Unity 2D Extras and used its prefab brush. I've actually tried this a couple of ways. First I just manually placed the prefabs and dragged them into the hierarchy under GameTileMap. When that didn't work I thought maybe I needed to do it with the prefab brush so I deleted everything and did the whole thing again that way. Still nothing.
Here is how my Hierarchy looks:

And this is the code I used to try and get that list of all the Tile prefabs I have there:
using UnityEngine.Tilemaps;
using UnityEngine;

public class TileManager : MonoBehaviour {

  public static TileManager instance;
  public Tilemap Tilemap;

  void Awake() {
    if (instance == null) {
      instance = this;
    }
    else if (instance != this) {
      Destroy(gameObject);
    }

    // Do I even have any tiles?
    TileBase[] allTiles = Tilemap.GetTilesBlock(Tilemap.cellBounds);

    // Print positions of each tile if I have any.
    foreach (Vector3Int pos in Tilemap.cellBounds.allPositionsWithin) {
      var localPlace = new Vector3Int(pos.x, pos.y, pos.z);
      Debug.Log(localPlace);
    }

  }
}

The above code is on my TileManager. When run, allTiles list is empty so of course no Debug output is logged.
Question:
Is it possible to get list of tiles that have been painted with the prefab brush?


texts: Best practice for frequent sending webSocket/Socketio/webRCT data

texts:
I already done game template for classic platformer. I use matter.js for physics and my own override draw functions. Everything works fine. Next stage is to make it multiplayer.

I interest is it good to send user input (force vector) only when play act with keyboard/mouse (apply force on remote gameplay) or to send on every change (for example) absolute x,y and then use set position method.

GamePLay is fully scaleable (In any resolution same diametric transformation).
webRTC look like best solution for communication in fly.

I worry about collisions moments.

Any suggest for this question ?


texts: Looking for a market price algorithm for a turn based game

texts:
I am new at game development and am now facing the problem for a market price algorithm in a turn based game.
What I try to achieve:

the market starts with fixed bidding and asking prices for one piece of goods. To keep it simple the minimum value is 1, the maximum 20
if the user buys/sells the same goods in too large quantities in a certain amount of turns, the prices should rise/drop; simple supply and demand logic. The maximum amount of a goods per transaction is 100
if the user doesn't trade that good for a few turns, it should adjust the price in the other direction
there are certain type of goods that can be "easily" produced by the player and are thus sold and some that are harder to get by and are usually bought.
the market can sell each good infinitely and would also buy everything, so it has no stock to take into account.

What I tried and didn't work:

if the accumulated quantity of bought/sold good reaches 500 (I use negative values for buying) the price rises or drops by 1 respectively
to factor the turns into it, I thought I just reduce the accumulated value by 10 each turn and then adjust the price if it reaches 0 again. This has one big flaw, as you can easily cheat by just selling a small amount, wait a few turns and the price will rise; repeat until the price reaches the maximum of 20.

Any simple ideas on how to fix this?
ps. I hope this is an appropriate question to ask here


texts: Calculation: Is a sphere/square/plane visible from a certain point?

texts:
I'm searching for a way to detect if a form (shape can be changed if algorithm requires it) is visible from a single point in a 3D tile-based world. This should be used as some kind of wall-hack protection to hide players from the client if they are fully covered behind a wall.

This does not have to be extremely precise. The only condition is that the algorithm never returns a false-negative. Therefore I thought it might be the easiest choice to create a rather large sphere around each other player and peform visibly operations from the viewpoint to that that imaginary sphere. I'm planning to use this on larger maps and only if players are far away from each other. It wouldn't be a problem if you could see players that a behind a wall right next to you.

Since I have no clue how the solution may look like I'm searching for a very abstract description of how such an algorithm works.

I found this very similiar question: Precomputing Visibility But I think this led me into the wrong direction since my main aspect ist speed rather than accurancy.


texts: How, if possible, do you add loop cuts to models in real time?

texts: I am working on a prototype for a very low poly game. I can't figure out a way for a player to cut or break objects in real time without predefined fractures. For example, if a player cuts a tree, it will separate at the cut point rather than at a predetermine fracture. So how can you create a vertex loop and separate the halves in real time?


texts: Can I render 3D objects in Ray Casting engines?

texts:
I was gathering some information on the glorious Ray Casting technique. As far as I've understood it's not a complete 3D rendering, and that's why objects and NPC's are often displayed as simple sprites (I might be wrong here, of course).

Then I've stumbled upon the Dark Forces' engine by Lucas Arts, called Jedi Game Engine and back in the days they were able to include fully 3D objects. Then a question arises: how did they do it? Do the objects "simply" boil down to a complex mixture of walls and floors?


texts: Materials aren't loading correctly from SketchUp into Unity

texts:
I imported a SketchUp COLLADA (.dae) file from 2017 SketchUp Make, and imported it into Unity. I then clicked "Use External Materials" and the colors began to load. But I noticed quickly that one of the wings of my imported B-29 was Dark Gray, while the other way a proper color. Random parts, such as the front engine housing piece, were also dark gray. Parts of my advanced dials were also dark gray, and I immediately decided that there is now ay that I am going to manually go in and fix every single dark-gray material, but at the moment, I found no alternative.
I began with the wing. I went to assign the material that I used for the other wing, which was white, to the dark gray wing, but I found out that the other wing already had that material in use. And when I went to assign a different white color, absolutely nothing changed, aside from the fact that the wing now claimed that it had that color in use. Is there a fix for this problem? I could try importing as a .SKP file, if the reason for the issue is something to do with the COLLADA (.dae) file.
What I had was 2 wings. they were both components in SketchUp, so whatever I did to one applied to the other, Then I made them unique before importing to Unity. The Wing that won't work right is the one wing that had the USAF Insignia on it. But I doubt this is the problem, because all engines on that wing were also not colored correctly, whereas the other wing was fine. Those engines were also components, but were also made unique before the import.
Each wing has 9 groups inside of it. The other wing is identical in this sense. I imported the file from file explorer by dragging the file from file explorer and dropping it into unity.
This is what the plane looks like in Unity:

My apologies for the crude handwriting, it is difficult to draw with a touchpad.
In the image, I numbered the incorrectly-colored parts visible in the image (Right/Left references are perspective to image)
1. Left Wing. Color: Dark gray. Color intended: White.
2. Propeller blade hub. This is the part that all propeller blades are connected to. Both hubs on the two propellers on the Left Wing are colored incorrectly. Color: white. Color Intended: Grey.
3. Pistons. All piston components, such as the pistons, securing poles, and piston heads are not colored correctly; same on the other engine on the Left Wing. Color: White. Color Intended: Grey pistons, darkish-grey piston heads, and copper-orange securing poles.
4. Cowl Flaps. In the image, this appears to be a stripe in the engine. Same with the other cowl flaps on the other engine on the Left Wing. Color: Dark gray. Color Intended: White.
5. Propeller blades. All 4 propeller blades on both engines on the left wing are not colored correctly. Color: White. Color Intended: Black, with yellow tips.
6. Right-Wing Pistons. Most piston components, such as the pistons heads and securing poles are not colored correctly. Same with the other engine on the Right Wing. Color: White Piston Heads, Grey Pistons, Almost-Black Gray in the lines on the pistons, white securing poles. Color Intended: Grey pistons, darkish-grey piston heads, and copper-orange securing poles.
7. Front Engine Casing. The same error is in the other engine's front engine casing on the Right Wing. Color: Dark Gray, with an apparent shine coming from beneath the part, which shouldn't be happening (the directional light is above the engine part). Color Intended: White.
8. Rear Engine Casing. The same error is in the other engine's rear engine casing on the Right Wing. Color: Dark Gray, with an apparent shine coming from beneath the part, which shouldn't be happening (the directional light is above the engine part). Color Intended: White.


texts:
I am having some issues with trying to detect collision of two isometric tile.

I have tried plotting the lines between each point on the tile and then checking for line intercepts however that didn't work (probably due to incorrect formula)

After looking into this for awhile today I believe I am thinking to much into it and there must be a easier way.

I am not looking for code just some advise on the best way to achieve detection of overlap


texts: Frame Buffer Object (FBO) is not working. What is the right way to use?

texts:
I am trying to use FBO but i am living some problems. I will show you my steps but first i will show my running screen ,so we can compare them. Like before fbo after fbo.

My running screen and Draw() function code:

glClearColor(0.5,0.5,0.5,1.0);
glLoadIdentity();
glTranslatef(0.0,0.0,-3.0);
glRotatef(0,0.0,1.0,0.0);
glUniform3f(glGetUniformLocation(mainShader->getProgramId(),"lightPos"),0,1,2);
mainShader->useShader();
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    scene->draw(mainShader->getProgramId());
mainShader->delShader();

After I tried to add FBO :

Create FBO texture function:

unsigned int createTexture(int w,int h,bool isDepth=false)
{
    unsigned int textureId;
    glGenTextures(1,&textureId);
    glBindTexture(GL_TEXTURE_2D,textureId);
    glTexImage2D(GL_TEXTURE_2D,0,(!isDepth ? GL_RGBA8 : GL_DEPTH_COMPONENT),w,h,0,isDepth ? GL_DEPTH_COMPONENT : GL_RGBA,GL_FLOAT,NULL);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);

    int i;
    i=glGetError();
    if(i!=0)
    {
        std::cout << "Error happened while loading the texture: " << i << std::endl;
    }
    glBindTexture(GL_TEXTURE_2D,0);
    return textureId;
}

Init() function :

void init()
{
    glClearColor(0,0,0,1);
    glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluPerspective(50,640.0/480.0,1,1000);
    glMatrixMode(GL_MODELVIEW);
    glEnable(GL_DEPTH_TEST);
    mainShader=new shader("vertex.vs","fragment.frag");
    quadRenderShader=new shader("quadRender.vs","quadRender.frag");
    scene=new meshLoader("test.blend");

    renderTexture=createTexture(640,480);
    depthTexture=createTexture(640,480,true);
    glGenFramebuffers(1,&FBO);
    glBindFramebuffer(GL_FRAMEBUFFER,FBO);
    //GL_COLOR_ATTACHMENT0
    //GL_DEPTH_ATTACHMENT
    glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,renderTexture,0);

    glFramebufferTexture2D(GL_FRAMEBUFFER,GL_DEPTH_ATTACHMENT,GL_TEXTURE_2D,depthTexture,0);

    int i=glCheckFramebufferStatus(GL_FRAMEBUFFER);
    if(i!=GL_FRAMEBUFFER_COMPLETE)
    {
        std::cout << "Framebuffer is not OK, status=" << i << std::endl;
    }
    glBindFramebuffer(GL_FRAMEBUFFER,0);

}

And Draw() function:

void display()
{
    //rendering to texture...
    glClearColor(0.5,0.5,0.5,1.0);
    glLoadIdentity();
    glTranslatef(0.0,0.0,-3.0);
    glRotatef(0,0.0,1.0,0.0);
    glUniform3f(glGetUniformLocation(mainShader->getProgramId(),"lightPos"),0,1,2);
    mainShader->useShader();
    glBindFramebuffer(GL_FRAMEBUFFER,FBO);
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
        scene->draw(mainShader->getProgramId());
    glBindFramebuffer(GL_FRAMEBUFFER,0);
    mainShader->delShader();

    glClearColor(0.0,0.0,0.0,1.0);
    //render texture to screen
    glLoadIdentity();
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    quadRenderShader->useShader();
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D,depthTexture);
    glUniform1i(glGetUniformLocation(quadRenderShader->getProgramId(),"texture"),0);
    quad->draw(quadRenderShader->getProgramId());
    quadRenderShader->delShader();

}

and Result only drawing last setup color (glClearColor) so black :

Result should be like in tutorial :

Note: I know tutorial monkey is purple but it is not problem.


texts: How to make my model's top section rotate without rotating the entire model?

texts:
I'm trying to learn a bit of Maya modeling so that I can be self sufficient when it comes to creating super basic assets for my game development. I'm trying to understand skeletal rigging and how it modifies the model geometry itself.

I've got the most basic model - a cube with proportions that make it into a 3D rectangle. I've rigged it with a very simplistic skeleton. My goal is to learn how all of this works, and create a character that has motion similar to maybe the magic carpet from Aladdin - it's a rectangle but the edges somewhat move like it has arms and legs.

When I rotate some joints, it distorts the entire model. I added a bit more geometry thinking that it'd allow the top section of my model to rotate a bit more without having to deform the entire model, but it still just seems to do the same thing.

How can I make the top section of my model be capable of moving forward and backward in such a way that it does not cause the entire model to move forward?

Here are some screenshots to help explain and show my situation ...

This is my model and skeleton (I told you it was super basic, lol) ...

And here is what happens when I rotate around the neck joint ...

And here is sort of what I was hoping to achieve ...


texts: Unity3D : Creating & Sharing light-baked levels without updating the game

texts:
I want to give myself freedom to add more levels after releasing the game. For creating levels I broke down structure and created a tilemap like a structure. here's an example :

I will add them up to create a level and send it to server from where I can download the JSON in game and read it at run time to place things around. The problem is I want to also use Global Illumination. What I can do is send lightmap data with created level to server and download and use it for lighting after generating level. But what If my map is huge?? I don't want to have lightmap size. The other thing I can do is create light baked prefabs, suggested by this article, https://unity3d.com/how-to/light-baked-prefabs-on-mobile. But every single object has to be attached to a surface and baked because of shadows. Is there a better approach?

Thank you.


texts: Should a server run all maps in one loop, or a thread/game loop per map?

texts:
I'm working on a real time multiplayer browser-based game.
The game is top down on variable size tile based maps. There is no central map where all players come together, the entire game plays out in multiple maps. (Player chooses one on login, but has the ability to switch whenever they want).
Let's take the following loop that runs on the server side of things:
let tick_time = Duration::from_millis(500); // e.g. Tick 2 times per second.
let mut next_tick = Instant::now();

loop {
    let now = Instant::now();

    if now >= next_tick {
        // Parse user input
        // Update state
        // Update to state to users in map

        next_tick += tick_time;
    } else {
        let wait_time = next_tick - now;
        sleep(wait_time - Duration::from_millis(1)).await;
    }
}

In my 'map based' gameplay scenario, would it make sense to spawn a thread for every map where one of these loops runs? Or would it be recommended to have only a singular thread with a singular game loop that updates every map? Or is there perhaps a better, already existing, pattern for this?


texts: Finding the site of the potential collision between 2 vehicles

texts:
I've been trying to implement the unaligned collision avoidance steering behavior. I get what needs to be done on a high level, but struggle with the maths behind it.

On Craig Reynolds site, he describes

  Collision avoidance is obtained for a vehicle by considering each of the other vehicles, and determining (based on current velocities) when and where the two will make their nearest approach. A potential for collision exists if that nearest approach is in the future, and if the distance between the vehicles at nearest approach is small enough. The nearest of these potential collisions, if any, is determined. The vehicle then steers to avoid the site of the predicted collision.

For the trajectory of the vehicles, I simply store a velocity vector (x, y), and to change it an acceleration vector is used. The collision avoidance behavior should return a force (in the form of a vector).

How you would find the nearest approach (Isn't this just where they collide?) and the site of the predicted collision?


texts: Blender mesh mirroring screws up normals when importing in Unity

texts:
My issue is as follows:

I've modeled a robot in Blender 2.6. It's a mech-like biped or if you prefer, it kindda looks like a chicken. Since it's symmetrical on the XZ plane, I've decided to mirror some of its parts instead of re-modeling them. Problem is, those mirrored meshes look fine in Blender (faces all show up properly and light falls on them as it should) but in Unity faces and lighting on those very same mirrored meshes is wrong. What also stumps me is the fact that even if I flip normals in Blender, I still get bad results in Unity for those meshes (though now I get different bad results than before).

Here's the details:

Here's a Blender screen shot of the robot. I've took 2 pictures and slightly rotated the camera around so the geometry in question can be clearly seen:

Now, the selected cog-wheel-like piece is the mirrored mesh obtained from mirroring the other cog-wheel on the other (far) side of the robot torso. The back-face culling is turned of here, so it's actually showing the faces as dictated by their normals. As you can see it looks ok, faces are orientated correctly and light falls on it ok (as it does on the original cog-wheel from which it was mirrored).

Now if I export this as fbx using the following settings:

and then import it into Unity, it looks all screwy:

It looks like the normals are in the wrong direction. This is already very strange, because, while in Blender, the original cog-wheel and its mirrored counter part both had normals facing one way, when importing this in Unity, the original cog-wheel still looks ok (like in Blender) but the mirrored one now has normals inverted.

First thing I've tried is to go "ok, so I'll flip normals in Blender for the mirrored cog-wheel and then it'll display ok in Unity and that's that". So I went back to Blender, flipped the normals on that mesh, so now it looks bad in Blender:

and then re-exported as fbx with the same settings as before, and re-imported into Unity. Sure enough the cog-wheel now looks ok in Unity, in the sense where the faces show up properly, but if you look closely you'll notice that light and shadows are now wrong:

Now in Unity, even though the light comes from the back of the robot, the cog-wheel in question acts as if light was coming from some-where else, its faces which should be in shadow are lit up, and those that should be lit up are dark.

Here's some things I've tried and which didn't do anything:

in Blender I tried mirroring the mesh in 2 ways: first by using the scale to -1 trick, then by using the mirroring tool (select mesh, hit crtl-m, select mirror axis), both ways yield the exact same result
in Unity I've tried playing around with the prefab import settings like "normals: import/calculate", "tangents: import/calculate"
I've also tired not exporting as fbx manually from Blender, but just dropping the .blend file in the assets folder inside the Unity project

So, my question is: is there a way to actually mirror a mesh in Blender and then have it imported in Unity so that it displays properly (as it does in Blender)? If yes, how?

Thank you, and please excuse the TL;DR style.